-2
vowel = ('A','E','I','O','U','a','e','i','o','u')
sentence = 'Write a script that encodes phrases'
def pig_latin(sentence):
    for words in sentence.split():
        if words[0] in vowel:
            words = words + 'ay'
        else: words = words[1:]+ words[0] + 'ay'
    return(words)
pig_latin(sentence)

I am trying to let this function print out all the words in the sentence but no matter where I place return, it always only gives me the first/ last word in the sentence. Can someone tell me what I did was wrong? Thank you!

3
  • 1
    You need to put some debugging print statements inside your loop. The critical problem is that you are trying to use words for two conflicting purposes at the same time. Each purpose destroys the other's progress. Use one loop variable, and another to accumulate results.
    – Prune
    Commented Oct 20, 2020 at 20:23
  • 1
    @Evorage, you ok there? Commented Oct 20, 2020 at 20:23
  • wow thanks for being so friendly man
    – FEI
    Commented Oct 20, 2020 at 20:48

1 Answer 1

2

One workaround is to simply use an aggregator to build the string as you go:

vowel = ('A','E','I','O','U','a','e','i','o','u')
sentence = 'Write a script that encodes phrases'
def pig_latin(sentence):
    aggregator = ''
    for words in sentence.split():
        if words[0] in vowel:
            words = words + 'ay'
        else: 
            words = words[1:]+ words[0] + 'ay'
        aggregator = aggregator + ' ' + words
   return aggregator
    
pig_latin(sentence)

Not the answer you're looking for? Browse other questions tagged or ask your own question.