Lesson 12 of 30 · Loops
For Loops
Repeat code with Python for loops. Loop over lists and strings, add up totals and combine loops with if statements, with runnable examples.
- 6 min read
- Beginner
- Reviewed
- Why loops exist and what a for loop does
- How to loop over a list and over the letters of a string
- How to build up a result, such as a total, inside a loop
- How to combine a loop with an if statement
Why loops?
Imagine you need to greet five students. You could write five print lines. But what about five hundred students? Or five million rows of data?
A loop repeats a block of code so you do not have to write it again and again. Loops are one of the most important ideas in programming, and AI code is full of them.
Your first for loop
A for loop takes a collection of items and runs the same code once for each item.
students = ["Ada", "Grace", "Alan"]
for student in students:
print("Hello,", student)
print("Done!")Read the loop like a sentence: "for each student in the list of students, print a greeting."
Here is what happens, step by step:
- Python takes the first item,
"Ada", and stores it in the variablestudent. - It runs the indented block, so it prints
Hello, Ada. - It goes back to the top, takes the next item and runs the block again.
- When there are no items left, the loop ends and Python continues with the next unindented line.
The variable student is called the loop variable. You choose its name. A common habit is a plural name for the list and the singular for the loop variable: for student in students.
The shape of a for loop
Like if, a for line ends with a colon, and the lines that repeat are indented. Everything indented belongs to the loop. The first line that returns to the left edge runs only once, after the loop has finished.
for colour in ["red", "green", "blue"]:
print("Colour:", colour)
print("---")
print("This line runs once.")Looping over a string
A string is a sequence of characters, so you can loop over it letter by letter.
for letter in "AI":
print(letter)Building up a result
A very common pattern is to start with an empty result and add to it on every pass. Here a loop adds up a list of prices.
prices = [250, 120, 80]
total = 0
for price in prices:
total = total + price
print("Added", price, "- total is now", total)
print("Final total:", total)The line total = 0 must come before the loop. If it were inside, the total would be reset on every pass.
Loops and if statements together
You can put an if inside a loop to treat items differently. Notice the two levels of indentation.
scores = [45, 82, 67, 91, 38]
passed = 0
for score in scores:
if score >= 50:
print(score, "- pass")
passed += 1
else:
print(score, "- fail")
print(passed, "students passed.")Common mistakes
Use a for loop to add up every number in prices, then print Total: 60.
prices = [12, 8, 25, 15] # Add up all the prices with a for loop, # then print the result as exactly: Total: 60
How many times does the indented block run in: for x in [10, 20, 30]:
Summary
- A loop repeats code so you do not have to copy it.
for item in collection:runs its block once for each item.- The loop variable holds the current item on each pass.
- Start a total at 0 before the loop, then add to it inside.
- Indentation decides which lines repeat.
Next: looping a set number of times with range().
Finished reading? Tick it off to track your progress.