Is there a correct way to have two walrus operators in 1 if statement?
if (three:= i%3==0) and (five:= i%5 ==0):
arr.append("FizzBuzz")
elif three:
arr.append("Fizz")
elif five:
arr.append("Buzz")
else:
arr.append(str(i-1))
This example works for three but five will be "not defined".
The logical operator
andevaluates its second operand only conditionally. There is no correct way to have a conditional assignment that is unconditionally needed.Instead use the "binary" operator
&, which evaluates its second operand unconditionally.Correspondingly, one can use
|as an unconditional variant ofor. In addition, the "xor" operator^has no equivalent with conditional evaluation at all.Notably, the binary operators evaluate booleans as purely boolean - for example,
False | TrueisTruenot1– but may work differently for other types. To evaluate arbitrary values such aslists in a boolean context with binary operators, convert them toboolafter assignment:Since assignment expressions require parentheses for proper precedence, the common problem of different precedence between logical (
and,or) and binary (&,|,^) operators is irrelevant here.