【发布时间】: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) -
哇,这解决了我的问题。非常感谢。