Is there a way to do variable assignments(as shown below) using ternary operators in python:
if(x>1):
y="yes"
else:
z="yes"
Something like (x='yes') if(x>1) else (z='yes')
, but this gives an error. Is there any other way to do this?
I know single variable assignments can be done like this: x="yes" if(l==0) else "no"
Edit: Assume x, y & z are assigned with some value before this is run.
You can use the following hack, which employs tuple unpacking:
y, z = ('yes', z) if x > 1 else (y, 'yes')
Don't miss those parentheses.
I wouldn't really recommend using this as it is harder to understand, has one redundant assignment statements, and uses unpacking unnecessarily. I'd recommend going for the normal if
statement wherever you can.
This is what it would be with normal if
s:
if x > 1:
y = 'yes'
z = z
else:
y = y
z = 'yes'
No, you can't do that. You can only have expressions, not statements, inside the ternary. print
works because (in Python 3 at least) it is a function call, therefore an expression; but assignment is always a statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With