Python Loops (while, for, break, continue, pass) Tutorial

In this tutorial we learn how to control the flow of an application through iteration logic with while and for loops. We also cover control statements like break, continue and pass.

Control program flow with loops

By default, the flow of a program written in Python is sequential. Often times we may need to alter the flow to allow specific code to repeat many times.

For this purpose, Python provides us with various types of looping logic, which are capable of repeating blocks of code statements. This helps with repetitive tasks and dealing with larger amounts of data.

As an example, let’s consider a database with users in a mailing list. The mailing list contains entries for a name and email address.

If we want to send an email to everyone, we would need to loop through all the users in the database. Each time we get to the next user, we send an email.

Concept:
# for user in database:
    # send email to user

The interpreter will start at the first user and send them an email. If there are more users in the database, it will start again at the top of the loop with the second user and send them an email as well.

This will continue until it has gone through all the users in the database or we tell it to quit manually in the code.

Python makes to two types of loop statements available to us:

  • The while loop
  • The for loop

While loop

A while loop is like an if statement. We can create a condition and if the condition is met, we start executing the code block. The while loop will then continue to execute the code block over and over until the condition is false, or we tell it to stop.

  The syntax for a while loop is almost identical to an if statement, but we use the keyword while instead.

Syntax:
while condition:
    code to execute multiple times

We need a way to stop our while loop otherwise we run the risk of looping forever. This is known as an infinite loop and can slow down the application significantly or even crash it.

Example: while loop with a counter variable
counter = 0

while counter <= 10:
    print(counter)
    counter += 1

The counter in the example above complicates the loop, so let’s take this step by step:

  1. First, we set up a variable called “counter”, we’ll use it to stop the loop.
  2. Next, we specify the condition to say: keep looping until the counter reaches the value of 10.
  3. In the code block we print the counter and add 1 to the counter to increment. So, the next iteration of the loop will start at the next value.

When the code executes it will:

  1. Check if the counter is 10, and if not it will continue the loop.
  2. Print the number of counter.
  3. Add 1 to the counter with the += operator.

This cycle continues until it sees that counter is 10, turning the condition false and allowing the loop to stop. When the loop stops it will continue to the next statement(s) after and outside the loop.

The easiest way to understand a while loop is to run the example above and look at the output.

For Loop

We use a for loop to iterate over a collection or sequence of items such as a string, list, dictionary etc.   A for loop in Python isn’t quite the same as a for loop in other programming languages. If you’re familiar with a language like C# you can compare a Python for loop to a C# foreach loop.   When creating a for loop we need 2 things:

  1. Something to loop over, a list, dictionary, string etc.
  2. A temporary variable that we use to access the data.

For this example, we’ll use a simple string. We haven’t covered collections like lists or dictionaries yet. We will revisit loops in those lessons.

String as example

In our Python Strings tutorial we explained that a string is actually an array of characters. Let’s recap.

Think of a string as a table with one big row, a single letter in the string occupying one cell. We can use a simple string:

Example: string
 message = 'Hello World'

If we use the table analogy, our table would look like this:

Hello World

Because each letter is actually on its own, we can loop through the string and pull out the individual letters to print, like we printed the counter in the while loop.

This loop is written with the for keyword followed by a temporary variable. Then we write the in keyword followed by the collection’s name that we want to loop through.

Syntax: for..in loop
for temp_var in collection:
    code to execute

We don’t need a way to stop the loop because the collection will have a known size. The interpreter will only loop for the amount of items in the collection.

Example: using a for loop to loop through a string
message = 'Hello World'

for letter in message:
    print(letter)

Once again, we’ll take it step by step:

  1. We set up a variable with a string that has 11 characters. The interpreter will know to run this loop only 11 times.
  2. We set up our temporary variable to hold each item (letter) in the string. Effectively, the statement reads:
    • for each letter in the “message” string, execute the statement in the code block
  3. Finally, we print out each letter as the loop goes through them.

The easiest way to understand a for loop is to run the example above and look at the output.

When we run the code, there is an empty line between o and W. That’s because a space is counted as a character.

Loop Control Statements

Loop control statements change the flow of execution inside the loop. Python makes three loop control statements available to us.

  • break
  • continue
  • pass

How to use the break control statement

The break control statement will stop execution of the loop and break out of it, jumping to the next statement after and outside the loop.   We use the break keyword anywhere we need inside the code block.

Syntax:
for temp_var in collection:
    code to execute
    break
Example: break out of a loop
message = "Hello World"

for letter in message:
    print(letter)
    if letter == "o": break

print("\nI am the next statement after the loop")

In the example above our for loop now has an added if statement in the code block stating that if the loop reaches the letter o, it must break out of the loop and jump to the next statement after and outside the loop, which is a printed string.

When we run the code we can see it only prints the letters H e l l o because it terminated the loop after it found the o.

The o is printed because the break statement is after the print statement, if we were to switch them around the o would not print.

Example:
message = "Hello World"

for letter in message:
    if letter == "o": break
    print(letter)

print("\nI am the next statement after the loop")

In the example above, when the loop gets to the letter o, it breaks out of the loop before it has a chance to print. So, the letter o never gets printed.

How to use the continue control statement

Where the break statement breaks out of the loop, the continue statement continues to the next iteration. It skips back to the start of the loop.   We use the continue statement where we need it inside the code block.

Syntax:
for temp_var in collection:
    code to execute
    continue
Example: continue to next loop iteration
message = "Hello World"

for letter in message:
    if letter == "o": continue
    print(letter)

print("\nI am the next statement after the loop")

We use the same code as with the break statement. However, we replace break with continue .

When we run the code we see that it skipped both o letters. When the loop got to each letter o, the continue statement told it to skip back to the start of the loop before the letter could print.

How to use the pass control statement

The pass statement is a null operation, which means that nothing happens when it executes. It’s useful as a placeholder for code that will exist but has not been written yet.

Similar to a break or continue statement, we write the keyword pass where we want it in our code.

Syntax:
for temp_var in collection:
    code to execute
    pass
Example: using the pass null operation in a loop
message = "Hello World"

for letter in message:
    if letter == "o": pass
    print(letter)

print("\nI am the next statement after the loop")

In the example above we pass when we get to the letter o. When the code executes we can see that nothing is affected.

In most cases we use it in skeleton code where we know we want a loop in a specific section of the code, but the looping execution logic has not been written yet.

Example: using the pass null operation in skeleton code
message = "Hello World"

for letter in message:
    pass

Summary: Points to remember

  • We can loop through sections of code multiple times with the while or for loops.
  • A while loop needs a counter to help it stop looping. Without a counter, a while loop could potentially loop infinitely.
  • While loops are used when we don’t know beforehand how many times a loop should run.
  • A for loop is similar to a foreach loop in other languages, such as C#.
  • For loops are used when the interpreter can calculate beforehand how many times the loop will run, like a collection.
  • The break control statement breaks out of a loop. It tells the interpreter to move on to the next section of code outside and below the loop.
  • The continue statement skips whatever code is below it and returns to the top of the loop to start the next iteration.
  • The pass statement is a null operation and tells the interpreter to skip the loop.