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 = 0while i < 10:print(i)i += 1
returns
012345678
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 = 0while i < 10:print(i)i += 1else:print('done')
returns
0123456789done
Break the loop
To interupt a while loop a solution is to use break:
i = 0while i < 10:print(i)i += 1if i == 4:break
returns
0123
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 timestart_time = time.time()i = 0while i < 10:current_time = time.time()runtime = current_time - start_timeif runtime > 5:break
