Working of the while loop in Python
Let us see how a while loop in Python works. Consider a program that
displays numbers from 1 to 4.
x = 1
while x<5:
print x
x=x + 1
1
2
3
4
Program Output
Code
1
x
x < 9
2 1
True
Working Output
x = 1
while x<5:
print x
x=x + 1
Code
2
x
x < 9
3 1
True
Working Output
2
x = 1
while x<5:
print x
x=x + 1
Code
3
x
x < 5
4 1
True
Working Output
2
3
x = 1
while x<5:
print x
x=x + 1
Code
x = 1
while x<5:
print x
x=x + 1
4
x
x < 5
5 1
True
Working Output
2
3
4
Code
x = 1
while x<5:
print x
x=x + 1
5
x
x < 5
1
False
Working Output
2
3
4
Since condition evaluates to False,
thus loop is terminated

Working of while loop

  • 1.
    Working of thewhile loop in Python Let us see how a while loop in Python works. Consider a program that displays numbers from 1 to 4. x = 1 while x<5: print x x=x + 1 1 2 3 4 Program Output
  • 2.
    Code 1 x x < 9 21 True Working Output x = 1 while x<5: print x x=x + 1
  • 3.
    Code 2 x x < 9 31 True Working Output 2 x = 1 while x<5: print x x=x + 1
  • 4.
    Code 3 x x < 5 41 True Working Output 2 3 x = 1 while x<5: print x x=x + 1
  • 5.
    Code x = 1 whilex<5: print x x=x + 1 4 x x < 5 5 1 True Working Output 2 3 4
  • 6.
    Code x = 1 whilex<5: print x x=x + 1 5 x x < 5 1 False Working Output 2 3 4 Since condition evaluates to False, thus loop is terminated