But please don't write code like that it will quickly become very difficult to understand.) (In 3.8 and above, the := "walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. Synta圎rror: cannot assign to conditional expression > # it can't be on the left-hand side of `=`. > # The `(1 if False else x)` part is actually valid, but > # Python parses this as `x = (1 if False else y) = 2` This means you can't use statements such as pass, or assignments with = (or "augmented" assignments like +=), within a conditional expression: > pass if False else pass Note that conditionals are an expression, not a statement. This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.įor example: > 'true' if True else 'false' If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored. The expression syntax is: a if condition else bįirst condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition.
0 Comments
Leave a Reply. |