Key Differences Between if-else & if-elif-else:
| Feature | if-else | if-elif-else |
|---|---|---|
| Number of conditions | Only two conditions | Multiple conditions |
| Execution Flow | One of the two blocks always executes | Checks multiple conditions sequentially |
| Efficiency | Simple and direct | More flexible but stops after the first match |
| Use Case | Binary choices (Yes/No, True/False) | Multiple possible values or categories |
Multiway if-elif-else statement:
- Represents an if statement that considers each condition until one evaluates to True or they all evaluate to False. When a condition evaluates to True the corresponding action is performed and the control skips to the end of the entire selection statement.
- If no condition evaluates to True, then the action after the trailing else is performed.
- The syntax is as follows:
python
1if condition1:
2 # Code to execute if condition1 is True
3elif condition2:
4 # Code to execute if condition2 is True
5elif condition3:
6 # Code to execute if condition3 is True
7# More elif blocks can be added as needed
8else:
9 # Code to execute if none of the above conditions are True- Example: Let’s imagine we want to write a statement to determine and print the letter grade corresponding to an input numeric grade:
- Prompt: Enter the numeric grade: 82
python
1number = int(input("Enter the numeric grade: "))
2
3if number > 89:
4 letter = "A"
5elif number > 79:
6 letter = "B"
7elif number > 69:
8 letter = "C"
9elif number > 59:
10 letter = "D"
11else:
12 letter = "F"
13print("The letter grade is, " + letter)Output:
1The letter grade is, BTesting Multiple Conditions:
- Often, you’ll need to categorize items into different groups based on multiple conditions.
-
In this case, we are categorizing pizzas as either regular pizzas (e.g., pepperoni, sausage) or specialty pizzas (e.g., breakfast, margherita, BBQ).
-
To achieve this, we use Python’s if-elif-else syntax, which allows us to evaluate multiple conditions efficiently.
-
Example:
-
python
1requested_pizzas = ["pepperoni", "sausage", "breakfast", "margherita", "bbq"]
2
3if requested_pizzas:
4 for requested_pizza in requested_pizzas:
5 if requested_pizza == "pepperoni" or requested_pizza == "sausage":
6 print("Preparing " + requested_pizza + " pizza (a regular pizza)")
7 elif requested_pizza == "breakfast" or requested_pizza == "margherita" \
8 or requested_pizza == "bbq":
9 print("Preparing " + requested_pizza + " pizza (a specialty pizza)")
10 else:
11 print("Sorry, we don't have " + requested_pizza + " pizza available.")
12else:
13 print("No pizzas to be prepared.")- Output:
1Preparing pepperoni pizza (a regular pizza)
2Preparing sausage pizza (a regular pizza)
3Preparing breakfast pizza (a specialty pizza)
4Preparing margherita pizza (a specialty pizza)
5Preparing bbq pizza (a specialty pizza)