10  The Grail Castle Test: Mastering ‘Elif’ and ‘Else’ Statements

In our previous lesson, we learned about ‘if’ statements. Today, we’ll expand our magical arsenal with ‘elif’ (else if) and ‘else’ statements. These powerful constructs will allow our code to make more complex decisions, just as a knight must navigate through a series of challenges in their quest.

10.1 Introducing ‘Else’: The Alternative Path

Sometimes in our quests, we want to do one thing if a condition is true, and something else if it’s not. This is where the ‘else’ statement comes in. It provides an alternative path for our code when the ‘if’ condition is false.

Here’s the structure of an ‘if-else’ statement:

if condition:
    # Code to execute if the condition is True
else:
    # Code to execute if the condition is False

Let’s see an example:

has_sword = False

if has_sword:
    print("You draw your sword, ready for battle!")
else:
    print("You reach for your sword, but realize you don't have one!")

print("The adventure continues...")

If has_sword is False, this will output:

You reach for your sword, but realize you don't have one!
The adventure continues...

10.2 The Power of ‘Elif’: Multiple Conditions

But what if we have more than two possibilities? This is where ‘elif’ (short for “else if”) comes in. It allows us to check multiple conditions in sequence.

Here’s the structure of an ‘if-elif-else’ statement:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition1 is False and condition2 is True
elif condition3:
    # Code to execute if condition1 and condition2 are False and condition3 is True
else:
    # Code to execute if all conditions are False

Let’s see a practical example:

knight_rank = "squire"

if knight_rank == "knight":
    print("Welcome, brave knight! You may enter the castle.")
elif knight_rank == "squire":
    print("Greetings, young squire. You may enter the training grounds.")
elif knight_rank == "wizard":
    print("Ah, a wizard! The magic tower awaits you.")
else:
    print("Halt! You are not authorized to enter.")

print("The castle gates close behind you.")

This will output:

Greetings, young squire. You may enter the training grounds.
The castle gates close behind you.

10.3 Combining ‘If’, ‘Elif’, and ‘Else’ with Logical Operators

We can create even more complex decision structures by combining these statements with logical operators:

has_sword = True
has_shield = False
has_magic = True

if has_sword and has_shield:
    print("You are well-equipped for close combat!")
elif has_sword and has_magic:
    print("You can fight with sword and sorcery!")
elif has_magic:
    print("You rely on your magical abilities.")
else:
    print("You might want to visit the equipment shop.")

print("Prepare for your next battle!")

This will output:

You can fight with sword and sorcery!
Prepare for your next battle!

10.4 The Importance of Order in ‘Elif’ Statements

The order of ‘elif’ statements matters! Python checks conditions from top to bottom and executes the first block where the condition is true. Consider this example:

player_score = 95

if player_score > 90:
    print("You earned an A!")
elif player_score > 80:
    print("You earned a B!")
elif player_score > 70:
    print("You earned a C!")
else:
    print("You need to study more.")

print("Keep up the good work!")

This will output:

You earned an A!
Keep up the good work!

Even though the score is also greater than 80 and 70, only the first true condition (score > 90) is executed.

10.5 Practice Your ‘Elif’ and ‘Else’ Magic

Now it’s your turn to practice these conditional spells:

  1. Create a variable player_health and set it to a number between 0 and 100. Write an ‘if-elif-else’ statement that prints “Full health!” if it’s 100, “Injured!” if it’s between 1 and 99, and “Game Over!” if it’s 0.

  2. Make a variable weapon and set it to either “sword”, “bow”, or “wand”. Use an ‘if-elif-else’ statement to print a unique message for each weapon, with a default message for any other weapon.

  3. Create variables has_key and has_potion. Write an ‘if-elif-else’ statement that checks if the player has both, only one, or neither of these items, with appropriate messages for each case.

  4. Write a program that takes a numerical grade (0-100) and converts it to a letter grade (A, B, C, D, F) using ‘if-elif-else’ statements.

Here’s a starting point for your practice:

# Quest 1: Health Check
player_health = 75  # Change this value to test your code
# Your code here

# Quest 2: Weapon Choice
weapon = "bow"  # Change this to test different weapons
# Your code here

# Quest 3: Inventory Check
has_key = True
has_potion = False
# Your code here

# Quest 4: Grade Converter
numerical_grade = 88  # Change this to test different grades
# Your code here

10.6 Common Bugs to Watch Out For

As you weave your ‘elif’ and ‘else’ statement spells, beware of these common pitfalls:

  1. Forgetting colons: Each ‘if’, ‘elif’, and ‘else’ line should end with a colon :.
  2. Incorrect indentation: All code blocks under ‘if’, ‘elif’, and ‘else’ must be indented.
  3. Using ‘else if’ instead of ‘elif’: Python uses ‘elif’, not ‘else if’.
  4. Overusing ‘elif’: If you have many ‘elif’ statements, consider using a dictionary or match statement (in Python 3.10+) instead.
  5. Redundant conditions: In ‘elif’ chains, don’t repeat checks that are implied by previous conditions.

10.7 Conclusion and Further Resources

You’ve now mastered the art of ‘elif’ and ‘else’ statements, expanding your ability to create complex decision-making structures in your code. Your programs can now navigate through multiple conditions, choosing the right path based on different scenarios.

To further enhance your conditional statement skills, check out these valuable resources:

  1. Python Official Documentation on if Statements
  2. Real Python’s Python Conditional Statements
  3. Programiz Python if…else Statement Remember, the key to mastering these concepts is practice. Keep experimenting with different combinations of ‘if’, ‘elif’, and ‘else’ statements, and soon you’ll be crafting intricate decision trees in your code with ease. Onward to your next Python adventure!