I made a simple two words translator, but I don't know how to loop it so it ask again to input a word, and then break it with a command or something. Here's the code:

print 'Translate "Dog" and "Water" to German.'
word = raw_input("Word: ")

if word == "Dog":
    print "German: Hund"
elif word == "Hello":]
    print "German: Hallo"
else:
    print 'Type "Dog" or "Hello"'
有帮助吗?

解决方案

How about a while loop? A while loop loops through the code until the specified condition is false. while True is always true, so the code will be executed until you choose to exit it.

print 'Translate "Dog" and "Water" to German.'
while True:
    word = raw_input("Word: ")

    # conditionals

You would include your above conditionals where the comment is, but also be sure to have them check for a word that exits the loop/program. For example, if word == 'quit': break would exit the loop when the user wants to quit.

Edit:

By 'quit' I simply mean to 'break out of the loop'. If you haven't worked with loops before, you may want to check out the link below, as it describes looping much better than I can, and will help you understand what the term 'break out of loop' means.

http://www.tutorialspoint.com/python/python_while_loop.htm

其他提示

Sometimes the right data structure can simplify your code, removing the need for conditional logic. For example, you could let a Python dict do most of the work.

translations = dict(
    dog   = 'Hund',
    hello = 'Hallo',
)

while True:
    eng = raw_input("Word: ")
    if not eng:
        break
    deu = translations.get(eng.lower())
    if deu is None:
        print 'Unknown word: {}'.format(eng)
    else:
        print 'German: {}'.format(deu)

FMc answer is great, but I would to something different, a bit more pythonic:

translations = {"Dog":"Hund", "Hello":"Hallo"}
eng = "sample"
while eng:
eng = input("Word: ")
if not eng in translations:
    print("Unknown word")
else:
    print (German: translations[eng])

First of all, we use the built-in dictionary; it's the same the FMc used, but it's less wordier.

The 'eng' is avaliated to False when it's empty ("") or None. Then we check if the word is on the dict. If it isn't, we say the word is unknown, if it's, we print the correspondent key, also known as translated word.

You can easily turn it into a function:

 def translator(translations, language):
 eng = "sample"
 while eng:
    eng = input("Word: ")
    if not eng in translations:
        print("Unknown word")
    else:
        print (language + ": " + translations[eng])

With it, you just have to pass a dictionary of translation and the name of your language.

For instance:

  translator({"Dog":"Cachorro","Hello":"Ola"},"Portuguese")

The eng = "sample" line is not so beautiful, but it works; you can try a different way so you can eliminate this line and still use eng in the while loop.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top