Python Level 4: Loops (for / while)

Goal of this Level

Today you will learn to:

By the end, you will be able to write programs that perform many repetitions automatically.

Step 1: What is a Loop?

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.

Step 2: The for Loop

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:

Output:


Round 1
Round 2
Round 3
Round 4
Round 5

Step 3: Understanding range()

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

Step 4: The while Loop

The while loop runs as long as a condition is true.


x = 0

while x < 5:
    print("Number", x)
    x = x + 1

Explanation:

Output:


Number 0
Number 1
Number 2
Number 3
Number 4

Step 5: Avoid Infinite Loops

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.

Step 6: break

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.

Step 7: continue

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.

Practice Example


for i in range(5):
    print("Round", i + 1)

x = 0

while x < 5:
    print("Number", x)
    x = x + 1

This program demonstrates: