Table of Contents
Example Description
The code includes user-defined functions for determining the light color and providing a corresponding message, stay safe on the roads.

Introduction:

This Python code simulates a traffic light using two user-defined functions. The first function, trafficLight(), prompts the user to enter the color of the traffic light and then calls the second function, light(), to determine the corresponding message. The second function, light(), returns a value based on the color input, which is used to display the appropriate message. Make sure to enter the traffic light color in CAPITALS. After running the code, a safety message is printed.

Code:

#Function to simulate a traffic light
#It is required to make 2 user defined functions trafficLight() and light().
def trafficLight():
 signal = input("Enter the colour of the traffic light: ")
 if (signal not in ("RED","YELLOW","GREEN")):
  print("Please enter a valid Traffic Light colour in CAPITALS")
 else:
  value = light(signal) #function call to light()
 if (value == 0):
  print("STOP, Your Life is Precious.")
 elif (value == 1):
  print ("PLEASE GO SLOW.")
 else:
  print("GO!,Thank you for being patient.")
#function ends here
 
def light(colour):
 if (colour == "RED"):
  return(0);
 elif (colour == "YELLOW"):
  return (1)
 else:
  return(2)
#function ends here

trafficLight()
print("SPEED THRILLS BUT KILLS")

Logic:

  1. Define the function trafficLight().
  2. Prompt the user to enter the color of the traffic light.
  3. If the input is not “RED”, “YELLOW”, or “GREEN”, display an error message.
  4. If the input is valid, call the function light() with the input as the argument.
  5. Store the return value from the function light() in the variable “value”.
  6. Based on the value of “value”, display the appropriate message.
  7. Define the function light() which takes the color as an argument.
  8. If the color is “RED”, return 0.
  9. If the color is “YELLOW”, return 1.
  10. For any other color, return 2.
  11. Call the function trafficLight().
  12. Print the safety message “SPEED THRILLS BUT KILLS”.

Output:

>> Enter the colour of the traffic light: RED

>> STOP, Your Life is Precious.

>> SPEED THRILLS BUT KILLS