Intro to Git — Snapshots, Branches & Sharing
WorkshopyOfficial10 stepsQuiz9 interactiveDiagram
gitversion controlbeginners
Python loops exercises for beginners: lists, for, range and while, with a line-by-line visualiser and practice you check as you go.

WorkshopyOfficial
78 lessons · used by 2 teachers
Sign in to copy it to your workspace. It’s free.
11 steps · 2 quizzes · open any step, or read it here
These Python loops and lists exercises start with a problem you meet in any real file: a list of orders, sales or tickets that is far too long to add up or check by hand. Writing one line per item doesn't work when the list has 500 items, or a different number every day.
Interactive · A loop walks the list and builds the answer — try it in the lesson
You just watched a for loop visit each order in turn while the total grew one block at a time. By the end of this lesson you'll write loops like that yourself, to add up, count and pick out the items you need.
You need print(), variables and if from your first programs, and any Python 3 for the short "Your turn" programs.
In this lesson you practise Python loops and lists with exercises: you keep many values in one list, then use for and while loops to go through them, add them up, count them and pick some out. A visualiser shows every line Python runs, so you can see what a loop does instead of guessing.
Here is the whole idea in five lines. Watch the loop visit each sale in turn while total grows:
Interactive · A loop adds up a week of sales — try it in the lesson
Each step has something to play with and most have a short program to run in your own Python. Press Step to run one line at a time, Back to go back, Play to watch it run.
Takeaway: a loop runs the same lines once for every item in a list.
A list keeps many values, in order, under one name. You write it with square brackets and commas:
tickets = ["login", "refund", "bug", "access", "spam"]
Each item has a position, its index. Python counts from 0, so the first item is tickets[0] and the fifth is tickets[4]. Negative indexes count back from the end: tickets[-1] is the last item, tickets[-2] the one before it. len(tickets) gives the number of items, here 5.
Asking for an index that doesn't exist stops the program with an IndexError.
Try it: move the slider, press Last, then press tickets[5]. Why is 5 out of range when the list has 5 items?
Interactive · Indexes in a list — try it in the lesson
tickets = ["login", "refund", "bug", "access", "spam"]
print(len(tickets), tickets[0], tickets[-1])
Check your work · Run the program above and paste what it printed. — check it in the lesson
Takeaway: indexes start at 0, and -1 is the last item.
A list can change after you make it. You change it with methods: a dot after the list's name, then the method and brackets.
| Method | What it does |
|---|---|
cart.append("eggs") |
adds an item at the end |
cart.insert(0, "tea") |
puts an item at index 0; the others move one place right |
cart.remove("milk") |
deletes the first item equal to "milk"; error if there is none |
cart.pop() |
takes the last item out and gives it back |
cart.sort() |
puts the items in order, in the same list |
append, insert, remove and sort change the list and give back nothing (None). Only pop gives back a value you can keep: last = cart.pop().
Try it: press each method. Then type cake as the item and press remove(item), and press pop() until the list is empty.
Interactive · List methods in a Python shell — try it in the lesson
cart = ["milk", "bread"]
cart.append("eggs")
cart.insert(0, "tea")
cart.remove("milk")
last = cart.pop()
print(cart, last)
Check your work · Before you run it, write down what you expect. Then run it and paste what it printed. — check it in the lesson
Takeaway: methods change the list in place; pop() also gives the item back.
A for loop runs the same lines once for every item in a list:
for name in team:
print("Hi", name)
Read it as "for each name in team". On every pass Python puts the next item into the variable name and runs the indented lines under the for. When there are no items left, the loop ends and Python carries on with the first line that is not indented.
:.Try it: press Step and watch the purple loop mark move along the list. Count how many times line 3 runs. Then pick Letters of a word.
Interactive · A for loop visits each item — try it in the lesson
team = ["Ana", "Ben", "Chen"]
for name in team:
print(name, len(name))
Check your work · Run it and paste what it printed. — check it in the lesson
Takeaway: for runs the indented lines once per item, with the item in the loop variable.
Sometimes you need numbers rather than items: do something 10 times, or number the lines of a report. range() gives a run of whole numbers for a loop:
| You write | Numbers it gives |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(1, 6) |
1, 2, 3, 4, 5 |
range(0, 15, 5) |
0, 5, 10 |
range(10, 0, -2) |
10, 8, 6, 4, 2 |
The three parts are start (included, 0 if you leave it out), stop (never included) and step (1 if you leave it out). Because the stop is never included, range(1, 6) is the way to count from 1 to 5.
for day in range(1, 6):
print("Day", day)
list(range(...)) shows the numbers as a list, which is handy for checking.
Try it: press the examples, then move the sliders. What happens with range(5, 1)? Set the step to 0.
Interactive · range(start, stop, step) on a number line — try it in the lesson
for n in range(2, 11, 3):
print(n)
Check your work · Run it and paste what it printed. — check it in the lesson
Takeaway: range(start, stop, step) counts from start up to, but not including, stop.
Four questions on the first half.
Question 1. tickets = ["a", "b", "c"]. What happens with print(tickets[3])?
Question 2. Which method takes the last item out of a list and gives it back?
Question 3. How many times does the body of for i in range(4): run?
Question 4. What does this print: for letter in "hi": print(letter)
Most work loops follow one pattern, the accumulator: a variable you set before the loop and update inside it.
| Goal | Before the loop | Inside the loop |
|---|---|---|
| Total | total = 0 |
total = total + amount |
| Count | big = 0 |
if amount > 100: then big = big + 1 |
| Biggest | biggest = orders[0] |
if amount > biggest: then biggest = amount |
After the loop, the variable holds the answer. An average is the total divided by the count: total / len(orders).
Try it: pick Total and press Play, then run Count and Biggest on the same orders. In Biggest, watch the line with if: the note under the picture shows the comparison Python makes, such as 135 > 40 is True.
Interactive · The loop visits each order and updates the answer — try it in the lesson
Why does Biggest start with orders[0] rather than 0? Think of a list where every number is negative.
hours = [7.5, 8, 6, 9.5]
total = 0
for h in hours:
total = total + h
print(total, total / len(hours))
Check your work · Run it and paste what it printed: the total hours and the average per day. — check it in the lesson
Takeaway: set the answer before the loop, update it inside, read it after.
A loop can also make a new list: start with an empty list [], and append to it inside the loop.
append only when an if is true. Orders of 100 or more go into large.append a changed copy of each item. Each name goes into tags in capitals with .upper().The original list stays as it was, so you can still use it.
Try it: step through Keep some items and watch large grow only when the condition is True. Then run Change every item.
Interactive · Filtering and changing items into a new list — try it in the lesson
scores = [72, 95, 58, 88, 61]
passed = []
for s in scores:
if s >= 70:
passed.append(s)
print(passed, len(passed))
Check your work · Run it and paste what it printed. — check it in the lesson
Takeaway: start with [], append inside the loop, and the original list is left as it was.
A for loop runs once per item. A while loop runs as long as a condition is True, and checks it again before every pass. Use it when you don't know in advance how many passes it takes:
savings = 0
months = 0
while savings < 1000:
savings = savings + 250
months = months + 1
Something inside the loop must change the condition, or it is True for ever and the program never ends (an infinite loop; press Ctrl+C to stop it).
break leaves a loop at once, for or while. It is how you stop when you have found what you were looking for: the first wait over 10 minutes is escalated, and the rest are never checked.
Try it: step through while: save to a goal. Look at the last check: why does 1000 < 1000 end the loop? Then run break: stop early and see which waits are never printed.
Interactive · A while loop and a break — try it in the lesson
tickets = 40
days = 0
while tickets > 0:
tickets = tickets - 15
days = days + 1
print(days, tickets)
Check your work · A support team closes 15 tickets a day. Run it and paste what it printed. — check it in the lesson
Takeaway: while repeats while its condition is True; break leaves the loop at once.
Each program below has a mistake that does not give an error message: it runs and prints the wrong answer. That makes these the hardest bugs to find.
range(1, 5) stops at 4. To include 5, the stop must be 6.print meant for the end runs once per item.total = 0 inside the loop starts again on every pass, so only the last item counts.Try it: run each program and compare what it prints with its goal. In 1. Removing while looping, watch the purple loop mark: after 40 is removed, which item does it skip?
Interactive · Four loop mistakes, run line by line — try it in the lesson
This program should print the total of the prices once: Total: 50. It has two mistakes. Fix them and run it.
prices = [12, 30, 8]
for p in prices:
total = 0
total = total + p
print("Total:", total)
Check your work · Paste what your fixed program printed. — check it in the lesson
Takeaway: if a loop gives the wrong answer, step through it and check what happens on each pass.
Work out what each program prints, then check. Run it in Python only after you've answered. A hint costs nothing, and a wrong answer costs nothing either.
nums = [4, 7, 1]
nums.append(9)
print(len(nums))
letters = ["a", "b", "c", "d"]
print(letters[-2])
total = 0
for n in [3, 5, 2]:
total = total + n * 2
print(total)
count = 0
for answer in ["yes", "no", "yes", "yes"]:
if answer == "yes":
count = count + 1
print(count)
n = 1
while n < 50:
n = n * 3
print(n)
Six questions on the whole lesson.
Question 1. To add up a list with a loop, what goes before the loop?
Question 2. Which loop keeps going for as long as a condition is True?
Question 3. What does break do inside a loop?
Question 4. You want to drop every order under 50 from a list. What is the safest way?
Question 5. Which of these give the list [0, 1, 2]? (pick all that apply)
Question 6. After xs = [5, 1, 4] and xs.sort(), what does print(xs[0]) show?
Workshopy shares this lesson under CC BY 4.0. Anyone may use and change it, with credit to you. Anyone can learn it here, free. A copy in your workspace is yours to change and run live; your students never need an account.
Version 2Current
· A new Start here step with the lesson's scene; the cover is now a frame of the loop you step through in the lesson.
Version 1
· First published
Copies are made from the current version. A copy you already have doesn’t change.
WorkshopyOfficial10 stepsQuiz9 interactiveDiagram
gitversion controlbeginners
WorkshopyOfficial16 steps2 quizzes15 interactiveDiagram
workshopyproduct touronboarding
WorkshopyOfficial10 steps2 quizzes10 interactive
data-literacystatisticsmean and median
WorkshopyOfficial12 steps2 quizzes15 interactive
pythonfunctionsreturn values
WorkshopyOfficial12 steps2 quizzes11 interactive
devopsregexregular expressions
WorkshopyOfficial12 steps2 quizzes11 interactive
gitpull requestscode review
Comments
No comments yet. Be the first to say how it went.