One simple way to check several possible answers, such as when an action could be described by multiple words [hit, smack, bash, thump, wallop, kick, bang, thwack], is to use a list and see if the user’s response contains any words or phrases in the “correct answers” list.
So a possible approach is:
- Break the user’s response into a list of words.
- See if any of the user’s words match a word on the answer list.
#STEP 1: Break response into words
respWords = []
response = input(prompt).lower()
i = 0
for j, char in enumerate(response):
if char == ' ':
respWords.append(response[i:j])
i = j + 1
respWords.append(response[i:len(response)])
print(respWords) #View result
This code uses “list slicing” to slice out the words, since a string value is treated as a list of characters. The notation is fairly simple: listName[start:stop]
where start
and stop
are positions in the list.
The last line before print()
adds the last word in the user’s response to the respWords
list. (The for:
loop does not add the last word because there is no space after it.)
Or you can use the built-in split()
function to make the list of words:
#STEP 1: Split the response
respWords = response.split()
NOTE: We aren’t stripping out commas or other punctuation that will stay attached to the words and mess up the ‘==
’ comparison.
Now we can compare the words in the two lists:
#STEP 2: Check for answer words
for word in respWords:
if word in action: correctAns = True
Putting it all together in a while:
loop gives:
actions = ['hit', 'smack', 'bash', 'thump', 'wallop', 'kick', 'bang', 'thwack']
respWords = []
prompt = "What would you like to do? : "
result = ''
response = ''
correctAction = False
while not correctAction:
print(result)
response = input(prompt).lower()
respWords = response.split()
for word in respWords:
if word in actions: correctAction = True
result = "Nothing happened."
print("The door lock broke.")
print("The door is open!!")
You could also process the respWords
list a second time to see if the user had mentioned ‘door’ as the target.
If you know about creating functions, then you can probably figure out how to make the code above into a function. If functions aren’t in your toolkit yet, just program it all linearly and learn about strings and loops. You’ll get to functions soon enough.