The Python ‘if’ Statement

Introduction

The Python if statement is a fundamental construct used for decision-making in programming. It allows you to execute specific blocks of code based on whether a certain condition is met.

Basic Python if Statement Syntax

The most basic form of an if statement in Python consists of the keyword if followed by a condition and a colon :. The condition is an expression that evaluates to either a boolean True or False.

If the condition is True, the indented block of code underneath it will be executed. If the condition is False, the block will be skipped.

Indentation is crucial for the correct execution of the code within if statements. Python relies on indentation to determine the scope of code blocks.

Here’s the syntax of the basic if statement:

if condition:
    if-block
  • condition: The condition that the if statement evaluates.
  • if-block: The code that will execute if condition is True and skipped if it’s False. This code can consist of one or more statements.

Example:

x = 5

if x > 0:
    print(f"The number {x} is positive.")
    print("But you already know that!")

Output:

The number 5 is positive.
But you already know that!

In this example, the condition x > 0 is True, because the value of x, which is 5, is indeed larger than 0, so the indented print statements are executed.

When x is changed to -5, the code block with the print statements is skipped, and nothing is printed.

Example:

x = -5

if x > 0:
    print(f"The number {x} is positive.")
    print("But you already know that!")

The example above has no output because x > 0 evaluates to False. Consequently, the code block is skipped, and the print statements are not executed.

The else Clause

The optional else clause can be added after the if block, and it allows you to specify another block of code to be executed when the if condition is False. When the else clause is present, the combined syntax is often called an if-else statement.

Here’s the syntax of the ifelse statement:

if condition:
    if-block
else:
    else-block
  • if-block: Executes if condition is True.
  • else-block: Executes if condition is False.

Example:

x = -2

if x > 0:
    print(f"The number {x} is positive.")
else:
    print(f"The number {x} is not positive.")

Output:

The number -2 not positive.

In this example, since x is not greater than 0, the code in the else block is executed, and the text “The number -2 not positive.” is printed.

The elif Clause

When you have multiple conditions to check, you can use the elif (short for “else if”) clause to incorporate those. The elif clause completes the full syntax of Python’s if statement, which includes the if and else clauses as well.

One or more optional elif clauses can be added between the if block and before the else clause, which must be the last clause of the if statement when used.

The full if statement will execute only the first block whose condition is met, beginning at the top with the if condition, and making its way down any additional elif conditions. If an else clause is supplied, its block is executed when no specified condition is met, i.e. they are all False. If it’s not supplied, the if statement skips all its code blocks.

Here is the syntax of the full ifelifelse statement:

if condition1:
    if-block
elif condition2:
    elif-block1
elif condition3:
    elif-block2
# Add more elif blocks as needed
else:
    else-block

Example:

temp = 75  # Temperature in Fahrenheit 

if temp < 40:
    print("It's very cold!")
elif 60 > temp >= 40:
    print("It's a little chilly.")
elif 80 > temp >= 60:
    print("It's a nice day.")
elif 100 > temp >= 80:
    print("it's a little hot outside")
elif 120 > temp >= 100:
    print("Scorching temperatures!")
else:
    print("Leave the planet!")

Output:

It's a nice day.

In the example above, the temperature variable temp is evaluated against multiple conditions, each representing a temperature range. Depending on which condition is met first, the corresponding message is printed. Since it’s set to 75 on line 1, the if statement skips the first two code blocks and executes the third, which prints “It’s a nice day.”.

Nesting if Statements

You can also nest if statements within the code blocks of other if statements. This is useful when you need to check multiple conditions in a specific order.

Example:

x = 10

if x > 0:  # Check if x is positive
    if x % 2 == 0:  # Check if x is even
        print(f"{x} is a positive even numbers.")
    else:
        print("{x} is a positive odd numbers.")
else:
    print(f"{x} is not a positive numbers.")

Output:

10 is a positive even numbers.

In the example above, the if statement checks whether x is positive, and only if so, it employs an inner if statement to check whether x is even or odd using the modulo operator %, which returns the remainder upon division.

Logical Operators with if Statements

Logical operators (and, or, not) can be used to combine multiple conditions within the if and elif clauses of the if statement.

Example:

dog_treats_remaining = 5
enthusiasm_level = "moderate"

if dog_treats_remaining > 0 and enthusiasm_level != "off-the-charts":
    print("Please give your dog another treat!")

Output:

Please give your dog another treat!

In this example, the code checks whether both conditions (there are dog treats remaining and the dog’s enthusiasm level is still not off the charts) are true before executing the indented block, which recommends giving your dog another treat.

Using the if Statement With Truthy And Falsy Values

In Python, every value (including all objects) has a boolean equivalent. The values with a True boolean equivalent are considered “truthy,” and those with False are considered “falsey.” Falsy values are typically those considered empty or void in some way such as an empty string, an empty list, None, and 0. All the rest are “truthy”.

Therefore, the if statement’s conditions can be expressions of any value, not just booleans.

Example:

my_list = []

if not my_list:
    print("The list is empty.")

Output:

The list is empty.

In the example above, the variable my_list is set to an empty list, which is a falsy value. The not operator negates the boolean value and, therefore, the expression not my_list evaluates to True. This allows the block to execute and print the correct statement, “The list is empty.”

Summary & Reference for the Python if Statement

The Python if statement is a construct used for decision-making in programming, which allows you to execute specific blocks of code based on whether a certain condition is met.


The basic if statement syntax involves the use of the keyword if, followed by a condition and a colon :. The indented block of code beneath it executes if the condition is True, and skips if it’s False. Proper indentation is crucial for code execution in Python.

if condition:
    if-block

The else clause can be added after the if block, allowing the specification of code to execute when the if condition is False. When combined, this creates an if-else statement.

if condition:
    if-block
else:
    else-block

For multiple conditions, one or more elif (else if) clauses can be added. elif can be used with if and an optional else to execute of the first block whose condition is met.

if condition1:
    if-block
elif condition2:
    elif-block1
elif condition3:
    elif-block2
# Add more elif blocks as needed
else:
    else-block

Nesting if statements within the code blocks of others is a useful technique when checking multiple conditions in a specific order.

if x > 0:
    if x % 2 == 0:
        print(f"{x} is a positive even number.")
    else:
        print(f"{x} is a positive odd number.")
else:
    print(f"{x} is not a positive number.")

Logical operators (and, or, not) can be employed with if statements to combine multiple conditions, offering a way to create more complex decision structures.

if condition1 and condition2:
    print("Both conditions are true.")

In Python, the conditions in if statements can involve truthy and falsy values. Every value has a boolean equivalent, allowing conditions to be expressions of any value.

my_list = []

if not my_list:
    print("The list is empty.")