CODE PATH
PRO ACCOUNT

Master Code
On The Go

Learn. Practice. Build.

Quest 1 • Lesson 5

🔄 Loops (for / while)

Loops let you repeat code multiple times. Python has two main loop types: for (iterate over a sequence) and while (repeat while a condition is true).

"Without loops, you'd have to write the same code 100 times to print numbers 1 to 100. With a loop, it's just 3 lines."
for_loop.py
for i in range(5):
    print(i)
# Output: 0 1 2 3 4

📌 The `for` Loop with `range()`

range_example.py
for i in range(2, 10, 2):
    print(i)
# Output: 2 4 6 8
while_loop.py
count = 0
while count < 5:
    print(count)
    count += 1

⏳ The `while` Loop

🔁 Iterating Over Lists

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

✨ Challenge 1: Sum of First N Numbers

Write a for loop to calculate the sum of numbers from 1 to 100. Print the result.

total = 0
for i in range(1, 101):
    total += i
print(total)   # 5050

✨ Challenge 2: Countdown

Use a while loop to print numbers from 10 down to 1, then print "Blast off!".

n = 10
while n > 0:
    print(n)
    n -= 1
print("Blast off!")

🧪 Mental Exercise

What is the output of this code?

x = 1
while x < 5:
    print(x)
    x += 2
Reveal answer

Output: 1 3 (stops when x becomes 5)

❤️ Support Free Education

This course is 100% free. If it helps you, consider buying me a coffee.

☕ Buy Me a Coffee

➡️ Ready for more?

Next lesson: Functions – reuse code with reusable blocks.

Continue to Lesson 1.6 →

(Coming soon – check back or buy Pro Pack for instant access)