簡體   English   中英

While循環給出不同的返回和打印結果?

[英]While loop giving different return and print results?

以下代碼用於課堂練習。 我們正在嘗試找到目標字符串的最后一個位置:

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 ,這是循環的第一個結果,而不是12當我使用return語句時?

閱讀有關return語句的信息

return 使 當前函數調用以表達式列表(或無)作為返回值。

當您這樣做時:

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內部,一次在它外部。

你想要這個嗎?

def find_last(search, target):
    if search.find(target, 0) != -1:
        count = len(search)
        while search.find(target, count) == -1:
            count -= 1
        return search.find(target, count)
    else:
        return None

print find_last('aaaabbaaabbbab', 'ab')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM