20220817 ******************************************************* Python Introduction Exercises ++++++++++++++++++++++++++++++++++++++++++++ 1. Discuss with your neighbor: A. the differences between an interpreter and a compiler Interpreter: Compiler: B. if Python is an interpreted or compiled language 2. Discuss with your neighbor the similarities and differences between Python and English. Display Hello, world: >>> print("Hello, world") Hello, world >>> =================== RESTART: /private/tmp/helloWorld.py =================== Hello, world >>> print('Hello, ya'll') SyntaxError: invalid syntax >>> print( ) >>> print("Hello, ya'll") Hello, ya'll >>> print("Questions?") Questions? >>> print(" Q u e s t i o n s ? ") Q u e s t i o n s ? >>> print ( "Questions?" ) Questions? 3. Write down python code to do the following: A. Display your full name B. Display your last name, first name (for example: Carroll, Hyrum) C. Create a variable named favNum and assign it your favorite number D. Display your favorite number (using favNum) E. Display your name and your favorite number (using favNum), all on one line F. Display your name and your favorite number (using favNum), on two lines (but with just one print()) G. Display the following (exactly as shown): One of my favorite quotes is, "Today's a good day to have a good day" H. Display the following: * ** * * **** I. Display the following (exactly as shown): _ _(")_ (_ . _) / : \ Yummy! (_/ \_) >>> print("Nikki") Nikki >>> print("Lastname, Nikki") Lastname, Nikki >>> favNum = 13 >>> favNum=13 >>> print( favNum ) 13 >>> favNum = 5 >>> print( favNum ) 5 >>> print( "Caleb", favNum) Caleb 5 >>> print( "Caleb", "F", favNum) Caleb F 5 >>> firstName = "Mav" >>> lastName = "L" >>> print( firstName, lastName, "has a favorite number of", favNum) Mav L has a favorite number of 5 >>> favNum = 10 >>> print( firstName, lastName, "has a favorite number of", favNum) Mav L has a favorite number of 10 >>> print( firstName, lastName, "\nHas a favorite number of", favNum) Mav L Has a favorite number of 10 >>> print("""Mav L Has a favorite number of 10""") Mav L Has a favorite number of 10 >>> print("Mav L Has a favorite number of 10") SyntaxError: EOL while scanning string literal >>> From Monday, January 23rd ================================= # Display your full name print('My Name') print("My Name") print(" My Name ") print ( "My Name" ) # Display your last name, first name (for example: Carroll, Hyrum) print( 'Doe, John') # Create a variable named favNum and assign it your favorite number favNum = 5 # Display your favorite number (using favNum) print(favNum) # print(My Name) # looking for a variable named My and a variable names Name # Display your name and your favorite number (using favNum), all on one line print("Your Name", favNum) # Your Name 5 firstName='John' lastName='Doe' print(firstName, lastName, favNum) # Displays John Doe 5 # Display your name and your favorite number (using favNum), # on two lines (but with just one print()) # Displays: # John # 5 print(firstName, lastName, '\n', favNum) # \n is the newline character print(firstName, lastName, '/n', favNum) # \n is the newline character print(firstName, lastName, '\n', favNum, sep='') # \n is the newline character print(firstName, ' ', lastName, '\n', favNum, sep='') # \n is the newline character print(firstName, lastName, '\n', favNum, sep=':)') # \n is the newline character print("\nUsing the 'end' keyword argument:") print(firstName, lastName, '\n', favNum, end=':)') print(firstName, lastName, '\n', favNum, end=':)') print("\nExplicitly controlling the defaults for the print function:") print(firstName, lastName, '\n', favNum, sep=' ', end='\n') # default separator is a space, default at the end is print(firstName, lastName, '\n', favNum, sep=':-(', end='Go Cougars!') # default separator is a space, default at the end is print("After are weird line") # Display the following (exactly as shown): # One of my favorite quotes is, "Today's a good day to have a good day" print('''One of my favorite quotes is, "Today's a good day to have a good day"''') print('One of my favorite quotes is, "Today\'s a good day to have a good day"') print("One of my favorite quotes is, \"Today's a good day to have a good day\"") print('One of my favorite quotes is, "',"Today's a good day to have a good day",'"', sep='') # Display the following: # * # ** # * * # **** print("""* ** * * ****""") print('''* ** * * ****''') print("*","**","* *","****", sep='\n') print("*","\n","**","\n","* *","\n","****", sep='') print("*""\n""**""\n""* *""\n""****") print("*\n**\n* *\n****") # Display the following (exactly as shown): # _ # _(")_ # (_ . _) # / : \ Yummy! # (_/ \_) print(""" _ _(")_ (_ . _) / : \ Yummy! (_/ \_) """) Python Errors Exercises ++++++++++++++++++++++++++++++++++++++++++++ 1. For each of the following types of errors in python, turn to your neighbor and describe the error and give an example of code that would generate that error: A. Syntax error: It's not correct Python syntax, meaning it can't be parsed by the Python interpreter. Example: print('Your Name") print('Mine Name' pr int(':)') B. Runtime error: The syntax is correct, but the instructions are not executable Example: print( favNum / 0 ) C. Logic/Semantic error: The syntax is correct, there was no runtime errors, but the outcome is not what you wanted Example: print('I have a total of', 5 + 2, 'fingers') # displays a 7 in the middle, really wanted 5 * 2 2. What kind of error produces a: A. Bug - Logic/Semantic error B. Crash - Runtime 20230125 ******************************************************* Binary Numbers ++++++++++++++++++++++++++++++++++++++++++++ 7189 7000 = 7 * 10^3 = 7 * 1000 +100 = 1 * 10^2 = 1 * 100 + 80 = 8 * 10^1 = 8 * 10 + 9 = 9 * 10^0 - 9 * 1 Shortcut method: 1000 100 10 1 7 1 8 9 10110_2 10000_2 = 1 * 2^4 = 1 *16 =16 +0000_2 = 0 * 2^3 = 0 * 8 = 0 + 100_2 = 1 * 2^2 = 1 * 4 = 4 + 10_2 = 1 * 2^1 = 1 * 2 = 2 + 0_2 = 0 * 2^0 = 0 * 1 = 0 ----------------------------- 22 11101 10000_2 = 1 * 2^4 = 1 *16 =16 +1000_2 = 1 * 2^3 = 1 * 8 = 8 + 100_2 = 1 * 2^2 = 1 * 4 = 4 + 00_2 = 0 * 2^1 = 0 * 2 = 0 + 1_2 = 1 * 2^0 = 1 * 1 = 1 ----------------------------- 29 16 8 4 2 1 1 0 1 0 1 16 +4 +1 == 21 Binary Numbers Exercises ================================= 1. What is the value (in base-10) of the following base-2 numbers? A. 0111_2 = 7 = (0+4+2+1) B. 0110_2 = 6 = (0+4+2+0) C. 1111_2 =15 = (8+4+2+1) D. 10111_2 = 23 = (16+0+4+2+1) 2. Using each of your fingers as a binary digit on just your right hand: A. How many numbers can you represent? B. What is the largest number you can represent (in base-2)? C. What is the smallest number you can represent (in base-2)? 20230127 ******************************************************* 2. Describe to your neighbor how int() works. Include: A general description What it takes as an argument A function that allows you to change a str (or a float) to an int. What it returns An int Any limitations The argument must be a str version of an int (so, not 'banana') 3. Describe to your neighbor how float() and str() work. Include: float() A general description What it takes as an argument A function that allows you to change a str (or an int) to an float. What it returns A float Any limitations The argument must be a str version of an float (so, not 'banana') Example: grade = float( input("Please enter your grade: ") ) 20230130 ******************************************************* Input Exercises ++++++++++++++++++++++++++++++++++++++++++++ 1. Turn to your neighbor and discuss how we get input from a user into a variable in a python script? Use the (built-in) input function A. What options do we have with that function? A = 'first' B = 'second' A = input() # notice, no prompt, so how is the user suppose to know what to enter It's good practice, to always prompt the user with what they should enter. A = input('Please enter the position: ') B. What do we need to do if we want to use the input as a number? age = int( input('Please enter your age: ')) // or age = input('Please enter your age: ') age = int(age) // or ageStr = input('Please enter your age: ') age = int(ageStr) 2. Write down python code to do the following: # A. Get (from the keyboard) a user's first name. firstName = input('Please enter your first name: ') # firstName = int( input('Please enter your first name: ') ) # B. Get a user's last name lastName = input('Please enter your last name: ') # C. Display the user's first and last name print(firstName, lastName) # D. Prompt the user to enter their favorite number and store it in a variable named favoriteNum favoriteNum = int( input( 'Please enter your favorite number: ') ) # E. Double favoriteNum and display the result to the screen print( 'BTW, your favorite number doubled is', favoriteNum * 2) # F. Prompt the user to enter a joke and store it in a variable name joke. Display the joke. joke = input('Please enter a joke: ') print('Your joke is', joke) Variables & Keywords Exercises ++++++++++++++++++++++++++++++++++++++++++++ 1. Variables + With your neighbor, come up with three reasons a variable name/identifier can be invalid. Provide an example for each one: 1. Starts with a number (Variables can not start with a number) 76thguy = "Da man" # will not work 2. keyword (Variable can not be a keyword) True = 1 # will not work 3. Has a special character (for example, !, $, #, *, space, etc) [anything that is not a number, letter or _] dollar#dollar my)variable multiply*Operator # Python would consider this as the multiply variable, multiplied by the Operator variable 2. Keywords + Python 3 (as of version 3.9.6) has 35 keywords. We will be covering the underlined ones in this course. Look-up 3 keywords that we're going to use this semester and explain what how they're used: False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield Official list HERE or by executing: import keyword print( keyword.kwlist ) Operators & Operands Exercises ++++++++++++++++++++++++++++++++++++++++++++ >>> numApples = 5 >>> numPeople = 2 >>> >>> print("numApples:", numApples) numApples: 5 >>> print("numPeople:", numPeople) numPeople: 2 >>> print("numApples / numPeople:", numApples / numPeople) numApples / numPeople: 2.5 >>> print("numApples // numPeople:", numApples // numPeople) numApples // numPeople: 2 >>> print("numApples % numPeople:", numApples % numPeople) numApples % numPeople: 1 >>> print("numApples ** numPeople:", numApples ** numPeople) numApples ** numPeople: 25 >>> print("numApples + 5 * numPeople:", numApples + 5 * numPeople) numApples + 5 * numPeople: 15 >>> print("(numApples + 5) * numPeople:", (numApples + 5) * numPeople) (numApples + 5) * numPeople: 20 round() ++++++++++++++++++++++++++++++++++++++++++++ >>> help( round ) >>> print( round(3.141596) ) 3 >>> print( round(3.141596, 4) ) 3.1416 >>> print( round(3.5555, 2) ) 3.56 >>> print( round(3.15111, 2) ) 3.15 >>> print( round(3.99999999999, 4) ) 4.0 >>> print( round(3.99999999999, 2) ) 4.0 20230201 ******************************************************* Debugging Exercises 1. Write a Python script that calculates the balance after the first payment of a loan (given the number of years, initial balance and the APR). What can we do: # get input for years, balance and APR (annual percentage rate, so the interest rate) # calculate the monthly interest rate # calculate the number of payments (years * 12) # calculate the principal (initial balance) # calculate the monthly payment = P * (r*(1+r)**n)/((1+r)**n - 1) # r is the monthly interest rate # n is the number of payments # P is the principal (the loan) # calculate the new balance is the previous balance * the interest rate minus the payment # Example $5,000 kayak 6 months (0.5 years) 4.5% APR # get input for years, balance and APR (annual percentage rate, so the interest rate) years = float(input('Please enter the number of years: ')) print('years:', years) balance = float(input('Please enter the balance: ')) print('balance:', balance) apr = float( input('Please enter the APR (for example, 0.045 for 4.5%): ')) print('apr:', apr) # calculate the monthly interest rate r = apr/12 # calculate the number of payments (years * 12) n = years * 12 # calculate the principal (initial balance) P = balance # calculate the monthly payment = P * (r*(1+r)**n)/((1+r)**n - 1) # r is the monthly interest rate # n is the number of payments # P is the principal (the loan) monthlyPayment = P * (r*(1+r)**n)/((1+r)**n - 1) print('monthlyPayment:', monthlyPayment) # calculate the new balance by the previous balance + the previous balance * the interest rate - the payment firstMonthsInterest = P * r print('firstMonthsInterest:', firstMonthsInterest) newBalance = balance + firstMonthsInterest - monthlyPayment print('newBalance:', round(newBalance, 2)) # # Example # $5,000 kayak # 6 months (0.5 years) # 4.5% APR Visualization of Python code: https://pythontutor.com/ 20230203 ******************************************************* Debugging Exercises ++++++++++++++++++++++++++++++++++++++++++++ 3. Discuss with your neighbor an example of each of the following errors: ParseError - the syntax is not correct TypeError - combine two different data types in a ways that's not support (for example, a 'Hi Mom!' + 42) NameError - Usually using a variable before is been it's been assigned value ValueError - "Value errors occur when you pass a parameter to a function and the function is expecting a certain limitations on the value, and the value passed is not compatible" 4. Match each error above with the correct type of error below: Syntax error - ParseError Runtime error - TypeError, NameError and ValueError Logic error - (for example, print('Based on the number of weeks in a year, there are', (52+7), 'days in a year')) Turtle Graphics ++++++++++++++++++++++++++++++++++++++++++++ >>> import turtle >>> canvas = turtle.Screen() >>> roger = turtle.Turtle() >>> roger.fd(50) >>> roger.left(50) >>> roger.left(40) >>> roger.fd(50) >>> roger.left(90) >>> roger.fd(150) >>> roger.left(90) >>> roger.fd(50) >>> roger.left(90) >>> roger.forward(50) >>> roger.right(50) >>> roger.right(40) >>> roger.fd(200) >>> roger.left(90) >>> roger.fd(50) >>> roger.left(90) >>> roger.fd(200) >>> roger.circle(150) >>> roger.right(180) >>> roger.circle(150, 360/3) >>> roger.circle(150, 360/3) >>> roger.circle(150, 360/3) >>> roger.width(10) >>> roger.fd(25) >>> roger.pencolor('red') >>> roger.fd(100) 20230226 ******************************************************* Draw a capital "I": import turtle # Allows us to use turtles wn = turtle.Screen() # Creates a playground for turtles crush = turtle.Turtle() # Create a turtle, assign to crush (from Finding Nemo) crush.width(20) horSideLen=45 # length of vertical sides vertSideLen=100 # length of horizontal sides crush.forward(horSideLen) crush.left(180) # Turn around crush.forward(horSideLen/2) crush.left(90) crush.forward(vertSideLen) crush.right(90) crush.forward(horSideLen/2) crush.left(180) # Turn around crush.forward(horSideLen) wn.exitonclick() # Close the window when the user clicks on the exit button Introduction to for loops: import turtle # Allows us to use turtles wn = turtle.Screen() # Creates a playground for turtles crush = turtle.Turtle() # Create a turtle, assign to crush (from Finding Nemo) crush.pensize(15) crush.speed(10) polySideLen=60 # Length of each side numSides=int(input('Please enter the number of sides: ')) angle=360/numSides # Angle at each vertex (ex: pentagon is 360/5 = 72) print("angle:", angle) for emreIsAwesome in range(numSides): print('DEBUGGING: emreIsAwesome:', emreIsAwesome) crush.forward(polySideLen) # Move forward crush.left( angle ) # Make one turn of the polygon wn.exitonclick() # Close the window when the user clicks on the exit button 20230213 ******************************************************* def birthdaySong( name ): print("Happy birthday to you!") print("Happy birthday to you!") print("Happy birthday dear", name) print("Happy birthday to you!") birthdayName = input("Please enter the name of who is having the birthday: ") birthdaySong( birthdayName ) 20230215 ******************************************************* 9. What does return do? 1) Returns a value (as in return num), which replaces the function with that value 2) End executing the function (as in return, which is the same as return None) For example, write a function the returns what you want most right now. def greatestDesire(): # print('SLEEP!') return 'SLEEP!' print( greatestDesire() ) import math ''' ADD sphereVolume() HERE ''' def sphereVolume( r ): # 4/3πr^3 return 4/3 * math.pi * r**3 for radius in range(1, 5): print('The volume of a sphere with a radius of', radius, end='') print(' is', round( sphereVolume( radius ), 1)) # Write a function that takes all of the parts of an address and # returns a single str for that address def address1Line( zipCodeKyuThankYouForThatResponse, state, city, street, houseNum ): address = str(houseNum) + " " + street + ", " + city + ", " + state + " " + str(zipCodeKyuThankYouForThatResponse) return address csuNum = 4225 csuStreet = 'University Avenue' csuCity = 'Columbus' csuState = 'GA' csuAdamIsAwesome = 31907 oneLiner = address1Line( csuAdamIsAwesome, csuState, csuCity, csuStreet, csuNum ) print('CSU\'s address is', oneLiner) 20230217 ******************************************************* import turtle # Allows us to use turtles ''' ADD drawStar() HERE ''' def drawStar( crush, n ): internalAngle = 180 - (180/n) for j in range(n): crush.forward(100) crush.right( internalAngle ) def main(): wn = turtle.Screen() # Creates a playground for turtles crush = turtle.Turtle() # Create a turtle, assign to crush (Finding Nemo) crush.width(15) for i in range(3, 11+1, 2): drawStar( crush, i) crush.fd(100) crush.penup() crush.forward(10) crush.pendown() wn.exitonclick() # Close the window when the user clicks on the exit button if __name__ == '__main__': main() Local Variables ++++++++++++++++++++++++++++++++++++++++++++ Variables have lifetimes and scopes A variable that is defined in a function Lifetime ================================= The lifetime of a variable is WHEN its value is in memory Scope ================================= Scope is WHERE in the code a variable is valid Variables declared in a function are local to the function, meaning only valid in that function Global Variables ================================= Global variables are not created inside a function nor in any other body Avoid using global variables Python first looks for a local variable before a global one (this is confusing and should be avoided) Functions Can Call Other Functions ++++++++++++++++++++++++++++++++++++++++++++ Demo: Blue gradient lines Don't have a function call itself, at least not until the end of Computer Science 2 main() ++++++++++++++++++++++++++++++++++++++++++++ C/C++ and Java require that execution start in a special function named main() __name__ is a special variable start is set before interpretation to either: 1) '__main__', if executing the script directly or 2) the name of the module, if using it with import 20230220 ******************************************************* Selection Exercises ++++++++++++++++++++++++++++++++++++++++++++ Comparison (relational and equality) Operators ================================= I. With your neighbor, identify the 6 common comparison operators and explain what each one does: 1. ==, tests for equality (Example: a*a == b*b + c*c) 2. !=, tests for inequality 3. <, tests if the expression on the left is less than the expression on the right 4. >, tests if the expression on the right is less than the expression on the left 5. <=, tests if the expression on the left is less than or equal to the expression on the right 6. >=, tests if the expression on the right is less or equal to than the expression on the left Logical Operators: ================================= I. With your neighbor, identify the 3 logical operators and explain what each one does: 1. and, combines two boolean expressions and results in True if and only if both of the boolean expressions are True (Example: (age >= 13) and (acceptedAgreementTerms == True)) 2. or, combines two boolean expressions and results in True if at least one is True 3. not, takes one operand / expression and evaluates to the opposite boolean value a = false b = true print( a and b) a b | a and b ------------+-------- false false | false false true | false true false | false true true | true a b | a or b ------------+-------- false false | false false true | true true false | true true true | true a | not a ------+-------- false | true true | false II. Given a variable age, write a boolean expression that evaluates to True only when age represents a teenager. (Can you come up with another way to evaluate age that meets this criterion?) age = int(input('Please enter your age: ') ) age == 13 or age == 14 or age == 15 or age == 16 or age == 17 or age == 18 or age == 19 age <= 19 and age > 12 age <= 19 and age >= 13 age < 20 and age >= 13 age < 20 and age > 12 not( age >= 20 or age <= 12 ) age = int(input('Please enter your age: ') ) if age <= 19: print('True') else: print('False') III. What does the following evaluate to? hairColor == "blond" or "brown" or "red" or "black" >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: black >>> print( hairColor == "blond" or "brown" or "red" or "black" ) brown >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: red >>> print( hairColor == "blond" or "brown" or "red" or "black" ) brown >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: brown >>> print( hairColor == "blond" or "brown" or "red" or "black" ) brown >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: blond >>> print( hairColor == "blond" or "brown" or "red" or "black" ) True hairColor == "blond" or "brown" or "red" or "black" Correct python code: hairColor == "blond" or hairColor == "brown" or hairColor == "red" or hairColor == "black" >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: black >>> print( hairColor == "blond" or hairColor == "brown" or hairColor == "red" or hairColor == "black" ) True >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: brown >>> print( hairColor == "blond" or hairColor == "brown" or hairColor == "red" or hairColor == "black" ) True >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: red >>> print( hairColor == "blond" or hairColor == "brown" or hairColor == "red" or hairColor == "black" ) True >>> hairColor = input('Please enter your the hair color: ') Please enter your the hair color: grey >>> print( hairColor == "blond" or hairColor == "brown" or hairColor == "red" or hairColor == "black" ) False hairColor = "brown" hairColor == "blond" or "brown" or "red" or "black" 1st: hairColor == "blond" -> False 2nd: False or "brown" -> "brown" hairColor = "blond" hairColor == "blond" or "brown" or "red" or "black" 1st: hairColor == "blond" -> True hairColor == "blond" and hairColor == "brown" and hairColor == "red" and hairColor == "black" as evaluates to False IV. Determine the correct order of precedence among the following: Category Operators addition +,- exponent ** logical and logical or logical not multiplication *,/,//,% relational ==,!=,<=,>=,>,< Category Operators Highest Precedence: exponent ** multiplication *,/,//,% addition +,- relational ==,!=,<=,>=,>,< logical not logical and logical or 20230222 ******************************************************* What are the data types that we've covered so far? str int float bool bool is a data type Only 2 values: True, False (keywords) >>> type(True) >>> type(False) Expression something that gets evaluated Examples: ----------- ... alreadyPaid = (balance <= 0) print( alreadyPaid ) ... usersGuess = int( input("Let's see if you can guess the number I'm thinking of. Enter a number: ") ) guessRight = (usersGuess == secretNumber) Logical Operators: ================================= not expression expression1 and expression2 expression1 or expression2 V. Add as many parenthesis as possible to the the following expressions (without the order of operations): 1. val * 3 > 10 and option == True or override == True (val * 3) > 10 and option == True or override == True ((val * 3) > 10) and option == True or override == True ((val * 3) > 10) and (option == True) or override == True ((val * 3) > 10) and (option == True) or (override == True) (((val * 3) > 10) and (option == True)) or (override == True) ((((val * 3) > 10) and (option == True)) or (override == True)) 2. 5 + 6 * 7 / 8 > 9 and 4 - 3 ** 2 / 10 or fee / 10 < 100 5 + 6 * 7 / 8 > 9 and 4 - (3 ** 2) / 10 or fee / 10 < 100 5 + (6 * 7) / 8 > 9 and 4 - (3 ** 2) / 10 or fee / 10 < 100 5 + ((6 * 7) / 8) > 9 and 4 - (3 ** 2) / 10 or fee / 10 < 100 5 + ((6 * 7) / 8) > 9 and 4 - ((3 ** 2) / 10) or fee / 10 < 100 5 + ((6 * 7) / 8) > 9 and 4 - ((3 ** 2) / 10) or (fee / 10) < 100 (5 + ((6 * 7) / 8)) > 9 and 4 - ((3 ** 2) / 10) or (fee / 10) < 100 (5 + ((6 * 7) / 8)) > 9 and (4 - ((3 ** 2) / 10)) or (fee / 10) < 100 ((5 + ((6 * 7) / 8)) > 9) and (4 - ((3 ** 2) / 10)) or (fee / 10) < 100 ((5 + ((6 * 7) / 8)) > 9) and (4 - ((3 ** 2) / 10)) or ((fee / 10) < 100) (((5 + ((6 * 7) / 8)) > 9) and (4 - ((3 ** 2) / 10))) or ((fee / 10) < 100) ((((5 + ((6 * 7) / 8)) > 9) and (4 - ((3 ** 2) / 10))) or ((fee / 10) < 100)) 3. fileExists == False or fileOpenedSuccessfully == True and errorReadingFile == True (fileExists == False) or fileOpenedSuccessfully == True and errorReadingFile == True (fileExists == False) or (fileOpenedSuccessfully == True) and errorReadingFile == True (fileExists == False) or (fileOpenedSuccessfully == True) and (errorReadingFile == True) (fileExists == False) or ((fileOpenedSuccessfully == True) and (errorReadingFile == True)) ((fileExists == False) or ((fileOpenedSuccessfully == True) and (errorReadingFile == True))) Selection: Conditional Execution / If-else Statements ++++++++++++++++++++++++++++++++++++++++++++ if-else statement Syntax: if boolean_expression: # executed if the condition evaluates to True statement1 statement2 statement3 statement4 ... else: # executed if the condition evaluates to False statement5 statement6 statement7 ... >>> fellowScouter = True >>> if fellowScouter == True: ... print( 'shake with left hand') ... else: ... print( 'shake with the right hand') ... shake with left hand >>> >>> >>> >>> name = 'President' >>> if name == 'Honey': ... print('Love ya!') ... else: ... print('See ya') ... See ya >>> 20230224 ******************************************************* if statement Syntax: ----------- if boolean_expression: # executed if the condition evaluates to True statement1 statement2 statement3 statement4 ... Examples: --------------------------------- if temperature < 40 and isRaining == True: callForARide() if value < 0: print('You entered a negative number. Please only use positive numbers.') if-elif-else Statements ================================= if-elif-else statement Syntax: ----------- if boolean_expression: # executed if the boolean_expression evaluates to True statement1 statement2 statement3 statement4 ... elif boolean_expression2: # executed if the boolean_expression2 evaluates to True statement8 statement9 statement10 statement11 ... elif boolean_expression3: # executed if the boolean_expression3 evaluates to True statement38 statement39 statement310 statement311 ... elif boolean_expression4: # executed if the boolean_expression4 evaluates to True statement48 statement49 statement410 statement411 ... else: # executed if the condition evaluates to False statement5 statement6 statement7 ... IV. How else can we write the if-elif-else statements below (without using an elif)? # Given an age from the user and whether or not they're showing significant signs of independence, # display if the person is a teenager, acting like one or is neither import sys age = int(input("Please enter the age: ")) userResponse = input("Is the person showing significant signs of independence? (yes/no) ").lower() if userResponse == "yes": showingSignsOfIndependence=True elif userResponse == "no": showingSignsOfIndependence=False else: print("ERROR: Please answer yes or no!") sys.exit(1) if (age >= 13) and (age <= 19): print("Teenager") elif (age < 13) and showingSignsOfIndependence == True: print("Acting like a teenager") else: print("Not a teenager") # Given an age from the user and whether or not they're showing significant signs of independence, # display if the person is a teenager, acting like one or is neither import sys age = int(input("Please enter the age: ")) userResponse = input("Is the person showing significant signs of independence? (yes/no) ").lower() if userResponse == "yes": showingSignsOfIndependence=True else: if userResponse == "no": showingSignsOfIndependence=False else: print("ERROR: Please answer yes or no!") sys.exit(1) if (age >= 13) and (age <= 19): print("Teenager") else: if (age < 13) and showingSignsOfIndependence == True: print("Acting like a teenager") else: print("Not a teenager") rightMsg = "Yeah, that was fun!" wrongMsg = "What was it and what question could extend this game?" print("Think of an animal") response = input("Does it fly? (yes/no) ") if response == "yes": response = input("Is it an eagle? (yes/no) ") if response == "yes": print(rightMsg) else: print(wrongMsg) else: response = input("Does it run over 30 MPH? (yes/no) ") if response == "yes": response = input("Does it have a mane? (yes/no ") if response == 'yes': response = input("Is it a lion? (yes/no) ") if response == "yes": print(rightMsg) else: print(wrongMsg) else: response = input("Is it a cheetah? (yes/no) ") if response == "yes": print(rightMsg) else: print(wrongMsg) else: print(wrongMsg) 20230227 ******************************************************* grade = float( input('Please enter your overall grade (ex: 98.7): ')) if grade >= 90.0: print(str(round(grade,1)) + '% is an A') elif grade >= 80.0: print(str(round(grade,1)) + '% is a B') elif grade >= 70.0: print(str(round(grade,1)) + '% is a C') elif grade >= 60.0: print(str(round(grade,1)) + '% is a D') else: print(str(round(grade,1)) + '% is an F') Loops ++++++++++++++++++++++++++++++++++++++++++++ Syntax for a for-loop: ----------- for loopVariable in container: loopBodyStatement1 loopBodyStatement2 loopBodyStatement3 ... statementOutsideOfLoopBody # Write a python script that requests a starting number and a stopping number from the user. Display each number from the starting number to the stopping number on its own line. num1 = int(input('Please enter a number: ')) num2 = int(input('Please enter another number: ')) # if num1 < num2: # for i in range( num1, num2 + 1): # print(i) # else: # for i in range( num2, num1 + 1): # print(i) # # # or start = num1 end = num2 if num1 > num2: start = num2 end = num1 for i in range( start, end + 1): print(i) # # or # # for i in range( num1, num2 + 1): # print(i) # # for i in range( num2, num1 + 1): # print(i) 20230303 ******************************************************* print('Right angles are 90, 180, 270 and 360. Let\'s display them one at a time:') angle = 90 for i in range(4): print(angle) print('All done!') # displays Right angles are 90, 180, 270 and 360. Let's display them one at a time: 90 90 90 90 All done! print('Right angles are 90, 180, 270 and 360. Let\'s display them one at a time:') step = 90 angle = step for i in range(4): print(angle) angle += step print('All done!') # displays Right angles are 90, 180, 270 and 360. Let's display them one at a time: 90 180 270 360 All done! import random print('10 random numbers:') num = random.randrange( 1, 100+1 ) # a single random number 1..100 for i in range( 10 ): print( num ) print('All done!') # displays 10 random numbers: 63 63 63 63 63 63 63 63 63 63 All done! import random print('10 random numbers:') for i in range( 10 ): num = random.randrange( 1, 100+1 ) # a single random number 1..100 print( num ) print('All done!') # displays 10 random numbers: 43 99 62 44 32 13 96 7 33 21 All done! Loop Iterators ================================= Syntax for a for-loop: ----------- for loopVariable in container: loopBodyStatement1 loopBodyStatement2 loopBodyStatement3 ... statementOutsideOfLoopBody The "container" can be lots of different things, so long as they are a sequence container or an iterable (for example, range() returns an iterable) # Displays every letter of the alphabet on its own line (by using a str (which is a sequence container type) in a for loop) alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for letter in alphabet: print( letter ) Flowchart of name game: https://automatetheboringstuff.com/images/000097.png Input Validation ================================= Demo: http://csc.columbusstate.edu/carroll/1301/loops/guessingGame.py.html 4. Write python code to request either "yes" or "no" from the user. Continue to prompt the user until either "yes" or "no" is entered. Then display their response. Examples: Please enter yes or no: maybe Please enter yes or no: Yes Please enter yes or no: yes Thank you for entering yes Please enter yes or no: why Please enter yes or no: why Please enter yes or no: why Please enter yes or no: no Thank you for entering no Please enter yes or no: yes Thank you for entering yes response = input('Please enter yes or no: ') # input was why: # while 'why' != 'yes' and 'why' != 'no': # while True and 'why' != 'no': # while True and True: # while True: # input was 'no' # while 'no' != 'yes' and 'no' != 'no': # while True and 'no' != 'no': # while True and False: # while False: while response != 'yes' and response != 'no': # invalid input response = input('Please enter yes or no: ') # or while not( response == 'yes' or response == 'no' ): # invalid input response = input('Please enter yes or no: ') print('Thank you for entering', response) 20230306 ******************************************************* Categorical Input Validation ================================= # the user's choice does not match any of the valid choices while choice != option1 and choice != option2 and choice != option3: print(choice, 'is not a valid option :(') choice = input('Please enter your selection: ') # # or # # if not any of the valid choices while not( choice == option1 or choice == option2 or choice == option3): print(choice, 'is not a valid option :(') choice = input('Please enter your selection: ') Numerical Ranges Input validation ================================= # choice is either too low or too high while choice < lowerBound or choice > upperbound: print(choice, 'is not between', lowerBound, 'and', upperbound) choice = input('Please enter your selection: ') # # or # # choice is not within the valid range while not ( choice >= lowerBound and choice <= upperbound): print(choice, 'is not between', lowerBound, 'and', upperbound) choice = input('Please enter your selection: ') Infinite Loops ================================= A loop that never stops Write an infinite loop: x = False while x != True: print(1) while True: print('Hello') Converting For Loops to While Loops ================================= You can write any for loop as a while loop Example: ----------- num1 = int(input('Please enter a number: ')) num2 = int(input('Please enter another number: ')) start = num1 end = num2 if num1 > num2: start = num2 end = num1 step = 1 # for i in range( start, end + 1): # for i in range( start, end + 1, step): # print(i) # # print('All done (i is now', str(i)+')') i = start while i < end + 1: print(i) i += step if start < end + 1: i -= step print('All done (i is now', str(i)+')') 5. Write python code using a while statement to produce the exact same results as the code below: print("Original (with for-loop):") # set the initial number startNum = 10 # count down until we get to 1 for num in range(startNum, 0, -1): print( num, "...") print( num, "!", sep='') print("With while-loop):") # set the initial number startNum = 10 num = startNum # count down until we get to 1 while num > 0: print( num, "...") num = num -1 # if we ever went into the loop, # then undo the last update if startNum > 0: num = num + 1 print( num, "!", sep='') Tables (Tabular Output) ================================= Two main data files types: Comma separated (.csv) and TAB separated (.tab) A tab character: Visually aligns to the next multiple of 8 In Python: "\t" 20230308 ******************************************************* Nested Loops ++++++++++++++++++++++++++++++++++++++++++++ What can you put in a loop? Code (including another loop) 20230310 ******************************************************* String ++++++++++++++++++++++++++++++++++++++++++++ int float bool str Empty String ================================= An empty string has no characters Examples: 1) '' 2) "" 3) somethingNice = '' Note, that ' ' is not an empty string, but a string with a space String Concatenation (+) ================================= What does concatenation mean? To add together Example: dish = 'pizza' dessert = 'fruit' + ' ' + dish # dessert is now 'fruit pizza' dessert = 'fruit ' + dish # dessert is now 'fruit pizza' dessert = 'fruit pizza' # dessert is now 'fruit pizza' String Repetition (*) ================================= In Python , if we have: str * int it returns multiple copies of str Examples: ----------- salutation = 'xo' print( salutation * 4 ) # displays xoxoxoxo reaction = 'ha' print( reaction * 3) # displays hahaha Index Operator ================================= Example ----------- greeting = 'Hello!' Index: 0 1 2 3 4 5 Character: H e l l o ! We can access individual letters, using the index and []s Examples ----------- # 012345 greeting = 'Hello!' print( greeting[3] ) # displays l print( greeting[4] ) # displays o print( greeting[0] + greeting[4] + greeting[2] + greeting[1] ) # displays Hole Indices can be negative as well Example ----------- greeting = 'Hello!' Index: 0 1 2 3 4 5 Index: -6 -5 -4 -3 -2 -1 Character: H e l l o ! print( greeting[ -2] + greeting[-3] + greeting[-5] + greeting[-1] ) # displays ole! # displays the same thing print( greeting[-1] ) print( greeting[ len(greeting) - 1] ) 20230313 ******************************************************* String Basics ++++++++++++++++++++++++++++++++++++++++++++ 1. Write Python code to do the following: # A. Assign your first name to a variable named fullName fullName = 'John' # B. Append (or add) a space and your last name to fullName fullName = fullName + ' ' + 'Smith' # C. Print out each of the characters in fullName with a loop print('With a for loop:') for i in fullName: print(i) print('With a while loop:') index = 0 while index < len( fullName ): print('index:', index, 'character at that index:', fullName[ index ] ) index += 1 # D. Display the number of characters in fullName print( fullName,'has', len(fullName),'characters') # E. Display just your surname (last) name using fullName and a string slicer (Hint: [ : ] ) # 01234567890123456789 # John Smith # slicing syntax: str[ start : stop ] # slicing syntax: str[ start : ] # implies go until the last character print('Just the last name:', fullName[5:]) 2. Answer the following questions then confirm with your neighbor: A. What is the index of the first letter of your first name in fullName? 0 B. What is the index of the first letter of your last name in fullName? 5 (for John Smith) 6 (for Dylan ...) C. How can we determine the length of any str variable in python? len( str ) D. What will be the result of the following python code? # fullName[0] = 'Z' # strings are immutable (can not change) # print('the full name is now:', fullName) fullName = 'Z' + fullName[1:] E. What does the following python script print out (if anything)? word = "stressed" startIndex = -1 lastIndex = 0 - len(word) # index of first letter step = -1 for charIndex in range( startIndex, lastIndex + step, step): # print the character in word specified by charIndex (and don't add a # newline at the end) print( word[ charIndex ], end='') # display just a newline print() String Methods ================================= For each of the following methods, write down what they do including what they return: 1. String testing methods: str.isalpha() - returns True if all of the characters in str are letters (found in the alphabet) and there is at least 1 character, False otherwise str.isalnum() - returns True if all of the characters in str are letters or numbers and there is at least 1 character, False otherwise str.isdigit() - returns True if all of the characters in str are numbers and there is at least 1 character, False otherwise str.islower() - returns True if all of the letters in str are lowercase letters and there is at least 1 letter, False otherwise str.isspace() - returns True if all of the characters in str are whitespace characters (spaces, tab (\t), newline (\n), etc) and there is at least 1 character, False otherwise str.isupper() - returns True if all of the letters in str are uppercase letters and there is at least 1 letter, False otherwise Examples ----------- greeting = 'Hello, world' print( greeting.isalnum() ) # displays False greeting = 'Helloworld' print( greeting.isalnum() ) # displays True >>> def countNumberOfLetters( myString ): ... count = 0 ... for c in myString: ... if c.isalpha(): ... count +=1 ... return count ... >>> >>> myStr = 'Hello, world' >>> print( myStr, 'has', countNumberOfLetters( myStr ), 'letters (and', len(myStr),'characters') Hello, world has 10 letters (and 12 characters >>> >>> myStr = 'I love Python!' >>> print( myStr, 'has', countNumberOfLetters( myStr ), 'letters (and', len(myStr),'characters') I love Python! has 11 letters (and 14 characters >>> >>> myStr = '!@#$%^&*()_+-={}|[]\:";\'<>?,./' >>> print( myStr, 'has', countNumberOfLetters( myStr ), 'letters (and', len(myStr),'characters') !@#$%^&*()_+-={}|[]\:";'<>?,./ has 0 letters (and 30 characters 2. String modification methods: 1. str.lower() - returns a copy of the str will all letters as lowercase letters (and other characters as well) >>> greeting = 'Hello, World' >>> print( greeting.lower() ) hello, world >>> print( greeting ) Hello, World # Notice, strings are immutable, we did not change the original string, but made a new string instead 20230315 ******************************************************* strings are immutable (they can not change) 2. String modification methods: 1. str.lower() - returns a copy of the str will all letters as lowercase letters (and other characters as well) 2. str.upper() - returns a copy of the str will all letters as uppercase letters (and other characters as well) 3. str.lstrip(), lstrip( chars ) - returns a copy of str without any leading whitespace (or any of the contiguous characters in chars) 4. str.rstrip(), rstrip( chars ) - returns a copy of str without any whitespace on the end (or any of the contiguous characters in chars) 5. str.strip(), strip( chars ) - returns a copy of str without any whitespace on either end (or any of the contiguous characters in chars) 20230317 ******************************************************* Examples: ----------- Numerical input validation (for positive values): count = input('Please enter the quantity you would like: ') # while not valid while not count.isdigit(): print('Sorry,', count, 'is not a number.') count = input('Please enter the quantity you would like: ') # we now know it is safe to cast count to an int quantity = int( count ) # now do range validation 3. String searching and replacing methods: 1. str.startswith( substring ) - returns True if str starts with substring; False otherwise 2. str.endswith( substring ) - returns True if str ends with substring; False otherwise 3. str.count( substring ) - return the number of occurrences of substring in str 4. str.find( substring ) - return the first index of substring in str, or if it's not found, it will return -1 5. str.replace( substring, newString ) - returns a copy of str with all occurrences of substring replaced by newString Examples ----------- # for each vowel, display how many counts there are of that vowel poem = 'Two roads diverged in a yellow wood' vowels = 'aeiou' for c in vowels: print('Found', c, poem.count( c ), 'times in', poem) searchStr = 'road' print('Found', searchStr, poem.count( searchStr ), 'times in', poem) word = 'supercalifragilisticexpialidocious' index = word.find('i') while index >= 0: print('Found an i at index', index) # look for another i index = word.find('i', index + 1) # remove all occur of (lowercase) vowels, one set of vowels at a time (meaning, first, remove all of the "a"s) poem = 'Two roads diverged in a yellow wood' print('Before:', poem) vowels = 'aeiou' for c in vowels: print('Working on removing the', c + 's') poem = poem.replace( c, '' ) print('After: ', poem) # returns True if s starts with substring; False otherwise def strStartswith( s, substring): # options: # 1) use string slicing return s[:len( substring )] == substring # 2) iterate over the characters in substring and check that they are the same in s for i in range(len(substring)): if substring[i] != s[i]: return False # else: # don't include else here, or only the first character would be looked at # return True return True # 3) Use find and test if find returns 0 return s.find( substring ) == 0 Non-string methods: int( str ) - returns an int representation of str, if possible float( str ) - returns a float representation of str, if possible bool( str ) - returns a bool representation of str, if possible Length: len(str) ================================= A built-in function that can take a string as an argument (either a string literal or a variable of type str) It returns the number of characters in the string String Slicing ================================= # 111 # Indices: 0123456789012 fullName = 'Humpty Dumpty' print( fullName ) # Humpty Dumpty # String Slicing Syntax: # str[ start : end ] # returns a copy of str from the start index to (but not including) the end index. Note, if start is missing, then start from index 0 (the beginning). Note, if end is missing, then go until (and including) the last character. # str[ start : end : step ] # returns a copy of str from the start index to (but not including) the end index, stepping by step indices print( fullName[ 5:8 ]) # displays y D print( fullName[ :8 ]) # displays Humpty D print( fullName[ 5: ]) # displays y Dumpty print( fullName[ : ]) # displays Humpty Dumpty print( fullName[ : len(fullName) ]) # displays Humpty Dumpty print( fullName[ -3: ]) # displays pty print( fullName[-50: ]) # displays Humpty Dumpty (but note, fullName[-50] is an IndexError) print( fullName[ :-2 ]) # displays Humpty Dump print( fullName[ 5:50 ]) # displays y Dumpty (but note, fullName[50] is an IndexError print( fullName[ 5:10:2]) # displays yDm print( fullName[ 5:10:3]) # displays yu 20230327 ******************************************************* # Indices: # 111 # 0123456789012 river = "Chattahoochee" print( river ) # Chattahoochee print( river[1:4] ) # hat print( river[2:4] ) # at print( river[4:5] + river[6:7] + river[11:12] ) # the print( river[6:8] + ', ' + river[6:8] + ', ' + river[10:] ) # ho, ho, hee print( river[:4] ) # Chat print( river[-3:] ) # hee print( river[:-3] ) # Chattahooc print( river[9:1] ) # (nothing) 20230329 ******************************************************* String Comparison and Operators: ++++++++++++++++++++++++++++++++++++++++++++ python pytHon ^^^^ |||| |||+ 'h' > 'H', therefore 'python' > 'pytHon' ||+ same |+ same + same in ================================= str1 in str2 returns True if str1 is found in str2 and False otherwise print('python' in 'pytHon') # display False print('python' not in 'pytHon') # display True print( 'py' < 'python' ) # displays True 13 9 ^ | + different 1 < 9, therefore, '13' < '9' str.split() ++++++++++++++++++++++++++++++++++++++++++++ myStr = 'Hello, world!' myStr.split() returns ['Hello,', 'world!'] myStr.split('o') returns ['Hell', ', w', 'rld!'] myStr = 'supercalifragilisticexpialidocious' myStr.split() returns [ 'supercalifragilisticexpialidocious' ] myStr.split('o') returns [ 'supercalifragilisticexpialid', 'ci', 'us'] myStr = 'See spot run. See spot run fast.' myStr.split() return ['See', 'spot', 'run.', 'See', 'spot', 'run', 'fast.'] myStr.split('o') return ['See sp', 't run. See sp', 't run fast.'] fullName = 'Humpty Sir Dumpty' names = fullName.split() >>> print( chr( 67 ) ) C >>> print( chr( 68 ) ) D >>> print( chr( 69 ) ) E >>> print( ord('C') ) 67 >>> print( ord('D') ) 68 >>> print( ord('E') ) 69 >>> intValue = ord('C') >>> print( chr( intValue + 1 ) ) D >>> print( ord('Adam') ) Traceback (most recent call last): File "", line 1, in TypeError: ord() expected a character, but string of length 4 found >>> for i not in range(10): File "", line 1 for i not in range(10): ^ SyntaxError: invalid syntax >>> print( 'py' < 'python' ) True >>> print( 'py' in 'python' ) True >>> print( 'th' in 'python' ) True >>> print( 'yo' in 'python' ) False >>> print( 'python' in 'py' ) False >>> print( '13' < '9' ) True >>> print( '13' < '8' ) True >>> print( '13' < '7' ) True >>> dataHeaderLine = 'first name\tlast name\tage\tphone number\taddress' >>> print( dataHeaderLine.split( ) ) ['first', 'name', 'last', 'name', 'age', 'phone', 'number', 'address'] >>> print( dataHeaderLine.split('\t') ) ['first name', 'last name', 'age', 'phone number', 'address'] >>> eventDescription = "We're going to meet @ the building @ 7:00 PM" >>> eventDescription.split('@') ["We're going to meet ", ' the building ', ' 7:00 PM'] >>> >>> >>> dataHeaderList = ['first name', 'last name', 'age', 'phone number', 'address'] >>> ''.join( dataHeaderList ) 'first namelast nameagephone numberaddress' >>> '\t'.join( dataHeaderList ) 'first name\tlast name\tage\tphone number\taddress' 20230331 ******************************************************* # Lists Exercises # Lists Introduction # Create a list with your favorite breakfasts # Syntax for a list: [ element1, element2, element3, ... ] breakfasts = ['cereal', 'chocolate chip waffles', 'pancakes', 'hash browns', 'bacon', 'toast', 'cinnamon rolls', 'cinnamon sticks', 'chocolate gravy and biscuits', 'eggs', 'orange juice'] # Calculate and display the number of elements in your list numBreakfastIdeas = len( breakfasts ) print( 'We have', numBreakfastIdeas, 'breakfast ideas') # Display just your very most favorite breakfast print('One of our favorite breakfasts is', breakfasts[1] ) print('Another one of our favorite breakfasts is', breakfasts[6] ) # Create an empty list named breakfastsToTry breakfastsToTry = [] # same as [ ] print( 'Currently, we have', len(breakfastsToTry), 'breakfasts to try') # List Membership # Test if "green smoothie" is in your favorites list (using the list membership operator) # The list membership operator is: in drCsFav = 'green smoothie' if drCsFav in breakfasts: print('Great, I like a', drCsFav,'too!') else: print('Maybe consider adding', drCsFav, 'to your list of favorites . . .') if 'pancakes' in breakfasts: print('Yeah, we included the one of most common breakfasts') else: print('Maybe consider adding this stable to the list ...') singularBreakfast = 'pancake' if singularBreakfast in breakfasts: print('Yeah, we included the one of most common breakfasts (singular)') else: print('Maybe consider adding the stable', singularBreakfast, 'to the list ...') # List Concatenation # Add one or more breakfasts to your favorite breakfast list (using the list concatenation operator) #breakfasts = breakfasts + 'stroopwafel' # need to add a list to a list (and not a str) breakfasts = breakfasts + ['stroopwafel'] breakfasts = breakfasts + ['breakfast skillet'] + ['omelette'] print( 'We now have', len(breakfasts), 'breakfast ideas:', breakfasts) # List Slicing # Display three or more breakfasts using list slicing # ['cereal', 'chocolate chip waffles', 'pancakes', 'hash browns', 'bacon', 'toast', 'cinnamon rolls', 'cinnamon sticks', 'chocolate gravy and biscuits', 'eggs', 'orange juice', 'stroopwafel', 'breakfast skillet', 'omelette'] print('Here are 3 or more breakfasts:', breakfasts[2:5] ) print('Here are 3 or more other breakfasts:', breakfasts[10:55] ) # breakfasts[:] # makes a copy of the entire list # List Deletion # Remove your least favorite breakfast from the list and then display the list # Let's remove 'chocolate gravy and biscuits' del breakfasts[ 8 ] print('Breakfast ideas (without Dr. C\'s suggestion:', breakfasts) # # Output: # We have 11 breakfast ideas One of our favorite breakfasts is chocolate chip waffles Another one of our favorite breakfasts is cinnamon rolls Currently, we have 0 breakfasts to try Maybe consider adding green smoothie to your list of favorites . . . Yeah, we included the one of most common breakfasts Maybe consider adding the stable pancake to the list ... We now have 14 breakfast ideas: ['cereal', 'chocolate chip waffles', 'pancakes', 'hash browns', 'bacon', 'toast', 'cinnamon rolls', 'cinnamon sticks', 'chocolate gravy and biscuits', 'eggs', 'orange juice', 'stroopwafel', 'breakfast skillet', 'omelette'] Here are 3 or more breakfasts: ['pancakes', 'hash browns', 'bacon'] Here are 3 or more other breakfasts: ['orange juice', 'stroopwafel', 'breakfast skillet', 'omelette'] Breakfast ideas (without Dr. C's suggestion: ['cereal', 'chocolate chip waffles', 'pancakes', 'hash browns', 'bacon', 'toast', 'cinnamon rolls', 'cinnamon sticks', 'eggs', 'orange juice', 'stroopwafel', 'breakfast skillet', 'omelette'] 20230403 ******************************************************* lunches = ['steak', 'chicken', 'shrimp', 'pork', 'rice', 'mashed potatoes', 'salmon', 'sandwich', 'broccoli', 'fajita bowl'] numLunches = len( lunches) print('There are', numLunches , 'in the list') print('For lunch today we\'ll have', lunches[9]+'!') drCFavorite = 'Brazilian Beans and Rice' if drCFavorite in lunches: print('Great! I like Dr. C\s favorite as well') else: print('Guess it\s Dr. C\'s own little island of Brazilian Bean and Rice as it\'s not in the list') lunches = lunches + ['ramen', 'Mac & Cheese'] numLunches = len( lunches) print('There are', numLunches , 'in the list') # remove mashed potatoes del lunches[5] numLunches = len( lunches) print('There are', numLunches , 'in the list') Objects and References ++++++++++++++++++++++++++++++++++++++++++++ 1. Explain what each of the following do: 1. == compares two things (operands) and determines if they are equivalent 2. id() returns the memory location of an object (for example, variable) 3. is a is b # The same as id(a) == id(b) >>> l = [] >>> l = [1, "2"] >>> print( type(l) ) >>> print( type(l[0]) ) >>> print( type(l[1]) ) >>> print( type(l[2]) ) Traceback (most recent call last): File "", line 1, in IndexError: list index out of range >>> print( type(l[0:1]) ) >>> print( l[0:1] ) [1] >>> help( id ) >>> print( id( l ) ) 140649769059008 >>> msg = 'Hi, Mom!' >>> print( id( msg ) ) 140649769275504 >>> print( id( m ) ) Traceback (most recent call last): File "", line 1, in NameError: name 'm' is not defined >>> print( id( 'M' ) ) 140649733223408 >>> print( id( 1 ) ) 140649726875952 20230405 ******************************************************* crazyList1 = [1, True, ['sublist', 42], 'A' ] crazyList2 = [2, False, ['sublist', 42], 'B' ] print( crazyList1[0] ) print( crazyList1[2] ) print( id( crazyList1 ) ) print( crazyList1 is crazyList2 ) print( crazyList1 == crazyList2 ) print( crazyList1[2] is crazyList2[2] ) print( crazyList1[2] == crazyList2[2] ) crazyList3 = crazyList1 # makes an alias print( id( crazyList3 ) ) # crazyList3 = 9 subList = crazyList1[2] print( subList[1], crazyList1[2][1]) print( crazyList1 is crazyList3 ) print( crazyList1 == crazyList3 ) crazyList4 = list( crazyList1 ) # makes a clone of crazyList1 print( id( crazyList4 ) ) print( crazyList1 is crazyList4 ) print( crazyList1 == crazyList4 ) def printAll( l ): for i in l: print(i) printAll( crazyList3 ) Aliases and Cloning Lists ++++++++++++++++++++++++++++++++++++++++++++ 1. What is a synonym for a Python alias? Nickname 2. What is a synonym for cloning in Python? Copy 3. What is the major difference between an alias and a clone? An alias is store in the same location, whereas a clone has its own independent memory location. 4. How do we make an alias for a list in Python? = (the assignment operator) 5. Name 2 ways to clone a list: l = [] x = list( l ) # built-in function y = l[ : ] # list slicing 6. Write some Python code that uses your favorite lunches list that exemplifies the differences between aliases and cloning. Write in the comments where you are making an alias and where you are cloning. lunches = ['steak', 'chicken', 'shrimp', 'pork', 'rice', 'mashed potatoes', 'salmon', 'sandwich', 'broccoli', 'fajita bowl'] easterLunch = lunches # alias del easterLunch[8] thanksgivingLunch = lunches[:] # clone del thanksgivingLunch[ 2 ] print('Lunches:', lunches) # notice that 'broccoli' is removed, but 'shrimp' is still there print('Easter Lunches:', easterLunch) print('Thanksgiving Lunches:', thanksgivingLunch) 20230407 ******************************************************* Repetition Operator and Lists ++++++++++++++++++++++++++++++++++++++++++++ 1. Explain what each of the following do: >>> ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] * 52 ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] >>> [ '' ] * 100 ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] >>> [ 0 ] * 100 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> [ ] * 100 [] 20230410 ******************************************************* Repetition Operator and Lists ++++++++++++++++++++++++++++++++++++++++++++ 2. What is the scenario that you need to be cautious about with repetition and lists (and why)? >>> baseList = [ 'Hi', 'Mom', ['sublist1', 'sublist2'], 42] >>> baseListRepeated = baseList * 3 >>> print( baseListRepeated) ['Hi', 'Mom', ['sublist1', 'sublist2'], 42, 'Hi', 'Mom', ['sublist1', 'sublist2'], 42, 'Hi', 'Mom', ['sublist1', 'sublist2'], 42] >>> baseListRepeated[2][1] = 'Hello' >>> print( baseListRepeated) ['Hi', 'Mom', ['sublist1', 'Hello'], 42, 'Hi', 'Mom', ['sublist1', 'Hello'], 42, 'Hi', 'Mom', ['sublist1', 'Hello'], 42] 20230412 ******************************************************* Built-in Functions for Lists ++++++++++++++++++++++++++++++++++++++++++++ 1. Write Python code that displays the average rainfall for last month using the following values: rainfall = [0.09, 0, 0, 0, 0, 0.81, 0, 0, 0, 0, 1.19, 0.08, 0, 0, 0, 0, 0, 0.22, 0.08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.77, 0.05, 0] # inches import random # Calculate what is the maximum possible value for two six-sided dice. Store that value as MAX_DICE_ROLL. MAX_DICE_ROLL = 6 + 6 # Create a list with MAX_DICE_ROLL + 1 elements (with each element set to 0). rolls = [ 0 ] * (MAX_DICE_ROLL + 1) for i in range(10000000): # Choose a random number between 1 and 6 (inclusive), twice. Sum those numbers. die1 = random.randrange(1,6+1) die2 = random.randrange(1,6+1) diceTotal = die1 + die2 # Add 1 to the value at that index of the sum. rolls[ diceTotal ] += 1 # Repeat steps 3-4 999,999 more times. # Calculate what is the minimum possible value for two six-sided dice. Store that value as MIN_DICE_ROLL. MIN_DICE_ROLL = 1 + 1 # Iterate through values MIN_DICE_ROLL..MAX_DICE_ROLL (inclusively) and display the value and count. for i in range( MIN_DICE_ROLL, MAX_DICE_ROLL + 1): print(f'{i:2d} was rolled {rolls[i]:7d} times') import random def main(): # Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec daysPerMonth = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] rainfall = [] month = 0 for days in daysPerMonth: rainfall.append( [] ) for i in range( days ): rainfall[month].append( round(random.random() * 3.0, 1) ) month += 1 print(f'rainfall: {rainfall}\n') # a list for all of the rainfall (for the year) print(f'rainfall[0]: {rainfall[0]}\n') # a list for all of January's rainfall print(f'rainfall[0][0]: {rainfall[0][0]}\n') # display the (random) amount of rain for January 1st print('rainfall = [') for month in rainfall: print( ' ' + str(month) + ',' ) print(']') if __name__ == '__main__': main() 20230414 ******************************************************* Files Exercises ++++++++++++++++++++++++++++++++++++++++++++ 1. File Basics A. Filenames: I. Discuss with your neighbor the difference between the following (and provide examples of each): Relative paths and absolute paths Relative path: starting from the current working directory Absolute path: From the root of the file system (for Windows: drive (for example, C:\, for Unix-based systems: /) Unix/Linux/macOS and Windows filenames Unix/Linux/macOS: Separates directories with "/", also see above Windows: Separates directories with "\", also see above II. Which type of path is better for each of the following scenarios? * Accessing a system file: Absolute path * Making your code more portable, for example, to be shared with other people: Absolute: Not going to work on the other person's machine: For example, C:\Users\adamsGreat\CPSC1301K\Projects\Project99\input.txt ***Needs to be relative*** B. List the 3 most common file modes and explain any potentially negative side effects: 1) r - reading 2) w - writing (if the file already exists, it is truncated, deleted, abolished, destroyed, nuked, obliterated, exterminated, punched, eradicated, thrown into a black hole, etc.) 3) a - appending - adds to the end Discover one of the other file modes. Explain to someone else what it is and when you would use it. 2. Opening Files A. Identify the two parts for opening a file: (what are the 2 arguments to open) 1) name of the file 2) mode (for example, 'r', 'w', 'a') B. Write code to open a file named testCases.txt. fileObj = open( 'testCases.txt', 'r' ) fileObj = open( 'testCases.txt' ) >>> fileObj = open('hello.txt') >>> print( type( fileObj ) ) >>> help( fileObj ) C. Write code to open a file named output.csv. filename = 'output.csv' outputFileObj = open( filename, 'w' ) 20230417 ******************************************************* D. Write code that prompts the user for a filename and then opens that file. If the file does not exist, tell the user that it does not exist and prompt them again for a filename and try to open that file. Repeat this process until the file is successfully opened. fileOpened = False while fileOpened == False: filename = input('Please enter a filename: ') try: inputFileObj = open( filename ) fileOpened = True except: # could not open file print('Sorry, could not open \"' + filename + '\". Please try again.') print('Opened', filename) 3. Closing Files A. Give the following code: inputFileObj = open( filename, mode ) write code to close the file. inputFileObj.close() 4. Reading From Files A. Discuss with your neighbor the difference between the following (discuss what each returns, any arguments, when you'd use each one of them): fileObject.read() reads the entire file and returns all of it as a str. Optionally, can take an argument for the number of characters to read. fileObject.readline() reads a single line from the file and returns it as a str. fileObject.readlines() reads the entire file and returns all of it as strs in a list. import sys total = 0 mode = 'r' # read mode filename = "values.txt" try: inputFileObj = open( filename, mode ) print('Opened the file') for line in inputFileObj: #print(f'line: "{line}"') line = line.rstrip() # remove the newline at the end print(f'line: "{line}"') if line.isdigit() == True: total += int( line ) print(f'total: {total}') except: print( 'ERROR! Unable to open or read from', filename) sys.exit() inputFileObj.close() print( 'Total of the values in', filename, 'is', total) 20230421 ******************************************************* # A real example, but an INCORRECT solution import sys filename = "letters.txt" mode = 'r' # read mode try: inputFileObj = open( filename, mode) for line in inputFileObj: # line = inputFileObj.readline() print(line, end='') except: print("ERROR! Unable to open or read from", filename) sys.exit() finally: inputFileObj.close() # A real example, but an INCORRECT solution import sys filename = "letters.txt" mode = 'r' # read mode try: inputFileObj = open( filename, mode) line = inputFileObj.readline() # priming read # print(f'line ({len(line)}): {line}') while line != '': # while not at the end of the file (EOF) print(line, end='') line = inputFileObj.readline() # print(f'line ({len(line)}): {line}') # Bad idea: exploring what will happen with a call to readline after reaching the end of the file line = inputFileObj.readline() print(f'line ({len(line)}): "{line}" (after the while loop)') except: print("ERROR! Unable to open or read from", filename) sys.exit() finally: inputFileObj.close() 6. Writing To Files B. Discuss with someone else the differences between print() and fileObject.write(). print(): ----------- Displays any and all arguments passed to it to standard output (for example, the screen) Takes any number of arguments (and makes a str out of each one of those) Defaults to adding a newline at the end of the line fileObject.write(): ----------- Add the argument passed to it to the file associated with fileObject Takes 1 argument, of type str Instead of fileObject.write("Hello", "world") do str concatenation first, then pass the resulting str to write: fileObject.write("Hello" + "world") # passing just 1 str to write() Also: fileObject.write( 42 ), instead use: fileObject.write( str(42) ) There's no default to add at the end of each call # Write a Python script that writes "Hello, world" to a file named "pythonOutput.txt". If an exception is thrown, display an error message to the user. import sys filename = "pythonOutput.txt" try: outputFileObj = open( filename, "w") outputFileObj.write( "Hello, world\n" ) except: print(f'Sorry, unable to open "{filename}"') sys.exit() outputFileObj.close() 20230424 ******************************************************* 6. Writing To Files D. Write a Python script that writes each letter of the alphabet on its own line to a file named "alphabet.txt". If an exception is thrown, display an error message to the user. import string import sys filename = 'alphabet.txt' try: outputFileObj = open( filename, 'w' ) for letter in string.ascii_uppercase: # print(letter) outputFileObj.write( letter + '\n') except: print('Sorry, there was an error opening or writing to', filename) sys.exit() outputFileObj.close() 7. Reading From and Writing To Files A. A bank has a text file called transactions.txt which has the transactions information for customers in the following format: Sarah Adams Deposit 350.00 Withdraw 200.00 Withdraw 50.00 Deposit 150.00 Deposit 100.00 Withdraw 200.00 Your task is to read the data from this file, calculate the resulting balance after all the transactions, and write customer's name and their updated balance in a new file called summary.txt: Sarah Adams: $150.00 Reading the input file: Step 1: Read the first line (which has the account holder's name) Step 2: Read the next line (should be Deposit or Withdraw) Step 3: Read the next line (should be the amount) Step 4: If not the end of the file, go to step 2 B. Write a Python script that reads in a file and sorts all of the words in the file and writes it out to another file. Exception Handling Exercises ++++++++++++++++++++++++++++++++++++++++++++ Exception Handling ================================= 1. List the Python keywords used in exception handling and what they do: * try - attempts to execute the code in its body and catches any exceptions * except 1) Without a specified exception: handles all exceptions raised in the try-block 2) With a specified exception: Handles the specified exception raised in the try-block * finally - executes after the try-block code or the exception handler * raise - creates an exception and throws it 2. Research 5 or more exceptions and what they do. 1. 2. 3. 4. 5. See https://runestone.academy/runestone/books/published/thinkcspy/Exceptions/02_standard_exceptions.html See https://docs.python.org/3/library/exceptions.html 3. except-statements A. What is the maximum number of except-statements a Python script can have? Lots B. What is the maximum number of except-statements that will execute? 1 C. What is the minimum number of except-statements a Python script can have? (Given that you have a try) 1 D. What is the minimum number of except-statements that will execute? 0 4. finally-statements A. What is the maximum number of finally-statements a Python script can have? 1 B. What is the maximum number of finally-statements that will execute? 1 C. What is the minimum number of finally-statements a Python script can have? 0 D. What is the minimum number of finally-statements that will execute? 0 5. By default, when a user pressing the control (CTRL) and "c" keys on the keyboard, a Python script will stop executing. Write a Python script that displays all of the numbers between 1 and 1,000,000. If the user presses CTRL-c, ask the user if they would like to continue. If they enter "y", have the script keep counting where it left off. Example: 1 2 3 ... ^C397046 397047 397048 Would you like to keep counting (Y/N)? y 397048 397049 ^C397050 397051 397052 Would you like to keep counting (Y/N)? n Have a nice day! keepCounting = 'Y' i = 1 while keepCounting == 'Y': try: for i in range(i, 1_000_000 + 1): print(i) keepCounting = 'N' except KeyboardInterrupt: keepCounting = input('Would you like to keep counting (Y/N)? ').upper() print('Have a nice day!') Error Checking and Exception Handling ================================= 1. Discuss with someone else the major differences between error handling and exception handling. 2. Should you always use error checking (if-statements) instead of exception handling? 3. Give an example of when to use error checking instead of exception handling. Dictionaries Exercises ++++++++++++++++++++++++++++++++++++++++++++ 1. Discuss with someone else how dictionaries work Dictionaries store key-value pairs. We use the key to find the value. 2. Discuss with someone else what is a key-value pair The key is an immutable object (for example, str, int, float, tuple) The value can by anything that you can store in Python (str, int, float, tuple, list, dictionary) 3. Compare and contrast using a dictionary and a list Both: Can store anything (for dictionaries, it's the value that's stored) Lists use indices (ints) to locate values, whereas dictionaries can also use strs, floats, tuples, etc. 4. Discuss with someone else at least three scenarios to use a dictionary and why I. Inventory system with parts (key) and prices (value) II. translations III. sparse matrices IV. unordered list (for example, team roster, lists of unprocessed URLs) 5. Dictionaries can be used to store similar items as keys and their respective values. Write Python code to create a dictionary with your cousins' names (as the keys) and ages (as the values). name = 'Craig' # the key age = 1 # the value cousins = {} # define a dictionary cousins[ name ] = age cousins[ 'Gronk' ] = 60000 cousins[ 'Caroline' ] = 72 print( cousins ) 6. Dictionaries can also be used to store several items related to a single object. Write Python code to create a dictionary with at least 5 items about your favorite movie (for example, lead actor/actress, year, budget, rating, best quote, genre) # Monsters Inc. favMovie = {} favMovie['main character'] = 'Sully' favMovie['year'] = 2001 favMovie['villain'] = 'Randall' favMovie['lead animator'] = 'Jo' print( 'Monsters Inc.:', favMovie) # Monty Python classicMovie = {'main character': 'King Arthur', 'year': 1975} classicMovie['special effects lead'] = 'Chris' print( 'Classic:', classicMovie) 7. Write a Python script that uses a dictionary to store student's grades. Give the user the following choices: 1. Add a new student 2. Update a student's grade 3. Display a student's grade 4. Remove a student 5. Quit < see grades-blank.py > 8. Dictionary Methods Given the following code: bread = { 'title': "Grandma's Honey Whole Wheat Bread", 'ingredients': { 'honey': '8 oz', 'oil': '3.5 oz', 'water': '3.1 pounds', 'whole wheat flour': '4.5 - 4.75 lbs', 'yeast': '3 Tablespoons', 'salt': '1.5 Tablespoons' }, 'servings': 84, 'Nutrition Facts': { 'calories': 105.5, 'total fat': '1.6 g', 'sodium': '118.2 mg', 'potassium': '3.3 mg', 'carbohydrates': { 'total': '21.1 g', 'dietary fiber': '3.2 g', 'sugars': '2.2 g' }, 'protein': '3.5 g' } } What do each of the following display: print( '\nbread.keys()') for variable in bread.keys(): print( variable ) print( '\nbread.values()') for variable in bread.values(): print( variable ) print( '\nbread.items()') for variable in bread.items(): print( variable ) print( '\nbread') for variable in bread: print( variable ) 9. in Operator Replace _________________ with appropriate code trailMix = { } trailMix['title'] = 'Trail Mix' ingredientsDictionary = dict( peanuts = '2 cups', raisins = '2 cups', MandMs = '1 1/2 cups' ) trailMix['ingredients'] = ingredientsDictionary trailMix['instructions'] = 'Combine all ingredients' recipes = [] recipes.append( bread ) recipes.append( trailMix ) nutritionFactsLabel = 'Nutrition Facts' for recipe in recipes: title = recipe.get('title', 'No title') _________________: print( f"{title}'s {nutritionFactsLabel}:" ) for nfKey in recipe[nutritionFactsLabel]: print( nfKey + ': ' + str(recipe[nutritionFactsLabel][nfKey]) ) else: print(f'Note, {title} does not have {nutritionFactsLabel} information') Replace _______________ with if nutritionFactsLabel in recipe: 10. Aliasing and Copying A. What will interpreting the following code display? gourmetTrailMix = dict( trailMix ) gourmetTrailMix['title'] = 'Gourmet Trail Mix' print( 'gourmetTrailMix:', gourmetTrailMix ) print( 'trailMix:', trailMix ) B. What will interpreting the following code display? # assumes that ingredients is a valid key gourmetTrailMix['ingredients']['almonds'] = gourmetTrailMix['ingredients']['peanuts'] del gourmetTrailMix['ingredients']['peanuts'] print( 'gourmetTrailMix:', gourmetTrailMix ) print( 'trailMix:', trailMix ) 11. Discuss with someone else which is faster (and why): A. Inserting 1,000,000 words into a sorted list (and continually maintaining it in sorted order) or Inserting 1,000,000 of words into a dictionary B. For each one of 1,000,000 words, determining if it is in a sorted list or a dictionary