Mthokozeleni
Mthokozeleni

Reputation: 11

complex iteration over a string in python

The aim of this code is to go through the users input check if check if any of the words match the words on the dictionary then give one response related to the first word that matches and if not reply with "I am curious tell me more". My problem is that I can't iterate over the list and print a single response.

def main():
    bank = {"crashed":"Are the drivers up to date?","blue":"Ah, the blue screen of death. And then what happened?","hacked":"You should consider installing anti-virus software.","bluetooth":"Have you tried mouthwash?", "windows":"Ah, I think I see your problem. What version?","apple":"You do mean the computer kind?","spam":"You should see if your mail client can filter messages.","connection":"Contact Telkom."}

def welcome():
    print('Welcome to the automated technical support system.')
    print('Please describe your problem:')

def get_input():
    return input().lower().split()
def mainly():
    welcome()    
    query = get_input()

    while (not query=='quit'):
        for word in query:
            pass
            if word in bank:
                print(bank[word])


            elif not(word=="quit"):
                print("Curious, tell me more.")


        query = get_input()
mainly()
if __name__=="__main__":
    main()

Upvotes: 1

Views: 82

Answers (1)

Nicolas M.
Nicolas M.

Reputation: 1478

In your code there is few mistakes. First one, when you start the script you run main which loading a local disctionnary 'bank' which does't exist out of the function. When the function end, it runs 'mainly' but doesn't remember the dictionary.

Second one, as you use a dictionnary structure you don't need to loop thru and check all elements 1 by 1. You can instead use the function dict.get

I can propose you this solution :

def welcome():
    print('Welcome to the automated technical support system.')
    print('Please describe your problem:')

def get_input():
    return input().lower().split()

def main():
    bank = {"crashed": "Are the drivers up to date?", ...}
    welcome()
    query = get_input()

    while query != 'quit':
        if bank.get(query, None) is not None:
            print(bank[query])
        else:
            print("doesn't exist")
        query = get_input()

    print("Curious, tell me more.") # will be triggered only when you are out of the loop

if __name__=="__main__":
    main()

In that case bank.get(query, None) will return the sentence if the word exist, else it returns None.

You can also simplify it as :

while query != 'quit':
    sentence = bank.get(query, "doesn't exist")
    print(bank[query])
    query = get_input()

this is because if it exist, sentence = what you want to display, if it doesn't, it displays the error message you want

I hope it helps,

Upvotes: 1

Related Questions