Python For Loop and While Loop

We learned how we can change the flow of our program with the conditional statements if and else. Another way to control the flow is by using a Python for-loop or a Python while-loop. Loops, in essence, allow you to repeat a piece of code.

Python For-loop

There are two ways to create a loop in Python. Let’s first look at Python’s for-loop. A for-loop iterates over the individual elements of the object you feed it. If that sounds difficult, an example will hopefully clarify this:

>>> for letter in 'Hello':
...     print(letter)

We stumbled upon two concepts here that need and explanation: iterability and objects.

An iterable is an object in Python that can return its members one at a time.

As you can see in the example code, a string of text is iterable. Most of Python’s data types are iterable in some way or another. If you want to know all the nitty-gritty details, head over to the page about iterators. If you’re new to programming, I suggest you keep reading here and save iterators for later.

The next thing we need to tackle: objects. This is a big subject, and it has its own chapter in this tutorial: Python classes and objects. You don’t need to learn about it now to understand Python for-loops. It’s enough to know that everything in Python is an object, and objects have a certain type and certain properties. Being iterable is one of those properties.

So we know that a for-loop can loop over iterable objects. By returning its members one by one, making it available in a variable (in the above example it’s the variable letter), you can loop over each element of an iterable with a for-statement.

The general template for a for-loop in Python is:

for <variable> in <iterable>:
    ... do something with variable

On each iteration, an element from iterable is assigned to variable. This variable exists and can be used only inside the loop. In Python, a string is iterable, and it returns one letter at a time. Hence, our for-loop prints ‘Hello,’ one letter at a time.

Python for-loops and lists

This is the ideal time to look at a new data type: lists. Lists also happen to be iterable; hence they work very well with a for-loop:

>>> mylist = [1, 'a', 'Hello']
>>> for item in mylist:
...     print(item)

We create lists with block quotes. Its contents are objects of whatever type you like, separated by commas, and they don’t need to be of the same type. A list can contain all the types we’ve seen so far: numbers, strings, booleans, and even other lists. Indeed, you can create a list of lists. We can access the individual elements of a list manually too:

>>> mylist = [1, 2, 'Hello', ['a', 'b'] ]
>>> mylist[0]
>>> mylist[0] + mylist[1]
>>> mylist[2]
>>> mylist[3][0]

From the last example, you can see how to access nested lists.

Python While-loop

While the for-loop in Python is a bit hard to understand, because of new concepts like iterability and objects, the while loop is actually much simpler! Its template looks like this:

while <expression is True>:
    do something

You should read this as: “while this expression is True, keep doing the stuff below”.

Let’s take a look at an actual example:

>>> i = 1
>>> while i <= 4:
...     print(i)
...     i = i + 1

Again, we see an expression that follows the while statement. As long as this expression evaluates to True, the block inside of the while-loop executes repeatedly.

In the example above, we start with i = 1. In the first iteration of the loop, we print i and increase it by one. This keeps happening as long as i is smaller than or equal to 4. The output of the print statement confirms that this loop runs four times.

Getting out of an Infinite loop

It’s easy to make a mistake here and find yourself caught in an infinite while-loop. This means the expression never evaluates to False. It happens to the best of us. You can get out of this situation by pressing control+ c at the same time. Let’s artificially create such a situation:

>>> while True:
...     print("Help I'm stuck in a loop!")

The output will look like this:

Help I'm stuck in a loop!
Help I'm stuck in a loop!
Help I'm stuck in a loop!
Help I'm stuck in a loop!
Help I'm stuck in a loop!
Help I'm stuck in a loop!^C
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>

If you look closely, you see the characters ^C right before the error, meaning control + c was pressed at that point. This key combination will get you out of most situations where your program runs indefinitely, so it’s good to remember it!

Infinite loops are less common in for-loops because most iterable objects will at some point run out of elements to iterate over. However, if you ever find yourself in an infinite for-loop, you can use this same trick to get out of it.

More types of loops

Later on in the tutorial, you will also learn about Python list comprehensions. A list comprehension is a powerful construct in Python that we can use to create a list based on an existing list. If you’re new to programming, you should learn about other essentials first, though and I suggest you continue with the following section.

About the author

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python!