-2

I just have a little bit confusion when I using python ternary operator. The sample code shown below:

a = 10
b = 5 if a < 9 else "s"

The else can add a string statement like 's' or '#' or ''. What is the meaning of the statement do? How to covert it as a traditional if-else statement?

Thanks

Di Wang
  • 33
  • 7
  • The `else` is required for ternary operators, this statement is assigning the value 5 to the variable `b` if the boolean expression `a < 9` evaluates to `True`, otherwise, the value `"s"` is assigned to `b`. It wouldn't make sense to assign a value based on a condition and not also provide a value to fall back on if the condition isn't satisified. – blorgon Apr 27 '21 at 02:02
  • 1
    See also https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator – larsks Apr 27 '21 at 02:02
  • Does this answer your question? [Putting a simple if-then-else statement on one line](https://stackoverflow.com/questions/2802726/putting-a-simple-if-then-else-statement-on-one-line) – Gino Mempin Apr 27 '21 at 05:30

1 Answers1

1

It means, if a < 9, the vale of b is 5, else the value is "s". It's the same with

if a < 9:
  b = 5 
else:
  b = 's'
Kevin Yobeth
  • 616
  • 5
  • 14