Here is a quick outline of what will be covered on Exam #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. Note that we will be going over these in detail during class as well.
Evaluate the following expressions and note the data type of the result (solutions below)
| 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) | ||
| ‘cat’ + ‘dog’ | ||
| not (5>2 and 5 < 4) |
Short Answers
For the short programs in this section, figure out what the output for those programs is.
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 #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', '?')
Problem #5:
Each ———— denotes the end of a single program.for x in [1,2,3,4,5]:
print (x)
————
for x in [0, 5]:
print (x)
————
for x in range(5):
print (x)
————
for p in range(1,10):
print (p)
————
for q in range(100,50,-10):
print (q)
————
for z in range(-500,500,100):
print (z)
————
for y in range(500,100,100):
print ("*", y)
————
x = 10
y = 5
for i in range(x-y*2):
print ("%", i)
————
for x in [1,2,3]:
for y in [4,5,6]:
print (x,y)
————
for x in range(3):
for y in range(4):
print (x,y,x+y)
————
c = 0
for x in range(10):
for y in range(5):
c += 1
print (c)
Write a Program (solutions below)
Use your programming skills to solve the following programming challenges:
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
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")
Number 1: 2.0 Number 2: 3.0 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! Student name: John Combined SAT Score: 1500 High school GPA: 3.1 # of extracurricular activities: 7 John should be admitted! Student name: Chris Combined SAT Score: 1300 High school GPA: 2.9 # of extracurricular activities: 8 Chris should not be admitted.
Enter a number of days: 3 Day 1: Enter a weight: 180 Day 2: Enter a weight: 175 Day 3: Enter a weight: 170 Average weight for 3 days: 175.0
Code Mangler Problems (solutions below)
Code mangler mixed up the lines of several programs. Try to unscramble the lines to create working programs.
else:
hours = float(input("How many hours did you work this week? "))
if hours < 40:
ot_pay = (hours-40) * (rate*1.5)
pay = rate * 40 + ot_pay
pay = rate * hours
print ("Your total pay is", pay)
rate = float(input("How much do you make per hour? "))
f = 9/5*c+32
for c in range(-10, 41, 2):
print("-------------------")
print("Celsius\tFahrenheit")
print (c, f, sep="\t")
total = ☺ ☺ ☺
start = int(input("Enter starting number"))
end = int(input("Enter ending number"))
for i in ☺ ☺ ☺ :
total += ☺ ☺ ☺
print("Sum from", start, "to", end, "inclusively:", total)
# add to this student's points
# ask the teacher for assignments
# ask the teacher for # students
# assume the student earned no points
for assignment in range(0,numassignments):
for student in range(0,numstudents):
# get points earned for this assignment
# go through each assignment
# go through each student
# loop is over - compute student's score
numassignments = int(input('assignments: '))
numstudents = int(input('students: '))
print ("Student #", student)
print ("This student earned:", studentpoints/numassignments)
score = float(input('Assignment: '))
studentpoints = 0
studentpoints += score
--- Enter your initial salary: 50000 Enter the percent increase at the end of each year [2, for 2%, for example]: 2 year salary 1 $51000.00 2 $52020.00 3 $53060.40 4 $54121.61 5 $55204.04 6 $56308.12 7 $57434.28 8 $58582.97 9 $59754.63 10 $60949.72 ---
#set the number of years to 10
#get the salary from the user
#get the percentage increase for the user
#print the header for the table
#iterate 10 times to print the salaries at the end of each year
#calculate the new salary
#print the year and the salary
————————
————————
————————
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 |
| 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)
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!"
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
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 #3
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 #4
# get sales
sales = float(input("Sales: "))
# calc profit
profit = 0.23 * sales
# output
print ("Projected profit:", profit)
Problem #5
# get square feet
square_feet = int(input("Square feet: "))
# convert to acres
acres = square_feet / 43560
# output
print ("In acres:", acres)
Problem #6
# 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 #7
# 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 #9
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 #10
# get two numbers
n1 = float(input("Number: "))
n2 = float(input("number: "))
# get an operation code, making sure to validate the data
op = input("Operation code (a/s/m/d): ")
if not(op == 'a' or op == 's' or op == 'm' or op == 'd'):
print ("Wrong operation")
# 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 #11
# 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")
Problem #12
for i in range(2, 100001, 2):
print (i)
Problem #13
total = 0
days = int(input("Enter a number of days: "))
for day in range(days):
prompt = "Day " + str(day) + ": Enter a weight: "
weight = input(prompt)
total += weight
print ("Average weight for", days, "days:", total/days)
Code Mangler Problems
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)
print("Celsius\tFahrenheit")
print("-------------------")
for c in range(-10, 41, 2):
f = 9/5*c+32
print (c, f, sep="\t")
total = 0
start = int(input("Enter starting number"))
end = int(input("Enter ending number"))
for i in range(start, end + 1): # +1 to make it inclusive
total += i
print("Sum from", start, "to", end, "inclusively:", total)
# ask the teacher for # students
numstudents = int(input('students: '))
# ask the teacher for assignments
numassignments = int(input('assignments: '))
# go through each student
for student in range(0,numstudents):
print ("Student #", student)
# assume the student earned no points
studentpoints = 0
# go through each assignment
for assignment in range(0,numassignments):
# get points earned for this assignment
score = float(input('Assignment: '))
# add to this student's points
studentpoints += score
# loop is over - compute student's score
print ("This student earned:", studentpoints/numassignments)
#set the number of years to 10
num_of_years = 10
#get the salary from the user
salary0 = float ( input ("Enter your initial salary: "))
#get the percentage increase for the user
percent_increase = float(
input ("Enter the percent increase at the end of each year [2, for 2%, for example]: "))
#print the header for the table
print("year\tsalary")
#iterate 10 times to print the salaries at the end of each year
for year in range(1,num_of_years+1):
#calculate the new salary
salary = salary0 * ( (1+percent_increase/100)**year )
#print the year and the salary
print (year, "\t$", format(salary, ".2f"), sep="")