Hey folks! Welcome back to another interesting article on Python Programming Language.
Here, we will discuss about python while loop with example and we will also learn about while loop with else.
What is Python while loop?
In Python, while loop is used to execute a given block of code or statement as long as the given condition is satisfied. And if the condition is not satisfied, then the next statement after the loop will be executed. Generally, the while loop is used when the number of iterations are not definite. In python, all non-zero values are interpreted as true and it will interpret None and 0 as false.
Syntax
while expression:
statement(s)
Python while loop flowchart
Simple python while loop example;
i = 2while i < 9:
print(i)
i += 2
Output
24
6
8
Example of python while loop using break statement;
i = 2while i < 9:
print(i)
if (i == 4):
break
i += 2
Output
2
4
Example of python while loop using continue statement;
i = 1while i < 9:
i += 2
if i == 4:
continue
print(i)
Output
35
7
9
While Loop with else
As we know that if the condition is not satisfied, then the next statement after the loop will be executed. But the programmers also has the option of adding else block. Similar to for loop, when the condition is not satisfied or is false then the part of else will be executed.
Syntax
while expression:statement(s)
else:
statement(s)
Let's understand While loop with else with the following illustration;
i = 1while i < 9:
print(i)
i += 2
else:
print("i is no longer less than 9")
Output
13
5
7
i is no longer less than 9
Conclusion
Above we have discussed about python while loop with example and we will also learn about while loop with else. In Python, while loop is used to execute a given block of code or statement as long as the given condition is satisfied.