Today you will learn to:
for and whilebreak and continueBy the end, you will be able to write programs that perform many repetitions automatically.
A loop repeats code automatically.
Examples:
Without a loop, you would write:
print("Round 1")
print("Round 2")
print("Round 3")
print("Round 4")
print("Round 5")
With a loop, this happens automatically.
The for loop is used when you know how many times something should be repeated.
for i in range(5):
print("Round", i + 1)
Explanation:
for starts the loopi is a counter variablerange(5) means 5 repetitionsi counts automatically from 0 to 4Output:
Round 1
Round 2
Round 3
Round 4
Round 5
range() generates a sequence of numbers.
Examples:
range(5) → 0,1,2,3,4
range(1,6) → 1,2,3,4,5
Example:
for i in range(1,6):
print(i)
Output:
1
2
3
4
5
The while loop runs as long as a condition is true.
x = 0
while x < 5:
print("Number", x)
x = x + 1
Explanation:
while means "as long as"x < 5 is truex = x + 1 increases the number each timeOutput:
Number 0
Number 1
Number 2
Number 3
Number 4
If a condition never becomes false, the loop runs forever.
x = 0
while x < 5:
print(x)
Missing:
x = x + 1
Without it, the program would never stop.
break stops a loop immediately.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
The loop stops at 5.
continue skips the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
The 2 is skipped.
for i in range(5):
print("Round", i + 1)
x = 0
while x < 5:
print("Number", x)
x = x + 1
This program demonstrates:
for loop with a fixed number of repetitionswhile loop with a condition