0

Java, c, c++ both have syntactic sugar like this:

int a = condition ? c : d// if condition is true , a = c, else a = d

Do python have similar syntactic sugar?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Jimmy Zhang
  • 939
  • 1
  • 10
  • 15

3 Answers3

5

Yes :)

a = c if condition else d

This was introduced in Python 2.5

Timo D
  • 1,723
  • 10
  • 16
2

Python doesn't have a classic "?" ternary operator, but does have a similar construct:

result = 'I am True' if condition else 'I am False'
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

see the example:- python ternory operator

syntax:-  a if test else b

In [54]: 'true' if True else 'false'
Out[54]: 'true'

so that:-

In [52]: a = 5 if 2> 3 else 3

In [53]: a
Out[53]: 3
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24