Home > Net >  how can I loop through search function - python
how can I loop through search function - python

Time:05-07

I am trying to make search program but I stuck in some loop part. There are several steps for function works. First, I will get a word(input) from users. Then, I will compare whether user's inputs are included in any values from any dictionary If user's inputs are included, then I want to print out the key value from dictionary as list type. If not, then I want to execute the loop and print out some messages.

For example, if I type nice as input, then program should print matthew as list type. Program should keep loop until I type the input that doesn't invovled in the dictionary value. For example, if i type any input from dic_1 and dic_2, the program should keep loop until i input input that is not involved in the dictionary value.

If I type trash or something that is not in the dictionary, then program should print out messages that nothing match.

dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}

def searchWords(*dicts):
  while(True):
     list_1 = []
     t = input('Enter a word for search:')
     for dic in dicts:
        for k,v in dic.items():
           if t in v:
              list_1 =[k]
          else:
              print("Nothing match, end program")
              break
    return list_1

print(searchWords(dic_1, dic_2)

Now on, I have no problem for print out key value when I input once but I get stuck on loop part. I want to keep loop thorugh the program until I input words that not invovled in dictionary value but I can't figure out any algorithms for solving loop issue. I try out for for loop and if loop but I failed it. So if you guys can give any advice or idea for loop, it would be appreciate it lots.

CodePudding user response:

The easiest way to handle this is with a True/False flag as follows:

dic_1 = {'matthew': 'he is a nice guy',
         'dennis': 'he is a bad guy',
         'alex': 'he is a good guy'}
dic_2 = {'manchester': 'city from england',
         'tokyo': 'city from japan',
         'rome': 'city from italy'}


def searchWords(*dicts):
    while True:
        t = input('Enter a word for search: ')
        found = []
        for dic in dicts:
            for k, v in dic.items():
                if t in v.split():
                    found.append(k)
        if not found:
            print('No match')
            break
        else:
            print(*found)
  • Related