Python While Loops
What is a while loop in Python?
The while loop is used to iterate over a block of code as long as the condition is true.
The while loop is often used when we don't know the number of iteration of a loop.
Syntax of While Loop
The syntax of the while loop statement can be given as follows:
while condition:
statement(s)
In the while loop, the condition is checked first. Statements of the body are executed only if the condition evaluates to True. After each iteration, the condition is checked again. The end of the loop occurs when the condition evaluates to False.
The statement(s) in the loop body is separated by an indentation, and it is executed every time the condition is true.
The body of the while loop starts with indentation, and the first unindented line marks the end.
Python interprets non-zero values as True. The 0 and None values are interpreted as False.
Flowchart of While Loop
The flowchart of the while loop statement is as follows:
While Loop - Example
In the following example, we will print the value of the "i" variable as long as "i" is less than 5.
i = 0
while i < 5:
print(i)
i = i+1
After running the above code, the output will be :
0
1
2
3
4
Note: Remember to increase the counter variable's value inside the body of the loop. If not, the loop will continue forever (infinite loop).
The break Statement
In Python, you can use the break statement to stop the while loop before it is finished.
Let us see the following example: we will exit the loop when the value of "i" is 4.
i = 0
while i < 7:
print(i)
if i == 4:
break
i +=1
The output of the above code will be:
0
1
2
3
4
The continue Statement
You can use the continue statement to stop the while loop's current iteration and continue with the next.
In the following example, we will print all the numbers from 1 to 6, but we will ignore the 4.
i = 0
while i < 7:
i += 1
if i == 4:
continue
print(i)
After executing the above code, the output will be:
1
2
3
5
6
7
While loop with else
A while loop can have an optional else block. The else part is executed when the loop is finished.
In the following example, we will print all numbers from 0 to 6 and print a message when the loop is finished.
i = 0
while i < 7:
print(i)
i += 1
else:
print("The end of the loop")
The output will be:
0
1
2
3
4
5
6
The end of the loop
The else part is ignored when the break statement is used to stop a while loop. However, a while loop's else part executed if not break happens.
In the following example, we will use the break statement to stop a while loop, so the else part will be ignored.
i = 0
while i < 7:
print(i)
if i == 4:
break
i += 1
else:
print("The end of the loop")
The output of the above code will be as follows:
0
1
2
3
4
As you can see above, when the break statement is executed in a while loop, the else part will be ignored.
