Discuss / Python / 这个代码放到pycharm里为什么总是运行不出来啊

这个代码放到pycharm里为什么总是运行不出来啊

Topic source

永远短毛

#1 Created at ... [Delete] [Delete and Lock User]

def fact(n): if n==0 or n==1: print (1) print (n * fact(n-1)) if name == 'main': n=int(input('n:')) fact(n)

得到 [Previous line repeated 994 more times] RecursionError: maximum recursion depth exceeded in comparison

是否是因为函数没有返回值? 而且, 函数中 print (n * fact(n-1))和if是平级的,所以无限递归了? 我改了一下

   def fact1(n):
    if n==0 or n==1:
        print(1)
        return 1
    else:
        x= n*fact1(n-1)
        print(x)
        return x
n=int(input('n:'))
fact1(n)

之所以没有直接打印,而是用了一个x过度了一下,是因为直接打印会增加递归的分支数目。。。。我自己的理解

永远短毛

#3 Created at ... [Delete] [Delete and Lock User]

确实是无限递归了,谢谢指点


  • 1

Reply