Skip to content

script_24.py - Traffic Light Simulator

Code

Python
#!/usr/bin/env python3
"""Traffic light simulator"""

light = input("Enter traffic light color (red/yellow/green): ").lower()

if light == "red":
    print("STOP")
elif light == "yellow":
    print("CAUTION - prepare to stop")
elif light == "green":
    print("GO")
else:
    print("Invalid traffic light color")

Explanation

Line 4: light = input("Enter traffic light color (red/yellow/green): ").lower() - input() returns string - .lower() method chaining converts to lowercase - Makes comparison case-insensitive ("Red", "RED", "red" all work) - light stores lowercase string

Line 6: if light == "red": - == string equality comparison (case-sensitive) - Since we used .lower(), only matches lowercase "red" - Returns True only for exact match

Line 8: elif light == "yellow": - Checks for "yellow" string - Only evaluated if light != "red"

Line 10: elif light == "green": - Checks for "green" string

Line 12: else: - Catches any input that isn't red, yellow, or green - Handles typos, invalid colors, empty input - Examples: "blue", "stop", "redd", ""