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)