# --- Data Types --- myInteger = 12 # variable assigned an integermyFloat = 12.0 # variable assigned a floatmyString = "twelve" # variable assigned a stringmySecondString = '12' # variable assigned a stringmyBoolean = False # variable assigned a BooleandataType = type(myFloat) # determines data type/class of objectconvInt = int(myFloat) # converts float to an integerconvFloat = float(myInteger) # converts integer to a floatconvString = str(myInteger) # converts integer to stringprint(round(4.8)) # rounds a float value to the nearest whole numberprint(var1) # print command
Arithmetic Operators
# --- arithmetic operators ---print( 2 + 2 ) # additionprint( 2 - 2 ) # subtractionprint( 2 * 2 ) # multiplicationsprint( 2.1 / 2 ) # division, always results in float: 2.1 / 2 evaluates to 1.05print( 2.1 // 2 ) # floor divisiion, gives the result of the last even division. Result will be a "mathematical integer" but whether it's a Python int or float depends on numbers used. 2.1 // 2 evaluates to the float 1.0, while 5 // 2 evaluates to int 2print( 5 % 2 ) # modulo (integer remainder), 5 % 2 evaluates to 1 (that's the 1 left over to get to 5 after 2 went into 4 evenly... see how floor division and modulo pair so well... 5 // 2 = 2, 5 % 2 = 1)print( 2 ** 2 ) # power of.. 2**2 evaluates to 4
Assignment/Reassignment Operators
# --- assignment/reassignment operators ---myNumt = 10 # assignmentmyNum += 5 # "add and"... adds to previous valuemyNum -= 5 # "substract and"... subtract from previous valuemyNum *= 5 # "multiply and"... multiply by previous valuemyNum /= 5 # "divide and"... divide by previous value
Comparison Operators
# --- comparison operators ---myNum = 4 print( myNum < 2 ) # less thanprint( myNum > 2 ) # greater thanprint( myNum <= 4 ) # less than or equal toprint( myNum >= 2 ) # greater than or equal toprint( myNum == 2 ) # equal to print( myNum != 2 ) # not equal to
String Operators
# --- string operations --- # view all string methods: https://docs.python.org/3/library/stdtypes.html# string-methodsmyCourse = "introduction to programming in Python"courseLength = len(myCourse) # length functioncourseProper = myCourse.title() # capitalizes first letter of each wordconfirmLower = myCourse.islower() # determines if the string consists of lowercase charactersstatement = "I love Python. Working with Python is amazing because, hello, it's Python!"countPython = statement.count('Python')name = 'John Jacob Jingleheimer Schmidt'name[0:4] # slice a stringusername = "Connie"code = "C859"userMessage = "Welcome to {}, {}.".format(code, username)print( userMessage )myNewPhrase = "cowabunga dude"mySplitPhraseList = myNewPhrase.split(" ") # split method, returns a listprint(mySplitPhraseList)
Functions with Input and Output
# --- function with both input and output ---def areaOf(width,height):# function that accepts two inputsreturn width * height # function body outputs calculated areamyArea = areaOf(4,6) # function call provides two arguments and saves return value to a variable -- we can assign a value with this function because it RETURNS a valueprint( myArea ) # displays myArea
if / elif / else Statements
# --- if / elif / else statements ---age = 16if age < 16: # condition will evaluate to either True or Falseprint('you are not old enough to drive') # if condition is True, execute this blockelif age >= 16 and age <= 18: # second condition will evaluate to either True or Falseprint('you may drive with adult supervision') # if second condition is True, execute this blockelse:print('you may drive a vehicle') # both earlier conditions are False, execute this block
Boolean Operations
# --- Boolean operations ---# Boolean and operation will always be false unless both sides are truebool01 = True and False # ... so it's Falsex = 3bool01a = (x == 3) and (x > 9) # False!bool01b = (x == 3) and (x >2) # True!bool02 = True or False # but that's True! OR combos are True when any single condition is True (pro tip: generally limit OR to joining 2 conditions -- any more than that and you're likely to have one evaluate True unexpectedly)bool03 = not (True and False) # True... since (True and False) is False, so the not flips it to True
Lists
# # --- Lists ---myNumbers = [1, 4.8, 7, 9.2, 3, 0] # creates listprint(myNumbers[3]) # prints the fourth number from the listprint(myNumbers[-1]) # prints the last element from the listyourNumbers = myNumbers[1:3] # creates a new list (via a slice) with the second and third values from myNumbersaltNumbers = myNumbers[:3] # creates a new list (slice!) with 1st, 2nd, and 3rd values from myNumbersnewNumbers = myNumbers[3:] # creates a new list (sliced again!) with 4th, 5th, and 6th values from myNumbersmatchList = 9.2 in myNumbers # looks for a match and returns Boolean value... True herenoMatch = 9.3 not in myNumbers # ensures a match does not exist in list... also True here since list does not contain 9.3listLength = len(myNumbers) # counts items in listlistMax = max(myNumbers) # returns greatest element of listlistMin = min(myNumbers) # returns smallest element of listlistSort = sorted(myNumbers) # returns copy of list ordered smallest to largestlistSortAgain = sorted(myNumbers, reverse=True) # returns copy of list ordered largest to smallestlistSum = sum(myNumbers) # returns total sum of list valuesmyNames = ['Jessica', 'Connie', 'Amy']myNames.append('Grace') # new value is added to end of listmyNames.pop() # removes last item from the listmyNames.pop(1) # removes second item from the listlistJoined = ", ".join(myNames) # a string is used to join together values from listprint('Welcome aboard ' + listJoined)
Sets
# --- Sets ---# note that sets aren't nearly as important to the OA as strings, lists, and dictionariesidNums = set() # creates a new set, emptyidNums.add(12345) # adds value to setidNums.add(12367) # adds second value to setidNums.add(12367) # adds third value to set, but it is duplicate so it will not be addedidNums.discard(12345) # removes value from set, if foundset(myNumbers) # converts the list from line 91 above to a setlist(idNums) # converts the set from line 121 into a list
Loops
# --- For Loop ---# a FOR loop is a natural fit for looping over a container item by itemcities = ['Albany', 'Chicago', 'Boulder', 'Tampa']for city in cities: # performs commands for each item within listprint('Welcome to the city of ' + city) # or# print('Welcome to the city of {}'.format(city)) # get to know str.format() or the similar f strings way of building larger strings... concatenation with + gets old fastsum = 0for num in range(1,5): # runs loop for numbers 1 through 4, as range is exclusive of the ending positionsum += num# --- While Loop ---# a WHILE loop is like an IF that repeats as long as its condition stays Truetemp = 34while temp >= 32: # while condition is True loop will iterateprint(temp) temp -= 1 # variable must change state, moving towards satisfying conditionprint('it is freezing') # loop is done (note indentation is moved back left), so temp must be down below 32 nowstartValue = 0while startValue < 20:startValue += 1if startValue == 4: # if statement checks for a specific valuebreak # stops the flow of the while loop prematurelyprint(startValue) # it's 4!
Dictionaries
# --- Dictionaries ---studentGrades = { # dictionary is created'Orfu': 83, # first entry is added with key of str 'Orfu' and value of int 83'Bismark': 98,'Igor': 72} # end of dictionaryif 'Igor' in studentGrades: # in verifies if key is in dictionaryprint('student is in course')print( studentGrades.get('Bismark') ) # get method looks up value by key, or...# print(studentGrades['Bismark'] ) # you can use the key as if it was an index (it's not, but the syntax is the same)for student in studentGrades: # for loop iterates over each entry in dictionaryprint('{}, you earned {} on the final exam'.format(student, studentGrades[student]))
Tuples
# --- Tuples ---# tuples aren't as important as strings, lists, and dicts either# think of a tuple as a row of data... it is IMMUTABLE because you shouldn't just change the order of columns of datamyPhone = (877, 435, 7948) # tuple is created with three sections of a phone numberprint( 'Call WGU at {}-{}-{}'.format(myPhone[0], myPhone[1], myPhone[2]) )
Reading and Writing Files
# --- Reading and Writing Files ---# older, simpler, but more cumbersome syntax for opening files...f1 = open('/my_path/my_file.txt','r') # opens a file object for reading (read-mode is default)... you can now use IO/filestream methods like read() and readlines() on f1f1 = open('/my_path/my_file.txt','w') # opens a file object for writing and deletes what is in the file previouslyf1 = open('/my_path/my_file.txt','a') # opens a file object for appending (don't worry about append mode for OA, just read and write modes)f1.read() # reads the data from file into a stringf1.write('hello, friend') # writes to filef1.readlines() # returns a list of strings, with each line of the file as one string entryf1.close() # closes file# a better structure for opening files!with open('/my_path/my_file.txt','r') as f: # opens a file, names if f (or whatever you like), performs operations and automatically closes filemy_lines = []for line in f: # looping directly over the file is also OKmy_lines.append(line.strip()) # this does essentially the same as what f.readlines() would do, except usign the string strip() method here removes newline characters# when you leave the with/open() block the file closes automatically
Modules & Python Standard Library
# --- Modules & Python Standard Library---# The only modules I would focus on for the exam are math and csv# mathimport math # imports the math moduleprint('The factorial of 3 is: {}'.format(math.factorial(3)))print('The largest integer less than or equal to 5.6 is: {}'.format(math.floor(5.6))) # 5print('The smallest integer greater than or equal to 5.6 is: {}'.format(math.ceil(5.6))) # 6print('3 to the 5th power is: {}'.format(math.pow(3, 5))) # 243.0print('The math constant e to the power of 3 equals: {}'.format(math.exp(3))) # don't confuse math.exp() with math.pow()print('The square root of 6 is: {}'.format(math.sqrt(6)))# csv# reading csv and tsv files without the csv module, using plain old IO/filestream methods, is fine...# with open("filename.txt", "r") as f:# # when reading, I grab contents and get out of the open block# contents = f.read()# whole file as one big string# contents = f.readlines() # a list of line by line strings, WILL have "\n" at the end of each# but using csv makes it a little easier...import csv# the reader() method is the only one I suggest knowing contents = list(csv.reader(f)) # csv.reader(f, delimiter="\t") for .tsv files... I like to recast the reader as a list. # does one more step for us... makes a list (since we recast it) of lists instead of the list of strings we get from readlines()# [ # ['1', 'Flossie', 'Levey', 'flevey0@jimdo.com', '129.134.226.30'],# ["2", "Bob"...],# ...# ] print(contents)