1
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ The factorial of 0 is 1. What does this code do for x==0? \$\endgroup\$ – Maarten Fabré May 22 at 12:42
  • \$\begingroup\$ @MaartenFabré - I have edited my code to include your question above. \$\endgroup\$ – Justin May 22 at 12:45
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Mast May 22 at 12:47
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Mast May 22 at 12:48
  • \$\begingroup\$ @MaartenFabré - if num == 0: print ("The factorial of 0 is 1") \$\endgroup\$ – Justin May 22 at 12:48
3
\$\begingroup\$

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.