Loops
Repeat code multiple times
Sometimes you need your computer to do the same thing many, many times. That's where loops come in!
What are loops?
Loops are super handy when you want to repeat a block of code multiple times. Instead of writing the same lines over and over, you can tell Python to loop through them.
Imagine printing a message ten times. Without a loop, you'd write ten print statements. With a loop, it's just a few lines of code.
For loops
for loops are great when you know how many times you want to repeat something, or when you want to go through each item in a collection.
Repeat a specific number of times
The range() function is your friend here. It gives you a sequence of numbers. You can loop through these numbers.
for i in range(5):
print("Hello!")This code will print "Hello!" exactly five times. The variable i will take values 0, 1, 2, 3, and 4.
Count from different starting points
You can tell range() where to start and stop. The first number is included, but the last one is not.
for count in range(1, 4):
print(f"Countdown: {count}")This prints "Countdown: 1", "Countdown: 2", then "Countdown: 3".
Loop through text
You can also loop through each character in a string. Python treats a string as a sequence of characters.
word = "Python"
for char in word:
print(char)This will print each letter of "Python" on a new line.
Loop through a list (preview)
While we haven't covered lists yet, they're another common thing to loop through. You'll often use for loops to process every item in a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}s!")While loops
while loops keep going as long as a certain condition is true. They're useful when you don't know exactly how many times you need to repeat something.
count = 0
while count < 3:
print("Counting...")
count = count + 1 # Don't forget to change the condition!This loop will print "Counting..." three times, then stop because count becomes 3, making the count < 3 condition false.
Common mistakes
- Forgetting the colon (
:) at the end of thefororwhileline. - Incorrect indentation. Python uses spaces to know what code belongs inside the loop.
- Forgetting to update the condition in a
whileloop, which can lead to an infinite loop (it never stops!). Press Ctrl+C to stop a runaway script.
Practice
Try these exercises to lock in what you just learned.
1total = 023 total += i4print(total)