Multiple choice › Python (code reading)
Python (code reading)
1. Python (code reading)
What does this Python code display?
nums = [4, 7, 1, 9] total = 0 for n in nums: if n > 3: total += n print(total)
- 21
- 9
- 20
- 4
Answer
C
Only numbers greater than 3 are added: 4 + 7 + 9 = 20 (1 is skipped).
2. Python (code reading)
What does this Python code display?
word = 'software' print(word[0:4])
- are
- soft
- soft'
- ftwa
Answer
B
Slicing [0:4] takes indexes 0 to 3: s, o, f, t.
3. Python (code reading)
What does this Python code display?
for i in range(3): print(i, end=' ')
- 0 1 2
- 1 2
- 1 2 3
- 0 1 2 3
Answer
A
range(3) produces 0, 1, 2. The end=' ' argument keeps output on one line separated by spaces.
4. Python (code reading)
What does this Python code display?
grid = [[1, 2, 3], [4, 5, 6]] print(grid[1][2])
- 3
- 2
- 5
- 6
Answer
D
grid[1] is the second row [4, 5, 6]; index 2 of that row is 6. Row first, then column (compare sample exam Q21a).
5. Python (code reading)
What does this Python code display?
def double(x): return x * 2
print(double(double(3)))
- 9
- 12
- 3
- 6
Answer
B
double(3) = 6, then double(6) = 12.
6. Python (code reading)
What does this Python code display?
try: x = int('abc') print('A') except ValueError: print('B') finally: print('C')
- A, B and C (on separate lines)
- B then C (on separate lines)
- B only
- A then C (on separate lines)
Answer
B
int('abc') raises ValueError, so 'A' is skipped, the except block prints B, and finally always runs, printing C.
7. Python (code reading)
What does this Python code display?
marks = {'Ann': 70, 'Bo': 85} marks['Bo'] = marks['Bo'] + 5 print(marks['Bo'], len(marks))
- 90 2
- 85 2
- 90 1
- 75 2
Answer
A
The value for 'Bo' becomes 90; the dictionary still has 2 keys.
8. Python (code reading)
What does this Python code display?
count = 0 while count < 10: count += 3 print(count)
- 12
- 3
- 10
- 9
Answer
A
count goes 0, 3, 6, 9 and 12; the loop stops when count is no longer < 10, so 12 is printed.
9. Python (code reading)
What does this Python code display?
class Pet: def init(self, name): self.name = name def speak(self): return self.name + ' makes a sound'
class Dog(Pet): def speak(self): return self.name + ' barks'
print(Dog('Rex').speak())
- An error occurs
- Rex makes a sound
- Rex barks
- Dog barks
Answer
C
Dog inherits init from Pet and overrides speak (polymorphism), so Dog('Rex').speak() returns 'Rex barks'.
10. Python (code reading)
What does this Python code display?
values = [3, 8, 5] values.append(1) values.sort() print(values[-1], len(values))
- 8 4
- 5 4
- 1 4
- 8 3
Answer
A
After append the list is [3, 8, 5, 1]; sort gives [1, 3, 5, 8]. values[-1] is the last item, 8, and the length is 4.