【发布时间】:2019-10-25 21:37:56
【问题描述】:
以下代码返回“True”。
check = [1,2,4,6]
def is_consecutive(a_list):
"""Checks to see if the numbers in a list are consecutive"""
total = 2
while total > 1:
test = a_list.pop(0)
if test == a_list[0] - 1:
total = len(a_list)
return True
else:
return False
break
works = is_consecutive(check)
print(works)
我找到了一个解决方案,通过在 while 循环之后将 return True 移动到一个新块:
check = [1,2,4,6]
def is_consecutive(a_list):
"""Checks to see if the numbers in a list are consecutive"""
total = 2
while total > 1:
test = a_list.pop(0)
if test == a_list[0] - 1:
total = len(a_list)
else:
return False
break
return True
works = is_consecutive(check2)
print(works)
我不完全理解为什么将这段代码移到 while 循环之外可以正常工作。在我看来,一旦你告诉一个函数返回 True,以后就不能在函数中更改它了。对吗?
【问题讨论】:
-
一旦函数返回,它就会退出,并且该函数中的任何代码都不会运行,直到再次调用该函数。为什么第一个代码不起作用,您能看到
while循环会循环的任何方式吗?有没有不以回报告终的案件?然后就第二段代码问自己同样的问题。 -
return表示很好的回报,你将你的函数计算的答案返回给调用它的函数。
标签: python python-3.x list