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");
-
If the input matches something from your list, why not simply use the input itself?Thmei Esi– Thmei Esi2016年12月08日 02:09:28 +00:00Commented Dec 8, 2016 at 2:09
4 Answers 4
You can use python's excellent list.index function:
if I in Y:
print("Working" + str(Y.index(I)));
1 Comment
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
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
for a in Y:
if I == a:
#do something