Ani Menon Ani Menon - 6 months ago 17
Python Question

Assign two variables with ternary operator

I know a simple

if
like this :

if condition:
print('yes')
else:
print('nah')


becomes this:

print('yes') if (condition) else print('nah')


My Question is, could I do variable assignments(as shown below) using ternary operator:

if(x>1):
y="yes"
else:
z="yes"


Something like
(x='yes') if(x>1) else (z='yes')
, but this given 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.

Answer

You can use exec function like this:

exec("y='yes'" if x > 1  else "z='yes'")
Comments