Python Tutorial
Python While Loop
What is While Loop in Python?
In the Python programming language, a while loop statement runs a target statement repeatedly as long as a specific condition is true.
Syntax
while expression:
statement(s)
Example:
#!/usr/bin/python
count = 0
while (count < 7):
print( 'The count is:', count)
count = count + 1
print ("bye bye!")
Output:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
bye bye!
The Infinite Loop in Python
If a condition is never FALSE, a loop becomes endless. While loops should be used with caution since it's possible that this condition will never resolve to a FALSE value. As a result, a never-ending cycle is created. An endless loop is a name given to such a loop.
Example:
var = 1
while var == 1 : # This constructs an infinite loop
num = input("Enter a number:")
print ("You entered: ", num)
print ("Good bye!")
Output:
Enter a number: 20
You entered: 20
Enter a number: 29
You entered: 29
Enter a number: 3
You entered: 3
.
.
.
.
.
You entered: 20
Enter a number: 29
You entered: 29
Enter a number: 3
You entered: 3
.
.
.
.
.
Example:
while True : # This constructs an infinite loop
num = input("Enter a number:")
print ("You entered: ", num)
print("Good bye!")
Output:
Enter a number: 20
You entered: 20
Enter a number: 29
You entered: 29
Enter a number: 3
You entered: 3
.
.
While loop with else
Python enables you to use an else statement with a loop statement. When using the else statement with a while loop, it is performed when the condition turns false.
Example:
count = 0
while count < 5:
print (count, "is less than 5" )
count = count + 1
else:
print(count, "is not less than 5")
Output:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5