0

I'm just wondering if it's possible to see if the users input equals an item's index within a list?

I am trying to do something like this:

data = ['hello', 'hi', 'hey']

user_choice = int(input("Enter 1,2 or 3: ")
user_answer = user_choice - 1
if user_answer in ....: # How would I finish this off line off?
    result = data[user_answer]
    print(result)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
SimpleJay_
  • 37
  • 5

2 Answers2

-1
data = ['hello','hi','hey']

user_choice = int(input("Enter 1,2 or 3: ")
user_answer = user_choice - 1
if user_answer in range(1,len(data)+1): #just give length of data
    result = data[user_answer]
    print(result)
Nanthakumar J J
  • 860
  • 1
  • 7
  • 22
  • 1
    This answer is wrong, it will fail if we input `1` and it's also inefficient. Instead use `if 0 <= user_answer < len(data)` as suggested in the comments by mkrieger. – Roy Cohen Dec 25 '20 at 13:39
  • @RoyCohen i did notice this to so i changed it but forgot to mention it in here. Thanks for noting this for others who check this question – SimpleJay_ Dec 25 '20 at 14:16
-1

I think you just need to put [1,2,3] or range(1,4) in your blank space.

data = ['hello','hi','hey']

user_choice = int(input("Enter 1,2 or 3: "))
user_answer = user_choice - 1
length = len(data)+1
if user_answer in range(1,length): #How would i finish this off line off?
    result = data[user_answer]
    print(result)

Results:

Enter 1,2 or 3: 2
hi
srishtigarg
  • 1,106
  • 10
  • 24