Skip to content

Instantly share code, notes, and snippets.

@AnsonT
Last active October 1, 2021 16:13
Show Gist options
  • Save AnsonT/016b8b65066c84c6d9bdb92e67085429 to your computer and use it in GitHub Desktop.
Save AnsonT/016b8b65066c84c6d9bdb92e67085429 to your computer and use it in GitHub Desktop.
Basic Python Usage Notes
# -----------------------------------------------
# Loops
# -----------------------------------------------
aList = ['apple', 'orange', 'pear']
## print all fruits
for fruit in aList:
print(fruit)
## skip 'apple'
for fruit in aList:
if fruit == 'apple':
continue
print(fruit)
## stop at 'orange'
for fruit in aList:
if fruit == 'orange':
break
print(fruits)
# -----------------------------------------------
# range
# -----------------------------------------------
## looping through a range of numbers
for i in range(...):
print(i)
range(10) # 0 to 10, excluding 10 -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range(2,6) # 2 to 6, excluding 6 -> 2, 3, 4, 5
range(2, 20, 3) # 2 to 30, excluding 20, step 3 -> 2, 5, 8, 11, 14, 17
range(5, 1, -1) # 5 to 1, excluding 1, backwards -> 5, 4, 3, 2
for i in range(len(aList)):
print(i, aList[i])
## better way to loop a list to get both the index and value
for i, fruit in enumerate(aList): # i - index, fruit - value
print(i, fruit)
# -----------------------------------------------
# Reversing a list
# -----------------------------------------------
## loop a list backwards
for fruit in reversed(aList):
print(fruit)
for i, fruit in enumerate(reversed(aList)):
print(i, fruit)
## To get a copy of reversed list
bList = list(reversed(aList)) # ['pear', 'orange', 'apple'], aList unchanged
## Reverse aList 'in place'
aList.reverse() # aList is now ['pear', 'orange', 'apple']
# -----------------------------------------------
# Indexing a string
# -----------------------------------------------
aStr = 'abcdefghijklmn'
aStr[1] == 'b' # char at position 1
aStr[2:5] == 'cde' # characters from position 2 to 4
aStr[::2] == 'acegikm' # every second character
aStr[:3] == 'abc' # from 0 to 2
aStr[5:] == 'fghijklmn' # starting from 5
aStr[::-1] == 'nmlkjihgfedcba' # reverse
aStr[2::-1] == 'cba' # starting from 2, backwards
# slice(,,) function works the same way
aStr[slice(2, 5)] == aStr[2:5] # why? you can assign slice to a variable and reuse
# -----------------------------------------------
# if statements
# -----------------------------------------------
a = 20
b = 30
if a > b:
print('a greater than b')
else:
print('b not greater than a')
if a == b:
print('a equals to b')
elif a > b:
print('a greater than b')
else:
print('a not equals to b and a not greater than b')
# -----------------------------------------------
# finding things in a loop
# -----------------------------------------------
foundApple = False
for fruit in aList:
if fruit == 'apple':
foundApple = True
break
print(foundApple)
# find position of first 'apple' in a list
applePosition = -1
for i, fruit in enumerate(aList):
if fruit == 'apple':
applePosition = i
break
print(applePosition)
# find position of last 'apple' in a list
applePosition = -1
for i in range(len(aList)-1, -1, -1):
if aList[i] == 'apple':
applePosition = i
break
print(applePosition)
## alternative
applePosition = -1
for i, fruit in enumerate(aList):
if fruit == 'apple':
applePosition = i # notice: no break, this is inefficient because it has to go through the entire list
print(applePosition)
## alternative
applePosition = -1
for i, fruit in enumerate(reversed(aList)):
if fruit == 'apple':
applePosition = len(aList) - 1 - i # starting at len(aList)-1
break
print(applePosition)
# -----------------------------------------------
# find maximum
# -----------------------------------------------
numList = [10, 30, 12, 34, 70, 3]
maxValue = max(numList)
## or with a for loop
maxValue = numList[0] # use the first value as the potential maximum
for i in numList[1:]: # loop from the next value (but start from 0 will work as well)
if i > maxValue:
maxValue = i
print(i)
# -----------------------------------------------
# sorted
# -----------------------------------------------
clothes = ['shirt', 'hat', 'socks', 'shorts']
for cloth in sorted(clothes):
print(cloth) # hat, shirt, shorts, socks
for cloth in sorted(clothes, key=len): # Sort by length
print(cloth) # hat, shirt, socks, shorts
for cloth in sorted(clothes, key=str.casefold): # ignoring upper/lower case
print(cloth) # hat, shirt, shorts, socks
# -----------------------------------------------
# Dictionaries
# -----------------------------------------------
scores = { 'david': 85, 'peter': 70, 'andrew': 69, 'alexander': 91 }
print(scores['alexander'])
for name, score in scores.items(): # get the items in a dictionary as a list
print(name, score)
# Nested dictionaries
classScores = {
'class1': { 'david': 85, 'peter': 70 },
'class2': { 'andrew': 69, 'alexander': 91 }
}
for className, students in classScores.items():
print('--------')
print(className, len(students))
for name, score in students.items():
print(name, score)
# -----------------------------------------------
# Parsing string in python
# -----------------------------------------------
## split string into a list, using " " as separator
myString = "What does the fox say?"
print(myString.split(" "))
# ["What", "does", "the", "fox", "say?"]
## split 2 separators only
print(myString.split(" ", 2))
# ["What", "does", "the fox say?"]
## split into a tuple: before and after the partition string
print(myString.partition("the"))
# ("What does ", "the", " fox say?")
## removes starting and ending spaces
stringWithSpaces = " some string "
print(stringWithSpaces.strip())
# "some string"
## strip left side
print(stringWithSpaces.lstrip())
# "some string "
print(stringWithSpaces.rstrip()) # strip left side
# " some string"
stringWithUpperAndLower = "aBcDeFg xYz"
print(stringWithUpperAndLower.upper())
# "ABCDEFG XYZ"
print(stringWithUpperAndLower.lower())
# "abcdefg xyz"
print(myString.startsWith("What")) # true
print(myString.startsWith("When")) # false
print(myString.endsWith("?")) # true
print("fox" in myString) # true
# -----------------------------------------------
# Printing with formatting
# -----------------------------------------------
className = 'COMP-204'
assignmentName = 'print something'
print("Class: {}, Assignment: {}".format(className, assignmentName))
print(f"Class: {className}, Assignment: {assignmentName}")
# see the f prefix to the string is called an interpolated string,
# you can put python code betwen the {} to print the expression's value
# -----------------------------------------------
# Reading from file
# -----------------------------------------------
f = open("somefile.txt", "r")
for line in f:
print(line)
# loading files into a nested dictionary
# E.g. Files containing lines with
# className,studentName,score
f = open("somefile.txt", "r")
classes = {} # Initialize classes as a dictionary
for line in f:
className, studentName, score = line.split(',', 2)
if not className in classes: # check to see if the className is already in the classes dictionary
classes[className] = {} # if not, initialize it with an empty dictionary
classes[className][studentName] = score # set the studentName/score in the class's dictionary
print(classes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment