【问题标题】:python: taking the return of a function and using it in another functionpython:获取函数的返回并在另一个函数中使用它
【发布时间】:2017-12-14 15:44:40
【问题描述】:

大家好,我的代码可以通过将所有内容放在一个函数中来运行,这就是

 spam = ''
def enterList (names):   
    newList = []
    while True:
        names = raw_input('list a series of items and press blank when finished: ')
        if names == '':
            break
    newList = newList + [names]

    a = ''
    finalText = ''
    listOfStuff = []
    item = 0
    for i in newList:
        if item < len(newList)-2:
            a = (i + ', ')
            listOfStuff.append(a)
            item +=1
        elif item == len(newList)-2:
            a = (i + ' and ')
            listOfStuff.append(a)
            item +=1
        else:
            a = i
            listOfStuff.append(a)
            break
    finalText = finalText.join(listOfStuff)
    return finalText

print enterList(spam)

所以上面的代码可以按我的意愿工作。但是我试图通过拥有两个独立的函数来做同样的事情,我遇到的问题是我无法获取一个函数的返回值并在下一个函数中使用它。

这是旧代码

spam = ''

def enterList (names):   
    newList = []
    while True:
        names = raw_input('list a series of items and press blank when finished: ')
        if names == '':
            break
        newList = newList + [names]

    return newList 

print enterList(spam)

def newFunc(Addand):
    a = ''
    finalText = ''
    listOfStuff = []
    item = 0
    for i in spam:
        if item < len(spam)-2:
            a = (i + ', ')
            listOfStuff.append(a)
            item +=1
        elif item == len(spam)-2:
            a = (i + ' and ')
            listOfStuff.append(a)
            item +=1
        else:
            a = i
            listOfStuff.append(a)
            break
    finalText = finalText.join(listOfStuff)
    return finalText


newFunc(spam)

print newFunc (spam)

我不确定我做错了什么。 感谢您帮助我解决这种方法的错误。

【问题讨论】:

  • print enterList(spam) 更改为spam = enterList(spam)
  • 哇,这解决了我的问题。非常感谢。

标签: python function return


【解决方案1】:

在你的第一个函数中创建 return 语句

return newFunc(newlist)

它不起作用,因为实际上从未调用过第二个函数。

【讨论】:

  • 你错了。 return工作。只是该值没有传递给下一个函数(我没有投反对票)。
  • 是的,我的错,我没有意识到滚动条,所以我认为 OP 试图仅使用 1 调用 2 个函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2020-03-27
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
相关资源
最近更新 更多