Sample Midterm 1 Answers
-
Which of the following Python identifiers are legal variable names?
For those that are not, say why not.
- x
- Celsius
- spam3
- <hello>
- question?
Answer: Choices a, b, and c are legal variable names. Choice d
is not because the characters “<” and “>”
are not allowed in variable names; neither is “?”, so choice
e is not.
-
What is the data type (int, long int, float, string, list) of the following:
- 3
- 3.0
- 3L
- "hello"
- 'x'
- [ 1, 2, 3 ]
Answer:
- int
- float
- long int
- string
- string
- list
-
Write the following formulas in Python:
- 7 × 9
- 42
Answer:
- (5.0 / 9.0) * f + 32
- 7 * 9
- 4 ** 2
-
What does the following program print?
for i in "hello":
print i, "-->", chr(ord(o)+1);
Answer:
h --> i
e --> f
l --> m
l --> m
o --> p
-
What does the following program print?
for i in [1, 7, 4]:
x = (-1) ** i * i;
print i, x;
Answer:
1 -1
7 -7
4 4
-
When I ran the following program:
x = input("Enter a number: ");
y = 1.0 / x;
print "The reciprocal of", x, "is", y;
I got the following error message:
Traceback (most recent call last):
File "test.py", line 3, in <module>
y = 1 / x;
ZeroDivisionError: integer division or modulo by zero
What caused the error? Please be specific.
Answer: The problem is that there was an attempt to divide by 0.
This occurred on line 2. As there is a division by x there,
and I entered the value of x in response to the prompt (see
line 1), I obviously entered 0.