python - 如何在 Python 中正确 elif/else?
问题描述
我需要编写一个名为 stop_light 的函数来确定 stop_light 是否应该改变颜色,如果是,它应该改变成什么颜色。
- Stoplight 函数应该有两个参数。第一个的值将是“绿色”、“黄色”或“红色”。这表示停车灯的当前颜色。
- 第二个参数告诉函数这种颜色显示了多长时间。如果绿色已显示超过 60 秒,则返回“黄色”。如果黄色已显示超过 5 秒,则返回“红色”。如果红色显示时间超过 55 秒,则返回“绿色”。
- 如果颜色没有显示足够长的时间(例如绿色已经显示了 17 秒),则返回当前颜色。以下是使用不同参数调用函数的一些示例。
我可以做,但我不能做这部分:
- 如果颜色没有显示足够长的时间(例如绿色已显示 17 秒),则返回当前颜色。”
我该怎么做那部分?
这是我的代码
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)
解决方案
这行得通
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))
推荐阅读
- c# - Windows:UWP 中的 ScrollViewer 不能与数据网格结合使用
- python-3.x - 用户输入不打印我分配给它打印的内容
- mysql - 使用子查询的查询比使用固定数据而不是子查询的相同查询需要更长的时间
- django - django.core.exceptions.ImproperlyConfigured: WSGI application '{project_name}.wsgi.application' could not be loaded; Error importing module
- html - HTML 问题 - 图像未在 Chrome 网络浏览器中显示
- javascript - 如何修复“.setFullYear 不是函数”
- git - git-rebase 何时会因功能分支的功能而失败?
- java - Camunda MyBatis 和 Java 12 问题
- jquery - 如何根据下拉列表设置 jQuery 验证?
- c# - 使用 EWS 创建的 MS-Graph API 检索 SingleValueExtendedProperties