我不明白爲什麼這個python函數返回無,如果它遞歸調用自己。遞歸返回無Python函數
這是我解決項目歐拉問題的一部分。無論如何,我已經以更好的方式解決了這個問題,但是這仍然讓我很煩惱,因爲這個函數似乎可以正常工作 - 而且它似乎知道我想要返回的變量的值。
def next_prime(previous):
if previous % 2 == 0:
candidate = previous + 1
else:
candidate = previous + 2
print "trying", candidate
prime = True
for div in range(2,candidate//2,1):
if candidate % div == 0:
prime = False
print candidate, "is not prime - divisible by", div
next_prime(candidate)
break
if prime is True:
print candidate, "is prime"
#return candidate
last = 896576
print "After", last, ", the next prime is..."
next_prime(last)
這給:
After 896576 , the next prime is...
trying 896577
896577 is not prime - divisible by 3
trying 896579
896579 is not prime - divisible by 701
trying 896581
896581 is not prime - divisible by 7
trying 896583
896583 is not prime - divisible by 3
trying 896585
896585 is not prime - divisible by 5
trying 896587
896587 is prime
但是,如果我去掉了return語句,如果第一次嘗試是素數只返回一個值,否則返回無。
你沒有使用遞歸調用的值,這是正常的嗎? – Tobu 2010-01-17 21:10:44