Skip to main content

Nested If Statements

An if statement may contain further if statements. When one sits inside another like this, we call them nested if statements.

Example

Prompt
Write a Python program that sets x to 41, then uses a nested if statement to check if x is above 10, and if so, checks if x is also above 20. Print appropriate messages for each case.
Output: complete Python program

How Nested If Works

Nesting adds depth to a decision, with one choice leading to the next. Python starts at the outermost condition and works its way inward.

Example

Two conditions checked through nesting:

Prompt
Write a Python program that checks if a person can drive using nested if statements. Set age to 25 and has_license to True, then check age >= 18 first, then check the license.
Output: complete Python program

Multiple Levels of Nesting

You can nest as deep as you like, but every extra level makes the code harder to follow.

Example

Nesting three levels deep:

Prompt
Write a Python program with three levels of nested if statements to evaluate a student. Check score >= 60, then attendance >= 80, then if submitted is True.
Output: complete Python program

Nested If vs Logical Operators

A logical operator such as and can sometimes replace nesting and shorten the code. Which one fits depends on your logic.

Either way you get the same result. Nesting suits inner logic that is complex or relies on the outer condition, while and suits two simple conditions of equal importance.

Example

Here is the nested version:

Prompt
Write a Python program that uses nested if statements to check if temperature > 20 and is_sunny is True. Print "Perfect beach weather!" if both conditions are met.
Output: complete Python program

Example

And the same check using and:

Prompt
Write a Python program that uses the and operator to check if temperature > 20 and is_sunny is True in a single condition. Print "Perfect beach weather!" if both conditions are met.
Output: complete Python program

More Examples

Example

Validating a login step by step:

Prompt
Write a Python program that validates login using nested if statements. Check username, then password, then is_active status, printing appropriate messages.
Output: complete Python program

Example

Working out a grade with nested conditions:

Prompt
Write a Python program that calculates a grade using nested if with elif. Check if score >= 90 with extra_credit > 0 for A+, otherwise A, B, or C grade.
Output: complete Python program