Skip to main content
Library homepage
Engineering LibreTexts

19.1: Conditional expressions

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    We saw conditional statements in Section 5.4. Conditional statements are often used to choose one of two values; for example:

    if x > 0:
        y = math.log(x)
        y = float('nan')

    This statement checks whether x is positive. If so, it computes math.log. If not, math.log would raise a ValueError. To avoid stopping the program, we generate a “NaN”, which is a special floating-point value that represents “Not a Number”.

    We can write this statement more concisely using a conditional expression:

    y = math.log(x) if x > 0 else float('nan')

    You can almost read this line like English: “y gets log-x if x is greater than 0; otherwise it gets NaN”.

    Recursive functions can sometimes be rewritten using conditional expressions. For example, here is a recursive version of factorial:

    def factorial(n):
        if n == 0:
            return 1
            return n * factorial(n-1)

    We can rewrite it like this:

    def factorial(n):
        return 1 if n == 0 else n * factorial(n-1)

    Another use of conditional expressions is handling optional arguments. For example, here is the init method from GoodKangaroo (see Exercise 17.13.2):

        def __init__(self, name, contents=None):
   = name
            if contents == None:
                contents = []
            self.pouch_contents = contents

    We can rewrite this one like this:

        def __init__(self, name, contents=None):
   = name
            self.pouch_contents = [] if contents == None else contents 

    In general, you can replace a conditional statement with a conditional expression if both branches contain simple expressions that are either returned or assigned to the same variable.

    This page titled 19.1: Conditional expressions is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?