Python 函数不返回 Bool 值

Mak*_*ris 0 python boolean return-value

可能的重复:
为什么“返回自我”返回 None?

我一直在尝试解决 Project Euler 上的问题 55 ( http://projecteuler.net/problem=55 ),现在我想我已经找到了答案,但我遇到了一个问题。我不想要问题 55 的解决方案,只想要我做错了什么。

这是我的代码:(我认为您不需要全部)

t=0
lychrel=0
called=0

def iteratepal(n):
    global t
    global called
    called+=1
    b = int(''.join(reversed(str(n))))
    #print ("n =",n,"\nb =",b,"\nb+n =",b+n,"\n")

    if ispal(b+n) or ispal(n):
        t=0
        return False

    if t<50:
        t+=1
        iteratepal(b+n)
    else:                          # Here's the prob
        t=0                        # this block is executed (because it prints "yea")
        print("yea")               # but it doesn't return True!
        return True                # you can try it yourself (even in the interpreter)

def ispal(n):
    if n == int(''.join(reversed(str(n)))):
        return True
    return False

print(iteratepal(196))

for i in range(0,200):
    if iteratepal(i)==True:
        lychrel+=1
        print(i,"is Lychrel!")
    else:
        print(i,"is not a Lychrel!")
print(lychrel)
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助,我对此感到非常困惑。

Mar*_*ers 5

当 时,您递归地调用该函数t < 50,但不对返回值执行任何操作:

if t<50:
    t+=1
    iteratepal(b+n)
else:                          
    t=0                        
    print("yea")               
    return True
Run Code Online (Sandbox Code Playgroud)

else:分支永远不会被执行,因此None会被返回。您可能想返回递归调用的结果:

if t<50:
    t+=1
    return iteratepal(b+n)
else:                          
    t=0                        
    print("yea")               
    return True
Run Code Online (Sandbox Code Playgroud)

一些进一步的提示: