Sacad Muhumed Sacad Muhumed - 1 month ago 8
Python Question

If an input is part of a list

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

Answer

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.