1

I'm trying to make a simple program which first checks to see if a user's input matches a list and then will check what element of the list that input matches and gives a response based on the input. The part I'm having trouble with is, coming up with a way to see what element of the list the input matches, so that I can give a certain response based off of that input. I really would appreciate any help I can get with this problem.

Thanks, Nova

This is my current code that I have so far. Under the first if statement is where I would like to put the check for what element of the list matches the input.

Y = ["How", "Hi", "Hey", "How are you doing", "How's it going", "How", "Hello"]
I = str(input("Start Conversation"))

if I in Y:
    print("Working");

elif I not in Y:
    print("I don't Understand");
1
  • If the input matches something from your list, why not simply use the input itself? Commented Dec 8, 2016 at 2:09

4 Answers 4

3

You can use python's excellent list.index function:

if I in Y:
  print("Working" + str(Y.index(I)));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much this is simple and works perfectly!
1

You can throw it in as a one-liner if you want:

Y = ["How", "Hi", "Hey", "How are you doing", "How's it going", "How", "Hello"]
I = str(input("Start Conversation"))

print("Working:", I) if I in Y else print("I don't understand")

As Thmei has already noted, the if matches I against Y, so you already know that the content of I is in the list and it can be printed. If you would prefer to output the actual index of I in Y (if it exists), you can do this:

print(Y.index(I)) if I in Y else print("I don't understand")

Or the long way:

if I in Y:
    print (Y.index(I))
else:
    print ("I don't understand")

Comments

0

Since you have already matched I against the items in your list, if I matched one of them, it will be the same as the item it matched.

print(I)

Comments

0
for a in Y:
      if I == a:
            #do something

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.