Writing Nested Conditional Statements in Python
Course: Python Programming
Topic: Writing Nested Conditional Statements
Course Link: Python Training at JustAcademy
Demo Link: Register for a Course Demo
Official Reference: Python Control Flow Documentation
1. Introduction to Nested Conditional Statements
Nested conditional statements are decision-making structures in Python in which one conditional statement is placed inside another conditional statement. They allow a program to evaluate multiple related conditions in a particular order and execute different instructions depending on the results.
In programming, some decisions depend on the outcome of an earlier decision. For example, an application may first check whether a user is logged in and then check whether the user has permission to access a particular page. The second condition should be evaluated only when the first condition is satisfied.
Nested conditional statements help developers represent these dependent decisions clearly. They can contain an if, if-else, or if-elif-else structure inside another conditional block.
Example
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print("You are eligible to enter the event.")
Output:
You are eligible to enter the event.
Explanation:
- The outer
if statement checks whether the person is at least 18 years old.
- If the age condition is true, Python evaluates the inner
if statement.
- The inner condition checks whether the person has a ticket.
- The message is printed only when both conditions are satisfied.
2. Learning Objectives
After studying this topic, learners will be able to:
- Define nested conditional statements in Python.
- Understand the syntax and structure of nested conditions.
- Write nested
if statements with correct indentation.
- Use nested
if-else and if-elif-else structures.
- Understand how outer and inner conditions are evaluated.
- Apply nested conditions to user input and real-world problems.
- Identify common logical and indentation errors.
- Determine when nested conditions can be simplified using logical operators.
- Develop programs that use multiple levels of decision-making.
3. What Is a Nested if Statement?
A nested if statement is an if statement written inside the body of another conditional statement. The inner condition is evaluated only when program execution reaches that statement.
Nested conditions are useful when the program needs to make a second decision after the first decision has been satisfied.
Basic Example
number = 15
if number > 0:
print("The number is positive.")
if number > 10:
print("The number is also greater than 10.")
Output:
The number is positive.
The number is also greater than 10.
Here, the outer condition checks whether the number is positive. The inner condition checks whether it is greater than 10. Since both conditions are true, both messages are displayed.
4. Syntax of Nested Conditional Statements
The general syntax of a nested if statement is:
if outer_condition:
# Outer block statements
if inner_condition:
# Inner block statements
The outer condition is evaluated first. If it evaluates to true, the outer block executes and the inner condition can be evaluated. If the outer condition is false, the inner condition is skipped.
Nested if-else Syntax
if outer_condition:
if inner_condition:
statement_1
else:
statement_2
else:
statement_3
Explanation:
outer_condition controls whether the inner conditional structure is reached.
inner_condition determines which inner branch executes.
- The inner
else belongs to the inner if.
- The final
else belongs to the outer if.
- Indentation makes the relationship between each condition and its branches clear.
5. How Nested Conditions Work
Python evaluates nested conditional statements from the outermost condition toward the innermost condition. Each condition controls whether execution proceeds into its associated block.
Execution Steps
- The program evaluates the outer condition.
- If the outer condition is false, its inner block is skipped.
- If the outer condition is true, Python executes the statements inside the outer block.
- When Python reaches the inner condition, it evaluates that condition.
- If the inner condition is true, its associated statements execute.
- If the inner condition is false and an inner
else exists, the inner else block executes.
- After the conditional structure finishes, execution continues with the next statement.
Example
age = 22
has_license = True
if age >= 18:
print("Age requirement satisfied.")
if has_license:
print("Driving requirement satisfied.")
print("Program completed.")
Output:
Age requirement satisfied.
Driving requirement satisfied.
Program completed.
The first message is displayed because the age is at least 18. The second message is displayed because the license condition is also true. The final message executes regardless of the results of the nested conditions because it is outside both blocks.
6. Understanding Indentation in Nested if Statements
Indentation is essential when writing nested conditional statements in Python. It determines which statements belong to the outer block and which belong to the inner block.
Python commonly uses four spaces for each indentation level. Every new nesting level should be indented consistently.
Correct Indentation
score = 85
if score >= 40:
print("The student has passed.")
if score >= 80:
print("The student has achieved distinction.")
Output:
The student has passed.
The student has achieved distinction.
Incorrect Indentation
score = 85
if score >= 40:
print("The student has passed.")
if score >= 80:
print("Distinction achieved.")
Problem: The inner if statement is indented inconsistently. Python raises an IndentationError for this example.
Indentation Best Practices
- Use four spaces per indentation level.
- Align statements that belong to the same block.
- Indent inner conditions one additional level relative to their containing block.
- Ensure each
else aligns with the corresponding if.
- Avoid mixing tabs and spaces.
- Use an editor that automatically manages indentation.
7. Nested if Statements with else
A nested if-else structure allows a program to make an initial decision and then choose between additional alternatives.
Example: Checking a Number
number = 12
if number >= 0:
if number == 0:
print("The number is zero.")
else:
print("The number is positive.")
else:
print("The number is negative.")
Output:
The number is positive.
Explanation:
- The outer condition checks whether the number is greater than or equal to zero.
- If true, the inner condition checks whether the number equals zero.
- If the inner condition is true, the zero message is printed.
- If the inner condition is false, the positive message is printed.
- If the outer condition is false, the negative message is printed.
Testing Different Values
| Number |
Outer Condition |
Result |
| -5 |
False |
The number is negative. |
| 0 |
True |
The number is zero. |
| 12 |
True |
The number is positive. |
8. Nested if Statements with elif
The elif keyword means "else if". It allows a program to test additional conditions when earlier conditions are false. An elif structure can also be placed inside an outer conditional block.
Example: Student Grade Classification
marks = 82
if marks >= 40:
print("Result: Pass")
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
else:
print("Grade: C")
else:
print("Result: Fail")
Output:
Result: Pass
Grade: A
Explanation:
- The outer condition checks whether the student has scored at least 40 marks.
- If the student passes, Python evaluates the inner grade conditions.
- The first true grade condition determines the displayed grade.
- If the outer condition is false, the program displays the fail message instead.
This example uses illustrative grading thresholds. Actual grading rules depend on the institution or examination system.
9. Multiple Levels of Nested Conditions
Python allows multiple levels of nested conditions. Each level represents another decision that depends on reaching the corresponding block. However, excessive nesting can make code difficult to understand and maintain.
Example: Online Shopping Eligibility
logged_in = True
has_address = True
payment_available = True
if logged_in:
print("User is logged in.")
if has_address:
print("Delivery address is available.")
if payment_available:
print("Payment method is available.")
print("Order can proceed.")
Output:
User is logged in.
Delivery address is available.
Payment method is available.
Order can proceed.
Explanation:
- The first condition checks the login status.
- The second condition checks whether a delivery address is available.
- The third condition checks whether a payment method is available.
- The order message appears only if all three conditions are true.
In a real application, these checks are only a simplified demonstration. Order processing must also validate inventory, payment results, delivery details, and other relevant requirements.
10. Nested Conditions with Logical Operators
Logical operators such as and, or, and not can combine or modify conditions. In some situations, a nested structure can be simplified using a logical expression.
10.1 Using and
Suppose an action should occur only when both the age requirement and the license requirement are satisfied.
age = 24
has_license = True
if age >= 18:
if has_license:
print("Eligible to drive.")
The same requirement can be expressed as:
if age >= 18 and has_license:
print("Eligible to drive.")
Both versions produce the same result for these conditions. The second version is shorter and may be easier to read when the requirements are simple.
10.2 Using or
Suppose a user receives access if they are either an administrator or a manager.
role = "manager"
if role == "admin" or role == "manager":
print("Access granted.")
Output:
Access granted.
The or operator returns a truthy result when at least one of the alternatives is true.
10.3 Using not
is_blocked = False
if not is_blocked:
print("The account is not blocked.")
Output:
The account is not blocked.
The not operator reverses the Boolean result of the expression.
11. Nested if Statements with User Input
The input() function allows users to provide information while the program is running. Nested conditions can evaluate that information and determine which instructions should execute.
Example: Voting Eligibility Checker
try:
age = int(input("Enter your age: "))
if age >= 0:
if age >= 18:
print("You meet the minimum voting age.")
else:
print("You are below the minimum voting age.")
else:
print("Age cannot be negative.")
except ValueError:
print("Please enter a valid whole number.")
Sample Output 1
Enter your age: 25
You meet the minimum voting age.
Sample Output 2
Enter your age: 16
You are below the minimum voting age.
Sample Output 3
Enter your age: -3
Age cannot be negative.
Sample Output 4
Enter your age: hello
Please enter a valid whole number.
Explanation: The program first validates whether the age is non-negative. If it is, the inner condition checks the minimum age requirement. The try-except block handles input that cannot be converted into an integer.
The example illustrates a programming rule, not a complete determination of legal voting eligibility. Actual eligibility depends on applicable laws and other requirements.
12. Nested if Statements with Strings
Strings can be used in nested conditions to check usernames, roles, categories, and user choices.
Example: Basic Role Check
username = "Amit"
role = "admin"
if username:
print("Username is provided.")
if role == "admin":
print("Administrator options are available.")
else:
print("Standard user options are available.")
else:
print("Username is missing.")
Output:
Username is provided.
Administrator options are available.
In this example, the outer condition checks whether the username is non-empty. The inner condition determines which role-related message is displayed.
In production applications, authorization must be checked using trusted authentication and permission data. A string comparison alone is not a security mechanism.
13. Nested if Statements with Lists
Nested conditions can check whether a collection contains data and then inspect its contents.
Example: Checking a Shopping Cart
cart = ["Laptop", "Mouse"]
discount_enabled = True
if cart:
print("Shopping cart is not empty.")
if discount_enabled:
print("A discount may be applied.")
else:
print("No discount is available.")
else:
print("Shopping cart is empty.")
Output:
Shopping cart is not empty.
A discount may be applied.
A non-empty list evaluates to true in a Boolean context, while an empty list evaluates to false. The inner condition is evaluated only when the cart is not empty.
14. Real-World Applications of Nested Conditional Statements
14.1 Login and Access Control
logged_in = True
is_admin = True
if logged_in:
if is_admin:
print("Open administrator dashboard.")
else:
print("Open user dashboard.")
else:
print("Please log in first.")
This demonstrates how a program can make a second decision after checking the login state.
14.2 Exam Result Processing
marks = 76
attendance = 90
if attendance >= 75:
if marks >= 40:
print("Student has passed.")
else:
print("Student has failed the examination.")
else:
print("Attendance requirement not satisfied.")
The program checks attendance before evaluating the marks. The thresholds are illustrative and should be adjusted to the applicable rules.
14.3 Employee Bonus Eligibility
years_of_service = 6
performance_rating = 5
if years_of_service >= 3:
if performance_rating >= 4:
print("Employee qualifies for bonus consideration.")
else:
print("Performance requirement not satisfied.")
else:
print("Service requirement not satisfied.")
The inner condition evaluates performance only after the service requirement has been met.
14.4 Product Purchase Validation
stock = 10
payment_confirmed = True
if stock > 0:
if payment_confirmed:
print("Purchase can be confirmed.")
else:
print("Payment is pending.")
else:
print("Product is out of stock.")
This example demonstrates the relationship between stock availability and payment status. A real purchasing system must use reliable inventory and payment verification.
14.5 Weather-Based Activity
temperature = 28
is_raining = False
if temperature >= 20:
if not is_raining:
print("Conditions are suitable for an outdoor activity.")
else:
print("Consider an indoor activity.")
else:
print("The weather is relatively cold.")
The program checks the temperature first and then evaluates the rain condition when the temperature requirement is met.
15. Difference Between Nested if and if-elif-else
Nested conditions and if-elif-else chains both support decision-making, but they are useful in different situations.
| Feature |
Nested if |
if-elif-else |
| Structure |
One conditional statement inside another. |
Several alternative conditions at the same level. |
| Best use |
Dependent decisions. |
Choosing between multiple alternatives. |
| Indentation |
Additional indentation for each nesting level. |
Branches generally align at the same level. |
| Complexity |
Can become difficult to read when deeply nested. |
Often easier to read for a sequence of alternatives. |
| Execution |
Inner conditions are evaluated only when their containing block is reached. |
Conditions are checked in order until a true branch is found. |
Nested if Example
age = 25
has_license = True
if age >= 18:
if has_license:
print("Eligible to drive.")
if-elif-else Example
marks = 85
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Grade C")
Use nested conditions when one decision depends on another. Use an if-elif-else chain when choosing among several alternatives at the same decision level.
16. Common Errors in Nested Conditional Statements
16.1 Incorrect Indentation
Incorrect:
if age >= 18:
if has_license:
print("Eligible")
Problem: The inner condition is not indented inside the outer block.
Correct:
if age >= 18:
if has_license:
print("Eligible")
16.2 Placing else at the Wrong Level
An else clause must align with the if statement to which it belongs.
Correct example:
age = 16
has_permission = True
if age >= 18:
if has_permission:
print("Condition satisfied.")
else:
print("Permission is missing.")
else:
print("Age requirement not satisfied.")
The first else belongs to the inner if, while the second else belongs to the outer if.
16.3 Using Assignment Instead of Comparison
Incorrect:
if age >= 18:
if age = 18:
print("Age is 18.")
Problem: A single equals sign is used for assignment, not equality comparison. This produces a syntax error in this condition.
Correct:
if age >= 18:
if age == 18:
print("Age is 18.")
16.4 Repeating Unnecessary Conditions
Repeating the same check inside a block can make the code unnecessarily complicated.
Less clear:
if age >= 18:
if age >= 18:
print("Adult")
Better:
if age >= 18:
print("Adult")
16.5 Using the Wrong Logical Operator
Consider a condition intended to check whether a number is between 10 and 20, inclusive.
Incorrect:
number = 25
if number >= 10:
if number <= 20:
print("Number is within range.")
The code itself is valid, but it does not print anything for 25 because the inner condition is false. Always check whether the conditions represent the intended range and test boundary values.
Alternative with a single condition:
number = 15
if 10 <= number <= 20:
print("Number is within range.")
16.6 Excessive Nesting
Too many levels of nesting can make a program difficult to maintain. Consider using logical operators, early returns inside functions, or simpler conditional structures when they express the same logic more clearly.
17. Best Practices for Writing Nested Conditions
- Use nesting only when needed: Nested statements should represent genuine dependencies between decisions.
- Maintain consistent indentation: Use four spaces for each level.
- Choose descriptive variable names: Names such as
has_permission and is_available make conditions easier to understand.
- Avoid deep nesting: Prefer simpler logic when possible.
- Test every branch: Test combinations where outer and inner conditions are true or false.
- Handle invalid input: Convert and validate user-provided values safely.
- Use logical operators appropriately: Combine simple dependent checks when doing so improves readability.
- Keep each block focused: Each conditional block should perform a clear and understandable task.
- Check boundary values: Test values at, below, and above important thresholds.
- Document complex logic: Use short comments when a condition's purpose is not obvious.
18. Mini Project: Student Admission Eligibility Checker
Project Objective: Create a Python program that checks whether a student satisfies a minimum marks requirement and an interview requirement.
Project Code
try:
marks = float(input("Enter your marks percentage: "))
if 0 <= marks <= 100:
if marks >= 60:
interview_passed = input(
"Did you pass the interview? (yes/no): "
).strip().lower()
if interview_passed == "yes":
print("You meet the admission criteria.")
elif interview_passed == "no":
print("Interview requirement not satisfied.")
else:
print("Please enter yes or no.")
else:
print("Marks requirement not satisfied.")
else:
print("Enter a percentage between 0 and 100.")
except ValueError:
print("Please enter a valid numeric percentage.")
Sample Output 1
Enter your marks percentage: 85
Did you pass the interview? (yes/no): yes
You meet the admission criteria.
Sample Output 2
Enter your marks percentage: 55
Marks requirement not satisfied.
Sample Output 3
Enter your marks percentage: 78
Did you pass the interview? (yes/no): no
Interview requirement not satisfied.
Project Explanation
- The program first accepts the student's marks percentage.
- The outer condition validates the percentage range.
- The next condition checks whether the marks meet the minimum threshold.
- If the marks qualify, the program asks about the interview result.
- A nested conditional checks the interview response and displays an appropriate message.
- The
try-except block handles invalid numeric input.
This project demonstrates several levels of decision-making, input validation, and error handling. The admission thresholds are examples and should be replaced with actual institutional criteria.
19. Practice Exercises
Exercise 1: Number Classification
Write a program that checks whether a number is non-negative. If it is, use an inner condition to determine whether it is zero or positive. Otherwise, display a negative-number message.
Exercise 2: Driving Eligibility
Ask the user for their age. If they meet the minimum age requirement, check whether they have a valid driving licence.
Exercise 3: Student Grade
Check whether marks are at least 40. If the student passes, use an inner conditional structure to assign a grade based on additional thresholds.
Exercise 4: Shopping Discount
Check whether a customer's purchase amount meets a minimum threshold. If it does, check whether the customer has a valid discount code.
Exercise 5: Account Access
Check whether a user is logged in. If the user is logged in, check whether the account has administrator permissions.
Exercise 6: Product Availability
Check whether the stock quantity is greater than zero. If the product is available, check whether delivery is supported for the selected location.
Exercise 7: Weather Conditions
Check whether the temperature is within a specified range. If it is, check whether it is raining before recommending an outdoor activity.
Exercise 8: Password Validation
Check whether a password contains at least eight characters. If it meets the length requirement, check another rule such as whether it contains a digit. This is a learning exercise, not a complete password-security solution.
Exercise 9: Employee Bonus
Check whether an employee has completed the required years of service. If eligible, check whether their performance rating meets the bonus threshold.
Exercise 10: Online Order
Check whether the shopping cart contains items. If it does, check whether payment has been confirmed before displaying an order confirmation message.
20. Interview Questions and Answers
Q1. What is a nested conditional statement in Python?
A nested conditional statement is a conditional statement placed inside another conditional statement. It supports decisions that depend on earlier conditions.
Q2. Why are nested if statements used?
They are used when a program must evaluate an additional condition only after a preceding condition has been satisfied.
Q3. What is the syntax of a nested if statement?
The general syntax is an outer if condition followed by an indented block containing another if statement and its own indented body.
Q4. What happens when the outer condition is false?
The outer block is skipped, so its nested conditions are not evaluated during that execution path.
Q5. Can an if statement be nested inside an else block?
Yes. An if statement can appear inside the body of an else block, an if block, or other suitable conditional blocks.
Q6. Why is indentation important in nested conditions?
Indentation defines the hierarchy of conditional blocks and determines which statements belong to each condition.
Q7. Can nested conditions contain elif statements?
Yes. An inner conditional structure can use if, elif, and else to evaluate multiple alternatives.
Q8. What is the difference between nested if and if-elif-else?
Nested if statements represent dependent decisions, while an if-elif-else chain selects among alternative branches at the same level.
Q9. Can nested conditions be replaced with logical operators?
Sometimes. If multiple conditions must all be true, the and operator may express the same logic more concisely. The correct choice depends on readability and whether the decisions are genuinely dependent.
Q10. What is a common problem with deeply nested statements?
Deep nesting can reduce readability and make code harder to test, debug, and maintain.
Q11. Can nested if statements be used with user input?
Yes. Programs can collect user input, convert it to the required type, validate it, and evaluate multiple conditions based on the entered values.
Q12. How can nested conditional code be tested effectively?
Test each possible path, including true and false outer conditions, true and false inner conditions, boundary values, and invalid input where applicable.
21. Quick Revision Checklist
- A nested conditional places one conditional statement inside another.
- The outer condition is evaluated before its inner conditions.
- An inner condition is evaluated only when execution reaches its block.
- Every nesting level requires appropriate indentation.
- An
else clause must align with its corresponding if.
- Nested structures can contain
if, elif, and else clauses.
- Logical operators can simplify some nested conditions.
- Excessive nesting should be avoided when clearer alternatives exist.
- User input should be validated before it is used in comparisons.
- Testing every branch helps identify logical errors.
22. Conclusion
Nested conditional statements are an important part of Python programming because they allow developers to implement multi-level decision-making. By placing one conditional statement inside another, a program can evaluate dependent conditions and select appropriate actions based on the results.
Understanding outer and inner conditions, correct indentation, nested if-else structures, logical operators, and common errors will help you write reliable and readable programs. Practical examples such as eligibility checking, grade classification, order processing, and access control provide opportunities to apply these concepts.
As you progress, practise simplifying unnecessary nesting with logical operators or alternative conditional structures. Choosing the clearest approach will make your Python programs easier to understand, debug, test, and maintain.
23. Learn More with JustAcademy
Continue learning Python programming concepts through the following resources: