Python Tutorials · Python If...Else

Nested If

Learn all about Nested If in this comprehensive tutorial.

5 min read beginner
  • You can have if statements inside if statements.
  • Each level of nesting creates a deeper level of decision-making.
  • You can nest as many levels deep as needed, but keep in mind that too many levels can make code harder to read.
  • Sometimes nested if statements can be simplified using logical operators like and.

Nested If Statements

You can have if statements inside if statements. This is called nested if statements.

python

In this example, the inner if statement only runs if the outer condition (x > 10) is true.

How Nested If Works

Each level of nesting creates a deeper level of decision-making. The code evaluates from the outermost condition inward.

python

Multiple Levels of Nesting

You can nest as many levels deep as needed, but keep in mind that too many levels can make code harder to read.

python

Nested If vs Logical Operators

Sometimes nested if statements can be simplified using logical operators like and. The choice depends on your logic.

python
python

Both approaches produce the same result. Use nested if statements when the inner logic is complex or depends on the outer condition. Use and when both conditions are simple and equally important.

More Examples

python
python

Module quiz

2 questions
1

Which of the following is true about Nested If?

2

What is the most common pitfall when working with Nested If?

Answer all questions to submit.