How to do something while a condition is true in python ?


In python to create a loop based on a condition, there is the while statement:

while (condition is true):
    (do something)

Examples

Create a simple while loop

Simplest example of a while loop in python:

i = 0
while i < 10:
    print(i)
    i += 1

returns

0
1
2
3
4
5
6
7
8

Note: be careful that the condition changes in the while loop or you will create an infinite loop (to avoid that see last section)

Create a simple while loop with a else statement

When the condition is not true anymore, it is also possible to do something using else:

i = 0
while i < 10:
    print(i)
    i += 1
else:
    print('done')

returns

0
1
2
3
4
5
6
7
8
9
done

Break the loop

To interupt a while loop a solution is to use break:

i = 0
while i < 10:

    print(i)

    i += 1

    if i == 4:
        break

returns

0
1
2
3

Avoid infinite loop by checking the execution time

To prevent infinite loop, for example here we forgot to update the value of the varibale i, a solution is to add a condtion a execution time. For example if it takes more than 5 seconds we can ask to stop the loop:

import time

start_time = time.time()

i = 0
while i < 10:

    current_time = time.time()
    runtime = current_time - start_time

    if runtime > 5:
        break

References