Sample Midterm 2 Answers
- Evaluate each expression. If any cannot be evaluated, say why.
- 3 + 5.0
- "hello" + "goodbye"
- 7 * True
- 6 / "spam"
- True and not False or True
- "monty" <= "python"
Answer:
- 8.0
- "hellogoodbye"
- 7
- A string cannot divide an integer, so this produces a TypeError
- True
- True
- Convert the following into Python:
- “hello” follows “goodbye” in the
character ordering of the computer
- The value of the variable answer is true or the value
of the variable y is less than 126
- The function gleep is called with an argument of
−21
Answer:
- "hello" > "goodbye"
- answer or (y < 126)
- gleep(-21)
- Convert the following into a “for” loop:
i = 1
while i < 10:
print i * "x"
i += 3
Answer:
for i in range(1, 10, 3):
print i * "x"
- What does the following function do when given a string as the
first argument and a string containing only one character as the
second argument?
def f(s, c):
i = 0
while i < len(s):
if s[i] == c:
return i
i += 1
return -1
Answer: This returns the index of the first occurrence of the character
c in the string s, or −1 if it does not occur in the
string. This is the same as the function string.find(w, c).
- In the following program:
try:
x = input("Enter a number: ");
y = 1 / x;
except ZeroDivisionError:
print "Nice try: you divided by 0"
except SyntaxError:
print "What on earth did you type?"
except NameError:
print "I have no clue what that name refers to"
except TypeError:
print "I don't handle conversions well today"
else:
print "The reciprocal of", x, "is", y;
please show five different inputs, each of which will execute a different
print statement in the program.
Answer: In the following, do not type the surrounding double quotes.
- The input “0” produces
“Nice try: you divided by 0”
- The input “I don't know” produces
“What on earth did you type?”
- The input “hello” produces
“I have no clue what that name refers to”
- The input “'hello'” (note the single quotes) produces
“I don't handle conversions well today”
- The input “5.0” produces
“The reciprocal of 5.0 is 0.2”
- What does the following program print?
def a(hi):
hi = 7
return hi + 3
def main():
hi = 8
lo = 3
print hi, lo
lo = a(hi)
print hi, lo
main()
Answer:
8 3
8 10