问题
I am new to Python, I am trying to write a Python program to calculate and print factorials up to n! as shown using recursion.

However, I only get the following result:

Here is my code right now:
def factorial( n ):
print("n n!")
if n <=1:
print(str(n) + ' ' + str(n))
return 1
else:
r = n * factorial( n - 1 )
print(str(n) + ' ' + str(r))
return r
What is wrong in my code?
回答1:
With recursion:
factorial = lambda n: n * factorial(n - 1) if (n > 1) else 1
This is similar to your function, except I don't print things out (because it slows it down and is unnecessary).
If you try to evaluate it, with, for example, the number 4:
factorial 4
4 * factorial(4 - 1)
4 * (3 * factorial(3 - 1))
4 * (3 * (2 * factorial(2 - 1)))
4 * (3 * (2 * 1)))
24
What this does is take the number n
, then checks if it is greater than 1. If so, it returns n
* the factorial of n - 1
. If it is less than or equal to 1, then it returns 1.
回答2:
Okay, I figured out what is the problem. I used the Python Interactive Shell to run the program, so resulting in double printing of final result.
I put the program in a .py file and run it using command line and I finally got the correct result.
The code finally becomes:
def factorial( n ):
if n <=1: # base case
print(str(n) + ' ' + str(n))
return 1
else:
r = n * factorial( n - 1 ) # recursive call
print(str(n) + ' ' + str(r))
return r
print("n n!")
factorial(9)
回答3:
Without recursion:
def factorial(n):
answer = 1
for i in range(2, n+1):
answer *= i
return answer
With recursion:
def factorial(n):
if n<=1:
return 1
else:
return n*factorial(n-1)
来源:https://stackoverflow.com/questions/25916065/writing-python-factorial-function-using-recursion