而循环给出不同的返回和打印结果?

2024-10-04 07:38:46 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码用于课堂练习。我们正在试图找到目标字符串的最后一个位置:

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?你知道吗


Tags: 答案代码target目标searchreturnabdef
3条回答

阅读^{} statement

returnleaves the current function call with the expression list (or None) as return value.

当您这样做时:

while search.find(target, count) != -1:
        return search.find(target, count) 

return返回结果并终止函数find_last的执行。你知道吗

把它取下来你就没事了。别忘了在循环之后return count。你知道吗

这是因为return终止当前函数并返回值。当到达return时循环就停止了,函数find_last退出了。你知道吗

您可以将值存储在变量中并在循环后返回,而不是在循环内返回。你知道吗

return丢弃当前函数中的剩余代码并继续在调用方中执行。你知道吗

要查看发生了什么,请运行以下命令:

def find_last(search, target):
    count = 0
    while search.find(target, count) != -1:
        print  search.find(target, count)
        return search.find(target, count)
        assert 0, 'unreached'
        count += 1

print find_last('aaaabbaaabbbab', 'ab')

它将只打印3两次:一次在find_last内部,一次在它外部。你知道吗

相关问题 更多 >