Exercise 5-4 Solution Python Crash Course Chapter 5: if Statements

 

📘 Python Crash Course – Chapter 5: if Statements – Exercise 5-4 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


📝 Exercise 5-4

Task:
Choose a color for an alien as you did in Exercise 5-3, and write an if-else chain .
• If the alien’s color is green, print a statement that the player just earned 5 points for shooting the alien .
• If the alien’s color isn’t green, print a statement that the player just earned 10 points .
• Write one version of this program that runs the if block and another that runs the else block

✅ Solution Code:


alien_color = "green"

if alien_color == "green":
    print("you earned 5 points")
else:
    print("you earned 10 points ")

print("------------------------------------------------------")

alien_color = "yellow"

if alien_color == "green":
    print("you earned 5 points")
else:
    print("you earned 10 points ")

print("------------------------------------------------------")

🧠 Code Explanation:

This Python code demonstrates the use of an if-else chain to handle two possible conditions based on the value of a variable. Here's how it works:

  1. Define the variable:

    The variable alien_color is assigned a value representing the color of an alien. In the first case, it is set to "green", and in the second case, it is set to "yellow".

  2. Use an if-else chain:

    An if statement checks whether the value of alien_color is "green". If the condition is true, a message is displayed indicating that the player earned 5 points. If the condition is false, the else block is executed, displaying a message that the player earned 10 points.

  3. Demonstrate both cases:

    The program includes two versions of the test: one where the condition passes (when alien_color is "green") and another where the condition fails (when alien_color is "yellow").

This code demonstrates how to use an if-else chain to handle two mutually exclusive conditions in Python.

🔍 Output:


you earned 5 points
------------------------------------------------------
you earned 10 points
------------------------------------------------------

📚 Related Exercises from Chapter 5:


🔗 Connect With Us:

“Programs must be written for people to read, and only incidentally for machines to execute.”
— Harold Abelson

📌 Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips

Previous Post Next Post

Contact Form