Loops (for/while)

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? total = 6 for i in range(1, 7): total += i * 1 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.

    Loops (for/while) explained

    Loops repeat a block of code. A for loop repeats over the items of a sequence, while a while loop repeats as long as its condition stays true. Python also provides break, continue and an else clause on loops.

    The for loop walks through an iterable such as a list, a string or a range. range(start, stop, step) produces numbers from start up to, but not including, stop. For example, range(2, 20, 3) produces 2, 5, 8, 11, 14 and 17.

    A while loop checks its condition before each pass. It is useful when the number of repeats is not known in advance, but the condition must eventually become false, or the loop never ends.

    break leaves the loop immediately, and continue skips to the next pass. A for loop can also have an else block, which runs only when the loop finished without a break. This is handy for search loops.

    Worked example

    total = 0
    for i in range(2, 20, 3):
        total = total + i
    print(total)
    
    n = 100
    count = 0
    while n > 0:
        n = n // 2
        count = count + 1
    print(count)
    
    1. range(2, 20, 3) gives 2, 5, 8, 11, 14 and 17, whose sum is 2+5+8+11+14+17=572 + 5 + 8 + 11 + 14 + 17 = 57.
    2. Halving 100 with floor division gives 50, 25, 12, 6, 3, 1 and 0, so the loop runs 7 times.

    Check: 100 is 1100100 in binary, which has 7 digits, and each halving removes one binary digit.

    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 = 2 for i in range(2, 10): total += i * 1 print(total)

    • Medium

      What does this Python code print? n = 2 while n < 97: n *= 2 print(n)

    • Hard

      What does this Python code print? count = 0 for i in range(4): for j in range(5): if j > i: break if (i + j) % 3 == 0: continue count += 1 print(count)