not sure why the output is 1 1, instead of 1123?

I took a quiz, the output for this following code is 1 1 instead of 1 1 2 3. And the explanitaion for this answer is that when the code encounter the break(when it reach 2) ,then loops stop.

I understand that the loops stop when it reach 2, but since print() has the same indentation as if() statement, I thought they are excuted seperately, (but both still under for loop). So when number reaches 2, even if the loop stops, it will still execute the print(), for it is still under for loops. Hence, the result is the 1 1 2 3. And no matter what if() statement is, the result is the same.

numbers = [1, 1, 2, 3]
for number in numbers:
  if number % 2 == 0:

2 Answers not sure why the output is 1 1, instead of 1123?

No, the commands are interpreted in order. When the if condition becomes true, the break exits the for loop before the print can execute. The first two loops the break is skipped since 1 % 2 == 0 is false, but 2 % 2 == 0 is true exiting the loop before getting to 3 which would also be true and print... if the loop hadn't already exited.

1 weeks ago

When the break statement executes the execution pointer goes to the next statement outside the loop, not the statement after the if block containing the break statement, so the print function is not called once break is executed as the execution is then outside the loop.

1 weeks ago