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

 

πŸ“˜ Python Crash Course – Chapter 5: if Statements – Exercise 5-3 Solution

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


πŸ“ Exercise 5-3

Task:
Imagine an alien was just shot down in a game . Create a variable called alien_color and assign it a value of 'green', 'yellow', or 'red' .
• Write an if statement to test whether the alien’s color is green . If it is, print a message that the player just earned 5 points .
• Write one version of this program that passes the if test and another that fails . (The version that fails will have no output) .

✅ Solution Code:


aline_color = "green"   # it passes the  test
if (aline_color == "green"):
    print("You earned 5 points")

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

aline_color = "yellow"   # it fails the test
if (aline_color == "green"):
    print("You earned 5 points")


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

🧠 Code Explanation:

This Python code demonstrates the use of if statements to test conditions and execute specific actions 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. Test the condition:

    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.

  3. Handle the failing condition:

    If the condition is false, the else block is executed. In this case, the pass statement is used, which means no action is taken, and no output is generated.

  4. 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 if statements to test conditions and handle both passing and failing cases in Python.

πŸ” Output:


You earned 5 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

“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python

πŸ“Œ Follow Us And Stay Updated For Daily Updates

Comments