-1

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
  • 48,723
  • 33
  • 63
  • 158
Jimmy Zhang
  • 889
  • 1
  • 9
  • 15

3 Answers3

5

Yes :)

a = c if condition else d

This was introduced in Python 2.5

Timo D
  • 1,633
  • 9
  • 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
  • 277,661
  • 50
  • 283
  • 320
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
  • 4,979
  • 1
  • 12
  • 26