# Python program to find the factorial of a number using recursion

A factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 5 (denoted as 5!) is 1*2*3*4*5 = 120. The factorial of 0 is 1.

def recur_factorial(x):

if x == 1:
return 1
else:
return (x * recur_factorial(x - 1))

num = int(input("Enter number: "))

print("The factorial of", num, "is", recur_factorial(num))


So I would like to know whether I could make this program shorter and more efficient.

Also, I would like to know the advantages and disadvantages of recursion.

• The factorial of 0 is 1. What does this code do for x==0? – Maarten Fabré May 22 at 12:42
• @MaartenFabré - I have edited my code to include your question above. – Justin May 22 at 12:45
• Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers. – Mast May 22 at 12:47
• Once a question has an answer, leave the code in it alone. If the original code wasn't complete, please learn something from this for your next question. – Mast May 22 at 12:48
• @MaartenFabré - if num == 0: print ("The factorial of 0 is 1") – Justin May 22 at 12:48

## 1 Answer

Looking over your code, this is what I have for you:

• Your function can be turned into a one-liner
• You should use if __name__ == '__main__' to ensure you're not running this program externally.

Refactored Code:

def recur_factorial(x):
return 1 if x == 1 else (x * recur_factorial(x - 1))

def main():
num = int(input("Enter number: "))
print("The factorial of", num, "is", recur_factorial(num))

if __name__ == '__main__':
main()


You can read this StackOverflow question for more information about the advantages and disadvantages of recursion

• Upvoted! Thanks, I will keep this in mind. – Justin May 22 at 12:24