Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
Hello, I can't seem to understand this code, it's about factor a number but I don't understand how works the function, I would be glad if someone can help with this.

def factor(x):
if x==0:
return 1
return x * factor(x - 1)

x=int(input())
print (factor(x))

What I have tried:

Just understanding....................................................................
Posted
Updated 6-Jan-18 7:59am

This function calculates the factorial of the number x.
Please see: https://en.wikipedia.org/wiki/Factorial[^]

The function calls itself: it's a recursive function.
Please see: https://www.programiz.com/python-programming/recursion[^]
 
Share this answer
 
Comments
Member 13609237 6-Jan-18 10:38am    
Hello, thanks for your answer, I have some little questions. How does the function knows how to stop calling itself? And, Why is necessary the "if statement" "If x == 0 then return 1" If I delete those 2 lines and let only the "return x*factor(x-1)", the program doesn't even work! Why is that?
Eventually the value of x reaches 0 (because of the x-1 instruction) and stops calling itself (the factorial of 0 is defined as 1).
The whole function is also explained in the second link in my first answer. You can also write the function as:
Python
def factor(x):
    result = 1
    while x > 0: # x > 1 will do
       result = x * result
       x = x - 1
    return result
 
Share this answer
 
Comments
Member 13609237 6-Jan-18 14:01pm    
Hi, I think now I see why are necessary the lines "if x == 0:
return 1"
It's because the function would not have a limit, and it could turn into a loop, right?
Well, thank you very much.
[no name] 6-Jan-18 14:17pm    
You're welcome and yes, you're right about the function limit. A function must end sometime... :)
A recursive function is usually not easy to follow and understand. Well done!
Thanks for your kind replies and votes!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900