Line-by-line Explanation
a = 5This initializes the variable a with the value 5.
while a < 20:
This starts a while loop that continues as long as a is less than 20.
print(a)
This prints the current value of a before it's updated.
a = a * 2 - 1
This is the key logic:
-
Multiply a by 2.
-
Subtract 1 from the result.
-
Store the new value back in a.
So the formula is:
new a = (old a × 2) - 1
What Happens in Each Iteration?
| Iteration | Value of a before print | Printed | New value of a (a * 2 - 1) |
|---|---|---|---|
| 1 | 5 | 5 | (5×2)-1 = 9 |
| 2 | 9 | 9 | (9×2)-1 = 17 |
| 3 | 17 | 17 | (17×2)-1 = 33 → loop ends |
Why the loop ends?
Because after the 3rd iteration, a becomes 33, which is not less than 20, so the loop condition a < 20 fails.
✅ Final Output:


0 Comments:
Post a Comment