How to restart query type program though user input

Good Morning! I have this code I’m playing with and it works great but I’m not sure how to get it to ask to run again from the user. It simply retrieves a definition (value) from a file that contains a huge dictionary of words and definitions (keys and values). I’ve tried a few things like making the “word” input function its own function but I cant get it to continually iterate if the user wishes to ask for another definition.

import json
import difflib

from difflib import get_close_matches


data = json.load(open("data.json"))

def translate(w):
    w=w.lower()
    if w in data:
        return data[w]
    elif len(get_close_matches(w, data.keys()))>0:
        answer = input("Did you mean %s Y or N?" % get_close_matches(w, data.keys())[0])
        if answer=="Y":
            return data[get_close_matches(w, data.keys())[0]]
        elif answer=="N":
           return "The word doesnt exist!"
        else:
            return "No understando"
    else:
        print("The word doesnt exist!")

word = input ("Enter word: ")
output = (translate(word))

if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)

Put the input in a loop.

2 Likes

Alexander,

The usual way to make things repeat is to set up conditions and enter one of the many versions of a python loop.

You also need some kind of exit condition.

The details vary depending on the kind of loop. The code you want inside the loop is this code, right:

word = input ("Enter word: ")
output = (translate(word))

if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)

The above will need to be indented in the loop and here is an
\textcolor{pink}{\textsf{example}} \textcolor{blue}{\textsf{:}}

# Initialize your loop controller
finished = False

# Loop as long as the user does not just hit 
# RETURN for an empty string.

while (!Finished)
    word = input ("Enter word: ")
    if (word == "")
        Finished = True
    else
    output = (translate(word))

    if type(output) == list:
        for item in output:
            print(item)
    else:
        print(output)
 
# Program exits

There are many variants you can use including using “word” and examining if it is “quit” or whatever your design requires.

Avi :clown_face: