Python While Loop
Python While Loop is used to execute a set of statements repeatedly based on the output of a boolean expression. While Loop is one the Looping statements available in Python programming.
In this tutorial, we shall learn how to write a while loop in Python program, and some the scenarios where while loop is used, with the help of example programs.
Syntax – While Loop
The syntax of while loop is given below.
while boolean_expression: statement(s)
The statements inside the while loop have to be indented as shown in the syntax. Usually when using a while loop, there can be many variables involved in the boolean expression. The variables’ initialization and update has to be taken care by the programmer.
Example 1: Python While Loop
In the following Python program, we will use while loop and print numbers from 0 to 3.
a = 4 i = 0 while i<a: print(i) i+=1
0 1 2 3
Let us analyze this example. We have used i and a in the boolean expression and during the loop a remains constant and i kind of changes with every loop iteration. So, for every iteration, i increments and reaches a value where the boolean expression becomes false and the control comes out to the loop.
Programmer has to take care that the while loop breaks at some point in the execution. Else, it may iterate indefinitely, which may not be desired all the times.
Example 2: While Loop with Break Statement
You can break the while loop prematurely before the boolean expression becomes false. This can be done using break keyword.
In the following example, we will break the loop prematurely using a break statement.
a = 4 i = 0 while i<a: print(i) i+=1 if i>1: break
During the iteration, when i becomes 2,
i>1 returns True, executing break statement. And therefore the execution of while loop is wrapped up.
Example 3: While Loop with Continue
You can skip executing an iteration of while loop using continue keyword.
In this example, we will skip the executing of statements in while loop when i=2. While loop continues with the next iterations.
a = 4 i = 0 while i<a: if i==2: i+=1 continue print(i) i+=1
0 1 3
Observe that we taken care of updating i when we are skipping an iteration. If you do not update i when you are skipping, your while loop may enter infinite loop.
In this tutorial of Python Examples, we have learned how to write and use while loop, use break and continue statements with while loop, with the help of well detailed examples.