Featured

Master Python Loops in Minutes

Loops are essential for efficient coding in Python—learn how to master while and for loops in just minutes!

 

A loop allows you to execute a block of code, the loop body, several times in a row. Python distinguishes between two types of loops: the while loop as a simple loop structure and the for loop for running through more complex data types.

 

The while Loop

The while loop is used to execute a block of code as long as a certain condition is met.

 

Basically, a while loop consists of a loop header containing the condition and a loop body corresponding to the code block to be executed (note that the loop runs as long as the condition is met, not until it is met):

 

while condition:

   Statement

  

   Statement

 

The following example is a somewhat abbreviated variant of the number-guessing game and is intended to illustrate the use of the while loop:

 

secret = 1337

attempt = -1

while attempt != secret:

   attempt = int(input("Guess: "))

print("You did it!")

 

The while keyword introduces the loop header, followed by the desired condition and a colon. In the subsequent lines, the loop body follows, indented one step further. There, a number is read by the user and given the name attempt. This process runs until the condition named in the loop header is met—that is, until the user's input (attempt) matches the secret number (secret).

 

Termination of a Loop

We’d like to enable the user to prematurely cancel a simple guessing game by entering 0. This can be achieved by modifying the loop condition to the following:

 

attempt != secret and attempt != 0

 

This is an acceptable solution in this case, but if the loop condition is complex in itself and several termination conditions are added on top of it, the readability of the source code will suffer significantly.

 

An alternative solution is provided by the break keyword, which can be placed anywhere in the loop body and breaks the loop:

 

secret = 1337

attempt = -1

while attempt != secret:

   attempt = int(input("Guess: "))

   if attempt == 0:

      print("Game will be finished")

      break

print("You did it!")

 

Immediately after the user input, an if statement is used to check whether the input is 0. If this is the case, a corresponding message is output and the while loop is terminated via the break statement.

 

Detecting a Loop Break

In the previous section, the user was given the option to end the number-guessing game prematurely by entering 0. Unfortunately, the success message, which is supposed to signal to the player that he has guessed the number he had searched for, is displayed in any case after the loop has ended, even after the user has canceled the game:

 

Guess: 10

Guess: 20

Guess: 30

Guess: 0

Game will be finished

You did it!

 

So at this point, we’re looking for a way to tell if the loop ended because of the loop condition or because of a break statement. For this purpose, similar to an if statement, a while loop can be extended by an else branch. The code block belonging to this branch is executed exactly once: when the loop has been completely processed—that is, when the condition returns False for the first time. In particular, the else branch doesn’t get executed if the loop was terminated prematurely by a break statement:

 

while condition:

   Statement

  

   Statement

else condition:

   Statement

  

   Statement

 

Let's take look at a concrete example:

 

secret = 1337

attempt = -1

while attempt != secret:

   attempt = int(input("Guess: "))

   if attempt == 0:

      print("Game will be finished")

      break

else:

   print("You did it!")

 

From the user's point of view, this means the success message is output when the correct number has been guessed:

 

Guess: 10

Guess: 1337

You did it!

 

Conversely, if the user enters 0 to cancel the game, the else branch won’t be executed, and thus no success message will be output:

 

Guess: 10

Guess: 0

Game will be finished

 

Aborting the Current Iteration

We have already presented a way to influence the flow of a loop using break. A second option is provided by the continue statement, which, in contrast to break, doesn’t terminate the entire loop but only the current iteration. To illustrate this, let's consider the following example, which so far doesn’t use a continue statement:

 

while True:

   number = int(input("Enter a number: "))

   result = 1

   while number > 0:

      result = result * number

      number = number - 1

   print("Result: ", result)

 

In an infinite loop—that is, a while loop whose condition is fulfilled under all circumstances— a number is read and the result variable is initialized with the value 1. In a subsequent while loop, result is multiplied by number until the condition number > 0 is met. In addition, in each pass of the inner loop, the value of number is decreased by 1.

 

After the inner loop has been passed through, the result variable is output. You’ll probably have already recognized that the sample program calculates the factorial of any number entered:

 

Enter a number: 4

Result: 24

Enter a number: 5

Result: 120

Enter a number: 6

Result: 720

 

However, the preceding code also allows the following input:

 

Enter a number: -10

Result: 1

 

By entering a negative number, the condition of the inner loop is False right from the tart, so the loop won’t be executed at all. For this reason, the value of result is output immediately, which in this case is 1.

 

This is not what you would expect in this case. A negative number is an invalid entry. Ideally, the program should abort the calculation when an invalid number is entered and not display any result. This behavior can be implemented via a continue statement:

 

while True:

   number = int(input("Enter a number: "))

   if number < 0:

      print("Negative numbers are not allowed")

      continue

   result = 1

   while number > 0:

      result = result * number

      number = number - 1

   print("Result: ", result)

 

