When writing Python code, you often need to make decisions based on multiple conditions. This is typically done using multi-branch conditional statements with if
, elif
, and else
. These statements allow your code to execute different blocks of code based on various conditions.
The basic structure of multi-branch conditional statements in Python looks like this:
if condition1:
# Block of code to execute if condition1 is true
elif condition2:
# Block of code to execute if condition2 is true
elif condition3:
# Block of code to execute if condition3 is true
else:
# Block of code to execute if none of the above conditions are true
Let’s consider a practical example where we determine the grade of a student based on their score:
def determine_grade(score):
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
return grade
# Example usage
score = 85
print(f"The grade for a score of {score} is {determine_grade(score)}")
determine_grade
that takes a parameter score
.if score >= 90
):elif score >= 80
):elif score >= 70
):elif score >= 60
):else
):Here’s another example that provides advice based on the weather conditions:
def weather_advice(weather):
if weather == 'sunny':
advice = "It's a sunny day! Wear sunglasses and apply sunscreen."
elif weather == 'rainy':
advice = "It's raining outside. Don't forget your umbrella."
elif weather == 'snowy':
advice = "It's snowy and cold. Wear a warm coat and boots."
elif weather == 'windy':
advice = "It's windy. A light jacket should be enough."
else:
advice = "Weather is unpredictable. Be prepared for anything."
return advice
# Example usage
current_weather = 'rainy'
print(weather_advice(current_weather))
weather_advice
that takes a parameter weather
.if weather == 'sunny'
):elif weather == 'rainy'
):elif weather == 'snowy'
):elif weather == 'windy'
):else
):