1

I am attempting to write some programming and I seem to be having some difficulties. I want to make a certain range into a list, and then take user's input and check if it is in the range. Here is what I have 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 a number that theoretically should be in the range (say, 5), it prints 'fee' rather than 'foo'. What am I doing wrong?

sou hiyori
  • 13
  • 3
  • Why do you want to make a range into a list? In any case, your list contains only `int` objects, but `input` always returns a `str` object, and `int` objects will never equal `str` objects – juanpa.arrivillaga Oct 22 '20 at 04:44
  • @juanpa.arrivillaga I'm a bit of a newbie to Python, sorry! In that case, how could I make it so that my user can only input int objects then? – sou hiyori Oct 22 '20 at 04:47
  • ```user_input = int(input())``` -- use this to convert the input to an int – Sushil Oct 22 '20 at 04:47
  • You can convert the user input into an `int` object. – juanpa.arrivillaga Oct 22 '20 at 04:47
  • Thank you @Sushil ! Is there a way I could preform validation for that then so that my program does not crash, but still allows me to check if the input is in the range? – sou hiyori Oct 22 '20 at 04:49

2 Answers2

0

You should first convert the input to int, otherwise str '5' will not match in 5. So try instead:

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
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Firstly, you need to define the "lower" variable. The reason your code outputs 'fee' is because you need to convert your input into integer like so:

upper = 10
lower = 0
range_list = list(range(lower, upper +1))
user_input = input()
while int(user_input) in range_list:
    print('foo')
else:
    print('fee')

even so, your program will output an infinite loop. you have to give a stopping clause and asks for input at the start/end of each loop

upper = 10
lower = 0
range_list = list(range(lower, upper +1))
user_input = ''
while user_input!='-1':
  user_input = input()
  if int(user_input) in range_list:
    print('foo')
  else:
    print('fee')