Reputation: 135
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");
Upvotes: 1
Views: 8997
Reputation: 341
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")
Upvotes: 1
Reputation: 442
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)
Upvotes: 0
Reputation: 4469
You can use python's excellent list.index
function:
if I in Y:
print("Working" + str(Y.index(I)));
Upvotes: 3