Loops
Repeat actions with for and while loops
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
A loop lets you repeat a block of code without writing it multiple times. Instead of copy-pasting print(1) through print(5), you write one for line and let Python handle the repetition. Each pass through the loop body is called an .
for loop — over a range or sequence:
for i in range(5):
print(i)range(5) generates the values 0, 1, 2, 3, 4 — the loop body runs once per value, with i set to each value in turn. The loop runs 5 times total.
while loop — repeat while a condition is True:
count = 0
while count < 3:
print(count)
count += 10 1 2
Each iteration checks count < 3. As long as it's True, the body runs. Once count reaches 3, the condition becomes False and the loop stops.
break — exit the loop early:
for i in range(10):
if i == 3:
break
print(i)0 1 2
break immediately terminates the innermost loop. Control resumes at the first statement after the loop — the rest of the values (3 through 9) are never reached.
continue — skip to the next iteration:
for i in range(5):
if i == 2:
continue
print(i)continue skips the rest of the current iteration's body and jumps to the next value. Value 2 is never printed.
Examples
Iterating a list
Loop through a list and transform each item
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit.upper())How well did you understand this?
Next in Programming Fundamentals
Comparison Operators