4

I'm trying to understand the walrus assignment operator.

Classic while loop breaks when condition is reassigned to False within the loop.

x = True
while x:
    print('hello')
    x = False

Why doesn't this work using the walrus operator? It ignores the reassignment of x producing an infinite loop.

while x := True:
    print('hello')
    x = False
  • 4
    `x := True` is evaluated at the top of the loop, every time the top of the loop is reached. So the value of `x` tested is always `True`. `x = False` was not ignored. `x := True` changes the binding of `x` to `True` _regardless_ of what `x` was bound to. – Tim Peters Dec 30 '20 at 22:54
  • Got it! too bad. I really wanted that to work! hehe. – Le_Prometheen Dec 30 '20 at 23:00

1 Answers1

8

You seem to be under the impression that that assignment happens once before the loop is entered, but that isn't the case. The reassignment happens before the condition is checked, and happens on every iteration.

x := True will always be true, regardless of any other code, which means the condition will always evaluate to true.

Carcigenicate
  • 35,934
  • 8
  • 48
  • 81