Python While Loop - Syntax, Examples
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 of the looping statements in Python.
In this tutorial, we learn how to write a while loop in Python program, and some of the scenarios where while loop is used, with the help of examples.
Syntax
The syntax of while loop statement is
while condition:
statement(s)
where
while
is Python keyword, condition
is a boolean expression, and statement(s)
is a block of code.
The statement(s) inside the while loop have to be indented as shown in the syntax.
When using a while loop, there can be one or more variables in the boolean expression. These variable(s) has/have to be initialized before while loop, and updated inside the while loop.
Care has to be taken by the programmer that the condition breaks or fails, else this while loop may become an infinite while loop.
Examples
1. Print 1 to N using While loop
In the following Python program, we will use while loop and print numbers from 0 to 3.
Python Program
n = 4
i = 1
while i <= n:
print(i)
i+=1
Output
1
2
3
4
Let us analyze this example. We have used i and n in the boolean expression. During the loop, n 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.
2. Break While loop
We can break the while loop prematurely before the condition becomes false. This can be done using break keyword.
In the following example, we break the while loop prematurely using a break statement.
Python Program
a = 4
i = 0
while i<a:
print(i)
i+=1
if i>1:
break
Output
0
1
During the iteration, when i
becomes 2
, i>1
returns True
, executing break statement.
3. While loop with Continue statement
We may skip executing an iteration of while loop using continue keyword.
In this example, we skip executing statements in while loop when i=2
. While loop continues with the next iterations.
Python Program
a = 4
i = 0
while i<a:
if i==2:
i+=1
continue
print(i)
i+=1
Output
0
1
3
Observe that we have taken care of updating i
when we are skipping an iteration. If we do not update i
in this case, our while loop could become infinite loop.
Summary
In this tutorial of Python Examples, we learned how to write a while loop in Python program; use break and continue statements with while loop, with the help of well detailed examples.