Execute Program

Python for Programmers: Ternaries

Welcome to the Ternaries lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Python has a second conditional syntax: value1 if condition else value2. If condition is true, it evaluates to value1. Otherwise it evaluates to value2.

  • >
    1 if True else 2
    Result:
    1Pass Icon
  • >
    1 if False else 2
    Result:
    2Pass Icon
  • These are called ternary expressions. (Ternary means "composed of three parts". Here, the three parts are the true value, the condition, and the false value.)

  • You might be familiar with C-style ternaries: condition ? value1 : value2. Python's ternaries use less punctuation, as usual, and the order is different. But the basic idea is the same.

  • Ternaries are useful in many situations, but their most notable use case is in lambdas. We've seen that lambda functions can only contain expressions, not statements. if is a statement, so we can't use it in a lambda. However, we can use a ternary.

  • >
    positive_or_zero = lambda x: x if x >= 0 else 0
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    positive_or_zero(15)
    Result:
    15Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    positive_or_zero(-2)
    Result:
    0Pass Icon
  • It's important to use ternaries sparingly. Chaining them can make code difficult to read.

  • >
    # This function "clamps" a value, ensuring that it's between 0 and 10
    # (inclusive).
    clamp = lambda x: 10 if x > 10 else 0 if x < 0 else x
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    clamp(4)
    Result:
    4Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    clamp(-10)
    Result:
    0Pass Icon
  • Note: this code example reuses elements (variables, etc.) defined in earlier examples.
    >
    clamp(103)
    Result:
    10Pass Icon
  • We can try to make that expression more readable by adding some newlines and parentheses.

  • >
    clamp = lambda x: (
    10 if x > 10
    else (
    0 if x < 0
    else x
    )
    )

    [clamp(4), clamp(-10), clamp(103)]
    Result:
  • At that point, it's better to give up on the lambda. A regular def and if are only slightly longer, but they're much easier to read.

  • >
    def clamp(x):
    if x > 10:
    return 10
    elif x < 0:
    return 0
    else:
    return x

    [clamp(4), clamp(-10), clamp(103)]
    Result: