如果这是一个愚蠢或重复的问题,我首先道歉。我已经学习python大约两周了,我一直在循环方面遇到小问题。例如
def factorial(n):
if n < 2: # I understand once the number becomes < than 2 the loop continues
return 1. #and here we return the value 1
result = n * factorial(n-1) #why do we subtract 1 from n?
return result
factorial(5) #my random number
我很难理解你为什么从n中减去1。你不应该加1来包括这个数字吗?
在我看来是这样的:result=n(1(*factorial((1(-1(#不是n保持=为1,还是我错了?
谢谢你的帮助。如果这是一个愚蠢的问题,再次抱歉。
例如,首先用5调用函数,然后用5再次调用它并相乘,它将溢出递归极限和无尽循环。
所以,你需要递减1,然后调用4,3,依此类推,当它小于2时,返回1。