+ 3
Why 'while <= ' stops this from working?
I just wonder, if this works just fine >>>i = 1 >>>while i <=5: >>> print(i) >>> i = i + 1 Why I don't get any output for this? >>>i = 5 >>>while i <=2: >>> print(i) >>> i = i - 1 I should get a similar output like this one, shouldn't I? >>>i = 5 >>>while True: >>> print(i) >>> i = i - 1 >>> if i <= 2: >>> break Why (instead of <=2) I have to put >=2 in the second case to make it work?
2 Answers
+ 3
A while loop runs while a condition is true.
In second case, i is 5, but the condition says, i has to be <= 2.
So your loop doesn't even start.
In your third example, you tell the loop to just run until you break it. And you break it as soon as i becomes 2. But it has run before already.
In second case you said under which condition the loop should run, the other time you told it when to stop - the opposite!
If in second case you had written...
while not i<=2:
...
... then it would have worked.
+ 2
Think about it tebkanlo as when you reach <= 2 that while is done... but >= 2 means anything beyond 2 will print