Immediately after the user's input has been read, an if statement checks whether it’s a negative number. If so, a corresponding error message is output and the current iteration is aborted. This means the program immediately jumps to the next iteration; that is, the loop condition is checked and then the next number is read in by the user. From the user's point of view, this means that after entering a negative number, no result is output but an error message and the user is prompted to enter the next number:

 

Enter a number: 4

Result: 24

Enter a number: 5

Result: 120

Enter a number: -10

Negative numbers are not allowed

Enter a number: -100

Negative numbers are not allowed

Enter a number: 6

Result: 720

 

In retrospect, we want to elaborate here once again on the difference between break and continue. While break terminates the loop completely, continue only terminates the current iteration; the loop itself continues to run:

 

while condition:

  

   if condition:

      continue     # jump back to while condition:

  

   if condition:

      break        # jump to First statement after loop

  

First statement after loop

 

The for Loop

In addition to the while loop described in the previous section, there is another loop available in Python—the for loop. A for loop is used to pass through an iterable object. For this purpose, the for keyword is written, followed by an identifier, the in keyword, and the iterable object. Then the loop body follows, which is indented one level further:

 

for variable in object:

   Statement

  

   Statement

 

The current element of the iterable object can be accessed in the loop body via the selected identifier. Specifically, a for loop can iterate lists or strings—for example:

 

>>> for x in [1,2,3]:

...    print(x)

...

1

2

3

>>> for c in "Python":

...    print(c)

...

P

y

t

h

o

n

 

Note: The for loop as it exists in Python is not a counterpart of the loop construct of the same name in C or Java. It’s comparable to the for each loop in PHP or Perl or to the range-based for loop in C++.

 

The break and continue keywords discussed in connection with the while loop for canceling a whole loop or a single iteration can also be used with the for loop and have the same meaning there. In addition, a for loop can have an else branch similar to the while loop, which is executed exactly when the loop has run through completely and hasn’t been terminated prematurely via break:

 

for variable in object:

   Statement

  

   Statement

else:

   Statement

  

   Statement

 

The for Loop as a Counting Loop

In connection with the for loop, the built-in range function is of particular interest. It creates an iterable object that yields all the integers in a given range:

 

range(stop)

range(start, stop)

range(start, stop, step)

 

The start placeholder represents the number to start with. The loop is terminated as soon as stop has been reached. You should know that the loop counter itself never reaches the value stop, as it always remains smaller. In each iteration the loop counter is incremented by step. Both start and stop as well as step must be integers. Once all values have been specified, the for loop looks like this:

 

for i in range(1, 10, 2):

   print(i)

 

The count variable i now starts with the value 1; the loop is executed as long as i is less than 10, and in each iteration i is incremented by 2. Thus the loop outputs the values 1, 3, 5, 7, and 9 on the screen.

 

A for loop can be used not only in a positive direction; it’s also possible to count down:

 

for i in range(10, 1, -2):

   print(i)

 

In this case, i is set to the value 10 at the beginning of the loop and is decreased by 2 in each pass. The loop runs as long as i is greater than 1, and outputs the values 10, 8, 6, 4, and 2 onto the screen.

 

This makes the for loop an ideal way to revise the example in the last section for calculating the factorial of a number. It’s also an example of how while and for loops can be nested within each other:

 

while True:

   number = int(input("Enter a number: "))

   if number < 0:

      print("Negative numbers are not allowed")

      continue

   result = 1

   for i in range(2, number+1):

      result = result * i

   print("Result: ", result)

 

After an input is made by the user and checked for its sign, a for loop is initiated. The loop counter i of the loop starts with the value 2. The loop runs as long as i is less than number+1; the highest possible value of i is therefore number. In each iteration, the result variable is then multiplied by i.

 

Editor’s note: This post has been adapted from a section of the book Python 3: The Comprehensive Guide by Johannes Ernesti and Peter Kaiser. Johannes is a research scientist at DeepL. He is a graduate mathematician and received his doctorate in applied mathematics from the Karlsruhe Institute of Technology (KIT). Peter is a research scientist at DeepL. He has a degree in computer science and received a doctorate in humanoid robotics from the Karlsruhe Institute of Technology (KIT).

Recommendation

Python 3
Python 3

Ready to master Python? Learn to write effective code with this award-winning comprehensive guide, whether you’re a beginner or a professional programmer. Review core Python concepts, including functions, modularization, and object orientation, and walk through the available data types. Then dive into more advanced topics, such as using Django and working with GUIs. With plenty of code examples throughout, this hands-on reference guide has everything you need to become proficient in Python!

Learn More
Rheinwerk Computing
by Rheinwerk Computing

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

Comments