Sample Final
 Evaluate each expression. Indicate floats by including a decimal point
(so to show 1 as a float, write “1.0”) If any cannot be evaluated,
say why.
 3 + 5.0
 10 % 4 + 7 / 2
 abs(5  20 / 3) ** 4
 range(4, 13, 3)
 "If %d + %d = %2.2f, then %s" % (2, 2, 4, "bye!")
 4 / "3"
Answer:
 8.0
 5
 1
 [4, 7, 10]
 "If 2 + 2 = 4.00, then bye!"
 A string cannot divide an integer, so this produces a TypeError
 Convert the following into Python:
 The volume vol of a sphere is 4πr divided by 3
(remember the result is a floating point number!).
 The value of the string variable str with all occurrences
of the letter “e” replaced by the character “3”
 Subtract 159 from the product of 3 and 27, using integers
Answer:
 include math
vol = 4.0 * math.pi * r / 3.0
 include string
string.replace('e', '3')
 3 * 27  159
 The A–F grading system assigns the following grades to scores. If your
score is less than 1 point, you get an F; if it is less than 2 points, you get a D;
if it is less than 3 points, you get a C; if you get less than 4 points, you get a
B; and if you get 4 points or more, you get an A. Write an “if”
statement that, given a score in the variable score, prints the corresponding
grade.
Answer:
if score < 1:
print "F"
elif score < 2:
print "D"
elif score < 3:
print "C"
elif score < 4:
print "B"
else:
print "A"
 What does the following function do when given a list of numbers as the argument?
def f(lst):
a = i = 0
n = len(lst)
while i < n:
if lst[i] <= 0:
i += 1
continue
a += lst[i]
i += 1
return float(a) / n
Answer: This computes the (floating point) average of the positive
numbers in the list lst.
 Rewrite the function in problem 4 so that it uses a “for” loop,
not a “while” loop.
Answer:
def f(lst):
a = 0
for i in lst:
if i <= 0:
continue
a += i
return float(a) / len(lst)

What does the following program do:
d = dict()
while True:
try:
line = raw_input("EOF to stop> ")
except EOFError:
break
for i in line:
d[i] = d.get(i, 0) + 1
u = d.keys()
for i in u:
print i, d[i]
Answer: This prints a list of characters in the input (excluding the
newlines and/or carriage return), and the number of times each character
appears in the input.

What does the following program do:
def y(n):
if n < 10:
return str(n)
else:
d = str(n % 10)
return y(n / 10) + d
print y(174)
Answer: The function prints the digits in the number n.
So, this prints
174