Nested If Statements in Python

If-ElseLoops

Nested if statements mean placing one if statement inside another. This creates multi-level decision-making: an inner condition is only checked if the outer condition is true.

Nesting is powerful for complex logic, but it can quickly make code harder to read and maintain. We'll explore how to use it effectively, when to prefer alternatives, and how to keep your code clean.

By the end, you'll be confident using nested if statements and know when to choose simpler approaches.

Basic Nested If – Two Levels

The simplest nesting has one if inside another. The inner block only runs if both conditions are true.

Example: Check if someone is an adult and has a ticket for entry.

Here, the ticket check only happens for adults – which makes logical sense.

Multiple Levels of Nesting

You can nest as many levels as needed. This is useful for detailed grading systems or game logic.

Example: A student evaluation with score and attendance.

Three levels of nesting – each deeper check depends on the previous one being true.

Using Logical Operators Instead of Deep Nesting

Deep nesting can become hard to follow. Often, combining conditions with and/or makes code cleaner and easier to understand.

Example: Access control – compare nested vs combined.

The second version is flatter, easier to read, and less prone to indentation errors.

When to Use Nested If Statements

Nesting is appropriate when:

  • Inner conditions only make sense if the outer is true.
  • You need different actions or messages at each level.
  • The logic is naturally hierarchical (like menu systems or game states).

Limit nesting to 2-3 levels when possible. For more, consider refactoring with functions or data structures.

Common Mistakes with Nesting

  • Forgetting indentation – Python will raise IndentationError.
  • Too much nesting – code becomes hard to follow ("spaghetti code").
  • Forgetting else for inner if – unexpected behavior.
  • Mixing tabs and spaces – use spaces only (PEP 8).

Quick Quiz

We have reviewed and checked the materials, but errors may still occur. The content is provided for educational purposes only, so use it at your own responsibility and verify with other sources if needed.

✨ Ask Lara — your AI study partner

Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.


Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.

Track Your Progress 🚀

Learn more easily by tracking your progress completely for free.