Conditional Expressions

suggest change

Python's conditional expression evaluates one of two values based on a condition:

For instance,

value_if_true if condition else value_if_false

For example:

n = 16
result = 20 if n <= 15 else 10
print(result)
10

Only the selected branch is evaluated. This matters when a branch performs expensive work or has side effects. Indexing a list with a Boolean value was sometimes used as a workaround in old code, but it eagerly evaluates both list elements and obscures the intent.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents