Loops and Iterability

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 loops.

While-loop

The simplest form of a loop is the while-loop:

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

The while statement is followed by an expression. As long as this expression evaluates to True, the block inside of the while loop is executed 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.

You might find yourself caught in an infinite while loop, meaning the expression never evaluates to True. You can get out of this situation by pressing + 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>
KeyboardInterrupt

If you look closely, you see the characters ^C right before the error, meaning + 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!

For-loops

Another loop variant is the for-loop. Instead of waiting for an expression to turn to True like in a while-loop, it iterates over the individual elements of the object you feed it:

>>> for letter in 'Hello':
...     print(letter)
... 
H
e
l
l
o

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

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

In Python, it's often said that everything is an object. Objects are a big subject; they deserve a seperate chapter. For now, it suffices to know that a for-loop can use iterable objects. By returning its members one by one, you can loop over each element of an iterable with a for-statement.

The general template for a for-loop is:

for <variable> in <iterable>

On each iteration, an element from the iterable is assigned to . 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.

Lists

Let's look at one more new data type before we wrap up. It's the list, and it also happens to be iterable:

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

A list can be created 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 (creating a list of lists). You can get to the individual elements of a list manually too:

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

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


If you liked this page, please share it with a fellow learner: