Loops: Using While and For in Python

By Russell Barnes. Posted

Learn to use While and For loops in Python programming

When learning programming in Python, you'll quickly discover While and For loops. These are used to repeat blocks of code over and over.

Computers are great because they don’t mind doing the same stuff over and over again. Their hard-working nature makes computers ideal for doing grunt work.

This article is based on Beginner’s Guide to Coding in issue 53 of The MagPi. Issue 54 of The MagPi has a companion piece on learning object orientated programming with a Raspberry Pi

See also:

Discovering loops in Python

When looking at variables, we printed out this nursery rhyme:

print("Polly put the kettle on")
print("Polly put the kettle on")
print("Polly put the kettle on")
print("We’ll all have tea")

We didn’t like the repetition of Polly, so we replaced it with a variable. But this code is foolish in another way: you have to write out the same print line three times.

We’re going to use a loop to get rid of the repetition. The first loop we’re going to look at is a ‘while loop’. In Python 3 IDLE, create a new file and save it as polly.py; enter this code:

name = "Polly"
counter = 0

while counter < 3:
    print(name + " put the kettle on")
    counter = counter + 1

print("We’ll all have tea")

Looking at loops in Python

We start with two variables:

name = "Polly"
counter = 0

Then we use the while statement followed by a condition: counter < 3.

On the next line down, you press the space bar four times to indent the code. Don’t press the TAB key.

while counter < 3:
    print(name + " put the kettle on")
    counter = counter + 1

The < symbol stands for ‘less than’. It checks if the item on the left is less than the item on the right. In this case, it sees if the variable counter (which starts at 0) is less than 3. This condition is known as ‘True’; if it wasn’t, it’d be known as ‘False’.

Finally, enter the last line of code:

print("We’ll all have tea")

It will print ‘Polly  put the kettle on’ three times and then ‘We’ll all have tea’.

While, condition and indent

There are three things here: the while statement, the condition, and the indented text, organised like this:

while condition:

For and lists in Python

The next type of loop is known as ‘for’. This is designed to work with lists.

Lists are a type of variable that contain multiple items (strings, numbers, or even other variables).Create a list by putting items inside square brackets:

banana_splits = ["Bingo", "Fleegle",  "Drooper", "Snorky"]

Now enter banana_splits in the Shell to view the list. It will display the four names inside the square brackets. You can access each item individually using the variable name and square brackets. Enter:


…and you’ll get ‘Bingo’. Lists in Python are zero-indexed; that means the first item in the list is [0]. Here are each of the items. Type them into the Shell to get the names returned:

banana_splits[0] # "Bingo"
banana_splits[1] # "Fleegle"
banana_splits[2] # "Drooper"
banana_splits[3] # "Snorky"

Zero-indexed lists can be confusing at first. Just remember that you’re counting from 0. A for loop makes it easy to iterate over items in a list. Create this program and save it as splits.py:

banana_splits = ["Bingo", "Fleegle", "Drooper", "Snorky"]

for banana_split in banana_splits:

It doesn’t matter what you use as the variable in a for loop, as long as you remember to use it in your indented code. You could put:

for dude in banana_splits:

It’s common to name the list as something plural (such as ‘names’, ‘pages’, and ‘items’) and use the singular version without the ‘s’ for the ‘in’ variable: ‘for name in names’, ‘for page in pages’, and so on.

Comparison operators in Python

These comparison operators are commonly used in conditions to determine if something is True or False:

== equal
!= not equal
< less than
<= less than or equal to
> greater than
>= greater than or equal to
<> less than or greater than

Tabs or spaces in Python?

There’s a massive nerd debate about whether to use spaces or tabs when indenting code. There are valid arguments on both sides, which you can learn in this clip from HBO’s comedy Silicon Valley. Use spaces for now. When you’re a hardcore coder, you can make the argument for tabs.

Watch out for infinite loops when creating a program

You must be careful to change the counter in a while loop, or you’ll get an infinite loop. If you delete the line counter = counter + 1 from our while loop, it will run forever: it never goes above 0, so the indented code runs over and over again. This bug is known as an ‘infinite loop’ and is a bad thing to have in your programs.

From The MagPi store