livepython.net
CHAPTER 10For Loops
10.1  FOR LOOP

Python for Loop: Repeat Code for Each Item

What Is a for Loop?

A for loop runs the same lines of code once for every item in a list. You write the lines once, and Python repeats them for you.

Say you want to greet three friends. Without a loop, you write one print() per friend:

PYTHONedit me
print("Hello, Sunny!")
print("Hello, Rocky!")
print("Hello, Lucky!")
OUTPUT
Hello, Sunny!
Hello, Rocky!
Hello, Lucky!

That works for three friends. But for 300? With a for loop and the list from chapter 9, two lines do it all:

PYTHONedit me
friends = ["Sunny", "Rocky", "Lucky"]
for friend in friends:
    print("Hello,", friend + "!")
OUTPUT
Hello, Sunny!
Hello, Rocky!
Hello, Lucky!

Add a fourth name to the list and run it again. The loop greets everyone, and you didn't touch the print() line.

Think of it like a teacher calling the roll: the teacher goes down the list, one name at a time, and does the same thing for each name.

How it runs

  • Python takes the first item from the list and puts it in friend.
  • It runs the indented lines.
  • Then it takes the next item and runs the lines again.
  • When there are no items left, the loop ends and Python carries on below it.

Each run of the indented lines is called an iteration (a fancy word for "one time round").

  1. Start:
    Start
  2. Step:
    Take the next name from the list
  3. Input or output:
    Show: Hello, name!
  4. Decision:
    Any names left?
    yes
    Go back up and take the next name
    no
    Leave the loop
  5. End:
    End
Greet every friend

The "go back up" is what makes it a loop: the same two boxes run again and again, once per name.

A for loop repeats its indented lines once for every item in a list.

your turnPredict the output

What will this print?

colors = ["red", "green"] for color in colors: print(color)
Your turn! What will this code show on the screen?
your turnPick the right idea

A list has 5 items. How many times does a for loop over it run its indented lines?

Think about it, then pick one.

Writing a for Loop: Colon and Indentation

A for loop has a fixed shape: the words for and in, a colon, and an indented block. It looks a lot like the if from chapter 8.

PYTHONedit me
prices = [20, 35, 50]
for price in prices:
    print("Price:", price)
    print("With tax:", price + 5)
print("All done")
OUTPUT
Price: 20
With tax: 25
Price: 35
With tax: 40
Price: 50
With tax: 55
All done

Think of it like a stamp: everything carved into the stamp (the indented lines) gets printed on every page (every item).

The parts

PartIn the exampleWhat it does
forforstarts the loop
a variablepriceholds the current item
ininjoins the variable and the list
a listpricesthe items to go through
::means "here comes what to repeat"
the blockthe two indented linesruns once per item

Inside or after the loop

  • Every line indented by 4 spaces under the for is inside the loop. It runs once per item.
  • The first line that is not indented is after the loop. It runs once, when the loop is finished.

That's why All done appears only once, at the end.

Forget the colon

PYTHONedit me
names = ["Sunny", "Rocky"]
for name in names
    print(name)
OUTPUT
SyntaxError: expected ':'

Forget to indent

PYTHONedit me
names = ["Sunny", "Rocky"]
for name in names:
print(name)
OUTPUT
IndentationError: expected an indented block after 'for' statement on line 2

Don't be scared of these errors! They're the same ones you met with if, and Python tells you exactly what's missing.

for item in list: then the block, indented by 4 spaces.

your turnFill the gap

Complete the loop

nums = [1, 2, 3] for n ? nums: print(n)

It should print: 1 2 3

Which piece makes this code work?
your turnPredict the output

What will this print?

for x in [1, 2]: print("A") print("B")
Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Looping Over a String

A for loop works on strings too. It goes through the string one character at a time: every letter, digit, space and symbol.

PYTHONedit me
word = "Sunny"
for letter in word:
    print(letter)
OUTPUT
S
u
n
n
y

Think of it like reading a word out letter by letter, the way you spell your name on the phone.

The rules

  • for ch in text: gives you one character per iteration, from left to right.
  • Spaces are characters too, so they get their own turn.
  • The loop runs len(text) times (chapter 5).
PYTHONedit me
for ch in "Hi Rocky":
    print(ch, end="-")
OUTPUT
H-i- -R-o-c-k-y-

See the space between the two dashes? That's the space character getting its turn. end="-" is the trick from chapter 2: it ends each print() with a dash instead of a new line.

Loop over what the user types

This works with input() from chapter 7, so your program can spell any word:

PYTHONedit me
name = input()
for ch in name:
    print(ch, end=" ")
OUTPUT
L u c k y

Type your own name in the Input box and run it again.

Common beginner doubt: "Can I loop over a number, like 12345?" No. A number isn't a sequence of characters, so Python stops with TypeError: 'int' object is not iterable ("iterable" means "something a loop can go through"). Loop over a string or a list instead. You'll see this error again in the last topic.

A for loop over a string gives you one character at a time, spaces included.

your turnType the output

Type what this prints

for ch in "abc": print(ch)
Read the code line by line, then type the output exactly.
your turnPredict the output

What will this print?

nums = [4, 8, 15] print(nums[-1])
Your turn! What will this code show on the screen?

The Loop Variable

The variable between for and in is the loop variable. Python gives it a new value at the start of every iteration: the next item.

PYTHONedit me
marks = [72, 38, 91]
for mark in marks:
    if mark >= 40:
        print(mark, "pass")
    else:
        print(mark, "fail")
OUTPUT
72 pass
38 fail
91 pass

Inside the loop, you can use it like any other variable: print it, do maths with it, or test it with an if from chapter 8. The if block is indented 8 spaces: 4 for the loop, 4 more for the if.

Think of it like a name badge passed down a line of people: whoever is wearing the badge right now is the current item.

Choose a good name

  • Name the list in plural and the loop variable in singular: for mark in marks:, for name in names:.
  • For characters, ch or letter is common: for ch in word:.
  • Any valid variable name works (chapter 4), but a clear name makes the loop read like English.

After the loop

The loop variable keeps the last value it had:

PYTHONedit me
for name in ["Sunny", "Rocky", "Lucky"]:
    pass
print(name)
OUTPUT
Lucky

pass means "do nothing". A block can't be empty, so pass fills the gap.

A common mistake

Printing the list instead of the loop variable prints the whole list every time:

PYTHONedit me
names = ["Sunny", "Rocky"]
for name in names:
    print(names)
OUTPUT
['Sunny', 'Rocky']
['Sunny', 'Rocky']

names is the whole list. name is the one item for this iteration. One letter makes all the difference!

The loop variable holds the current item; use it inside the block.

your turnFix the code

Make it print each name on its own line

It should print: Sunny Rocky Lucky

names = ["Sunny", "Rocky", "Lucky"]
for name in names:
    print(names)
This code does not work yet. Fix it, then press Run.
your turnPredict the output

What will this print?

for n in [3, 6, 9]: total = n * 2 print(n)
Your turn! What will this code show on the screen?

Practice: for loop

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 80.Python Program to Print Each Letter of a WordEasySolve
  2. 81.Python Program to Remove Spaces from a SentenceMediumSolve