Ad

Checking If Input Is In A List Of Numbers In Python

- 1 answer

numbers = [1,2,3,4,5,6,7]
x = input()
if x in numbers:
    print("Hey you did it")
else:
    print("Nope")

I'm not sure what I'm doing wrong here, but it always tells me that my number is not in the list.. even though it is. Works fine with strings, though.

Help would be appreciated. Thanks!

Ad

Answer

Input is a string, so you are comparing strings to integers. First convert to an int then do the membership test:

numbers = [1,2,3,4,5,6,7]
x = input()
if int(x) in numbers:
    print("Hey you did it")
else:
    print("Nope")

To make this slightly more robust, you should handle the ValueError that will occur if the user does not input an integer (there's always one user who will enter 'cheeseburger' instead of a number):

numbers = [1,2,3,4,5,6,7]
x = input()
try:
    i = int(x)
    if i in numbers:
        print("Hey you did it")
    else:
        print("Nope")
except ValueError:
    print("You did not enter a number")
Ad
source: stackoverflow.com
Ad