Python 如何打印句子列表中的独立句子?附代码报错修正
错误根因
list_benefits函数的返回逻辑错误:内部写了for k in things: return k,return会直接终止函数执行,因此仅第一次循环拿到列表首元素就直接返回了单个字符串,没有返回完整的things列表。- 后续
name_the_benefits_of_functions中拿到的list_of_benefits不是列表,是单个字符串。Python中字符串属于可迭代对象,for循环遍历字符串时会逐个取出每个字符,因此出现逐字符打印的异常输出。
修正方案
移除list_benefits内多余的循环,直接返回完整的things列表即可,其余函数逻辑不需要改动。
修正后完整代码
def list_benefits(): things = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"] return things 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()
修正后输出结果
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!
内容的提问来源于stack exchange,提问作者Isaac Attuah
相关产品推荐
相关产品推荐

