If-elif-else statement in Python

Overview

The if-elif-else statement in Python allows us to build programs that can make decisions based on certain conditions.

The if-elif-else statement consists of:

  • if statement
  • elif statement
  • else statement

They combine to conditionally execute blocks of statements based on the logical expression.

If statement

The if statement executes a single block of statements based on a certain logical expression.

The syntax is given as:

if expression:
    statement(s)
    ----

The expression in the line of code above is usually a boolean expression (true or false). The program above will execute the statement provided only if the expression is true.

Code

is_odd = True
if is_odd:
print("it's an odd number")
print('They are not divisible by 2')

if-else statement

The if-else statement has two blocks of statements and executes them based on certain logical expressions.

The syntax is given as:

if expression:
    statement_1(s)
    ---
else:
    statement_2(s)

The code above will execute the if block only if the expression is true. If the expression is false, then the program executes the statement_2 in the else block.

Code

is_odd = False
if is_odd:
print("it's an odd number")
print('They are not divisible by 2')
else:
print("it's an even number")
print('They are divisible by 2')

if-elif-else statement

The elif statement, short for else if and in other words “otherwise if”, is added to the if-else block when there are many more conditions. So basically, the if-elif-else statement consists of several blocks.

The syntax is given as:

if expression:
    statement_1(s)
    ---
elif expression_2:
    statement_2(s)
    ---
else:
    statement_3(s)

The code above will execute for just a block, only when it finds an expression to be true.

Code

is_odd = False
is_prime = True
if is_odd:
print("it's an odd number")
print('They are not divisible by 2')
elif is_prime:
print("it's a prime number")
print("They only have two factors, itself and 1.")
else:
print("it's an even number")
print('They are divisible by 2.')

Free Resources