Python While Loop

Python while loop statement is used to execute a block of code repeatedly. The syntax of while loop statement as follows:

The condition is an expression that evaluates to boolean value of  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 the while loop statement.

We defined two variables x and max, the initial value of x is 1 and max is 10. The expression x < max is evaluated to be true for the first time so the code inside while loop executed. Inside while loop, we increased x by 1 each time so the expression x < max is only to evaluate to true until x reach 10. Therefore 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 two statements which are used to control loop statements: break and continue.

  • If the break is executed, it immediately terminate the while loop.
  • If the 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.

In this example, we have a list of strings 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 using the continue statement as follows:

In this example, you’ve learned how to use while-loop statement as well as break and continue statements to control the flow of the loop.