0

I wrote the following function in Python, however it does not work. I tried different colors from the paint_colors list and the function only returns found if I give pink as an input. Moreover, for example if I type green as input it returns not found, but this color is also in the paint_colors list.. Why does my function not work for the other 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())
2
  • 3
    You always return the first time through the loop. You should only return "not found" after the loop has finished. Commented May 14, 2020 at 15:42
  • 1
    The solutions below are correct. However, I am almost certain that, at the very least, you want color_input as a parameter of your function, not a global variable (even though these solutions "work"). For example: def function(color_input):. That is a more important point than the syntax that the other answers are helping you with. Commented May 14, 2020 at 18:25

3 Answers 3

2

An easier way to find whether color_input is in paint_colors is just to say color_input in paint_colors:

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

For simple tasks involving a list there's frequently a simpler option than iterating over the entire list!

Sign up to request clarification or add additional context in comments.

Comments

1
  1. You check only first element in list.
  2. Make sure that all variables has same type.

def function():
    for color in paint_colors:
        if str(color) == str(color_input):
            return "found"
    return "not found"

paint_colors = ["pink", "white", "red", "green", "brown", "purple", "blue"]
color_input = input("Enter the color you are looking for:")

print(function())

Comments

0

The easiest way to do this is

def function():
    return "true" if color in paint_colors else "false"

Here, color in paint_colors is checking if the value color is equal to any of the values in the list paint_colors, effectively doing the same thing as a for loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.