if statements, we have
else statements, we can also have
Now you may be asking yourself, what the heck is an
elif statement? It’s exactly what it sounds like, “else if”. An
elif statement checks another condition after the previous
if statements conditions aren’t met.
We can use
elif statements to control the order we want our program to check each of our conditional statements. First, the
if statement is checked, then each
elif statement is checked from top to bottom, then finally the
else code is executed if none of the previous conditions have been met.
Let’s take a look at this in practice. The following function will display a “thank you” message after someone donates to a charity: It takes the donation amount and prints a message based on how much was donated.
def thank_you(donation): if donation >= 1000: print("Thank you for your donation! You have achieved platinum donation status!") elif donation >= 500: print("Thank you for your donation! You have achieved gold donation status!") elif donation >= 100: print("Thank you for your donation! You have achieved silver donation status!") else: print("Thank you for your donation! You have achieved bronze donation status!")
Take a second to think about this function. What would happen if all of the
elif statements were simply
if statements? If you donated $1000.00, then the first three messages would all print because each
if condition had been met.
But because we used
elif statements, it checks each condition sequentially and only prints one message. If I donate $600.00, the code first checks if that is over $1000.00, which it is not, then it checks if it’s over $500.00, which it is, so it prints that message, then because all of the other statements are
else, none of them get checked and no more messages get printed.
Try your hand at some other
Calvin Coolidge’s Cool College has noticed that students prefer to get letter grades over GPA numbers. They want you to write a function called
grade_converter that converts an inputted GPA into the appropriate letter grade. Your function should be named
grade_converter, take the input
gpa, and convert the following GPAs:
- 4.0 or higher should return
- 3.0 or higher should return
- 2.0 or higher should return
- 1.0 or higher should return
- 0.0 or higher should return
You can do this by creating a variable called
Then, you should use
elif statements to set
grade to the appropriate letter grade for the
At the end of the function, return