Here is a quick outline of what will be covered on Midterm #1. We will be going over this in detail during class this week as well.
In addition, here are a few sample problems that you can try. (We may be going over some of these in detail during class if you wish).
Evaluate the following expressions and note the data type of the result (solutions will be posted below later)
Expression | Evaluates To | Data Type |
5 – 2 | ||
5 ** 2 | ||
‘5’ + ‘2’ | ||
‘5’ * 2 | ||
5 / 2 | ||
5 // 2 | ||
5 % 2 | ||
5 + 2.0 | ||
5.0 * 2.0 | ||
10 > 2 | ||
2 < 1 | ||
2 != 4 | ||
4 == 2**2 | ||
‘cat’ < ‘dog’ | ||
‘Cat’ < ‘dog’ | ||
5 > 2 and 10 > 11 | ||
5 > 2 or 10 > 11 | ||
5 > 2 and not (10 > 11) | ||
str.lower(‘HeLLo’) | ||
str.upper(‘HeLLo’) | ||
format(5.1, ‘.2f’) | ||
format(5.1, ‘>10.2f’) | ||
random.randint(1,5) | ||
len(‘cat’) | ||
len(‘cat’ + ‘dog’) | ||
not (5>2 and 5 < 4) |
Short Answers
keepgoing = "yes" while keepgoing == "yes": # statements go hereDescribe two different ways to stop this loop from iterating?
Program #1:
a = 10 b = 20 c = 30 if c > b + a: print ("N\nY\nU\n") else: if b + a >= c: print ("C\nO\nU\nR\nA\nN\nT\n") else: print ("S\nT\nE\nR\nN\n") print (a,b,c)
Program #2:
x = 'cupid' z = 'arrow' if x < z: t = x x = z z = t v = x + " <--> " + z if ( ( (5 + 2 >= 6.0) and (1.0 < 0.5) ) or True): print (x,z,v, sep='\t') else: print (v,z,x, sep='\n')
Program #3:
a = 5 b = 10 c = 25 if a + b == c: print ("X1") else: if c == a + b*2: print ("Y1") elif a == c - 2 * b: print ("Y2") else: print ("Y3")
Program #3: Trace the output of each loop (the "-----" divider denotes a new program):
count = 0 while count < 10: print ('Hello') count += 1 ———— x = 10 y = 0 while x > y: print (x, y) x = x - 1 y = y + 1 ———— keepgoing = True x = 100 while keepgoing: print (x) x = x - 10 if x < 50: keepgoing = False ———— x = 0 while True: x += 1 print (x) if x ** 2 > 36: break elif x % 2 == 0: continue print ("looping!")
Program #4:
a = 5 b = 6 c = 20 d = 24 if a < b and b * 2 < c: print ("Python Case 1") print ("A", '\t', "B", '\t', "C") if a * 2 == c: print (a*2, '\t', a*2, '\t', a*2) elif a * 3 == c: print (a*3, '\t', a*3, '\t', a*3) elif a * 4 == c: print (a*4, '\t', a*4, '\t', a*4) else: print ('?', '\t', '?', '\t', '?') else: print ("Python Case 2") print ("a", '\t', "b", '\t', "c") if b * 2 == d: print (b*2, '\t', b*2, '\t', b*2) elif b * 3 == d: print (b*3, '\t', b*3, '\t', b*3) elif b * 4 == d: print (b*4, '\t', b*4, '\t', b*4) else: print ('?', '\t', '?', '\t', '?')
Write a Program (solutions will be posted below later)
Use your programming skills to solve the following programming challenges:
Virtual dice roll: 3 and 5
Here is a sample running of the program:
Credit card qualifier How much do you make per year? 30000 Do you own your home? (y/n) y You qualify! Credit card qualifier How much do you make per year? 35000 Do you own your home? (y/n) n How much do you pay in rent per month? 1000 You qualify! Credit card qualifier How much do you make per year? 50000 Do you own your home? (y/n) n How much do you pay in rent per month? 5000 Sorry, you don't qualify. Your rent is too high
Please enter a two digit integer: 23 23 reversed is: 32 23 + 32 is 55
Enter "even" or "odd": apple Sorry, that's not a valid choice! Enter "even" or "odd": odd Here we go! 1 3 5 ... 95 97 99
Enter a number: 3 Too low! Try again! Enter a number: 6 Too high! Try again! Enter a number: 5 Congratulations! You guessed it!
Lucky number generator! How many digits do you want? -5 Invalid entry, try again How many digits do you want? 3 Here we go! 9 75 34
Number Number * 2 0 0 1 2 2 4 3 6 4 8 5 10 6 12 7 14 8 16 9 18
rate = str(input("How much do you make per hour? ‘)) hours = input("How many hours did you work this week? ") if hours < 40: pay = rate * hours if hours > 40 pay = rate * 40 ot_pay = (hours-40) ** (rate*1.5) print ("Your total pay is, pay + ot_pay")
How much money do you have?: 10.00 What would you like to buy? Donut (d) – 1.50 Coffee (c) – 1.00 Bagel (b) – 2.50 Scone (s) – 2.75 Enter your choice (d/c/b/s): d You can purchase 6 donuts with $ 10.0Note that you cannot assume that the user will enter a valid product (i.e. they could type in the string "donut" instead of the string "d"). In this case you will need to present the user with some kind of error (i.e. "Sorry, that’s not a valid product") – you do not need to re-prompt them (you can just end the program). Also, you can assume that the user will input valid floating-point numbers when prompted.
Number 1: 2.0 Number 2: 3.0 Operation (a/s/d/m): add Invalid operation! Try again. Operation (a/s/d/m): a 2.0 + 3.0 = 5.0Note that you cannot assume that the user will enter a valid operation code (i.e. they could type in the string "multiply" instead of the string "m"). In this case you will need to present the user with some kind of error (i.e. "Sorry, that’s not a valid operation code") and re-prompt them. However, you can assume that the user will input valid floating-point numbers when prompted. Also note that dividing a number by 0 will result in a runtime error. Prevent this from happening in your program by providing special output in this case (i.e. 5.0 / 0.0 = undefined)
Student name: Craig Combined SAT Score: 1800 High school GPA: 3.2 # of extracurricular activities: 3 Craig should be admitted! Another student? yes Student name: John Combined SAT Score: 1500 High school GPA: 3.1 # of extracurricular activities: 7 John should be admitted! Another student? yes Student name: Chris Combined SAT Score: 1300 High school GPA: 2.9 # of extracurricular activities: 8 Chris should not be admitted. Another student? no
————————
————————
————————
Solutions
————————
————————
————————
Evaluation Problems
Expression | Evaluates To | Data Type |
5 – 2 | 3 | integer |
5 ** 2 | 25 | integer |
‘5’ + ‘2’ | 52 | string |
‘5’ * 2 | 55 | string |
5 / 2 | 2.5 | float |
5 // 2 | 2 | integer |
5 % 2 | 1 | integer |
5 + 2.0 | 7.0 | float |
5.0 * 2.0 | 10.0 | float |
10 > 2 | True | Boolean |
2 < 1 | False | Boolean |
2 != 4 | True | Boolean |
4 == 2**2 | True | Boolean |
‘cat’ < ‘dog’ | True | Boolean |
‘Cat’ < ‘dog’ | True | Boolean |
5 > 2 and 10 > 11 | False | Boolean |
5 > 2 or 10 > 11 | True | Boolean |
5 > 2 and not (10 > 11) | True | Boolean |
str.lower(‘HeLLo’) | hello | string |
str.upper(‘HeLLo’) | HELLO | string |
format(5.1, ‘.2f’) | 5.10 | string |
format(5.1, ‘>10.2f’) |
" 5.10" |
string |
random.randint(1,5) | 3 | integer |
len(‘cat’) | 3 | integer |
len(‘cat’ + ‘dog’) | 6 | integer |
not (5>2 and 5 < 4) | True | Boolean |
Short Answers
Explain what a Boolean expression is and why you would use one while programming. Give three examples.
A Boolean expression is an expression that compares two or more values. It almost always involves the use a relational operator (>, <, ==, !=, etc) and always evaluates to True or False. We use Boolean expressions in Python to ask a question (i.e. if number < 0 then print "no negative numbers allowed!"), to control a repetition structure (i.e. while keepgoing == True, perform some operation) and to store a logical value in a variable (i.e. answer = 5 > 2)
Identify three functions that convert data from one data type to another. Provide a practical example of each function and describe when you would use it in an actual program.
The float(), int() and str() functions convert data from one data type to another. Here are a few examples:
# turn the user's input into a floating point number answer = float(input("Enter a number: ")) # turn a String into an integer a = "525" b = int(a) # convert a number into a String a = 525 b = str(a)
Explain the differences and simliarities between the "if" statement and a "while" statement in Python
Both an "if" statement and a "while" statement utilize Boolean expressions. In the case of an "if" statement, if the attached Boolean expression evaluates to True then the body of the "if" statement will execute one time. In the case of a "while" statement, if the attached Boolean experession evalutes to True then the body of the "while" statement will execute, and then the condition will be re-evaluated at the end of the statement to see if it is still True - if so the body of the "while" statement will be executed again.
Name and describe three different data types in Python and when they could be used in a program
Integer: used to store whole number values. Useful for creating "counter" accumulator variables. Float: used to store floating point numbers. Useful for storing currency values. String: used to store sequences of characters, such as "Hello, World!"
Imagine you have the following while loop. Describe two different ways to stop this loop from iterating.
keepgoing = "yes" while keepgoing == "yes": # statements go here
You could call the "break" statement from within the loop or you could flip the value of "keepgoing" to something other than "yes"
Trace The Output
(just copy and paste the code into IDLE to see the output!)
Programming Problems
Problem #1
word1 = input("Word 1: ") word2 = input("Word 2: ") if word1 > word2: print (word2, word1) else: print (word1, word2)
Problem #2
word1 = input("Word 1: ") word2 = input("Word 2: ") if len(word1) > len(word2): print (word2, word1) else: print (word1, word2)
Problem #3:
import random die1 = random.randint(1,6) die2 = random.randint(1,6) print ("Virtual dice roll:", die1, "and", die2)
Problem #4
import random usernum = int(input("Enter an integer (1-6): ")) compnum = random.randint(1,6) if usernum == compnum: print ("you win!") else: print ("try again!")
Problem #5
print ("Credit card qualifier") salary = int(input("How much do you make per year? ")) own = input("Do you own your home? (y/n) ") if own == 'y': if salary >= 30000: print ("You qualify!") else: print ("You don't qualify. You need to make at least 30,000 per year and own your home.") else: if salary < 30000: print ("You don't qualify. You need to make at least 30,000 per year and own your home.") else: rent = int(input("How much do you pay in rent per month? ")) if rent > 0.05 * salary: print ("Sorry, you don't qualify. Your rent is too high") else: print ("You qualify!")
Problem #6
test1 = float(input("Test 1: ")) test2 = float(input("Test 2: ")) test3 = float(input("Test 3: ")) homework = float(input("Homework: ")) test_avg = (test1 + test2 + test3) / 3 class_avg = (test_avg + homework) / 2 print ("Class average:", format(class_avg, '.2f')) print ("Letter Grade: ", end='') if class_avg > 90: print ("A") elif class_avg > 80: print ("B") elif class_avg > 70: print ("C") elif class_avg > 65: print ("D") else: print ("F")
Problem #7
# get sales sales = float(input("Sales: ")) # calc profit profit = 0.23 * sales # output print ("Projected profit:", profit)
Problem #8
# get square feet square_feet = int(input("Square feet: ")) # convert to acres acres = square_feet / 43560 # output print ("In acres:", acres)
Problem #9
# get 5 prices p1 = float(input("Price 1: ")) p2 = float(input("Price 2: ")) p3 = float(input("Price 3: ")) p4 = float(input("Price 4: ")) p5 = float(input("Price 5: ")) # calc subtotal subtotal = p1+p2+p3+p4+p5 # calc tax tax = 0.06 * subtotal # output print ("Subtotal:", subtotal) print ("Tax:", tax) print ("Total:", subtotal+tax)
Problem #10
# get 2 digit integer num = int(input("Number: ")) # extract tens and ones tens = num // 10 ones = num % 10 # construct the reversed number rev = ones*10 + tens*1 # output print (num, "reversed is:", rev) print (num, "+", rev, "is", num+rev)
Problem #11
counter = 1 while counter <= 100: print (counter, " ", end="") counter += 1
Problem #11 Extension #1
counter = 1 while counter <= 100: if counter % 2 == 0: print (counter, " ", end="") counter += 1
Problem #11 Extension #3
while True: choice = input("Enter \"even\" or \"odd\": ") if choice == "even" or choice == "odd": break else: print ("Sorry, that's not a valid choice!") if choice == "even": counter = 2 while counter <= 100: print (counter, " ", end="") counter += 2 if choice == "odd": counter = 1 while counter <= 100: print (counter, " ", end="") counter += 2
Problem #12
total = 0 keepgoing = "yes" while keepgoing == "yes": price = float(input("Enter a price value: ")) total += price keepgoing = input("Go again? ") print ("Total is", total)
Problem #13
secret = 5 while True: guess = int(input("Guess a number between 1 and 10: ")) if guess == secret: print ("Congrats!") break elif guess < secret: print ("Too low") else: print ("Too high")
Problem #14
import random while True: numdigits = int(input("Enter a number of digits, positive numbers only: ")) if numdigits < 1: print ("Try again!") else: break counter = 1 while counter <= numdigits: print (random.randint(1, 100), " ", end="") counter += 1
Problem #15
print (format("Number", "<10s"), format("Number*2", "<10s")) counter = 0 while counter < 10: print (format(counter, "<10d"), format(counter*2, "<10d")) counter += 1
Problem #16
rate = float(input("How much do you make per hour? ")) hours = float(input("How many hours did you work this week? ")) if hours < 40: pay = rate * hours else: ot_pay = (hours-40) * (rate*1.5) pay = rate * 40 + ot_pay print ("Your total pay is", pay)
Problem #17
# get money from the user money = float(input("How much money do you have?: ")) print ("What would you like to buy?") print ("Donut (d) – 1.50") print ("Coffee (c) – 1.00") print ("Bagel (b) – 2.50") print ("Scone (s) – 2.75") # get user choice choice = input("Enter your choice (d/c/b/s): ") # evaluate choice if choice == 'd': # note -- the // operator performs integer division and generates the # integer result of a division operation. HOWEVER, both money and the value # 1.5 are floats! Remember what happens when you have a math expression with # floating point numbers. the integer division operator will generate an integer, # but Python will cast the result as a float (essentially adding .0 to the integer) # casting the result as an int using the int() function fixes this print ("You can purchase", int(money//1.5), "donuts with", money) elif choice == 'c': print ("You can purchase", int(money//1.0), "cups of coffee with", money) elif choice == 'b': print ("You can purchase", int(money//1.0), "bagels with", money) elif choice == 's': print ("You can purchase", int(money//1.0), "scones with", money) else: print ("Sorry, we don't sell that!")
Problem #18
# get two numbers n1 = float(input("Number: ")) n2 = float(input("number: ")) # get an operation code, making sure to validate the data # (keep the user "caught" until they supply a good value) while True: op = input("Operation code (a/s/m/d): ") if op == 'a' or op == 's' or op == 'm' or op == 'd': break else: print ("Bad, try again") # evaluate operation if op == 'a': print (n1, "+", n2, "=", n1+n2) elif op == 's': print (n1, "-", n2, "=", n1-n2) elif op == 'm': print (n1, "*", n2, "=", n1*n2) elif op == 'd': # make sure we don't crash if denom is 0 if n2 == 0: print (n1, "/", n2, "=", "undefined") else: print (n1, "/", n2, "=", n1/n2)
Problem #19
# continually ask the user for input while True: # get info name = input("Student name: ") sat = float(input("SAT score: ")) gpa = float(input("GPA: ")) act = float(input("# of activities: ")) # evaluate - normal admission if sat >= 1600 and gpa >= 3.0 and act >= 3: print (name, "should be admitted") elif act >= 5 and sat >= 1400 and gpa >= 2.8: print (name, "should be admitted") else: print (name, "should not be admitted") # keep going? again = input("Enter another student? ") if again == "no": break