Using multiple elifs in if statements #
You can use multiple elif statements in an if block to specify more than two possible conditions to be checked. The first elif statement whose condition is True executes its block of code, and the rest of the elif statements are skipped.
Here's an example:
def get_age_description(age):
if age < 18:
return "You are not yet an adult."
elif age >= 18 and age < 21:
return "You are an adult, but you cannot drink."
elif age >= 21 and age < 65:
return "You are an adult and can drink."
elif age >= 65:
return "You are a senior citizen."
print(get_age_description(25)) # Output: You are an adult and can drink.
In this example, we use multiple elif statements to check if someone is an adult, if they can drink alcohol, or if they are a senior citizen.
Exercise #
- Use an
if-ellf-elsestatement so that the functionget_grade()returns the correct value:- If
scoreis greather than or equal to 90, returns"A". - If
scoreis greather than or equal to 80, returns"B". - If
scoreis greather than or equal to 70, returns"C". - If
scoreis greather than or equal to 60, returns"D". - For any other values of
score, returns"F".
- If
Tests #
get_grade(90)should returns"A".get_grade(80)should returns"B".get_grade(70)should returns"C".get_grade(60)should returns"D".get_grade(50)should returns"F".
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules