【问题标题】:(PYTHON) How to return all the words in the function? (instead of just one [closed](PYTHON) 如何返回函数中的所有单词? (而不仅仅是一个[关闭]
【发布时间】:2021-02-03 17:32:25
【问题描述】:
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)

我试图让这个函数打印出句子中的所有单词,但无论我将return 放在哪里,它总是只给我句子中的第一个/最后一个单词。有人可以告诉我我做错了什么吗?谢谢!

【问题讨论】:

  • 您需要在循环中放入一些调试print 语句。关键问题是您试图同时将words 用于两个相互冲突的目的。每一个目的都会破坏对方的进步。使用一个循环变量,另一个来累积结果。
  • @Evorage,你还好吗?
  • 哇,谢谢你这么友好

标签: python function for-loop return


【解决方案1】:

一种解决方法是简单地使用聚合器来构建字符串:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多