Master Nested If Statement in Python Example w3schools Guide

Logan Jul 13, 2026

Python, renowned for its simplicity and readability, provides a wealth of control structures for decision-making. One such structure is the 'if' statement, which allows programmers to execute different blocks of code based on certain conditions. In this article, we will explore the usage of nested 'if' statements in Python, as demonstrated on W3Schools, along with practical examples.

Python If...Elif...Else Statement - PythonForBeginners.com
Python If...Elif...Else Statement - PythonForBeginners.com

Before diving into nested 'if' statements, let's briefly recap the basic 'if' statement. The structure is straightforward: it begins with the 'if' keyword, followed by a condition, and finally, the block of code to be executed if the condition is true. Here's a simple example from W3Schools:

the if statement in python is true or false, and it's very easy to read
the if statement in python is true or false, and it's very easy to read

Basic 'if' Statement

Consider the following simple 'if' statement in Python:

Decision-Making Statements in Python with Examples
Decision-Making Statements in Python with Examples

if x > 0:    print("The number is positive")

In this example, the number 'x' is checked. If it's greater than zero, the message "The number is positive" is printed.

Now, let's delve into nested 'if' statements.

Python if, elif, else Statement: Overview of Conditional Statements
Python if, elif, else Statement: Overview of Conditional Statements

What are Nested 'if' Statements?

Nested 'if' statements are 'if' statements inside other 'if' statements. They allow for more complex decision-making structures, enabling one condition to depend on the outcome of another. Let's examine a basic example:

if x > 0:    if x < 10:       print("The number is positive and less than 10")

In this nested 'if' statement, the variable 'x' is first checked if it's greater than zero. If it is, a second condition checks if 'x' is less than 10. Only if both conditions are true, the message is printed.

Python Else If, Python If Else | How to Use Python If Condition? ⋆ IpCisco
Python Else If, Python If Else | How to Use Python If Condition? ⋆ IpCisco

Handling Multiple Conditions with 'elif'

The 'elif' (short for 'else if') statement allows you to add additional conditions after an 'if' statement. It's a way to add more conditions on the same level, without nesting. Here's how you can use 'elif' to handle multiple conditions:

if x > 0:    print("The number is positive")

elif x < 0:

an image of a computer screen with the text, 2 leverage for multiple conditions
an image of a computer screen with the text, 2 leverage for multiple conditions

   print("The number is negative")

else:

   print("The number is zero")

In this example, the 'elif' statements check if 'x' is negative and if 'x' is zero. A match with any of these conditions will execute the corresponding print statement.

🐍 Python – if-else Statement (Complete Beginner Guide)
🐍 Python – if-else Statement (Complete Beginner Guide)
Decision Making in Python using if, if-else, if-elif and nested statements - TechVidvan
Decision Making in Python using if, if-else, if-elif and nested statements - TechVidvan
an image of a rabbit in front of a black background with the words python if else inside print
an image of a rabbit in front of a black background with the words python if else inside print
Conditional Statements in Python - The Engineering Projects
Conditional Statements in Python - The Engineering Projects
🐍 Python elif Statement Explained | Conditional Statements Made Easy
🐍 Python elif Statement Explained | Conditional Statements Made Easy
Coding For Beginners Python - Learn the Basics - Conditionals
Coding For Beginners Python - Learn the Basics - Conditionals
| Pythonista Planet
| Pythonista Planet
Inheritance in Python✨
Inheritance in Python✨
How to Use If Else Statements in Python (Python Tutorial #2)
How to Use If Else Statements in Python (Python Tutorial #2)
Python Remove Substring with Examples
Python Remove Substring with Examples
Conditional Statements In Python | if, if-else, if-elif-else, nested | python for Beginners | Python
Conditional Statements In Python | if, if-else, if-elif-else, nested | python for Beginners | Python
OOP in Python
OOP in Python
append() vs insert() in Python (Easy Guide πŸ”₯)
append() vs insert() in Python (Easy Guide πŸ”₯)
Python Try and Except | Finally | Else | Raise Statements ⋆ IpCisco
Python Try and Except | Finally | Else | Raise Statements ⋆ IpCisco
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Python Data Structures Cheat Sheet for Beginners (Lists, Tuples, Sets & Dictionaries)
Save This Python If-Else Cheat Sheet Before Your Exam
Save This Python If-Else Cheat Sheet Before Your Exam
Conditional Statements in Python – Real Python
Conditional Statements in Python – Real Python
three different types of python programming
three different types of python programming
PYTHON BASICS
PYTHON BASICS
9 Python Projects for Beginners (Build Your Portfolio Fast)
9 Python Projects for Beginners (Build Your Portfolio Fast)

Practical Example: Grade Calculation

Let's consider a practical example where we need to calculate and print a student's grade based on their score. We'll use nested 'if' statements to determine the grade.

score = 85

if score >= 90:

   grade = "A"

elif score >= 80:

      grade = "B"

elif score >= 70:

        grade = "C"

elif score >= 60:

        grade = "D"

else:

        grade = "F"

print("Your grade is " + grade)

In this example, the score is first checked against the highest grade (A). If it doesn't meet that condition, the next grade (B) is checked, and so on. If none of the conditions are met, the score is considered an 'F'.

Real-world Applications

Nested 'if' statements are prevalent in real-world applications. They are used in various scenarios like game logic, decision-making systems, and complex data validations. For instance, in a game, you might use nested 'if' statements to control enemy behavior based on the player's actions and the current game state.

Best Practices and Pitfalls

While nested 'if' statements are powerful, they can also lead to code that's difficult to read and maintain if not used judiciously. Here are a few best practices and pitfalls to keep in mind:

Keep it Shallow

Try to avoid nesting 'if' statements too deeply. Deeply nested 'if' statements can lead to complex Boolean expressions that are difficult to follow. A good rule of thumb is to keep your nesting depth to three levels at most.

Use Descriptive Variables and Comments

Good variable names and comments can greatly enhance the readability of your code. Instead of using variables like 'x' and 'y', use names that reflect what they represent, like 'user_score' and 'passing_grade'. Additionally, comment on why you're using a certain condition or nested structure to guide future readers of your code.

Avoid Nesting 'if' Statements Whenever Possible

Sometimes, logic that requires nested 'if' statements can be refactored into a more readable, linear structure. For example, the grade calculation example could be refactored using a dictionary to map scores to grades.

Understanding and effectively using nested 'if' statements is a crucial aspect of Python programming. They allow for complex decision-making structures and are invaluable for many real-world applications. By keeping these best practices in mind, you can write effective and maintainable Python code.

Remember, every 'if' statement is a decision point in your code. Each decision makes your code go down a different path. So, use them wisely. Keep your code simple, readable, and maintainable. With practice, you'll find that nested 'if' statements become second nature, allowing you to write complex decision-making systems with ease.

Now that you've learned about nested 'if' statements in Python, don't forget to practice and experiment with them. The best way to learn is by doing. Happy coding!