- #1
late347
- 301
- 15
example code from python-course.eu
Looking at the code I don't understand how the program is able to print so many "intermediate result for n" messages ...
when you call the function called factorial with parameter 3:
I know how factorial works in math and in my brain, but I can't seem to understand the extra message "intermediate result for 3* factorial(2)=6"
of course in real life the factorial of 3 is indeed as follows
3*2*1 = 6
Python:
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
print(factorial(3))
Looking at the code I don't understand how the program is able to print so many "intermediate result for n" messages ...
when you call the function called factorial with parameter 3:
- "factorial has been called with 3" is printed
- if clause is negative
- res = 3* (something...?) at this point the factorial is called again from inside itself with parameter 2 This step is a little bit confusing because I can't really deduce from the code immediately what value will be assigned to the variable res...
- "factorial has been called with 2" is printed
- if clause is negative
- res = something and factorial is called with parameter 1
- "factorial has been called with 1" is printed
- if clause is positive.
- at this point I think the program should probably come out from the line factorial(2-1)...
- "intermediate result for 2*factorial(1) =2"" is printed
- why doesn't the program just end there? I don't get it why the program prints the extra "intermediate result for 3*factorial(2)=6"
I know how factorial works in math and in my brain, but I can't seem to understand the extra message "intermediate result for 3* factorial(2)=6"
of course in real life the factorial of 3 is indeed as follows
3*2*1 = 6