In the previous lessons, you learned how to use the if, if...else, and if...elif...else statements to make decisions in Python. These statements are suitable for many situations, but sometimes a program must make a second decision only after the first condition has been satisfied.
For example, consider the following real-life situations:
These situations require one condition to be checked before another. In Python, this is achieved using nested if statements.
A nested if statement is simply an if statement placed inside another if statement. The inner if statement is evaluated only when the outer if condition is True.
Nested if statements are commonly used in login systems, banking software, admission systems, shopping applications, online forms, and many other real-world programs.
After completing this lesson, you will be able to:
if statement is.if statements.if Statement?A nested if statement is an if statement that appears inside another if statement.
The outer if statement is evaluated first. If its condition is True, Python enters the outer block and evaluates the inner if statement. If the outer condition is False, the inner if statement is skipped completely.
This allows a program to perform step-by-step decision making.
if condition1:
statement
if condition2:
statement
Notice that the second if statement is indented inside the first one. This indentation tells Python that the second condition belongs to the first condition.
if Statements?Some decisions depend on earlier decisions. In such cases, using a single if statement is not sufficient.
Consider a college admission system.
The program should first verify whether the student passed the entrance examination.
If the student passed, the program should then verify whether all required documents have been submitted.
If the student failed the entrance examination, checking the documents makes no sense.
This is an ideal situation for using a nested if statement.
passed_exam = True
documents_submitted = True
if passed_exam:
if documents_submitted:
print("Admission Confirmed")
Output
Admission Confirmed
The inner condition is evaluated only because the first condition is true.
if Statements WorkPython evaluates nested if statements from the outside toward the inside.
if condition.False, skip the entire nested block.True, enter the block.if condition.True, execute its statements.This process can continue for additional nested levels if required.
if ProgramLet’s write a simple program that checks whether a person is eligible to drive.
age = 20
has_license = True
if age >= 18:
if has_license:
print("You are allowed to drive.")
Output
You are allowed to drive.
Python first verifies that the person is at least 18 years old. Since this condition is true, it checks the second condition.
age = 16
has_license = True
if age >= 18:
if has_license:
print("You are allowed to drive.")
print("Program Finished.")
Output
Program Finished.
The outer condition is false, so Python never evaluates the inner if statement.
if Statement and a Nested if StatementSimple if |
Nested if |
|---|---|
| Checks a single condition. | Checks one condition inside another condition. |
| Suitable for simple decisions. | Suitable for multi-step decision making. |
| Contains only one decision level. | Contains two or more decision levels. |
| Easier to understand. | Useful when one decision depends on another. |
if StatementsIndentation becomes even more important when using nested conditional statements.
Each level of nesting must be indented consistently.
marks = 85
attendance = 90
if marks >= 40:
if attendance >= 75:
print("Eligible for Final Result")
Output
Eligible for Final Result
marks = 85
if marks >= 40:
if attendance >= 75:
print("Eligible")
Output
IndentationError: expected an indented block
Every nested block must have one additional indentation level compared to its parent block.
if Statements?Nested if statements are useful whenever one decision depends on another.
Common applications include:
In this section, you learned what a Python nested if statement is and why it is useful for solving multi-step decision-making problems. You explored its syntax, execution flow, indentation rules, and differences from a simple if statement. Through beginner-friendly examples, you saw how Python evaluates the outer condition before checking the inner condition. In the next section, you will learn how to build more advanced nested conditional programs using comparison operators, logical operators, Boolean variables, user input, and multiple levels of nesting.
Now that you understand what a nested if statement is, it’s time to explore how it works in more realistic situations. Nested if statements become especially useful when one decision depends on the result of another decision.
In this section, you will learn how to combine comparison operators, logical operators, Boolean variables, and user input with nested if statements. You will also explore multiple levels of nesting and common mistakes that beginners should avoid.
if StatementsA nested if statement can contain another nested if statement. This creates multiple levels of decision making.
Python evaluates each condition step by step. If any outer condition evaluates to False, Python skips all inner conditions that belong to it.
age = 22
has_license = True
has_helmet = True
if age >= 18:
if has_license:
if has_helmet:
print("You are allowed to ride the motorcycle.")
Output
You are allowed to ride the motorcycle.
In this example, Python performs three checks:
Only when all three conditions are satisfied does the program display the final message.
if StatementsComparison operators are commonly used to compare values before moving to the next level of decision making.
marks = 92
attendance = 88
if marks >= 90:
if attendance >= 75:
print("Eligible for Scholarship")
Output
Eligible for Scholarship
The scholarship is awarded only if both conditions are satisfied.
salary = 50000
experience = 4
if salary >= 40000:
if experience >= 3:
print("Eligible for Promotion")
Output
Eligible for Promotion
if StatementsLogical operators such as and, or, and not can also be combined with nested if statements.
age = 24
has_license = True
has_identity_card = True
if age >= 18:
if has_license and has_identity_card:
print("Driving Permission Granted")
Output
Driving Permission Granted
The logical operator and ensures that both conditions must be true before permission is granted.
Boolean variables simplify nested conditional statements because they already store either True or False.
is_member = True
has_coupon = True
if is_member:
if has_coupon:
print("Extra Discount Applied")
Output
Extra Discount Applied
The program checks whether the customer is a member before checking for a coupon.
Nested if statements become more useful when decisions are based on values entered by the user.
marks = int(input("Enter your marks: "))
documents = input("Documents Submitted (yes/no): ")
if marks >= 60:
if documents == "yes":
print("Admission Confirmed")
Sample Output
Enter your marks: 82
Documents Submitted (yes/no): yes
Admission Confirmed
The second condition is checked only after the student qualifies based on marks.
if StatementsNested conditional statements are commonly used in many real-world applications.
| Application | Outer Condition | Inner Condition |
|---|---|---|
| Online Banking | User Logged In | Sufficient Balance |
| College Admission | Passed Entrance Exam | Documents Submitted |
| Driving License | Age Verification | License Available |
| Online Shopping | Premium Member | Purchase Amount Eligible |
| Library System | Membership Active | No Pending Fine |
In each situation, one decision depends on another, making nested if statements an appropriate choice.
Consider the following program.
marks = 78
attendance = 82
if marks >= 40:
print("Marks Verified")
if attendance >= 75:
print("Attendance Verified")
print("Program Completed")
Execution Steps
marks >= 40.True, so the first message is displayed.attendance >= 75.True, so the second message is displayed.Output
Marks Verified
Attendance Verified
Program Completed
The most common mistake is forgetting to indent the inner if statement correctly.
Incorrect
age = 20
if age >= 18:
if True:
print("Allowed")
This results in an IndentationError.
if StatementsSometimes a logical operator such as and can replace a nested if statement and make the code shorter.
Instead of:
if age >= 18:
if has_license:
print("Allowed")
You can write:
if age >= 18 and has_license:
print("Allowed")
Both versions produce the same result. However, nested if statements are often easier to understand when each condition represents a separate step in the decision-making process.
Deeply nested code becomes difficult to read and maintain. If your program contains many levels of nesting, consider simplifying the logic or using functions.
In this section, you learned how to build more advanced programs using nested if statements. You explored multiple levels of nesting, comparison operators, logical operators, Boolean variables, user input, and real-world applications. You also learned how Python evaluates nested conditions step by step and reviewed common beginner mistakes such as incorrect indentation, unnecessary nesting, and excessive nesting levels. In the next section, you will apply these concepts by building practical projects such as ATM transaction systems, login authentication, college admission checkers, employee bonus calculators, and online shopping discount systems.
Nested if statements are widely used in real-world applications where one decision depends on the result of another. Instead of checking all conditions at once, a program verifies them one by one in a logical sequence. This makes the program easier to understand and ensures that unnecessary checks are avoided.
In this section, you will build practical programs that demonstrate how nested if statements are used in applications such as ATM systems, login authentication, college admission, employee bonus calculations, online shopping, and library management.
if StatementsBefore allowing a withdrawal, an ATM must verify whether the user has entered the correct PIN. If the PIN is correct, the ATM then checks whether the account has sufficient balance.
correct_pin = 1234
entered_pin = 1234
balance = 5000
withdraw_amount = 2000
if entered_pin == correct_pin:
if withdraw_amount <= balance:
print("Transaction Successful")
Output
Transaction Successful
The balance is checked only after the PIN has been verified.
A website first checks the username. If it is correct, the password is verified.
username = "admin"
password = "Python123"
if username == "admin":
if password == "Python123":
print("Login Successful")
Output
Login Successful
This two-step verification process is common in login systems.
A student must first qualify based on marks. After that, the documents are verified.
marks = 82
documents_submitted = True
if marks >= 60:
if documents_submitted:
print("Admission Confirmed")
Output
Admission Confirmed
An employee receives a bonus only if they have completed the required years of service and achieved a satisfactory performance rating.
experience = 6
performance = "Excellent"
if experience >= 5:
if performance == "Excellent":
print("Bonus Approved")
Output
Bonus Approved
An online shopping platform first checks whether the customer is a premium member. If so, it checks the purchase amount for an additional discount.
premium_member = True
purchase_amount = 6500
if premium_member:
if purchase_amount >= 5000:
print("Extra Discount Applied")
Output
Extra Discount Applied
A library allows members to borrow books only if their membership is active and they have no pending fines.
membership_active = True
pending_fine = 0
if membership_active:
if pending_fine == 0:
print("Book Issued Successfully")
Output
Book Issued Successfully
if StatementsMost real-world applications interact with users. The following example demonstrates how nested if statements work with user input.
age = int(input("Enter your age: "))
qualification = input("Passed Class 12? (yes/no): ")
if age >= 17:
if qualification == "yes":
print("Eligible for Admission")
Sample Output
Enter your age: 19
Passed Class 12? (yes/no): yes
Eligible for Admission
The second condition is checked only after the age requirement has been satisfied.
Consider the following program.
registered = True
fees_paid = True
if registered:
print("Registration Verified")
if fees_paid:
print("Fees Verified")
print("Exam Hall Ticket Generated")
print("Process Completed")
Execution Steps
True, so the first message is displayed.True, so the remaining messages are displayed.Output
Registration Verified
Fees Verified
Exam Hall Ticket Generated
Process Completed
if StatementsToo many nested levels make programs difficult to understand. Whenever possible, limit nesting to two or three levels.
Choose variable names that clearly describe the data.
student_marks = 88
attendance_percentage = 92
These names are easier to understand than short names such as x or y.
Each new level of nesting should be indented by four additional spaces.
Do not check the same condition multiple times inside different nested blocks.
If a nested if statement contains only one simple condition, consider using logical operators such as and to make the code shorter.
if age >= 18 and has_license:
print("Driving Allowed")
However, when each condition represents a separate decision-making step, nested if statements often improve readability.
if executes only if the outer condition is true.age = 20
if age >= 18:
if True:
print("Eligible")
This program generates an IndentationError because the inner if statement is not properly indented.
age = 20
if age >= 18:
if True:
print("Eligible")
Output
Eligible
In this section, you applied nested if statements to practical programming problems such as ATM transactions, login authentication, college admission, employee bonus eligibility, online shopping discounts, and library membership verification. You also learned how nested conditions work with user input, followed the execution flow step by step, and explored coding best practices. Finally, you reviewed common beginner mistakes and learned how to write cleaner, more readable nested conditional programs. In the final section, you will review everything covered in this lesson through a summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on the Python Match Case Statement.
In this lesson, you learned how Python uses nested if statements to perform multi-level decision making. Unlike a simple if statement, which evaluates only one condition, a nested if statement allows one condition to be checked only after another condition has been satisfied.
You explored the syntax, execution flow, and indentation rules of nested conditional statements. You also learned how to combine nested if statements with comparison operators, logical operators, Boolean variables, and user input to create more intelligent programs.
Through practical examples such as ATM transactions, login authentication, college admissions, employee bonus calculations, online shopping discounts, and library management systems, you saw how nested conditions are used in real-world applications.
Although nested if statements are powerful, they should be used carefully. Excessive nesting can make code difficult to understand, so always keep your logic as simple and readable as possible.
if statement is an if statement inside another if statement.if statement executes only if the outer condition is True.if statements are useful for multi-step decision making.if statements.if statements are widely used in authentication systems, banking software, admission systems, and many other applications.if statement?A nested if statement is an if statement placed inside another if statement.
if statements?Use nested if statements when one decision depends on the result of another decision.
Yes. Python allows multiple levels of nesting, although excessive nesting should generally be avoided because it reduces readability.
The inner if statement is skipped completely.
if statements contain else blocks?Yes. Both the outer and inner if statements can have their own else blocks.
if statements with logical operators?Yes. Operators such as and, or, and not are commonly used together with nested if statements.
if statements?In some situations, logical operators or the if...elif...else statement can simplify the code. The best choice depends on the problem being solved.
if statements?Indentation tells Python which statements belong to each conditional block. Incorrect indentation results in an IndentationError.
if statement?if statements?if condition evaluates to False?if statements contain multiple levels?if statements?if statements.Create a Python program that simulates a simple banking security system using nested if statements.
Your program should:
Enter PIN: 1234
Enter Withdrawal Amount: 2500
Transaction Successful
Thank You for Using Our Banking System.
Enter PIN: 4321
Incorrect PIN
Thank You for Using Our Banking System.
Congratulations! You have successfully learned how to use Python nested if statements to build multi-level decision-making programs. You now understand how Python evaluates nested conditions, how to organize decision logic effectively, and how nested conditional statements are used in many real-world applications.
In the next lesson, you will learn the Python Match Case Statement. Introduced in Python 3.10, the match...case statement provides a clean and readable way to compare a value against multiple possible cases. It is particularly useful for menu-driven applications, command processing, and programs with many possible choices.