Core programming fundamentals · Lesson 10 of 60 · Code lesson, JavaScript or Python · Optional
Loops and iteration
A loop repeats code until a stopping rule says to finish.
A for loop counts through a range, a while loop runs as long as a condition stays true, and a do-while loop always runs once before checking.
break leaves a loop early, and continue skips straight to the next turn.
Worked example
This for loop starts count at 1, continues while count <= 3 (at most 3), and adds 1 after each turn. A while or do...while loop does the same with just a condition.
for (let count = 1; count <= 3; count += 1) {
console.log(count);
}Output:
1 2 3
In Python, range(1, 4) gives 1, 2 and 3: it starts at 1 and stops just before 4. Python has no do-while; a while loop with break does the same job.
for count in range(1, 4):
print(count)Output:
1 2 3
Your turn
The loop prints 1 to 5. Change it so it skips 3 and prints 1, 2, 4 and 5, each on its own line.
Expected output:
1 2 4 5
Loading your practice…
Preparing your workspace…