Conditional Statements: Elif and Else
Welcome to the lesson on extended conditional statements. Building upon the foundations of the if statement, we now introduce elif and else.
Elif Statement
The elif (short for "else if") statement allows you to check multiple conditions sequentially. When an if statement evaluates to False, the program checks the next elif condition, and so on.
The syntax for an elif statement :
- if condition:
tab code to execute if the condition is true
- elif another_condition:
tab code to execute if the elif condition is true
#Example: Elif statement
age = 16
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
In this example, the program first checks if age >= 18. Since this condition is false, it moves to the elif condition age >= 13, which is true, so it prints "You are a teenager."
Else Statement
The else statement provides a fallback option when none of the preceding conditions are true. It executes a block of code if all previous conditions are false.
The syntax for an else statement:
- if condition:
tab code to execute if the condition is true
- elif another_condition:
tab code to execute if the elif condition is true
- else:
tab code to execute if all previous conditions are false
#Example: Else statement
age = 10
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
In this example, the program first checks if age >= 18. Since this condition is false, it checks the elif condition age >= 13, which is also false. Therefore, it executes the else block and prints "You are a child."
Practical Application
In the Chamber of Choices, more complex decisions require the use of elif and else spells to handle multiple conditions.
Create a spell that checks your power level and grants access based on different thresholds:
• Above 70: Enter the High Council Chamber.
• Above 50: Enter the Inner Sanctum.
• Else: Access denied.
⋆˖⁺‧₊ Use if, elif, and else statements to determine your access level. ₊‧⁺˖⋆
Sample Output:
Your level is 95.
You may enter the High Council Chamber.