Question bank › IB Computer Science › Theme B – Computational thinking & problem-solving

B2 Programming in Python (data types, control, functions, files, recursion)

Answer on paper first, then reveal the mark scheme one mark at a time.

1Core5 marks

State the value produced by each Python expression.

(a) 17 // 5
(b) 17 % 5
(c) 2 ** 3
(d) "hello"[1:4]
(e) 7 / 2

[5]

2Standard4 marks

Consider the following Python program.

total = 0
for i in range(1, 6):
    if i % 2 == 0:
        total = total + i * i
    else:
        total = total - i
print(total)

(a) Complete a trace table showing the value of total at the end of each iteration, and state the output. [3]

(b) State the output if range(1, 6) is changed to range(1, 5). [1]

3Standard4 marks

Write a Python function count_vowels(text) that returns the number of vowels (a, e, i, o, u) in the string text. Upper-case and lower-case vowels must both be counted. For example, count_vowels("Education") returns 5.

[4]

4Hard6 marks

A text file scores.txt stores one integer test score on each line, for example:

60
75
90

Write a Python function average_score(filename) that:

  • returns the mean of all the scores in the file;
  • returns 0 if the file contains no scores;
  • returns None if the file does not exist.

[6]

5HardHL only5 marks

Consider the recursive function below.

def digit_sum(n):
    if n < 10:
        return n
    return n % 10 + digit_sum(n // 10)

(a) State the base case. [1]

(b) Show the sequence of calls made by digit_sum(4729). [1]

(c) Show the value returned by each call as the recursion unwinds and state the final result. [2]

(d) State what would happen if the base case were removed. [1]

6StandardHL only4 marks

Consider the Python program below.

words = "the cat and the dog and the bird".split()
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
print(freq)
print(max(freq, key=freq.get))

(a) State the output of the program. [3]

(b) Outline the purpose of freq.get(w, 0). [1]

Still losing marks on this topic?

Book a free introductory session and we'll find exactly which step is costing you.

Book a free intro