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.
1 Answer 1
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
Explore related questions
See similar questions with these tags.
The factorial of 0 is 1.
What does this code do forx==0
? \$\endgroup\$if num == 0: print ("The factorial of 0 is 1")
\$\endgroup\$