Conditional Statements

Conditional execution in Python is done using the if or if/else statement.

Recall that indentation is used to indicate groups of statements.

Indentation will indicate the statement or groups of statements that will be executed conditionally.

A condition is an expression that evaluates to true or false.

if statement - Generic

# Python if

if condition:
   statement_1
   ...
   statement_n
statement_after_if

Indentation is used to denote the group of statements that is executed conditionally.

Note the required colon after the condition.

if With else Statement

# Python if with else

if condition:
   statements_A
   ...
else:
   statements_B
   ...
statement_after_if

Note the required colon after the condition and in the else.

elif Statements

Python if statements have the form with multiple elses have the form:

if condition_a:
   statement_1
   statement_2
   ...
elif condition_b:
   statement_3
   ...
elif condition_c:
   statement_4
   ...
else:
  statement_5
  ...
statement_after_if

Only one of the if, elifs, or else group of statements will be executed.

There can be as many elifs as necessary.

If Statement - Example

Example, assume total and count have values:

if count > 0:
   average = total / count
else: print('The average cannot be computed')