Archive

Posts Tagged ‘?:’

Ternary operator (?:) in Python

In C, the ternary operator looks like this:

condition ? value_if_true : value_if_false

In Python, it’s a bit different:

value_when_true if condition else value_when_false

Example:

>>> name = None
>>> msg = "Hello %s" % name if name else 'gimme your name'
>>> msg
'gimme your name'
>>> name = 'Jabba'
>>> msg = "Hello %s" % name if name else 'gimme your name'
>>> msg
'Hello Jabba'
Categories: python Tags: ,