While loop
while condition:
some work
Until the condition is true the loop will keep on working.
x = 4
while x == 4:
print("Hello There!")
The above code will keep on printing Hello There! infinitely.
x = 0
while x <= 4:
print("Hello There!")
x = x + 1
The above code will print Hello There! 5 times.
| x before increment | x after increment | Is x <= 4 applicable ? |
Will print Hello There! or not ? |
|---|---|---|---|
| 0 | 1 | Yes | Yes |
| 1 | 2 | Yes | Yes |
| 2 | 3 | Yes | Yes |
| 3 | 4 | Yes | Yes |
| 4 | 5 | No | Yes |
Key Breakdown
- The loop runs while
x <= 4. - When
x = 4, it still satisfies the condition, so it incrementsxto5and prints"Hello". - Now,
x = 5, so the conditionx <= 4fails. - The loop immediately stops before printing anything further.
- The condition
x <= 4depends on the originalxat the start of each iteration because:-
Condition Check First:
while x <= 4 -
The loop checks
xbefore executing the body. -
Then
xis Incremented:x = x + 1 -
The increment happens inside the loop, after the condition has already been checked.
-
- x = 0 , check the condition , it is true print hello there, increment x by 1, check the condition again , again it is true , print hello there and it will keep going until x = 4, then the loop will break.