2

Not quite sure on how this works as I'm still in my introductory class for python. My question is, during a while loop, if the conditional you set inside of it (example while x != 1) if you're inside the loop and your break conditional is met, will it terminate instantly or will it continue on down the loop and then terminate once it loops back up to the top?

mossy
  • 61
  • 7

2 Answers2

1

In your example, while the x is not equal to 1 the loop will work, and if it equals to 1 the loop ends. However you can also have break, so when the condition of break command is met the loop exits

paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

The condition is checked just before the loop restarts, not after every statement in the loop:

x = 0
while x < 1:
    x += 1
    print(x)

will output

1

Initially, the loop is entered because x == 0 < 1. After x += 1, now x == 1, but we don't check the loop condition again until after the body completes. So we execute print(1), then check if 1 < 1 again. Since that's false, the loop terminates.

chepner
  • 497,756
  • 71
  • 530
  • 681