Question

for word in sentence.split():

    if word[0] in VOWELS:
        pig_latin = word + "ay"

    else:
        pig_latin = word[1:] + word[0] + "ay"

    return pig_latin

How do I make it so that the return prints the whole sentence in the main, not just the one word?

Était-ce utile?

La solution

You have to build the whole sentence in some way. For example, you can build up a list of words:

pig_words = []

for word in sentence.split():
    if word[0] in VOWELS:
        pig_latin = word + "ay"
    else:
        pig_latin = word[1:] + word[0] + "ay"
    pig_words.append(pig_latin)

return pig_words

If you want to turn it back into a sentence, the opposite of split is join, so just change the last line to:

return ' '.join(pig_words)

Autres conseils

You need to append the values to a list and remove the return statement from the loop, so that it will return the list after the for loops has finished iterating.

words = []
for word in sentence.split():
    if word[0] in VOWELS:
        pig_latin = word + "ay"
    else:
        pig_latin = word[1:] + word[0] + "ay"

    words.append(pig_latin)

return words

Your return statement is executed on the first pass though your for loop. Even if you un-indented the return statement to run at the conclusion, you would then only have the last translated word in the pig_latin variable.

To translate the whole sentence, you should only return after the entire for loop runs to completion, saving the accumulated list of translated words.

entensesay = []
for word in sentence.split():
    if word[0] in VOWELS:
        entensesay.append(word + "ay")
    else:
        entensesay.append(word[1:] + word[0] + "ay")
return ' '.join(entensesay)

It is also good habit to avoid doing string concatenation in loops in Python. List append method is more efficient, and then use ' '.join() to produce the final concatenated string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top