Question bank › IB Computer Science › B2 Programming

Programming fundamentals: variables, data types, strings, exceptions, debugging

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]

2Core6 marks

A school is writing a program to record results on sports day. For each runner it stores the five items of data below.

ItemExample
(i) House the runner belongs to, stored as a single letterR
(ii) Number of events the runner has entered3
(iii) Finishing time in the 100 m, in seconds12.84
(iv) Whether a medical consent form has been receivedyes / no
(v) Parent's phone number07700 900123

(a) State the most appropriate data type for each of items (i) to (iv). Choose from Boolean, char, decimal, integer and string. [4]

(b) Explain why item (v) should be stored as a string rather than as an integer. [1]

(c) A runner has scored a total of 17 points across 4 events. The program calculates the runner's average points per event and stores the result in a variable of type integer. State the value that is stored. [1]

3Core5 marks

A program calculates bus fares. It runs without crashing and produces output, but some passengers are charged the wrong fare.

(a) State the type of error that the program contains. [1]

(b) Describe how a programmer could use a breakpoint and step-by-step execution to find the line that causes the wrong fare. [3]

(c) Outline one disadvantage of debugging with print statements compared with using breakpoints. [1]

Stuck on Programming fundamentals: variables, data types, strings, exceptions, debugging?

Get it sorted in a free 30-minute session

We work through your weakest questions on this topic on Zoom. I reply the same day.

4Standard5 marks

Consider the following Python program.

points = 10
bonus = 3

def award(bonus):
    global points
    points = points + bonus
    level = points // 5
    return level

def reset():
    points = 0
    return points

print(award(4))
print(reset())
print(points, bonus)

(a) State the three lines of output produced when the program runs. [3]

(b) Explain why the call reset() does not change the value printed for points on the last line. [2]

5Standard5 marks

A school creates usernames for new students using this rule:

  • the first three letters of the surname (or the whole surname if it is shorter), then
  • the first letter of the first name, then
  • the last two digits of the year of entry.

All letters in the username are lower case. For example, Priya Okonkwo entering in 2009 has the username okop09.

(a) Construct a function make_username(first, surname, year) that returns the username. first and surname are strings and year is an integer. [4]

(b) State the username returned for Li Ng entering in 2010. [1]

6Standard5 marks

Consider the following Python code.

card = "4929 1234 5678 9012"
masked = "**** **** **** " + card[-4:]
print(masked)
code = "ab-12-cd"
code.replace("-", "")
print(code)
code = code.replace("-", "").upper()
print(code, len(code))

(a) State the three lines of output. [3]

The programmer then adds the line code[0] = "X" to change the first character of code to X. This causes an error.

(b) Explain why this line causes an error, and write a correct line of code that makes code hold XB12CD. [2]

7Standard5 marks

A reading-planner program asks a student how many pages they will read per day, and the input is passed to this Python function as a string.

def plan(entry):
    try:
        pages = int(entry)
        per_day = 240 // pages
        print("A", per_day)
    except ValueError:
        print("B")
    except ZeroDivisionError:
        print("C")
    finally:
        print("D")
    print("E")

(a) State the output when the function is called with each of these inputs:

(i) plan("16") [1]

(ii) plan("0") [1]

(iii) plan("7.5") [1]

(b) State the purpose of the finally block. [1]

(c) The call plan("-48") outputs A -5, D, E. Outline why the exception handling does not deal with this unexpected input. [1]

8Hard6 marks

A weather station saves temperature readings in a text file, one reading per line. Some lines are corrupted, for example err, N/A or blank.

Construct a function average_reading(filename) that:

  • outputs File not available and returns -1 if the file cannot be opened
  • skips any line that cannot be converted to a decimal number, counting how many lines are rejected
  • makes sure the file is closed, even if an error occurs while it is being read
  • outputs the number of rejected lines and returns the mean of the valid readings (or -1 if there are no valid readings).

You may answer in Python or Java. [6]

9Hard6 marks

The function below is intended to return the longest word in a sentence. Words are separated by single spaces.

def longest_word(sentence):
    longest = ""
    current = ""
    for ch in sentence:
        if ch == " ":
            if len(current) > len(longest):
                longest = current
            current = ""
        else:
            current = current + ch
    return longest

The function is called with longest_word("go far away"). The table shows the values of the variables at the end of each iteration of the loop.

Iterationchcurrentlongest
1gg""
2ogo""
3(space)""go
4
5
6
7
8
9
10
11

(a) Copy and complete the trace table for iterations 4 to 11. [3]

(b) State the value returned by the function. [1]

(c) Identify the logic error in the function. [1]

(d) Describe the change needed to correct the error. [1]

10Stretch5 marks

A programmer expects this program to add 0.1 to total ten times and then stop, but it never finishes. They set a breakpoint on line 4 and run the program. The diagram shows the debugger the 11th time execution pauses at the breakpoint.

(a) The programmer resumes execution until the next pause. State the values of total and count shown at that pause. [1]

(b) Explain why the loop never terminates. [2]

(c) A student suggests changing line 3 to while total < 1.0:. Using the values in the diagram, explain why the program would still not output 10 steps. [1]

(d) Suggest a change that makes the loop run exactly ten times while still adding amounts of 0.1. [1]

Editor: savings.py 1total = 0.0 2count = 0 3while total != 1.0: 4total = total + 0.1 5count = count + 1 6print(count, "steps") ● = breakpointshaded line = paused here (line 4 not yet run) Variables (paused) Name Type Value total float 0.9999999999999999 count int 10

Stuck on this topic?

Book a free 30-minute session on WhatsApp and we'll find exactly which step is costing you the marks. Or build a timed paper on it.

Free 30-minute session