Member-only story
Python 101 — Nested if Statements
Nested if statements in Python are a way to combine multiple if statements into a single block of code. This can be useful when you need to check multiple conditions and execute different code blocks based on the results of those tests.
Let’s look at an example.
age = int(input("Enter your age: "))
monthly_subscription_amount = float(input("Enter your preferred monthly subscription amount: "))
if age >= 18:
if monthly_subscription_amount >= 50:
membership_plan = "Premium"
monthly_fee = 49.99
elif monthly_subscription_amount >= 30:
membership_plan = "Standard"
monthly_fee = 29.99
else:
membership_plan = "Basic"
monthly_fee = 19.99
else:
print("You must be 18 or older to subscribe to a membership plan.")
exit()
print(f"You have selected the {membership_plan} membership plan with a monthly fee of ${monthly_fee:.2f}.")
In this example, the outer if statement checks if the customer is 18 or older. If they are not, the code prints an error message and exits the program.
The elif statements check if the customer’s preferred monthly subscription amount is $50 or more, $30 or more, or less than $30. Based on their selection, the code assigns the corresponding membership plan and monthly fee.