jeudi 7 octobre 2021

How to elif/else correctly in Python?

I need to Write a function called stop_light that determines whether a stop_light should change color, and, if so, what color it should change to.

  • The Stoplight function should take two arguments. The value of the first will be either "green", "yellow", or "red". This represents the stop light's current color.
  • The second parameter tells the function how long this color has been showing. If green has been showing longer than 60 seconds, return "yellow". If yellow has been showing longer than 5 seconds, return “red”. If red has been showing longer than 55 seconds, return “green”.
  • If the color hasn’t been showing long enough (e.g. green has been showing for 17 seconds), return the current color. Here are some examples of calling the function with different arguments.

That I could do, but I cannot do this part:

  • If the color hasn’t been showing long enough (e.g. green has been showing for 17 seconds), return the current color."

How can I do that part?

Here is my code

def stop_light(color, seconds):
    if color == "green" and seconds > 60:
        print("yellow")
    elif color == "yellow" and seconds > 5:
        print("red")
    elif color == "red" and seconds > 55:
        print("green")
    else:
        return color 

stop_light("yellow", 3) 

Aucun commentaire:

Enregistrer un commentaire