Formula for factorials, don't get it | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Formula for factorials, don't get it

Hi if you look below, here's some code for calculating a factorial. Ie. the factorial of 5 is 5! = 5*4*3*2*1 the factorial of 0 is 0!=1 After going round in circles I picked the code below off the internet. But I am having difficulty with it. The code creates a function called factorial and in its definition calls on itself It's a recursive process I know... but how can a function be defined by itself? Anyone can explain? Thanks! ____________ """Here we are setting up a prompt to ask for number going in""" number=int(input("The factorial for ")) """ This is creating a function based on variable i""" def factorial(i): if i==0: return 1 else: return i * factorial(i-1) print ( number, "is", factorial(number))

15th Apr 2019, 1:58 PM
Josie The Ritalin Dog
Josie The Ritalin Dog - avatar
1 Answer
+ 3
The function isn't defined by itself, but it keeps calling itself with the argument i-1 until the break condition (i==0) is True. If you call factorial(5), the function will return 5 * factorial(4). So now the function needs to call itself again because it has no idea what factorial(4) is. And it learns that factorial(4) is 4 * factorial(3), so now the temporary result is 5 * (4 * factorial(3)). The function still has no idea what factorial(3) is, so it calls itself again with the argument 3 and the result is now 5 * (4 * (3 * factorial(2))). The function calls itself again: 5 * (4 * (3 * (2 * factorial(1)))). And again: 5 * (4 * (3 * (2 * (1 * factorial(0))))). Now, factorial(0) is called and that is the break condition. The function knows that when i == 0, it can stop calling itself and just return the result * 1. So factorial(5) is 5 * (4 * (3 * (2 * (1 * 1)))). If you're on a PC, check this link to see a visualization of how your code works: http://pythontutor.com/visualize.html#mode=display . Paste your code there and click "Visualize"
15th Apr 2019, 2:35 PM
Anna
Anna - avatar