Only Boring People Get Bored
Imagine if your teacher asked you to write “I will not talk in class” 100 times on the blackboard. You would hate it. Your hand would hurt. You would make mistakes.
A computer? It would love it. It can do it in a blink of an eye.
The for Loop
In Python, when we want to repeat something, we use a loop.
for i in range(3):
print("Python is fun!")
Output:
Python is fun!
Python is fun!
Python is fun!
Breaking it Down
for: Start the loop.i: A variable that counts for us (0, 1, 2…).in range(3): How many times? 3 times.:: Don’t forget the colon!- Indentation: The lines pushed in are the ones that get repeated.
Using the Counter
The variable i changes every time the loop runs. You can use it!
for i in range(5):
print("Countdown:", i)
Wait, why does it start at 0? Computer scientists count from 0. It’s just a quirk we love. (0, 1, 2, 3, 4) — that is still 5 numbers!
Making a Pattern
Loops are great for art.
text = "*"
for i in range(5):
print(text)
text = text + "*"
Output:
*
**
***
****
*****
Loops with Variables
You can do math inside a loop! Let’s count how many steps we take.
steps = 0
for i in range(5):
steps = steps + 1
print("I have taken", steps, "steps")
Or we can add up numbers.
total = 0
for i in range(1, 6): # Numbers 1 to 5
total = total + i
print("The total is:", total)
Stopping Early ( The Emergency Brake)
Sometimes you want to stop the loop before it finishes. We use the command break.
Imagine you are looking for a lost key. Once you find it, you stop looking!
for i in range(100):
print("Looking in box", i)
if i == 5:
print("FOUND IT!")
break
The computer will stop at box 5, even though the range was 100!
Try It Yourself
Can you write a loop that counts down from 10 to 1?
(Hint: range(10, 0, -1) counts backwards!)
This post is part of the Python Basics for Kids series, based on “Python for Kids from 8 to 88”.