livepython.net
CHAPTER 08If Statements
8.4  NESTED IF

Nested if and Common if Mistakes in Python

An if Inside an if

A block under an if can contain another if. This is called a nested if. It's useful when the second question only makes sense if the first answer was yes:

PYTHONedit me
username = input()
password = input()
if username == "sunny":
    if password == "py123":
        print("Welcome, Sunny!")
    else:
        print("Wrong password.")
else:
    print("Unknown user.")
OUTPUT
Welcome, Sunny!

Try different inputs: a wrong password, then a wrong username. Each gets its own message.

Read the indentation

  • The outer if and its else sit at the left edge.
  • The inner if and its else are indented 4 spaces: they belong to the outer if.
  • The inner print() lines are indented 8 spaces: they belong to the inner if.

Each level of nesting adds 4 more spaces. That's how Python knows which else belongs to which if.

Think of security at an airport: only after your ticket is checked do they check your bag. No ticket, no bag check.

Don't go too deep

Two levels are fine. Three or more become hard to read and easy to get wrong. In the next lesson, you'll see how and and elif can often flatten nested code.

A nested if asks a second question only when the first answer was yes.

your turnPredict the output

What will this print?

a = 5 b = 2 if a > 3: if b > 3: print("both") else: print("only a") else: print("not a")
Your turn! What will this code show on the screen?

Nested if or and?

Many nested ifs can be written more simply. When the inner if has no else, and usually does the same job in one line:

PYTHONedit me
age = 20
has_ticket = True
if age >= 18:
    if has_ticket:
        print("Enjoy the concert!")
OUTPUT
Enjoy the concert!
PYTHONedit me
age = 20
has_ticket = True
if age >= 18 and has_ticket:
    print("Enjoy the concert!")
OUTPUT
Enjoy the concert!

Same result, one level of indentation less. Flat code is easier to read.

When nesting is better

Keep the nested version when each "no" needs its own message, like the login program in the last lesson ("Unknown user" and "Wrong password"). With a single and, you couldn't tell the user which part was wrong.

SituationUse
Both must be true, one messageif a and b:
Different message for each failurenested if, each with its own else
Several cases of one value (grades, prices)if / elif / else

elif can flatten too

Nested ifs inside else blocks often turn into a neat elif chain:

PYTHONedit me
n = -4
if n > 0:
    print("positive")
elif n < 0:
    print("negative")
else:
    print("zero")
OUTPUT
negative

Think of instructions for a friend: "if it's open and you have money, buy bread" is clearer than "if it's open, then, if you have money, buy bread".

If the inner if has no else, an and is usually simpler.

your turnFix the code

Flatten it: one if with and, same output

It should print: one digit

x = 7
if x > 0:
if x < 10:
    print("one digit")
This code does not work yet. Fix it, then press Run.

Common if Mistakes

These are the if mistakes every beginner makes. Learn them now, and you'll spot them in seconds.

1. = instead of ==

PYTHONedit me
age = 18
if age = 18:
    print("Exactly 18")
OUTPUT
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

One = stores, two == compare (chapter 5). Python even suggests the fix.

2. A missing colon

if age >= 18 without : gives SyntaxError: expected ':'. Every if, elif and else line ends with a colon.

3. Wrong indentation

A block that isn't indented gives an IndentationError. A line that's indented when it shouldn't be changes the meaning without any error, which is worse: always check which lines are inside the block.

4. Comparing input text with a number

PYTHONedit me
age = input()
if age == 18:
    print("Exactly 18")
print("checked")
OUTPUT
checked

No error, but the message never appears: the text "18" is never equal to the number 18. Convert with int() first (chapter 7).

5. or with half a comparison

if day == "Saturday" or "Sunday": is always true. Write both sides in full (topic 3).

6. elif in the wrong order

The widest condition first catches everything (topic 2). Put the most specific one first.

Think of this list as a pre-flight checklist: run through it whenever an if doesn't do what you expect.

Check the =, the colon, the indentation, the types and the order.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

What will this print?

x = input() if x == 5: print("five") print("end")

The user types: 5

Your turn! What will this code show on the screen?

Check Input Before You Use It

In chapter 7 you saw programs stop when the user typed something unexpected, like 0 for a division. With if, your program can check first:

PYTHONedit me
total = float(input())
people = int(input())
if people > 0:
    print(f"Each pays {total / people:.2f}")
else:
    print("There must be at least one person.")
OUTPUT
There must be at least one person.

Without the if, typing 0 would stop the program with a ZeroDivisionError. Now it explains the problem instead.

This is called validating input: checking that it makes sense before using it.

Things worth checking

CheckExample condition
not zero before dividingif people > 0:
inside an allowed rangeif 0 <= marks <= 100:
not emptyif name: (an empty string counts as false)
one of a few answersif answer == "yes" or answer == "no":

Think of a bouncer at a door: they check before letting anyone in, so there's no trouble inside.

What you can't check yet

If the user types ten instead of 10, int() still stops the program before your if even runs. Catching that needs try and except, from the Exceptions chapter. For now, clear prompts help: "Number of people (digits): ".

Check the input with if before you use it, and explain what's wrong.

your turnOrder the lines

Put the lines in order to divide safely

  1. print("Cannot divide by zero")
  2. if b != 0:
  3. print(a // b)
  4. else:
  5. a = int(input())
  6. b = int(input())

The user types: 90

These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

print(f"{3 * 4} items")
Your turn! What will this code show on the screen?

Practice: Nested if

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 68.Python Program to Divide Two Numbers SafelyEasySolve
  2. 67.Python Program to Check a Username and PasswordMediumSolve
  3. 69.Python Program to Make a Simple ATMHardSolve