Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Ternary operator (Conditional Operator)

  • ?:

x = 3
answer = 'positive' if x > 0 else 'negative or zero'
print(answer)   # positive

x = -3
answer = 'positive' if x > 0 else 'negative or zero'
print(answer)   # negative or zero
x = 3
if x > 0:
    answer = "positive"
else:
    answer = "negative or zero"
print(answer)  # positive

x = -3
if x > 0:
    answer = "positive"
else:
    answer = "negative or zero"
print(answer)  # negative or zero

In other languages this is the ?: construct.