My assignment is to use nested if statements to construct a simple translator. Yes, I know that's an awful way to do it, but that's what the assignment says. Here's what I have so far:
def translate(word, language):
'''
Takes as parameters a string to translate,
and a second string as the language to translate to.
Returns the original word, the language, and the word's
translation in the entered language.
'''
en_word = word.lower()
lang = language.lower()
# French
if lang == "french":
if en_word == "cat":
print("chat")
if lang == "french":
if en_word == "dog":
print("chein")
# German
if lang == "german":
if en_word == "cat":
print("katze")
if lang == "german":
if en_word == "dog":
print("hund")
# Spanish
if lang == "spanish":
if en_word == "cat":
print("gato")
if lang == "spanish":
if en_word == "dog":
print("perro")
translate('cat', 'french')
After being called as translate('cat', 'french'), for example, the output should be:
The translation of cat in French is chat
As it is, my function finds and prints the correct word. I tried using a return statement such as
return en_word, 'French', 'chat' and a print statement such as
print('The translation of', translate[0], 'into', translate[1], 'is', translate[2])
but the error message TypeError: 'function' object is not subscriptable popped up. I could put virtually identical print statements into each end of the if statements in the function, but that seems terribly inelegant.
How can I get the function to return the English word, the language and the translated word to insert into a generic print statement?
Aucun commentaire:
Enregistrer un commentaire