Fall 2024 - P3
3.7 Homework Question
Test your understanding of nested conditionals
from IPython.core.display import HTML
def load_css():
styles = open("custom2.css", "r").read()
return HTML(f"<style>{styles}</style>")
load_css()
Testing Your Skills (Hack #1)
- Create a simple system using
if
andelse
statements that determines whether or not a user (based on their age) is eligible to vote - If the person is less than 18 years old, they should not be able to vote
- If the person is 18 years old or older, they are able to vote
- You should get something like this:
def check_voting_eligibility(age):
"""Check if the user is eligible to vote based on age."""
if age >= 18:
return "You are eligible to vote."
else:
return "You are not eligible to vote."
Explanation
- The if statement checks if the user’s age is greater than or equal to 18. If they are 18, that means that the statement is true and will print “You are eligible to vote.” If the age requirement is not met, that means the statement will be false and the else statement will print “You are not eligible to vote.”
Quick Quiz
- What would the function output if the user’s age was 16?
- A: It would say, “You are not eligible to vote.”
- When the age of the user is less than 18, what is the condition in the if statement?
- A: age < 18, meaning that the statement is false
- What is the purpose of the if statement in the function?
- A: To check if the user is eligible to vote
Hack #2
- Create a simple system using
if
andelse
statements that determines what the user would eat - If the person is healthy, make them eat an apple
- If the person doesn’t care about what they eat, make them drink coffee
- If the person is unhealthy, make them eat chocolate
- You should get something like this:
// Get user input
let healthStatus = prompt("Are you healthy, unhealthy, or indifferent about food? (healthy/unhealthy/indifferent)").toLowerCase();
if (healthStatus === "healthy") {
console.log("You should eat an apple!");
} else {
// Check for the other conditions within the else block
if (healthStatus === "unhealthy") {
console.log("You should eat chocolate!");
} else {
console.log("You don't care about what you eat. How about a coffee?");
}
}
File "/tmp/ipykernel_742471/4079008279.py", line 1
// Get user input
^
SyntaxError: invalid syntax
Explanation
- The if statement checks if the user’s health status is “healthy.” If this condition is true, the program will print “You should eat an apple!” indicating a healthy choice.
- If the health status is not “healthy,” the else statement is executed. Within this block, another if statement checks if the user’s health status is “unhealthy.” If this condition is true, the program will print “You should eat chocolate!”
- Lastly, if neither condition is met when the user doesn’t care about what they eat, the else statement will execute, printing “You don’t care about what you eat. How about a coffee?” This covers the case for users who are indifferent about their food choices. Keep in mind, you can also achieve this same result using
elif statements
instead of having to create chains ofif
andelse statements
. However, it’s important to note thatelif statements
are NOT nested conditionals because they form a single-level structure.
# Get user input
health_status = input("Are you healthy, unhealthy, or indifferent about food? (healthy/unhealthy/indifferent): ").strip().lower()
if health_status == "healthy":
print("You should eat an apple!")
elif health_status == "unhealthy":
print("You should eat chocolate!")
elif health_status == "indifferent":
print("You don't care about what you eat. How about a coffee?")
else:
print("Invalid input! Please enter 'healthy', 'unhealthy', or 'indifferent'.")
- Notice how there’s no inner constructs with
elif statements
Quick Quiz
- What would the function output if the user’s age was healthy?
- A: It would say, “You should eat an apple!”
- When the age of the user is unhealthy, what is the condition in the if statement?
- A: Since the user is unhealthy, it doesn’t meet the requirements for eating an apple, meaning that the statement is false
- How can you use
elif statements
to replace theif and else statement
chains? - A: You could get something like this:
- Why are
elif statements
not nested conditionals? - A: Because they are not nested and form a flat structure, they are not conditional statements