python-course.eu

19. While Loops

By Bernd Klein. Last modified: 08 Nov 2023.

General Structure of a Loop

Moebius ring as an infinite 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:

Flowchart of a loop

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

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See our Python training courses

See our Machine Learning with 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

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

Upcoming online Courses

See our Python training courses

See our Machine Learning with Python training courses

The else Part

While Loop with 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