Python Walrus Operator in While Loops


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:
    x = False

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

while x := True:
    x = False


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.

Answered By – Carcigenicate

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published