Python for Loops · Exercises
Beginner

Python for Loops Exercises

4 exercises that build on the Python for Loops lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A for loop runs the same block of code once for every item in a collection, giving the current item a name while its turn runs. By the end you can loop over lists, strings and range(), number items with enumerate(), stop early with break, skip items with continue, and build a running total. You will practise: Add up the cart; Predict break and continue; Fix the numbered menu; Which day was the goal reached?.

0 / 4 completed

Python for Loops practice exercises

1. Add up the cart

Write code Easy

Use a for loop (not sum()) to add up all the prices in prices. Store the result in total, then print it.

Your code
prices = [12.5, 3.0, 7.25, 20.0]
total = 0

# loop over prices and add each one to total

2. Predict break and continue

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
for n in range(1, 10):
    if n == 7:
        break
    if n % 2 == 0:
        continue
    print(n)
print("done")

3. Fix the numbered menu

Fix the bug Medium

This code should print a numbered menu:

1. Pizza
2. Pasta
3. Salad

but it prints only two lines, and the first dish is missing. Fix it.

Your code
menu = ["Pizza", "Pasta", "Salad"]
for i in range(1, len(menu)):
    print(f"{i}. {menu[i]}")

4. Which day was the goal reached?

Write code Hard

steps holds the step counts for each day, in order. Add them up day by day in total. As soon as total reaches goal or more, store the day number (counting from 1) in goal_day and stop the loop. Finally print Goal reached on day N.

Your code
steps = [4200, 6100, 8800, 5300, 10400, 7600]
goal = 20000
total = 0
goal_day = None

# loop over the days, add each day's steps to total,
# and stop as soon as total reaches goal

Next lessonPython while Loops

More Python for Loops examples · All Python exercises