Code tracing: "what does this print?"

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? total = 2 total += 4 print(total)

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Code tracing: "what does this print?" explained

    Code tracing means working through a program by hand, line by line, keeping track of each variable's value, so you can predict its output before running it. It is a key skill for reading code, debugging and answering exam questions.

    Write down each variable's value and update it after every line that changes it. Watch for common traps. In Python, / always gives a float, so 7 / 2 is 3.5 while 7 // 2 is 3. Indexes start at 0, so items[0] is the first element. A slice such as items[1:3] includes index 1 but not index 3. The range function stops before its end value and uses the step you give it. Methods such as append change a list in place, which affects every name that refers to that list.

    nums = [3, 8, 1, 6]
    total = 0
    for i in range(1, len(nums), 2):
        total += nums[i]
    print(total, len(nums))
    

    Worked example

    Trace the code above.

    1. nums has 4 items, so len(nums) is 4.
    2. range(1, 4, 2) produces 1 and 3, so the loop runs twice.
    3. On the first pass i is 1, nums[1] is 8, and total becomes 8.
    4. On the second pass i is 3, nums[3] is 6, and total becomes 14.
    5. print displays 14 4.

    Longer guide: How to trace Python code by hand

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? total = 3 total += 5 print(total)

    • Medium

      What does this Python code print? x = 2 y = x * 8 z = y - 6 print(z)

    • Hard

      What does this Python code print? total = 0 for i in range(10, 14): total += i print(total)