KAHIBARO Bookshelves
Discord Login Register

6.4. Nested conditions

Understanding Nested Conditions

A nested condition is an if, elif, or else block inside another if, elif, or else block.

You already know how basic if, elif, else statements work. Nested conditions are just conditions inside conditions. They let you make more detailed decisions step by step.

Conceptually:

  • First condition: a broad decision
  • Inside it: more specific decisions, only checked if the outer condition was true

Basic Structure of Nested `if` Statements

General pattern:

if condition1:
    # this block runs if condition1 is True
    if condition2:
        # this block runs if condition1 AND condition2 are True
        ...
    else:
        # this block runs if condition1 is True AND condition2 is False
        ...
else:
    # this block runs if condition1 is False
    ...

Key idea: Python uses indentation to know which if belongs to which block. Each level of nesting is indented more.

Step-by-Step Example

Imagine a simple login-like check:

  • First, check if the username is correct.
  • Only if the username is correct, check the password.
username = "alice"
password = "1234"
user_input_name = input("Enter username: ")
user_input_pass = input("Enter password: ")
if user_input_name == username:
    print("Username OK")
    if user_input_pass == password:
        print("Access granted")
    else:
        print("Wrong password")
else:
    print("Unknown user")

Flow:

  • If the username is wrong, Python never checks the password condition.
  • The inner if runs only when the outer if is true.

Nested `if` vs Multiple `and` Conditions

Sometimes you could use either a nested if or a single if with and.

Same logic, different styles:

age = 20
has_ticket = True

Using nested conditions:

if age >= 18:
    if has_ticket:
        print("You can enter")
    else:
        print("You need a ticket")
else:
    print("You are too young")

Using and in a single if:

if age >= 18 and has_ticket:
    print("You can enter")
elif age >= 18 and not has_ticket:
    print("You need a ticket")
else:
    print("You are too young")

Neither style is “always better.” Use nested conditions when:

  • The decision is naturally step-by-step
  • You want to clearly separate “bigger” checks from “smaller” ones
  • The inner checks only make sense if the outer checks pass

Nesting with `if`, `elif`, and `else`

You can mix nested if with elif and else at different levels.

Example: grading with extra message for top scores:

score = 95
if score >= 50:
    print("You passed")
    if score >= 90:
        print("Excellent work!")
    elif score >= 75:
        print("Good job!")
    else:
        print("You passed, keep improving")
else:
    print("You failed")
    if score >= 40:
        print("Almost there, study a bit more")
    else:
        print("You need to improve a lot")

Notice:

  • Inner if/elif/else runs only in their parent block.
  • There are two different inner decision trees:
    • One for passing scores
    • One for failing scores

Multiple Levels of Nesting

You can nest more than once (though too much nesting can get hard to read).

Example: checking country, then age, then ticket:

country = "USA"
age = 20
has_ticket = True
if country == "USA":
    if age >= 18:
        if has_ticket:
            print("Welcome to the event in the USA!")
        else:
            print("You need a ticket for the event in the USA.")
    else:
        print("You are too young for the event in the USA.")
else:
    print("This event is only for people in the USA.")

Here you have three levels:

  1. Country
  2. Age
  3. Ticket

This is valid, but when you see more than 2–3 levels, it might be time to rethink the structure (more on that below).

When Nested Conditions Are a Good Idea

Nested conditions are especially useful when:

  • One check depends on another
    (e.g., “check password only if username is correct”)
  • You want to avoid unnecessary checks
    (e.g., don’t ask about tickets if the person is too young anyway)
  • You want to group related logic inside a larger decision

Examples of natural nesting:

  • Login: username → password → 2FA code
  • Online order: in stock? → can ship to your country? → payment success?
  • Game logic: is player alive? → has enough energy? → can perform special attack?

Avoiding Confusing Nesting

Too much nesting can make code hard to read.

Example of code that works but is messy:

age = 19
has_id = True
is_member = False
if age >= 18:
    if has_id:
        if is_member:
            print("Free entry")
        else:
            print("Paid entry")
    else:
        print("You need an ID")
else:
    print("You are too young")

A clearer version that keeps some nesting but is easier to follow:

if age < 18:
    print("You are too young")
elif not has_id:
    print("You need an ID")
elif is_member:
    print("Free entry")
else:
    print("Paid entry")

Guidelines to reduce confusion:

  • If nesting is only used to avoid repeating a condition, consider elif or logical operators.
  • If you see a “staircase” shape of many nested blocks, consider rewriting.
  • Keep related decisions close together; don’t jump around too much inside nested blocks.

Common Mistakes with Nested Conditions

1. Wrong Indentation

Indentation shows which if belongs where. Misplaced indentation changes meaning.

Incorrect:

age = 20
has_ticket = True
if age >= 18:
    if has_ticket:
        print("You can enter")
else:
    print("You are too young")

Here, the else is attached to the inner if has_ticket, not if age >= 18.

Python reads it as:

  • If age >= 18:
    • If has_ticket: print “You can enter”
    • Else: print “You are too young”

So if age >= 18 but has_ticket is False, it will say “You are too young,” which is wrong.

Correct (attach else to the outer if):

if age >= 18:
    if has_ticket:
        print("You can enter")
    else:
        print("You need a ticket")
else:
    print("You are too young")

Notice how indentation lines up:

  • if age >= 18: and else: are at the same level
  • if has_ticket: and its else: are inside that block

2. Unreachable Inner Conditions

Sometimes people write conditions inside a block that can never be true.

Example:

x = 5
if x > 10:
    if x > 20:
        print("x > 20")

If x is 5, the outer if is already false, so the inner if is never checked. That might be fine, but if you expect the inner block to run, you have a logic error.

Be sure the inner condition actually can be reached with the values you expect.

3. Doing Too Much in One Nested Block

If you find yourself writing a very long nested structure (many levels, many prints, many checks), it might be a sign you should:

  • Simplify conditions
  • Use elif
  • Or move some logic into a function (which you’ll learn about in the functions chapter)

Practice Ideas (Using Nested Conditions)

You can try writing small programs that use nested conditions:

  1. Age and country check
    • Ask user for age.
    • Ask user for country.
    • If country is “USA”:
      • If age $\geq 21$: allow to “buy a ticket”.
      • Else: print “too young in USA”.
    • Else:
      • If age $\geq 18$: “rules may differ, but allowed here”.
      • Else: “too young”.
  2. Simple menu with login
    • Ask for a username.
    • If username is “admin”:
      • Ask for a PIN.
      • If PIN is correct: show “Admin menu”.
      • Else: “Wrong PIN”.
    • Else:
      • “Access denied”.
  3. Quiz with bonus
    • Ask how many questions were correct.
    • If correct $\geq 3$:
      • Ask if they used hints (yes/no).
      • If no: “Great! Full credit.”
      • If yes: “Good, but hints used.”
    • Else:
      • “Try again.”

As you practice, pay special attention to:

  • Which conditions are outer vs inner
  • How indentation matches your logic
  • Whether some branches can never be reached

Nested conditions are simply about breaking decisions into steps. Used well, they make your programs more precise and easier to understand.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms