首页 > 解决方案 > 如何在 Python 中正确 elif/else?

问题描述

我需要编写一个名为 stop_light 的函数来确定 stop_light 是否应该改变颜色,如果是,它应该改变成什么颜色。

我可以做,但我不能做这部分:

我该怎么做那部分?

这是我的代码

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) 

标签: pythonpython-3.xif-statementboolean

解决方案


这行得通

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)

或者

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))

推荐阅读