Python 101 - Learning About Loops

There are many times when you are writing code that you will need to find a way to iterate over something. Perhaps you'll need to iterate over the letters in a string or the objects in a list. The process of iterating over something is done via a loop.

A loop is a programming construct that allows you to iterate over chunks. Those chunks could be the letters in the string or the lines of a file.

In Python, there are two types of loop constructs:

  • The for loop
  • The while loop

Besides iterating over sequences, you can use a loop to do the same thing multiple times. One example is a web server that is basically an infinite loop. A server waits, listening for a client to send it a message. When it receives the message, the loop will call a function in response.

Another example is the game loop. When you beat a game or lose a game, the game doesn't usually exit. Instead, it will ask you if you want to play again. This is also done by wrapping the entire program in a loop.

In this chapter you will learn how to:

  • Create a for loop
  • Loop over a string
  • Loop over a dictionary
  • Extract multiple values from a tuple
  • Using enumerate with loops
  • Creating a while loop
  • Breaking out of a loop
  • Using continue
  • Loops and the else statement
  • Nesting loops

Let's get started by looking at the for loop!

Creating a for Loop

The for loop is the most popular looping construct in Python. A for loop is created using the following syntax:

for x in iterable:
    # do something

Now the code above does nothing. So let's write a for loop that iterates over a list, one item at a time:

>>> my_list = [1, 2, 3]
>>> for item in my_list:
...     print(item)
... 
1
2
3

In this code, you create a list with three integers in it. Next you create a for loop that says "for each item in my list, print out the item".

Of course, most of the time you will actually want to do something to the item. For example, you might want to double it:

>>> my_list = [1, 2, 3]
>>> for item in my_list:
...     print(f'{item * 2}')
... 
2
4
6

Or you might want to only print out only the even-numbered items:

>>> my_list = [1, 2, 3]
>>> for item in my_list:
...     if item % 2 == 0:
...         print(f'{item} is even')
... 
2 is even

Here you use the modulus operator, %, to find the remainder of the item divided by 2. If the remainder is 0, then you know that an item is an even number.

You can use loops and conditionals and any other Python construct to create complex pieces of code that are only limited by your imagination.

Let's learn what else you can loop over besides lists.

Looping Over a String

One of the differences of the for loop in Python versus other programming languages is that you can iterate over any sequence. So you can iterate over other data types.

Let's look at iterating over a string:

>>> my_str = 'abcdefg'
>>> for letter in my_str:
...     print(letter)
... 
a
b
c
d
e
f
g

This shows you how easy it is to iterate over a string.

Now let's try iterating over another common data type!

Looping Over a Dictionary

Python dictionaries also allow looping. By default, when you loop over a dictionary, you will loop over its keys:

>>> users = {'mdriscoll': 'password', 'guido': 'python', 'steve': 'guac'}
>>> for user in users:
...     print(user)
... 
mdriscoll
guido
steve

You can loop over both the key and the value of a dictionary if you make use of its items() method:

>>> users = {'mdriscoll': 'password', 'guido': 'python', 'steve': 'guac'}
>>> for user, password in users.items():
...     print(f"{user}'s password is {password}")
... 
mdriscoll's password is password
guido's password is python
steve's password is guac

In this example, you specify that you want to extract the user and the password in each iteration. As you might recall, the items() method returns a view that is formatted like a list of tuples. Because of that, you can extract each key: value pair from this view and print them out.

This leads us to looping over tuples and getting out individual items from a tuple while looping!

Extracting Multiple Values in a Tuple While Looping

Sometimes you will need to loop over a list of tuples and get each item within the tuple. It sounds kind of weird, but you will find that it is a fairly common programming task.

>>> list_of_tuples = [(1, 'banana'), (2, 'apple'), (3, 'pear')]
>>> for number, fruit in list_of_tuples:
...     print(f'{number} - {fruit}')
... 
1 - banana
2 - apple
3 - pear

To get this to work, you take advantage of the fact that you know each tuple has two items in it. Since you know the format of the list of tuples ahead of time, you know how to extract the values.

If you hadn't extracted the items individually from the tuples, you would have ended up with this kind of output:

>>> list_of_tuples = [(1, 'banana'), (2, 'apple'), (3, 'pear')]
>>> for item in list_of_tuples:
...     print(item)
... 
(1, 'banana')
(2, 'apple')
(3, 'pear')

This is probably not what you expected. You will usually want to extract an item from the tuple or perhaps multiple items, rather than extracting the entire tuple.

Now let's discover another useful way to loop!

Using enumerate with Loops

Python comes with a built-in function called enumerate. This function takes in an iterator or sequence, like a string or list, and returns a tuple in the form of (position, item).

This allows you to know the position of the item in the sequence easily while looping over the sequence.

Here's an example:

>>> my_str = 'abcdefg'
>>> for pos, letter in enumerate(my_str):
...     print(f'{pos} - {letter}')
... 
0 - a
1 - b
2 - c
3 - d
4 - e
5 - f
6 - g

