5.4: Conditional execution

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    5.4: Conditional execution

    In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

    if x > 0:
        print('x is positive')
    

    The boolean expression after if is called the condition. If it is true, the indented statement runs. If not, nothing happens.

    if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements.

    There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

    if x < 0:
        pass          # TODO: need to handle negative values!

    This page titled 5.4: Conditional execution was last modified on Tue, 01 Dec 2020 03:31:09 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.