Register to get access to free programming courses with interactive exercises

The while loop Python Basics

The while loop

The code we write in this course becomes more complex and extensive. Although our programs are still far from real-life programs, we are not making it easier for you.

In this lesson, we will come to one of the most difficult fundamental topics in programming — loops.

Reasons to use loops

Applications can help you manage employees, control your finances, and provide entertainment. Despite the differences, they all execute embedded algorithms that are similar to each other. Algorithms are sequences of actions that lead to expected results.

Suppose we have a book and want to find a particular phrase there. We remember the words but not what page it is on. We have to go through the pages until we find the right one. It is an example of an algorithm.

This algorithm includes logical checks and page lookups. We do not know how many pages we will need to look at. But the viewing process itself is repeated in the same way. To perform repetitive actions, you need loops. Each repetition is an iteration.

We will write a function with a simple loop that will display the string 'Hello!' for n times:

def print_hello(n):
  counter = 0
  while counter < n:
      print('Hello!')
      counter = counter + 1

print_hello(2)
# => Hello!
# => Hello!

Now we will analyze an example function with a loop that displays numbers from one to n.

We pass the n to the function as an argument:

print_numbers(3)
# => 1
# => 2
# => 3

You cannot implement this function with the tools you have learned so far because we do not know the number of outputs beforehand. But this is not a problem for loops:

def print_numbers(last_number):
  # The `i` is short for index (an ordinal number)
  # This is a generally agreed way of expressing the iteration number
  # as a loop counter
  i = 1
  while i <= last_number:
      print(i)
      i = i + 1
  print('finished!')

print_numbers(3)
# => 1
# => 2
# => 3
# => finished!

The while loop

A while loop consists of three elements:

  • The keyword while
  • The predicate — a condition we compute at each iteration
  • The code block — a loop body

Each execution of a body is an iteration. In the example above, print_numbers(3) is three iterations, each displaying the i variable. Here we say:

Execute the loop body as long as the condition i <= last_number is True

Let us look at how this code works when you call print_numbers(3):

# We initialize `i`
i = 1

# The predicate returns true, so we execute the body of the loop
while 1 <= 3
# print(1)
# i = 1 + 1

# The loop body has ended, so it goes back to the beginning
while 2 <= 3
# print(2)
# i = 2 + 1

# The loop body has ended, so it goes back to the beginning
while 3 <= 3
# print(3)
# i = 3 + 1

# The predicate returns false, so the loop runs again
while 4 <= 3

# print('finished!');
# At this point, i is equal to 4, but we do not need it anymore
# The function ends

The end of the loop

The process that generates the loop must stop. The programmer is responsible for this.

Usually, this boils down to introducing a variable called the loop counter. First, we initialize it by giving it an initial value. In our example, it is the line i = 1. The loop condition then checks if the counter has reached its limit.

In the example, the limit depends on the function argument. The program does not execute the body if the loop does not satisfy the condition. The interpreter continues with the instructions after the loop.

If the loop condition is True, we execute the body that contains the stop element. In this case, it is changing the counter. Usually, it is at the end of the body, and you cannot change the counter without a variable. In the example above, the line i = i + 1 is responsible for the change.

At this point, beginners make a lot of mistakes. For example, you may forget to increment the counter or check it incorrectly in the predicate. It will cause the loop to run indefinitely, and the program will never stop. In this case, you need to force it to stop:

def print_numbers(last_number):
  i = 1
  # This loop will never stop
  # and will always print the same value
  while i <= last_number:
      print(i)
  print('finished!')

In some cases, infinite loops are helpful. We will not look at these situations right now, but we can show you what this code looks like:

while True:
  # Doing something

You cannot do without loops when an algorithm for performing a task requires repeating actions, and we do not know how many times we need to repeat those actions.

The syntactic sugar

In Python, constructions like index = index + 1 are widespread, so the creators of the language added an abbreviated version: index += 1.

The only difference is how we write them. The interpreter will turn an abbreviated construction into its expanded form.

Such abbreviations are syntactic sugar because they make code writing a little easier and more pleasant.

There are abbreviated forms for all arithmetic operations and string concatenation:

  • a = a + 1a += 1
  • a = a - 1a -= 1
  • a = a * 2a *= 2
  • a = a / 1a /= 1

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY