WHILE in Python
WHILE loop is especially useful in Python programming, and we use it many times. In the WHILE loop, we start a loop until the condition in the loop becomes True and the loop stops.
In this loop, while first evaluates the desired condition, if the condition is correct, the command inside the loop is executed. After that, the condition is reevaluated and this process continues until the desired condition is violated and when the condition becomes False, the loop will stop.
Syntax:
while condition:
statement
In WHILE loop, we need a condition to stop loop, if we don’t write a condition to stop, loop will continue without stop. here are some examples:
while a > X:
print(‘Y’)
→ a=a-1
while a >= X:
print(a)
→ a-=1
Example :
- a=1
- while a <= 5:
- print (a)
- a=a+1
Output:
1
2
3
4
5
Example :
- a=1
- while True:
- print (a)
- if a==5:
- break
- a=a+1
Output :
The output for this example is same as the last one, I just wanted to teach you the same result in two ways.
Infinite while Loop in Python:
In this model of the loop, if the condition is True, the loop will run for infinity. In Python, to prevent this model of infinite loops, a workaround has been considered that if the compiler detects that the loop is not able to stop, it stops automatically. To avoid such infinite loops, we need a condition in the loop to stop.
while True:
statement
while True :
print(a)
a-=1
→ if a==X:
→ break
Example :
- a=1
- while True:
- print (a)
- a=a+1
Output :
This loop will continue with non-stop
Python While loop with else:
while condition:
statement
else:
statement
Example :
a = 1
while a <= 5:
print(a)
a = a + 1
else:
print(‘a is over‘)
Output :
1
2
3
4
5
a is over
let’s to see video from our YouTube channel
If you want to learn more Python, please click here.