gpt4 book ai didi

递归后返回 None 的 Python 函数

转载 作者:太空宇宙 更新时间:2023-11-03 13:24:40 28 4
gpt4 key购买 nike

<分区>

我不明白为什么这个 python 函数在递归调用自身时返回 None。

这是我解决 Project Euler 问题的一部分。无论如何,我已经以更好的方式解决了这个问题,但这仍然让我很烦,因为该函数似乎工作正常 - 并且它似乎知道我想要返回的变量的值。

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 语句的注释,它只会在第一次尝试为质数时返回一个值,否则返回 None。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com