Friendly introduction
Have you ever done something again and again, like taking 10 shots in basketball or practicing a song 5 times? A loop in Python is a way to tell the computer: "Repeat this task for me!" Loops save time and make your programs shorter and smarter.
What is a loop?
A loop repeats a block of code multiple times.
- for loop: Best when you know exactly how many times to repeat or when you're going through items in a list.
- while loop: Best when you want to repeat until a condition becomes false.
Step 1: The for loop
Use for when you want to loop a certain number of times or over a collection like a list or a word.
Example 1: Count from 1 to 5
for i in range(1, 6): # 1 to 5 (6 is not included)
print(i)Example 2: Loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)Example 3: Loop over each letter in a word
word = "code"
for letter in word:
print(letter)Step 2: The while loop
A while loop runs as long as a condition is true. Make sure something inside the loop changes, or it will loop forever!
Example 1: Countdown
count = 5
while count > 0:
print(count)
count -= 1 # subtract 1 each time
print("Blast off!")Example 2: Keep doubling until you reach 100
x = 1
while x < 100:
print(x)
x *= 2 # multiply x by 2 each time
print("Done")Important: Avoid infinite loops!
This will never end because the condition is always True and we never change it:
# Don't do this:
# while True:
# print("looping forever!")If you do need a forever loop, make sure you have a way to stop it (like a break).
Step 3: Stopping or skipping in a loop (bonus)
- break stops the loop immediately.
- continue skips just the current turn and moves to the next one.
# break example
for n in range(1, 10):
if n == 5:
break
print(n)
print("Stopped at 5")
# continue example
for n in range(1, 6):
if n == 3:
continue # skip printing 3
print(n)Mini exercise: Your turn!
Task: Print the multiplication table of 7 from 1 to 10 (like "7 x 1 = 7" up to "7 x 10 = 70") using a for loop.
Hints:
- Use range(1, 11) to get numbers 1 to 10.
- Multiply 7 by the loop variable and print neatly.
Sample answer (peek if you're stuck):
for i in range(1, 11):
print("7 x", i, "=", 7 * i)Challenge (optional): Do the same table using a while loop.
i = 1
while i <= 10:
print("7 x", i, "=", 7 * i)
i += 1Quick summary
- Loops repeat code so you don't have to.
- Use for to loop a set number of times or over items (range, lists, strings).
- Use while to repeat until a condition becomes false—remember to update your variables!
- break stops a loop; continue skips one turn.
- Practice by writing loops that count, list items, or print patterns like tables.