Legends ofPythos
Claim your name
Python Basics

Repeating work with loops

Lesson 9 of 13

Watch the lesson1:10 ยท with Sigrid
Computers are great at doing the same thing many times. A loop lets you repeat a block of code without writing it over and over.

The for loop

friends = ['Ana', 'Ben', 'Cy']
for name in friends:
    print('Hi, ' + name)
Prints a greeting for each friend.
The for loop visits every item in the list. On each pass, it puts that item into the variable between for and in. Here, name holds 'Ana', then 'Ben', then 'Cy'. The indented line runs once for each friend.

range()

for i in range(5):
    print(i)
Prints 0, 1, 2, 3, 4.
range(n) gives you the numbers from 0 up to (but not including) n. If you pass two arguments, like range(2, 6), it starts at 2 and stops before 6. This is handy when you need a specific count or range.

Looping over strings

word = 'cat'
for letter in word:
    print(letter)
Prints c, a, t on separate lines.
A string is just a sequence of characters. You can loop over it exactly like you would a list.

Building totals

total = 0
for n in [1, 2, 3]:
    total = total + n
print(total)
Prints 6.
Start a variable at zero. Inside the loop, add each number to it. By the end, total holds the sum of everything you added.

The while loop

count = 3
while count > 0:
    print(count)
    count = count - 1
print('Liftoff!')
Prints a countdown.
while repeats as long as its condition is true. You must change something inside the loop to make it false eventually, or your program will run forever and freeze.

break and continue

for i in range(10):
    if i == 5:
        break
    print(i)
Prints 0-4, then stops.
break exits the loop immediately. continue skips the rest of this pass and jumps to the next one. Use them carefully; too many can make code hard to follow.

Your turn

0 of 3 solved

Exercise 1

+30 XP
A five-a-side tournament just ended. The scoreboard scores holds each team's goal count in order (Alpha, Beta, Gamma). Write a for loop that prints every score on its own line so the crowd can see who scored what.
scores = [3, 1, 2]
for s in scores:
    pass

Run your code to check it against the tests.

Exercise 2

+30 XP
Using range(1, 6), add each number to a running total. Print the final total.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+30 XP
Loop over the characters of word using for ch in word:. As soon as you reach the letter 'z', print it and stop the loop with break.
word = 'abczdef'

Run your code to check it against the tests.