Home > Software engineering >  Why is the for loop just returning one element?
Why is the for loop just returning one element?

Time:12-15

I need to translate a sentence in python using a dict file, while the whole sentence should be translated in one swoop.

My approach was to first tokenize the sentence using a helper method.

After tokenizing was successfully done, I tried to loop over the tokenized sentence using a for loop and comparing each element to the dict file. But for some reason just the last word gets translated.

This is my Code so far_

tokenizedSentence = helperMethodTokenizer(sentence)

    tokenizedSentence.remove(".")


    for word in tokenizedSentence:
         translation = dict_file[word]

    return translation

My Output looks like this so far:

Expected: I like you now

Actual: now

Can somebody pls tell me why I only get the last translation and not the whole sentence?

CodePudding user response:

The problem is that you overwrite the translation variable for each iteration in the loop. One of many possible solutions could be to put it in a list instead:

tokenizedSentence = helperMethodTokenizer(sentence)

tokenizedSentence.remove(".")

translation_list = []
for word in tokenizedSentence:
     translation_list.append(dict_file[word])

return translation_list
  • Related