Home > database >  What would be the correct code in order to get the factorial of n?
What would be the correct code in order to get the factorial of n?

Time:12-06

n=int(input("Enter a number: ")) p=1 for i in range(n): p*=i print(p)

I wanted to find out the factorial of a number but I always get 0 as output

CodePudding user response:

The problem with your code is that you are starting your range at 0, so your loop never runs. The factorial of a number is the product of all numbers between 1 and that number. So, you should start your loop at 1 instead:

n = int(input("Enter a number: ")) p = 1 for i in range(1, n 1): p *= i print(p)

CodePudding user response:

range(x) is from 0 by default to x-1, so e.g. range(3) is 0, 1, 2

You want to start from 1 and go to x 1 probably:

n = int(input("Enter a number: "))
factorial = 1
for i in range(1,n 1):
    factorial*=i
    print(factorial)

CodePudding user response:

def factorial(n):
  # Check if the input is a positive integer
  if n >= 0 and n == int(n):
    # If n is 0 or 1, the factorial is 1
    if n == 0 or n == 1:
      return 1
    # Otherwise, the factorial is n multiplied by the factorial of n-1
    else:
      return n * factorial(n-1)
  # If the input is not a positive integer, return None
  else:
    return None

Test the function by calculating the factorial of 5

print(factorial(5))
  • Related