Python if-else Statements: Flow Control

Python uses if and else statements to control the flow of your code. They are used to execute code when specific conditions are met.

For example, you can use an if-else block to determine an age group that a person falls into. For example, say we had the following rules:

  • If the age is below 13, they should be labeled a child πŸ‘Ά,
  • If the age is below 20, they should be labeled a teenager πŸ§’,
  • If the age is below 65, they should be labeled an adult πŸ§‘,
  • Otherwise, they should be labeled a senior πŸ‘΄ .

Give the slider below a try to see how we can change our inputs to control the output:

Category: πŸ§‘ Adult


Age: 25


We can accomplish this in Python using if-else statements. In this guide, you'll learn how!

Understanding the Python if Statement

The Python if statement is used to execute some line (or lines) of code if a condition is met. Following Python's principles of readability, we only need to write the if keyword and some conditions to be met.

if condition:
    # What to run if the condition is met

The condition is simply a statement that evaluates either to True or False. If the condition is True, then the code in the indented block runs; otherwise, nothing occurs.

Example of a Python if Statement

Let's look at an example of how the Python if statement works, following the age group idea from the introduction.

age = 19
if age < 13:
    print(f'Person is {age} years old and is a child.')

print('Other statement.')

This could work not execute the statement in the if block because the condition is False. Instead, the code will only print out "Other statement.".

On the other hand, if we modified the age to 12, the condition would be met and the code would run differently:

age = 12
if age < 13:
    print(f'Person is {age} years old and is a child.')

print('Other statement.')

# Returns:
# Person is 12 years old and is a child.
# Other statement.

We can visualize what this looks like using a flowchart. We use an if statement to test whether a condition is met. If it is, then it moves to the indented code - otherwise, it skips it.

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#CADCFC', 'edgeLabelBackground': '#cccccc'}}}%%
graph LR;
    A[Start] --> B{Condition?};
    B -- No --> D[End];
    B -- Yes --> C[Execute if-block];
    C --> D;

Python if-else Statement

Python if statements allow us to use the else statement to execute code if a condition is not met.

In our previous example, we only used an if statement, meaning that the code simply moved on if a condition was not met. Adding the else statement gives us much more flexibility.

Let's take a look at the basic syntax:

if condition:
    # What to run if the condition is met
else:
    # What to run if the condition is not met

Example of a Python if-else Statement

Let's look at an example of how the Python if-else block works, following the age group idea from the introduction.

age = 19
if age < 13:
    print(f'Person is {age} years old and is a child.')
else:
    print(f'Person is {age} years old and is not a child.')

This would not execute the statement in the if block because the condition is False. Instead, the code will move to the else statement, indicating that the person is not a child.

We can visualize what this looks like using a flowchart. We use an if statement to test whether a condition is met. If it is, then it moves to the indented code - otherwise, moves to the else block.

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#CADCFC', 'edgeLabelBackground': '#cccccc'}}}%%
graph LR;
    A[Start] --> B{Condition?};
    B -- Yes --> C[Execute if-block];
    B -- No --> D[Execute else-block];
    C --> E[End];
    D --> E;

Multiple Tests in Python if-elif-else Statements

Python allows you to extend if-else blocks by using more than two tests by using elif (or else if) statements. The elif statement is used to check a condition that hasn't yet been met without needing to nest multiple if statements.

if condition:
    # What to run if the condition is met
elif condition2:
    # What to run if condition2 is met
else:
    # What to run if the condition is not met

Example of a Python if-elif-else Statement

Let's look at an example of how the Python if-elif-else block works, following the age group idea from the introduction.

age = 19
if age < 13:
    print(f'Person is {age} years old and is a child.')
elif age < 20:
    print(f'Person is {age} years old and is a teenager.')
elif age < 65:
    print(f'Person is {age} years old and is an adult.')
else:
    print(f'Person is {age} years old and is a senior.')

In the code block above, the code would terminate following the first elif statement, since the age is less than 20.

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#CADCFC', 'edgeLabelBackground': '#cccccc'}}}%%
graph LR;
    A[Start] --> B{If condition?};
    B -- Yes --> C[Execute if-block] --> G[End];
    B -- No --> D{Elif condition?};
    D -- Yes --> E[Execute elif-block] --> G;
    D -- No --> F[Execute else-block] --> G;

Nested if Statements

We can take this one step further by nesting if statements within other if statements. This is useful if you want to check a condition only if another condition is already met.

if condition:
    # What to run if the condition is met
else:
    if condition2:
         # What to run if condition2 is met
    else:
         # What to run if the condition2 is not met

Example of a Python if-elif-else Statement

Let's look at an example of how a nested if block works in Python.

age = 40
if age >= 20:
    if age < 65:
        print("You are an adult πŸ§‘")
    else:
        print("You are a senior πŸ‘΄")
else:
    print("You are not an adult")

In the code block above, the code would let you know that you're an adult!

We can visualize what this looks like:

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#CADCFC', 'edgeLabelBackground': '#cccccc'}}}%%
graph LR;
    A[Start] --> B{Condition?};
    B -- Yes --> C[Run block if condition is met] --> H[End];
    B -- No --> D{Condition2?};
    D -- Yes --> E[Run block if condition2 is met] --> H;
    D -- No --> F[Run block if condition2 is NOT met] --> H;

Conclusion

Understanding how to use if, if-else, elif, and nested if statements is an important part of understanding how to control the flow of your code. Using this condition logic allows you to respond to different scenarios, which can be especially useful when validating data or user input.

  • Use if when you only need to test a single condition.
  • Add else to define what happens when that condition isn’t met.
  • Use elif when you need to check multiple exclusive conditions in sequence.
  • And reach for nested if statements when decisions depend on earlier checks, or when conditions are hierarchically related.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top