19. While Loops
By Bernd Klein. Last modified: 08 Nov 2023.
General Structure of a Loop
In this chapter of our python course, we delve into the powerful world of while loops, a fundamental concept in programming. You will hardly find any programming language with a way to loop over code. While loops provide a mechanism for executing a block of code (or sequence of statements) repeatedly as long as a certain condition holds true. The code within the loop, i.e. the code carried out repeatedly, is called the body of the loop.
Essentially, there are three different kinds of loops:
-
Count-controlled loops A construction for repeating a loop a certain number of times. An example of this kind of loop is the for-loop of the programming language C:
for (i=0; i <= n; i++)
Python doesn't have this kind of loop.
-
Condition-controlled loop A loop will be repeated until a given condition changes, i.e. changes from True to False or from False to True, depending on the kind of loop. There are 'while loops' and 'do while' loops with this behaviour.
-
Collection-controlled loop This is a special construct which allows looping through the elements of a 'collection', which can be an array, list or other ordered sequence. Like the for loop of the bash shell (e.g. for i in *, do echo $i; done) or the foreach loop of Perl.

Python supplies two different kinds of loops: the while loop and the for loop, which correspond to the condition-controlled loop and collection-controlled loop.
Most loops contain a counter or more generally, variables, which change their values in the course of calculation. These variables have to be initialized before the loop is started. The counter or other variables, which can be altered in the body of the loop, are contained in the condition. Before the body of the loop is executed, the condition is evaluated. If it evaluates to False, the while loop is finished. In other words, the program flow will continue with the first statement after the while statement, i.e. on the same indentation level as the while loop. If the condition is evaluated to True, the body, - the indented block below the line with "while" - gets executed. After the body is finished, the condition will be evaluated again. The body of the loop will be executed as long as the condition yields True.
Live Python training
See our Python training courses
A Simple Example with a While Loop
It's best to illustrate the operating principle of a loop with a simple Python example. The following small script calculates the sum of the numbers from 1 to 100. We will later introduce a more elegant way to do it.
n = 100
total_sum = 0
counter = 1
while counter <= n:
total_sum += counter
counter += 1
print("Sum of 1 until " + str(n) + " results in " + str(total_sum))
OUTPUT:
Sum of 1 until 100 results in 5050
Exercise
Write a program, which asks for the initial balance K0 and for the interest rate. The program shall calculate the new capital K1 after one year including the interest.
Extend the program with a while-loop, so that the capital Kn after a period of n years can be calculated.
K = float(input("Starting capital? "))
p = float(input("Interest rate? "))
n = int(input("Number of years? "))
i = 0
while i < n:
K += K * p / 100.0
# or K *= 1 + p / 100.0
i += 1
print(i, K)
print("Capital after " + str(n) + " ys: " + str(K))
OUTPUT:
1 1023.0 2 1046.529 3 1070.599167 4 1095.2229478410002 5 1120.413075641343 6 1146.182576381094 7 1172.544775637859 8 1199.5133054775297 9 1227.1021115035128 10 1255.3254600680937 11 1284.19794564966 12 1313.734498399602 13 1343.950391862793 14 1374.861250875637 15 1406.4830596457768 16 1438.8321700176298 17 1471.9253099280352 18 1505.77959205638 19 1540.4125226736767 20 1575.8420106951712 Capital after 20 ys: 1575.8420106951712
The else Part

Similar to the if statement, the while loop of Python has also an optional else part. This is an unfamiliar construct for many programmers of traditional programming languages. The statements in the else part are executed, when the condition is not fulfilled anymore. Some might ask themselves now, where the possible benefit of this extra branch is. If the statements of the additional else part were placed right after the while loop without an else, they would have been executed anyway, wouldn't they? We need to understand a new language construction, i.e. the break statement, to obtain a benefit from the additional else branch of the while loop. The general syntax of a while loop looks like this:
while condition: statement_1 ... statement_n else: statement_1 ... statement_n
