Python - One line if-elif-else statement
Try:
print {1: 'one', 2: 'two'}.get(a, 'none')
The "ternary" operator in Python is an expression of the form
X if Y else Z
where X
and Z
are values and Y
is a boolean expression.
Try the following:
print "one" if a==1 else "two" if a==2 else "none"
Here, the value of the expression "two" if a==2 else "none"
is the value returned by the first when a==1
is false. (It's parsed as "one" if a == 1 else ( "two" if a==2 else "none")
.) It returns one of "one"
, "two"
, or "none"
, which is then passed as the sole argument for the print
statement.