-1

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"
cosmos-1905-14
  • 783
  • 2
  • 12
  • 23
  • 2
    You can nest them. I guess `"a" if x >= 90 else "b" if x >= 60 else "c"` would work, although not good for readability. – j1-lee Aug 12 '21 at 18:05
  • 1
    You might want to look up the definition of ternary before using that term. Java has a ternary expression. So called because it has 3 parts. Python does have this useful construct but it's not a ternary expression –  Aug 12 '21 at 18:10
  • 1
    The term is "ternary *operator*" because it's a single operator that takes 3 operands, the operator in Java being `? ... :` rather than a contiguous string. There's really no *technical* reason why `... if ... else ...` couldn't be called a ternary operator for the same reason. Operators usually consist of non-alphanumeric characters like `+` and `*=`, but Python happily refers to `is`, `is not`, `in`, and `not in` as operators. – chepner Aug 12 '21 at 18:16
  • Does this answer your question? [Putting an if-elif-else statement on one line?](https://stackoverflow.com/questions/14029245/putting-an-if-elif-else-statement-on-one-line) – mkrieger1 Aug 12 '21 at 18:25

2 Answers2

1

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.

BTables
  • 4,413
  • 2
  • 11
  • 30
0

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")
mattdood
  • 48
  • 9