1. Evaluate each expression. If any cannot be evaluated, say why.
1. 3 + 5.0
2. "hello" + "goodbye"
3. 7 * True
4. 6 / "spam"
5. True and not False or True
6. "monty" <= "python"
1. 8.0
2. "hellogoodbye"
3. 7
4. A string cannot divide an integer, so this produces a TypeError
5. True
6. True
2. Convert the following into Python:
1. “hello” follows “goodbye” in the character ordering of the computer
2. The value of the variable answer is true or the value of the variable y is less than 126
3. The function gleep is called with an argument of −21
1. "hello" > "goodbye"
2. answer or (y < 126)
3. gleep(-21)
3. Convert the following into a “for” loop:
i = 1
while i < 10:
print i * "x"
i += 3
for i in range(1, 10, 3):
print i * "x"
4. 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).
5. 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.
1. The input “0” produces “Nice try: you divided by 0
2. The input “I don't know” produces “What on earth did you type?
3. The input “hello” produces “I have no clue what that name refers to
4. The input “'hello'” (note the single quotes) produces “I don't handle conversions well today
5. The input “5.0” produces “The reciprocal of 5.0 is 0.2
6. 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()