Skip to main content

Python: 11 Iteration - Loops - While

Iteration is the programming concept of repeating or looping sections of code.

In Python there are two main types of loops while and for.

The while loop runs code so long as a condition is true.

While loops are often used when you do not know how many times a loop needs to run.

A while loop will always check the condition first and then run the code inside the while loop if the condition was true.

If the loop condition never becomes false it will never end. This is known as an infinite loop and is a common logic problem when programming.

The code thare we want to loop follows a : on the following line and is indented.

Below is an example of an infinite loop in Python. The variable number contains 1. The while loop checks if 1 == 1. This is true so the code runs. The program then prints the message "In loop" as the program is at the end of the loop if goes back to the condition and checks it again. As it's still true it runs the indented code block again.

number = 1
while number == 1:
print("In loop")

The next example will print the numbers 1,2,3,4 and then End of Program.

It runs through the loop four times. The first time i = 1, it runs the while loop code block and adds one to i in the last line of the block. i is now 2 and it checks if 2 < 5, this is still true so the program runs the code block again. It continues until i = 5. 5 is not less than 5 so the program stops.

i = 1
while i < 5:
print(i)
i += 1
print("End of program")

For more information about Python while loops look on W3 Schools.