I Was wondering how to make a string turn into an array of every word and I came across the .split() function and that split it, but now I want to compare it to another array. How can I do that?
keywords = ["help", "where", "find"]
x = input("How can I help: ")
search = x.split(" ")
for search in keywords:
if search == keywords:
print("it looks like you need help with: ", keywords)
else:
print("I did not understand")
print(search, " ", keywords)
I dont really know what to do and any help would be appreciated
>Solution :
When using for (iterating variable) in list, you can’t use an already defined variable name for the iterating variable ! this variable takes the value of every word you’re iterating through in your list, one after the other.
Hope this helps ! I tried keeping as much of your own code as simple as possible. If you’re looking for a more optimized solution, use user2390182’s answer.
Feel free to ask further questions if needed.
keywords = ["help", "where", "find"]
x = input("How can I help: ")
search = x.split(" ")
success = False
for word in search : #iterate through each word of variable 'search'
if word in keywords: #if the word we're currently iterating is in the list 'keywords' :
print("it looks like you need help with: ", word) #we show the word that triggered the 'if'
success = True #we take note of the fact we successfully helped the user
if not success:
print("I did not understand")
print(search, " ", keywords)
#the 'if' is located after the loop, outside of its scope.
#this way it only triggers once after the loop instead of triggering with each iteration of the loop
output :
How can I help: i want to find excalibur
it looks like you need help with: find