Link Search Menu Expand Document

Conditionals

Table of contents

  1. Description
  2. Composition
  3. Examples
    1. if/else Statements
    2. elif Statements
    3. Compound if Statement
  4. Python Control Structures
  5. Instructional Videos

Description

Conditionals allow our programs to make choices based on the result of analyzing certain information. In more technical terms, conditionals execute alternate sets of code (branches) based on the evaluation of a boolean expression.

Composition

  1. if: A conditional must have only one if statement. It must have a boolean expression.
  2. elif: A conditonal may have 0 to infinity elif statements. It must have a boolean expression.
  3. else: A conditional may have 0 or 1 else statements. It must never have a boolean expression.
if (boolean-expression):
    # this code block executes only if its boolean expression is TRUE
elif (boolean-expression):
    # this code block executes only if all previous boolean expression were FALSE,
    # but this elif's boolean expression is TRUE
else:
    # This code block only executes if all previous boolean expressions were FALSE

Examples

if/else Statements


elif Statements


Compound if Statement

Python Control Structures

Conditionals are one of three program control structures. These control structures dictate the order in which a program’s code executes:

  • Sequential: Code is executed linearly, one after the other.
  • Selection: Different block(s) of code are executed based on the results of a condition.
  • Iteration: Repeating a block of code several times.

Instructional Videos