python - 用 Python 编写函数
问题描述
我在 Python 中编写了以下函数,但是它不起作用。我从列表中尝试了不同的颜色,paint_colors
并且该函数仅found
在我pink
作为输入提供时才返回。此外,例如,如果我输入green
作为输入,它会返回not found
,但这种颜色也在paint_colors
列表中。为什么我的函数不适用于其他颜色?
paint_colors = ["pink", "white", "red", "green", "brown", "purple", "blue"]
color_input = input("Enter the color you are looking for:")
def function():
for color in paint_colors:
if color == color_input:
return "found"
else:
return "not found"
print(function())
解决方案
查找是否color_input
在中的更简单方法paint_colors
是说color_input in paint_colors
:
def function():
if color_input in paint_colors:
return "found"
else:
return "not found"
对于涉及列表的简单任务,通常有比遍历整个列表更简单的选项!
推荐阅读
- bigcommerce - 我如何从结帐页面 Bigcommerce 中隐藏“税款”
- javascript - 如何从 google appscript 中的另一个 html 页面调用另一个 HTML 页面
- c++ - 如何读取带有方括号的 Json 字符串?
- python - 如何在 python 3 中向 SHA256 提供十六进制输入?
- php - 在 woocommerce_before_calculate_totals 挂钩中获取购物车小计
- ms-word - 使用 OpenXML 在 MS Word 中添加/更新 TOC 时出现问题
- android - 使用 Koin 在运行时切换基本 url
- r - 从现有数据框列分配行名时出错
- visual-studio-code - 自定义模式的 Ctrl+Mouseover 上的自定义超链接
- javascript - 从 Jquery Returned Object 获取每个对象的返回数据