-4

I'm stuck on this part of a code. Here is an example of a sample text

items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if choice != items:
    print("Item not found")
else:
    print("Item found")

That is an example of what I'd like to do. I want to work out if what the user has inputted in is part of a given list. This is python 3.5

  • 1
    Should be `if choice not in items`. If `items` is large, you'd be better off making it a set, i.e. `items = {}` – Chris_Rands Oct 25 '16 at 09:31
  • Hey there, thanks for your response but that didn't work, it always outputs 'Item not found'. – Sacad Muhumed Oct 25 '16 at 09:57
  • Are you sure you are testing the content of the value, and not just its name? – Efferalgan Oct 25 '16 at 10:04
  • 1
    Chris's code will work if the data in `items` are strings. If Neill's answer doesn't fix your problem you should post a [mcve] that illustrates your problem. – PM 2Ring Oct 25 '16 at 10:06

1 Answers1

0

It is going to depend on the type of data in the list. input returns everything as str. So if the list data type is float then the if statement will evaluate as True. For int data use the following:

items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if int(choice) not in items:
    print("Item not found")
else:
    print("Item found")

for float is must be:

items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if float(choice) not in items:
    print("Item not found")
else:
    print("Item found")

This should now correctly evaluate the if statement.

Neill Herbst
  • 2,072
  • 1
  • 13
  • 23