+ 1
When a break breaks?
i=5 while True: print(i) i=i-1 if i<=2: break Why it doesn't print 2 even if it's before the break in the code?
4 ответов
+ 4
Dario Zaccheroni
because the break statement is executed when 'i' is less than or equal to 2`if i<=2`
If you want to print 2 before breaking out of the loop,
change the statement `i==2` insted of`if i<=2`.
+ 3
Dario Zaccheroni
Your mistake is little bit, that you use '=' sign if you remove '=' sign in if block then counting print like this:
5
4
3
2
+ 3
Since are subtracting before the check where you break, it is not printing it.
So when i=3,
1. The prints "i" which is 3
2. Subtracts 1 from "i" that is currently 3 and gives you 2 and assigns "i" to 2
3. Checks if "i" is equal to or less then 2.
4. That check results in True which means the program breaks.
+ 2
The code you've provided prints numbers starting from 5 and decreasing by 1 in each iteration of the `while` loop. However, it stops when `i` becomes less than or equal to 2 due to the `if i<=2` condition and the `break` statement.
In the last iteration, when `i` is equal to 2, the loop prints 2 as expected, and then the `if i<=2` condition is checked. Since 2 is indeed less than or equal to 2, the `break` statement is executed, which immediately exits the loop before another iteration can take place.
So, in this case, the code behaves correctly and stops before printing 1 because the `break` statement interrupts the loop once the condition is met.