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:
username = input()
password = input()
if username == "sunny":
if password == "py123":
print("Welcome, Sunny!")
else:
print("Wrong password.")
else:
print("Unknown user.")Welcome, Sunny!
Try different inputs: a wrong password, then a wrong username. Each gets its own message.
Read the indentation
- The outer
ifand itselsesit at the left edge. - The inner
ifand itselseare indented 4 spaces: they belong to the outerif. - The inner
print()lines are indented 8 spaces: they belong to the innerif.
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.