Reputation: 39
I am working on a problem that takes a list of paint colors and gets the user to input a color name. If they match, then it says the color is found in the list; otherwise it says it is not found. If for user input, I use the first value in the list, it tells me that it is found; however, for all of the other colors, it gives the not found message.
I have checked for any variable differences between the paint color list and the input variable, I have changed variable names, tried converting input to upper and lower.
paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
for color in paint_colors:
if color_request.lower() == color:
print("Color exists in list!")
break
else:
print("Color is not in the list!")
break
I would expect that by entering the word White or white into the input box, then it would tell me that it was found, but the only way I get it to return found is if I put in black.
Upvotes: 0
Views: 44
Reputation: 5414
Your second break
statement is causing the problem. You can try this:
paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
for color in paint_colors:
if color_request.lower() == color:
print("Color exists in list!")
break
else:
print("Color is not in the list!")
Using one more variable in a different way:
paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
found = 0
for color in paint_colors:
if color_request.lower() == color:
found = 1
break
if found:
print("Color exists in list!")
else:
print("Color is not in the list!")
Using in
operator:
paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
if color_request in paint_colors:
print("Color exists in list!")
else:
print("Color is not in the list!")
Upvotes: 0
Reputation: 2477
We can set a flag colour_found
which keeps track of whether we found the colour in the list or not. If we found the color then we can exit the loop.
paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
colour_found = False
for color in paint_colors:
if color_request.lower() == color:
colour_found = True
break
if colour_found:
print("Color exists in list!")
else:
print("Color is not in the list!")
Upvotes: 0
Reputation: 195418
The second break
is redundant, because when color doesn't match first index, you are breaking from the loop prematurely:
paint_colors = ['black', 'blue', 'green', 'white', 'yellow']
color_request = input("Enter color name: ")
for color in paint_colors:
if color_request.lower() == color:
print("Color exists in list!")
break
else:
print("Color is not in the list!")
Upvotes: 1