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
print(i)
# Output: 0 1 2 3 4
๐ The `for` Loop with `range()`
forโ keyword that starts the loop.iโ loop variable (takes each value from the sequence).range(5)โ generates numbers0,1,2,3,4.- The indented block runs once for each value.
range_example.py
for i in range(2, 10, 2):
print(i)
# Output: 2 4 6 8
print(i)
# Output: 2 4 6 8
while_loop.py
count = 0
while count < 5:
print(count)
count += 1
while count < 5:
print(count)
count += 1
โณ The `while` Loop
- Repeats while a condition is
True. - You must manually update the variable that affects the condition (otherwise infinite loop).
- Use
whilewhen you don't know how many iterations you need (e.g., user input until valid).
๐ Iterating Over Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
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
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)