Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.7 Mastering Nested Conditionals - Unlocking Advanced Decision-Making in Programming
A supplemental blog on nested conditionals. Learn how nested conditionals allow for more complex decision-making by enabling multiple levels of conditions than regular conditionals.
IF exam_score >= 60
{
IF attendance >= 75
{
DISPLAY "Pass"
}
ELSE
{
DISPLAY "Fail due to low attendance"
}
}
ELSE
{
DISPLAY "Fail due to low exam score"
}
## Python Segment
# Ask the user for input values
weight = float(input("Enter the weight of the package in pounds: "))
delivery_days = int(input("Enter the delivery speed (number of delivery days): "))
# Determine if the delivery is under 3 days or not
is_express = delivery_days < 3
# Nested conditionals to calculate shipping cost
if is_express: # More expensive if under 3 days
if weight <= 5:
print("Shipping cost is $15")
else:
print("Shipping cost is $25")
else: # Less expensive if 3 days or more
if weight <= 5:
print("Shipping cost is $5")
else:
print("Shipping cost is $10")
## Another Example
# Ask the user for input values
age = int(input("Enter your age: "))
is_student = input("Are you a student? (yes or no): ")
# Determine if the user is a student
student_discount = (is_student == 'yes' or is_student == 'Yes' or is_student == 'YES')
# Nested conditionals to calculate ticket price
if age < 12: # Child ticket
ticket_price = 8 # Base price for children
elif age >= 12 and age <= 64: # Adult ticket
ticket_price = 12 # Base price for adults
else: # Senior ticket
ticket_price = 10 # Base price for seniors
# Apply student discount if applicable
if student_discount:
ticket_price *= 0.8 # 20% discount
print(f"The ticket price is: ${ticket_price:.2f}")
# Example program to classify the type of triangle based on the lengths of its sides
# Step 1: Get input for the three sides of the triangle
side1 = float(input("Enter the length of side 1: "))
side2 = float(input("Enter the length of side 2: "))
side3 = float(input("Enter the length of side 3: "))
# Step 2: Check if the entered sides can form a valid triangle
if (side1 + side2 > side3) and (side1 + side3 > side2) and (side2 + side3 > side1):
# Step 3: Use nested conditionals to determine the type of triangle
if side1 == side2 == side3:
print("This is an Equilateral Triangle.")
elif side1 == side2 or side1 == side3 or side2 == side3:
print("This is an Isosceles Triangle.")
else:
print("This is a Scalene Triangle.")
else:
# If it's not a valid triangle
print("The entered sides do not form a valid triangle.")