【发布时间】:2016-09-20 05:50:35
【问题描述】:
我正在学习 learnpython.org 上的“函数”练习,并且有一个问题是为什么我的代码版本在输出的每个字符串之后都返回“无”(我首先定义字符串列表然后返回它在那个特定的函数中)而不是解决方案(它们在一行中返回字符串列表)。这是他们给我的代码、说明以及我们希望看到的内容:
说明:
添加一个名为 list_benefits() 的函数,它返回以下字符串列表:“更有条理的代码”、“更易读的代码”、“更容易的代码重用”、“允许程序员共享和连接代码”
-
添加一个名为 build_sentence(info) 的函数,该函数接收包含字符串的单个参数并返回一个以给定字符串开头并以字符串结尾的句子“是函数的好处!”
李> 运行并查看所有功能协同工作!
代码(给定):
# Modify this function to return a list of strings as defined above
def list_benefits():
pass
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
pass
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print build_sentence(benefit)
name_the_benefits_of_functions()
预期输出:
More organized code is a benefit of functions!
More readable code is a benefit of functions!
Easier code reuse is a benefit of functions!
Allowing programmers to share and connect code together is a benefit of functions!
现在,这是我实施的解决方案 - 一切似乎都很好,除了每隔一行我得到一个“无”:
代码(我的):
# Modify this function to return a list of strings as defined above
def list_benefits():
list = "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"
return list
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
print "%s is a benefit of functions!" % benefit
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print build_sentence(benefit)
name_the_benefits_of_functions()
输出(我的):
More organized code is a benefit of functions!
None
More readable code is a benefit of functions!
None
Easier code reuse is a benefit of functions!
None
Allowing programmers to share and connect code together is a benefit of functions!
None
这就是实际的解决方案,它会产生前面显示的预期输出:
代码(解决方案):
# Modify this function to return a list of strings as defined above
def list_benefits():
return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
return "%s is a benefit of functions!" % benefit
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print build_sentence(benefit)
name_the_benefits_of_functions()
如您所见,我的代码和解决方案之间的唯一区别在于,在我的代码中,我将字符串分配给变量“list”,然后返回该变量,与解决方案代码一样,它们正在返回字符串列表本身。我的版本每隔一行返回“无”,而正确的版本却没有,究竟是什么原因?
谢谢!
【问题讨论】:
标签: python