Now let's look at the other type of loop that Python supports!

Creating a while Loop

Python has one other type of looping construct that is called the while loop. A while loop is created with the keyword while followed by an expression. In other words, while loops will run until a specific condition is met.

Let's take a look at how these loops work:

>>> count = 0
>>> while count < 10:
...     print(count)
...     count += 1

This loop is formulated in much the same way as a conditional statement. You tell Python that you want the loop to run as long as the count is less than 10. Inside of the loop, you print out the current count and then you increment the count by one.

If you forgot to increment the count, the loop would run until you stop or terminate the Python process.

You can create an infinite loop by making that mistake or you could do something like this:

Since the expression is always True, this code will print out the string, "Program running", forever or until you kill the process.

Breaking Out of a Loop

Sometimes you want to stop a loop early. For example, you might want to loop until you find something specific. A good use case would be looping over the lines in a text file and stopping when you find the first occurrence of a particular string.

To stop a loop early, you can use the keyword break:

>>> count = 0
>>> while count < 10:
...     if count == 4:
...         print(f'{count=}')
...         break
...     print(count)
...     count += 1
... 
0
1
2
3
count=4

In this example, you want the loop to stop when the count reaches 4. To make that happen, you add a conditional statement that checks if count equals 4. When it does, you print out that the count equals 4 and then use the break statement to break out of the loop.

You can also use break in a for loop:

>>> list_of_tuples = [(1, 'banana'), (2, 'apple'), (3, 'pear')]
>>> for number, fruit in list_of_tuples:
...     if fruit == 'apple':
...         print('Apple found!')
...         break
...     print(f'{number} - {fruit}')
... 
1 - banana
Apple found!

For this example, you want to break out of the loop when you find an apple. Otherwise you print out what fruit you have found. Since the apple is in the second tuple, you will never get to the third one.

When you use break, the loop will only break out of the innermost loop that the break statement is in.

You can use break to help control the flow of the program. In fact, conditional statements along with break are known as flow control statements.

Another statement you can use to control the flow of your code is continue. Let's look at that next!

Using continue

The continue statement is used for continuing to the next iteration in the loop. You can use continue to skip over something.

Let's write a loop that skips over even numbers:

>>> for number in range(2, 12):
...     if number % 2 == 0:
...         continue
...     print(number)
... 
3
5
7
9
11

In this code, you loop over a range of numbers starting at 2 and ending at 11. For each number in this range, you use the modulus operator, %, to get the remainder of the number divided by 2. If the remainder is zero, it's an even number and you use the continue statement to continue to the next value in the sequence. This effectively skips even numbers so that you only print out the odd ones.

You can use clever conditional statements to skip over any number of things in a sequence by using the continue statement.

Loops and the else Statement

A little known fact about Python loops is that you can add an else statement to them like you do with an if/else statement. The else statement only gets executed when no break statement occurs.

Another way to look at it is that the else statement only executes if the loop completes successfully.

The primary use case for the else statement in a loop is for searching for an item in a sequence. You would use the else statement to raise an exception if the item was not found.

Let's look at a quick example:

>>> my_list = [1, 2, 3]
>>> for number in my_list:
...     if number == 4:
...         print('Found number 4!')
...         break
...     print(number)
... else:
...     print('Number 4 not found')
... 
1
2
3
Number 4 not found

This example loops over a list of three integers. It looks for the number 4 and will break out of the loop if it is found. If that number is not found, then the else statement will execute and let you know.

Try adding the number 4 to the list and then re-run the code:

>>> my_list = [1, 2, 3, 4]
>>> for number in my_list:
...     if number == 4:
...         print('Found number 4')
...         break
...     print(number)
... else:
...     print('Number 4 not found')
... 
1
2
3
Found number 4

A more proper way of doing this would be to raise an exception rather than printing a message.

Nesting Loops

Loops can also be nested inside of each other. There are many reasons to nest loops. One of the most common reasons is to unravel a nested data structure.

Let's use a nested list for your example:

>>> nested = [['mike', 12], ['jan', 15], ['alice', 8]]
>>> for lst in nested:
...     print(f'List = {lst}')
...     for item in lst:
...         print(f'Item -> {item}')

The outer loop will extract each nested list and print it out as well. Then in the inner loop, your code will extract each item within the nested list and print it out.

If you run this code, you should see output that looks like this:

List = ['mike', 12]
Item -> mike
Item -> 12
List = ['jan', 15]
Item -> jan
Item -> 15
List = ['alice', 8]
Item -> alice
Item -> 8

This type of code is especially useful when the nested lists are of varying lengths. You may need to do extra processing on the lists that have extra data or not enough data in them, for example.

Wrapping Up

Loops are very helpful for iterating over data. In this article, you learned about Python's two looping constructs:

  • The for loop
  • The while loop

You also learned about flow control using the break and continue statements. Finally you learned how to use else in your loops and why you might want to nest loops.

With a little practice, you will soon become quite adept at using loops in your own code!

Copyright © 2024 Mouse Vs Python | Powered by Pythonlibrary