TK Study

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)

  1. 21
  2. 9
  3. 20
  4. 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])

  1. are
  2. soft
  3. soft'
  4. 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=' ')

  1. 0 1 2
  2. 1 2
  3. 1 2 3
  4. 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])

  1. 3
  2. 2
  3. 5
  4. 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)))

  1. 9
  2. 12
  3. 3
  4. 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')

  1. A, B and C (on separate lines)
  2. B then C (on separate lines)
  3. B only
  4. 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))

  1. 90 2
  2. 85 2
  3. 90 1
  4. 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)

  1. 12
  2. 3
  3. 10
  4. 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())

  1. An error occurs
  2. Rex makes a sound
  3. Rex barks
  4. 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))

  1. 8 4
  2. 5 4
  3. 1 4
  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.