Skip to content

Mastering Python If, If-Else & Nested Statements with Examples

Updated on

Python is a versatile programming language with various control structures that enable developers to create efficient decision-making programs. One of the most fundamental control structures in Python is the if statement. In this tutorial, we'll explore the syntax and usage of Python if, if-else, and nested if statements, with practical examples to enhance your skills in decision-making and flow control.

Before diving into conditional statements, make sure you have a good understanding of Python basics. To learn more about Python data structures, check out our Pandas DataFrame tutorial.

Want to quickly create Data Visualization from Python Pandas Dataframe with No code?

PyGWalker is a Python library for Exploratory Data Analysis with Visualization. PyGWalker (opens in a new tab) can simplify your Jupyter Notebook data analysis and data visualization workflow, by turning your pandas dataframe (and polars dataframe) into a tableau-alternative User Interface for visual exploration.

PyGWalker for Data visualization (opens in a new tab)

Python If Statement

The syntax of the Python if statement is simple:

if condition:
    # Code to execute if condition is True

The condition is a boolean expression that evaluates to either True or False. If the condition is true, the code inside the if block will be executed. For example:

age = 18
if age >= 18:
    print("You are eligible to vote.")

Python If-Else Statement

The if-else statement in Python allows you to execute one block of code if a condition is true, and another block of code if the condition is false. The syntax for the if-else statement is:

if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

For example:

age = 17
if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Python If-Elif-Else Statement

The if-elif-else statement in Python allows you to test multiple conditions and execute a specific block of code if any of the conditions are true. The syntax for the if-elif-else statement is:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if none of the conditions are True

For example:

score = 85
 
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
 
print(f"Your grade is {grade}.")

Nested If Statement

You can nest an if statement inside another if statement in Python. This is useful when you need to test multiple conditions sequentially. The syntax for a nested if statement is:

if condition1:
    # Code to execute if condition1 is True
    if condition2:
        # Code to execute if condition1 and condition2 are True

For example:

age = 35
country = "USA"
 
if age >= 18:
    if country == "USA":
        print("You are eligible to vote in the USA.")

Examples of Python If, If-Else, and Nested If Statements

Now that we have covered the syntax and usage of Python if, if-else, and nested if statements, let's dive into some practical examples.

Python If Statement with String

Python if statements can also be used with strings, as shown in this example:

username = "Alice"
 
if username == "Alice":
    print("Welcome, Alice!")

Python If Statement with Multiple Conditions

You can use logical operators like and, or, and not to create more complex conditions in a Python if statement. Here are some examples:

Python If Statement with And

age = 25
country = "USA"
 
if age >= 18 and country == "USA":
    print("You are eligible to vote in the USA.")

Python If Statement with Or

age = 16
parent_permission = True
 
if age >= 18 or parent_permission:
    print("You can attend the event.")

Python If Statement with Not

user_is_admin = False
 
if not user_is_admin:
    print("You do not have admin privileges.")

Python If-Else Statement with Multiple Conditions

You can also use multiple conditions in if-else statements. Here's an example:

temperature = 75
is_raining = False
 
if temperature >= 70 and not is_raining:
    print("It's a perfect day for a picnic!")
else:
    print("Not the best day for a picnic.")

Python If-Elif-Else Statement with Multiple Conditions

Using multiple conditions in if-elif-else statements allows you to create more complex decision-making programs. Consider this example:

weather = "sunny"
temperature = 75
 
if weather == "sunny" and temperature >= 70:
    print("It's a perfect day for a picnic!")
elif weather == "cloudy" and temperature >= 70:
    print("It might be a good day for a picnic, but watch out for rain.")
else:
    print("Not the best day for a picnic.")

Python Nested If Statement Example

Nested if statements can be used to create more complex decision-making programs. Here's an example:

age = 35
country = "USA"
is_registered_voter = True
 
if age >= 18:
    if country == "USA":
        if is_registered_voter:
            print("You are eligible to vote in the USA.")
        else:
            print("You need to register to vote in the USA.")
    else:
        print("You cannot vote in the USA.")

Conclusion

In this tutorial, we have covered the syntax and usage of Python if, if-else, and nested if statements, along with various examples to enhance your skills in decision-making and flow control. Mastering these concepts is crucial for creating efficient Python programs.

If you're looking to expand your Python knowledge further, you might find these tutorials helpful:

By mastering Python conditional statements and flow control, you can create more efficient and versatile programs. Combining these skills with other powerful Python libraries like NumPy, Pandas, Seaborn, and Matplotlib will allow you to tackle a wide range of programming challenges and build sophisticated applications.

As you continue your Python learning journey, always remember that practice makes perfect. Try to incorporate the concepts discussed in this tutorial into your projects and practice using them in different scenarios. This will help you gain a deeper understanding of Python control structures and decision-making processes, enabling you to become a more proficient Python programmer.