[英]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.