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)
2
  • 1
    if 0 <= user_answer < len(data)? Commented Dec 25, 2020 at 13:31
  • 2
    Does this answer your question? If list index exists, do X Commented Dec 25, 2020 at 13:32

2 Answers 2

-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)
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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
-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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.