Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Usual recursive function for calculating factorial
- def factorial(n):
- if n == 1:
- return 1
- else:
- return n * factorial(n - 1)
- print("5! is", factorial(5))
- print("10! is", factorial(10))
- '''
- Another version to see what is happening with print statements in the conditions.
- Notice in the output how the execution climbs down the ladder from the original value of n to 1, then climbs back up the latter from 1 to n.
- '''
- def factorial(n):
- if n == 1:
- print("Base case reached!")
- return 1
- else:
- print("Finding ", n, " * ", n-1, "!", sep = "")
- result = n * factorial(n - 1) #since it calls back the same function it goes to if condition again then to this else
- print(n, " * ", n-1, "! = ", result, sep = "") #after we got return 1, it comes back to this line to calculate the result
- return result
- print("5! is", factorial(5))
- '''
- Output will show:
- Finding 5 * 4!
- Finding 4 * 3!
- Finding 3 * 2!
- Finding 2 * 1!
- Base case reached!
- 2 * 1! = 2
- 3 * 2! = 6
- 4 * 3! = 24
- 5 * 4! = 120
- 5! is 120
- '''
Add Comment
Please, Sign In to add comment