Python While Loop
Python while loop statement is used to execute a block of code repeatedly. The syntax of while loop statement as follows:
while condition:
body
Condition is an expression that evaluates to be true or false. As long as the expression is true, the code inside the while loop body will be executed.
Let’s take a look at an example of using while loop statement.
max = 10
x = 1
while x < max:
print x
x = x + 1
We defined two variables x and max, the initial value of x is 1 and max is 10. The expression x < max evaluated to be true for the first time so the code inside while loop get executed. Inside while loop, we increased x by 1 each time so the expression x < max is to be true until x reach 10. There the code was executed 9 times.
Note that in order to use while loop statement, you must have an exit point to escape the loop; otherwise you will have an infinitive loop.
Break and continue
Python provides you two statement which is used to control while loop statement.
- If the break is executed, it immediately stops terminate the while loop.
- If continue is executed, it skips the remaining code after it. Expression in the while loop statement is evaluated again and the loop proceeds as normal
Let’s take an example of using break and continue statements.
list =['while','loop','demo','with','break','and','continue']
max = len(list)
word = "break"
i = 0
while i < max:
print("Checking element:",i)
if word == list[i]:
print("Find it at position:",i)
break
i = i + 1
In the above example, we have a list of string which contains the string “break”. We examined from the first element to the end, if we find the element we print it out and escape the loop.
We can rewrite the code snippet above by using continue statement as follows:
list =['while','loop','demo','with','break','and','continue']
max = len(list)
word = "break"
i = 0
while i < max:
print("Checking element:",i)
if word != list[i]:
i = i + 1
continue
print("find it at ",i)
i = max # stop the loop