Abdul Mustapha Abdul Mustapha - 11 days ago 5
Python Question

Python - Words in string affect outcome

I am new to python and I am trying to develop a phone troubleshoot program where I ask the user what is wrong with their device, and if my program detects the word 'wet' or 'water' it will reply with an outcome. Another example would be 'screen is cracked'. I am having a problem that if I input 'My screen is cracked'. My code does not detect it. Any help appreciated!

Snippet of my code

print (60 * '-')
print ('Could you describe what is wrong with your device?')
print (60 * '-')
time.sleep(1)
userproblem = input('')

if userproblem in ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river',):
print('WATERDAMAGE VARAIBLE')

elif userproblem in ('screen', 'cracked', 'shattered', 'smashed',):
print('SCREEN VARIABLE')

Answer

userproblem is your whole user's input. You are checking if it belongs to a tuple with those keywords. So, if the input is "My phone is wet", this string does not belong to ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river',) since it's not equal to any of these words. Same problem in the second if.

The correct solution is to ask if any of these words is contained in the input, which is quite the opposite. You would have something like:

userproblem_words = userproblem.split(' ')

water_related_words = ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river')
if (any([(word in water_related_words) for word in userproblem_words])):
    print('WATERDAMAGE VARIABLE')

break_related_words = ('screen', 'cracked', 'shattered', 'smashed')
elif (any([word in userproblem for word in break_related_words])):
    print('SCREEN VARIABLE')

Or, if you don't like the list comprehension's readability in this case, you can use a plain for:

water_related_words = ('water', 'waterdamage', 'rain', 'toilet', 'pool', 'sea', 'ocean', 'river')
break_related_words = ('screen', 'cracked', 'shattered', 'smashed')

for word in userproblem.split(' '):
    if word in water_related_words:
        print('WATERDAMAGE VARIABLE')

    elif word in break_related_words:
        print('SCREEN VARIABLE')
Comments