The while loop

The while loop in Python is used to repeatedly execute statements as long as the given condition is true. When the condition becomes false, the program execution is resumed at the next statement after the body of the while loop. The syntax of the while loop is:

while condition:
	statements

Here is a simple example of the while loop in action:

x = 0

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

The code above will print the value of the variable x as long as x is less than 10. The output:

>>> 
0
1
2
3
4
5
6
7
8
9
>>>

Notice how we have added 1 to x in each loop iteration (the x += 1 statement). This is important because without it, the loop would be an endless loop, meaning that it would never end – the value of x would never increase and the loop would execute forever. Try removing the x+=1 line and see what happens.

Here is another example:

x = int(input('Enter a number: '))

while x != 0:
    y = x*10
    print(x, 'times 10 equals', y)
    x = int(input('Enter a number. Press 0 to quit: '))

The code above asks the user to enter a number and it multiply it by 10. If the user enters 0, the program will terminate:

Enter a number: 14
14 times 10 equals 140
Enter a number. Press 0 to quit: 54
54 times 10 equals 540
Enter a number. Press 0 to quit: 47
47 times 10 equals 470
Enter a number. Press 0 to quit: 11
11 times 10 equals 110
Enter a number. Press 0 to quit: 2
2 times 10 equals 20
Enter a number. Press 0 to quit: 14
14 times 10 equals 140
Enter a number. Press 0 to quit: 0
>>>
Geek University 2022