Elif Statement in Python
The elif statement (short for "else if")
is used to check multiple conditions in sequence. It allows you to handle more than two possible outcomes in your control flow. If the first condition is False
, the elif
statement checks another condition, and if this condition is True
, the associated block of code will run.
Using elif
makes your code cleaner by avoiding excessive nesting of if
statements.
Syntax of elif
You can have as many elif statements as needed, and you can also combine if, elif, and else to handle different situations.
Example 1: Grading System
Let’s create a program that assigns a letter grade based on a student’s score:
Explanation:
- If the score is greater than or equal to 90, the program prints “You got an A!” and stops checking further conditions.
- If the score is less than 90 but greater than or equal to 80, it prints “You got a B!” and stops.
- This process continues until the program finds a condition that is True, or defaults to the else block if none of the conditions match.
Example 2: Categorizing Age Groups
Let’s categorize people based on their age:
Complex Conditions with elif
You can use comparison and logical operators (and, or, not) in elif statements to check more complex conditions.
Exercise: elif Statements
Write a program that asks the user for a number and then prints whether the number is:
- Positive
- Negative
- Zero
Create a program that asks for a person’s age and prints which type of movies they are allowed to watch:
- Under 13: “G-rated”
- 13 to 17: “PG-13”
- 18 and above: “R-rated”