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)
CodePudding user response:
To me, it looks like you are confusing the purpose of print
and return
. Change all of your print
function calls to return
statements.
print
takes whatever you hand it, converts it to it's string representation, and then sends that to the screen.
return
ends the function, and sends the values back up to whatever called the function in the first place.
These are easy to confuse if you are using jupyter or the repl. Both of these will automatically print some items to the screen.
CodePudding user response:
this works
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:
print(color)
stop_light("yellow", 3)
or
def stop_light(color, seconds):
if color == "green" and seconds > 60:
return "yellow"
elif color == "yellow" and seconds > 5:
return "red"
elif color == "red" and seconds > 55:
return "green"
else:
return color
print(stop_light("yellow", 3))
CodePudding user response:
Add more elif
statements that look like this:
elif color == "green" and seconds < 60:
print("green")