[英]Function would not return value, instead it returns “None”
請幫助我看看這段代碼,該代碼應該計算兩個數字(a, b)
之間的最大公除數。 我遇到的問題是程序不會按預期返回c
,而是返回None
。 但是,當我使用print
語句時,它會打印出c
的值。
這是我的代碼:
def gcd(a, b):
if a == 0:
return b
elif b == 0:
return a
elif a > b:
big, small = a, b
else:
big, small = b, a
c = big % small
if c == 0:
print(small)
return small
gcd(small, c)
print(gcd(1071, 462))
多謝你們。
當未遇到顯式return
且函數主體結束時,Python隱式返回None
。
在您的情況下,如果它通過了所有其他情況,則只會命中:
gcd(small, c)
return None # you haven't put that in explicitly but that's how Python processes it
因此,您可能只需要將最后一行更改為:
return gcd(small, c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.