I'm trying to execute code like the following
y = 6
x = 7 if y/6 == 1 elif y/6 == 2 x = 5 else x = 4
Simply, it does not work. I'm not sure how to make elif statements fit into defining variables on one line.
I'm able to use else statements like the following
y = 6
x = 7 if y/6 == 1 else x = 4
I want to be able to set x to 7 if y/6 ==1, x to 5 if y/6 == 2 and x to 4 if neither of those are the case
CodePudding user response:
Use chained ternary expressions:
>>> y = 6
>>> x = 7 if y/6 == 1 else 5 if y/6 == 2 else 4
>>> x
7
The way to read this is:
x = ((7) if y/6 == 1 else ((5) if y/6 == 2 else (4)))
i.e. each expr1 if pred else expr2
is itself an expression.
CodePudding user response:
You only need x = ...
once at the beginning. The rest of the expression is evaluated as a value that will be assigned to x. You don't need to mention x
again.
x = 7 if y/6 == 1 else 5 if y/6 == 2 else 4
In general, the syntax is
var = value1 if condition1 else value2 if condition2 else value3