Taking Conditional Logic Further with Nested if Statements
Previously, we learnt how to use if, elif, and else to make decisions in Python. Those allowed our programs to choose between different paths depending on whether a condition evaluated to True or False.
Most of the real world decisions depend on more than one condition.
Think about logging into your bank account to withdraw money. Entering the correct PIN is only the first step. Once you're in, the system still needs to check whether you have sufficient funds before approving the withdrawal.
How do we build that kind of layered decision-making in Python?
That's exactly what we'll explore in this article as we learn about nested if statements.
Nested if Statements
A nested if statement is simply an if statement placed inside another if statement. It allows a program to evaluate another condition only after the first condition has been met.
Syntax
if condition_1:
if condition_2:
# Code to execute
The inner if statement is only evaluated if the outer if statement is True.
Example:
Suppose you're analysing survey responses for a scholarship programme. Applicants must first be at least 18 years old. If they meet that requirement, then you can check whether their household income qualifies them for financial assistance.
age = 21
monthly_income = 18000
if age >= 18:
if monthly_income < 30000:
print("Eligible for the scholarship.")
else:
print("Age requirement met, but income is above the eligibility threshold.")
else:
print("Applicant does not meet the minimum age requirement.")
Here's what happens step by step:
Python stores the value
21in the variableageand18000in the variablemonthly_income.It evaluates the first condition:
age >= 18.Since
21is greater than or equal to18, the first condition evaluates toTrue.Because the first condition is
True, Python moves to the nestedifstatement and evaluates the second condition:monthly_income < 30000.Since
18000is less than30000, the second condition also evaluates toTrue.Python executes the nested
ifblock and prints:
Eligible for the scholarship.
Because both conditions were satisfied, the two else blocks are skipped and the program ends.
Notice the order of the checks. Python only evaluates the applicant's income after confirming they meet the minimum age requirement.
If the applicant were under 18, the income would never be checked because the program would immediately execute the outer else block. This is what makes nested ifstatements useful; they allow one decision to depend on the outcome of another.
Here are a few other examples, that demonstrate how multiple conditions can be evaluated one after another.
# Scenario 1: Job Application Screener
# Check whether the applicant has tertiary education. If they do, ask for their years of experience.
# If they have at least 3 years of experience, ask for their expected salary. If the salary expectation is Ksh 80,000 or less, shortlist them for an interview; otherwise, indicate that their salary expectation is too high.
# If they have fewer than 3 years of experience, print "Minimum 3 years of experience required." If they do not have tertiary education, print "Higher education is required for this position."
tertiary_education= input("Do you have a diploma, degree or higher?").lower()
if degree == "yes":
experience = int(input("How many years of experince"))
if experience >= 3:
salary = float(input("Enter your expected salary"))
if salary <= 80000:
print("Shortlisted for interview")
else:
print("Salary expectation too high")
else:
print("Minimum 3 years experience required")
else:
print("Higher education is required for this position")
`
`
# Scenario 2: Mobile Money Transfer Validator
# Write a program to validate a mobile money transfer.
# If the user has an account, check that they have sufficient funds and that the transfer amount does not exceed the daily limit of Ksh 150,000.
# If the transfer is successful, display the amount sent and the remaining balance. If the user does not have an account, print "Please register first."
mobile_checker = input("Do they have an active account? (Yes/No)")
if mobile_checker == "yes":
acc_balance = float(input("What is your account balance?"))
if acc_balance > 0:
amount_to_send = float(input("How much do you want to send??"))
if amount_to_send <= acc_balance:
new_balance = acc_balance - amount_to_send
if amount_to_send > 150000:
print("Amount exceeded daily limit")
else:
print("Successful transfer")
print(f"Amount sent: Ksh., {amount_to_send}, Your account balance is: Kshs., {new_balance}")
else:
print(f"Insufficient funds: Kshs., {acc_balance}")
else:
print("You have a low balance")
else:
print("Please register first.")
# Scenario 3: School Report Card Generator
# Write a program that generates a student's report card. Ask for the student's name and marks (out of 100) in Mathematics, English, Kiswahili, Science, and Social Studies. For each subject, assign a grade and remark using the grading scale provided. Then calculate the total marks (out of 500), the average score, and the overall grade based on the average using the same grading scale.
# Next, determine the student's promotion status: students with an average of 75 or above are promoted, those with an average between 50 and 74 are promoted but advised to work harder, while those below 50 should repeat the class.
# Finally, check whether the student received a grade E in any subject. If so, display a warning indicating that remedial lessons are required for the relevant subject(s).
# Print a neatly formatted report showing the student's name, subject grades, total marks, average, overall grade, promotion status and any remedial warning.
subjects = ["Maths", "English", "Kiswahili", "Science", "Social Studies"]
student_name = input("What is your name?")
print(f"{student_name} : Performance Summary")
print("==================================")
total_marks = 0
failed = ""
for subject in subjects:
marks = int(input(f"What was your score in {subject}"))
if 75<= marks <= 100:
grade = " A - Excellent"
elif 60<= marks <= 74:
grade = " B - Very Good"
elif 50<= marks <= 59:
grade = " C - Good"
elif 40<= marks <= 49:
grade = " D - Pass"
else:
grade = " E - Need Improvement"
total_marks += marks
print(f"{subject} | Score: {marks} | Grade:{grade}")
if grade == " E - Need Improvement":
failed += subject + " "
print(f"Total marks: {total_marks} / 500")
if failed:
print(f"NOTE: Remedial lessons required in {failed}")
print()
average = total_marks / len(subjects)
print(f"Average Score: {average}")
if average >= 75:
print("PROMOTED to next class")
elif 50 <= average <= 74:
print("PROMOTED - work harder next term")
else:
print("REPEAT - see your class teacher")
Result:
Mary Nancy : Performance Summary
==================================
Maths | Score: 43 | Grade: D - Pass
English | Score: 23 | Grade: E - Need Improvement
Kiswahili | Score: 56 | Grade: C - Good
Science | Score: 89 | Grade: A - Excellent
Social Studies | Score: 67 | Grade: B - Very Good
Total marks: 278 / 500
NOTE: Remedial lessons required in English
Average Score: 55.6
PROMOTED - Work harder next term
Don't stop with the examples in this article. Modify them, build your own, and experiment with different scenarios, because the best way to master programming is by writing and testing your own code.
As you continue practicing, you may find yourself using nested conditionals whenever a problem requires multiple levels of decision-making.
Bonus Tip: f-Strings
Before we wrap up, there's one small feature you've probably noticed throughout the examples in this article. Many of the print() statements begin with the letter f, like this;
print(f"{subject} | Score: {marks} | Grade:{grade}")
The f stands for formatted string (or f-string). It allows you to insert the value of a variable directly into a string by placing it inside curly braces {}.
Without an f-string, you would have to write:
print(subject, " | Score: ", marks, " | Grade: ", grade)
While both approaches work, f-strings are easier to read and become especially useful as your programs grow longer and your output includes multiple variables.
As we continue through this series, we'll use f-strings regularly to produce cleaner and more readable output.
Top comments (0)