下面的代码用于课堂练习。我们正在试图找到目标字符串的最后一个位置:
def find_last(search, target):
count = 0
while search.find(target, count) != -1:
return search.find(target, count)
count = count +1
print find_last('aaaabbaaabbbab', 'ab')
答案应该是12
,但是如果我运行代码,就会得到答案3
。你知道吗
但是,如果我使用此代码:
def find_last(search, target):
count = 0
while search.find(target, count) != -1:
print search.find(target, count)
count = count +1
print find_last('aaaabbaaabbbab', 'ab')
我得到的答案是:
3 3 3 3 8 8 8 8 8 12 12 12 12 None
所以,看起来我的函数正在找到正确的答案12
,问题是为什么它要打印出3
,这是循环的第一个结果,而不是我使用return
语句时的12
?你知道吗
阅读^{} statement :
当您这样做时:
return
返回结果并终止函数find_last
的执行。你知道吗把它取下来你就没事了。别忘了在循环之后
return count
。你知道吗这是因为
return
终止当前函数并返回值。当到达return
时循环就停止了,函数find_last
退出了。你知道吗您可以将值存储在变量中并在循环后返回,而不是在循环内返回。你知道吗
return
丢弃当前函数中的剩余代码并继续在调用方中执行。你知道吗要查看发生了什么,请运行以下命令:
它将只打印
3
两次:一次在find_last
内部,一次在它外部。你知道吗相关问题 更多 >
编程相关推荐