Control flow: loops
Computer Science · Programming fundamentals
Question 1 of 10
0What values does range(5) produce in Python?
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
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.
Control flow: loops explained
A loop repeats a block of instructions either a set number of times or while a condition holds. Loops are one of the three basic control structures, alongside sequence (one step after another) and selection (choosing a path with an if statement).
There are two main kinds. A count-controlled loop, such as FOR in pseudocode or for in Python, runs a known number of times. A condition-controlled loop, such as WHILE, checks a condition and repeats while it stays true. A WHILE loop checks before each run, so its body may never run. A REPEAT UNTIL loop checks after each run, so its body always runs at least once.
Conventions differ between courses. In pseudocode, FOR i = 1 TO 5 includes the end value and runs five times, but Python's range(1, 5) stops before 5.
A common mistake is an off-by-one error, such as using the wrong end value. Another is forgetting to change the variable in a WHILE loop, which can make the loop run forever.
Worked example
Start with x = 3 and double it while x is less than 100:
x = 3
count = 0
while x < 100:
x = x * 2
count = count + 1
The values of x after each run are 6, 12, 24, 48, 96 and then 192. The loop runs 6 times, and it stops at 192, the first value that is 100 or more.
What you will practise
105 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- A loop repeats code:
- A for loop is best when:
- A while loop runs while its condition is:
- An infinite loop:
- The break statement:
- What is the body of a loop?
- In a while loop, when is the condition checked?
- What is an iteration of a loop?
…and 97 more.