Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I want to make a certain range into the list, and then take the user's input and check if it is in the range. Here is what I have done so far:

lower = 1

upper = 10

range_list = list(range(lower, upper +1))

user_input = input()

while user_input in range_list:

    print('foo')

else:

    print('fee')

Currently, if I input the number that theoretically should be in a range (say, 5), it prints 'fee' rather than 'foo'. Where am I going wrong?

1 Answer

0 votes
by (36.8k points)

You should first convert your input to int, or to an str '5' will not match in 5. So use the below code:

lower = 1

upper = 10

range_list = list(range(lower, upper +1))

user_input = int(input())

while user_input in range_list:

    print('foo')

else:

    print('fee')

To validate, inside a try..except:

try:

  user_input = int(input())

except ValueError:

  # Input not int, do something

Learn Python for Data Science Course to improve the technical knowledge

Browse Categories

...