+2 votes
in Programming Languages by (73.8k points)
Does Python support ternary operator like C or PHP? If yes, how can I use?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

Ternary operators are known as conditional expressions in Python. You can use conditional expressions as follows: 

True if True else False

E.g. 

>>> from datetime import datetime 

>>> str(datetime.today().second) if datetime.today().second>9 else '0'+str(datetime.today().second)

'59'

>>> str(datetime.today().second) if datetime.today().second>9 else '0'+str(datetime.today().second)

'00'

>>> str(datetime.today().second) if datetime.today().second>9 else '0'+str(datetime.today().second)

'02'


...