[英]Is there a difference between adding a scalar to a vector inside a for loop and outside it, using numpy?
[英]what is difference between returning return from inside loop and outside loop?
實際上,我是python的新手。 我對 for 循環部分的回報有疑問。 -> 如果我返回內部循環輸出為 1(對於字符串“abcd”)。 -> 如果我返回與代碼中使用的相同的縮進,輸出將為 4。你能解釋一下這種情況嗎?
我還使用代碼中的注釋簡要添加了我的問題。
def print_each_letter(word):
counter = 0
for letter in word:
counter += 1
return counter #its returning length 1 why ?
return counter # its returning length 4 why?
print_each_letter("abcd")
return
退出函數,它返回4
因為它在循環之外,並且循環完成了它的所有操作並加起來為4
(因為abcd
的長度是 4)並返回值。
因為循環內部的return
是第一次執行循環時執行的,所以會出現這種情況:
counter = 0
for letter in word:
#'a'
counter += 1
return counter #return counter (1) and terminate function.
但是如果你讓循環先運行:
counter = 0
for letter in word:
#'a'
counter += 1 #1
#'b'
counter += 1 #2
#'c'
counter += 1 #3
#'d'
counter += 1 #4
return counter #return counter (4) and terminate function.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.