首页 > 解决方案 > 用 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())

标签: pythonfunction

解决方案


查找是否color_input在中的更简单方法paint_colors是说color_input in paint_colors

def function():
    if color_input in paint_colors:
        return "found"
    else:
        return "not found"

对于涉及列表的简单任务,通常有比遍历整个列表更简单的选项!


推荐阅读