Lesson 7: What are Nested Conditionals?
“Can I buy a New Coat?” Example
Here is the Python code for this scenario:
bank_balance = int(input("How much money do you currently have in your bank account?"))
colour_preference = input("What colour coat do you prefer - grey or black?")
if bank_balance >= 50:
if colour_preference == "grey":
print("You are able to buy a grey coat.")
else:
print("You are able to buy a black coat.")
else:
print("You do not have enough money to buy a new coat.")
The code prompts the user to enter their bank balance and their preferred coat colour.
The outer IF statement checks whether the entered amount exceeds 50. If it does not, the ELSE statement is activated, and the user is told they cannot buy a new coat. Otherwise, the inner IF statement is checked and the preferred colour is chosen.
The following image shows sample output of the program:
Why use Boolean operators with conditional statements?
The three fundamental Boolean operators are:
- and
- or
- not
We can rewrite the “Can I buy a new coat?” code example with Boolean operators.
int(input("How much money do you currently have in your bank account?"))
colour_preference = input("What colour coat do you prefer - grey or black?")
if bank_balance >= 50 and colour_preference == "grey":
print("You are able to buy a grey coat.")
elif bank_balance < 50:
print("You do not have enough money to buy a new coat.")
else:
print("You are able to buy a black coat.")
The code rewrites the first example by using the and Boolean operator to test whether the user has the necessary money for a coat and also whether they want a grey coat.
The resulting output would be: