I want to use elif in ternary operator, but it does not work. Is there any workaround?
"a" if x >= 90 "b" elif x >= 60 else "c"
I want to use elif in ternary operator, but it does not work. Is there any workaround?
"a" if x >= 90 "b" elif x >= 60 else "c"
You cannot do an elif in a ternary operator. You can, however, do a chained ternary like:
i=15
x = 10 if i <15 else 1 if i > 15 else 0
I'm not saying a long chain like this is always recommended, though; you shouldn't really sacrifice readability to cut down on your line count.
You chain another ternary on the end to do the elif
portion; however, readability takes a nose dive.
Further reading from this blog after I Googled 'how to do elif in python ternary operations'
print("not equal") if some_condition != some_other else print("greater") if some_condition >= some_other else print("other thing")