Lesson 6 - Loops
Loops in Python
For Loop
For Loop is used to repeat a block of code multiple times. It goes through a sequence (like numbers, strings, or lists) one by one.
for letter in "HELLO":
print(letter)
for i in [1, 2, 3, 4, 5]:
print(i)
fruits = ["apple", "banana", "cherry"]
for f in fruits:
print(f)
For Loops with Conditions
You can combine for loops with if statements to make them more powerful.
for i in range(1, 11):
if i % 2 == 0:
print(i)
for i in range(1, 6):
print("2 x", i, "=", 2*i)
for x in range(3):
for y in range(3):
print(x, y)
Tip: range(n) generates numbers from 0 up to n-1.
You can also use range(start, end) or range(start, end, step).
for x in range(3):
print(x)
for y in range(0, 10, 3):
print(y)
While Loop
While Loop is used when you want to repeat a block of code as long as a condition is true.
i = 1
while i <= 4:
print(i)
i = i + 1
1
2
3
4
⚠️ Be careful! If the condition is always True, the loop will run forever.
Always make sure the loop updates the variable so it can eventually stop.
Break Statementexits the loop early.
while i <= 10:
if i == 5:
break
print(i)
i = i + 1
Continue Statementskips the current loop step and goes to the next one.
while i < 5:
i = i + 1
if i == 3:
continue
print(i)
Print numbers from 1 to 5
print(i)
💡 Change the range to print 1–10.
Print each letter of a word
print(letter)
💡 Try changing the word.
Print items in a list
for f in fruits:
print(f)
💡 Add another fruit and run again.
Print a multiplication table for 2
print("2 x", i, "=", 2*i)
💡 Try table of 5.
Add all numbers 1 to 10
for i in range(1, 11):
total = total + i
print(total)
💡 Change to add numbers 1–20.
Print only even numbers between 1 and 20
if i % 2 == 0:
print(i)
💡 Can you make it print odd numbers instead?
Sum numbers until 0 is entered
num = int(input("Enter a number (0 to stop): "))
while num != 0:
total = total + num
num = int(input("Enter a number (0 to stop): "))
print("Total:", total)
👉 Try different numbers.
Print a square of stars ⭐
print("*****")
💡 Change it to make a rectangle.
Try nested loop
starRow = ""
for x in range(4):
starRow += "*"
print(starRow)
Cooking recipe
ingredients = ["flour", "sugar", "eggs", "milk", "butter"]
print("Let's make muffins!")
print("We need:")
for item in ingredients:
print("- " + item)
print("Mix everything together and bake! 🎂")
💡 Try your favorite food recipe
Guess the secret number
guess = 0
while guess != secret:
guess = int(input("Guess the number: "))
print("Correct! 🎉")
👉 Change the secret number.
Use break to stop the loop
while i <= 10:
if i == 5:
break
print(i)
i = i + 1
👉 What numbers will print?
Use continue to skip a number
while i < 5:
i = i + 1
if i == 3:
continue
print(i)
👉 Which number is skipped?