Python: How to create a function to compute Factorial

Team,

Can you help with below? I tried, but unable to get the correct code.



Thanks

Viren



You will use a function to compute the factorial of 5. 

Instructions

  1. Using the num variable, create a range to make the code run through it and find the factorial of num. The end value should be sufficient large to compute the factorial correctly. Save the value in end.
  2. Use a math operation to compute recursively the factorial of num. Save the operation in fact. Use the correct inputs to compute the value. Hint: The factorial is a sum of values? A multiplication?

Hi Viren,



You can refer to this link to understand how to write the required function. 

 

Please see below code - getting output "error" incorrect.




Create function to compute the factorial

def factorial(num):

    # Specify the initial factorial value

    fact = 1

    

    # If the number is less than zero

    if num < 0:

        

        # Print the following message

        print("Factorial cannot be computed for negative number")

        return

    

    # If the above condition is not met, do the following

    # Line 1: Create the correct end value for a range to be used to make the loop run

    end = 5

    

    # Create the range

    range1 = range(1, end)

    

    # Go through each value of range1

    for i in range1:

        # Line 2: Create a math operation between two variables from the function

        fact = fact*=i

    # Return the factorial

    return fact


Compute the factorial of 5

print("The factorial of {0} is {1}".format(5, factorial(5)))

Hi Viren,



There are two errors in the above code:

  1. The range should include the number itself, so the end value should be num + 1. If num is 5 then range1 = range(1, 6)
  2. The line fact = fact *= i contains a syntax error. It should be fact *= i.

Thanks Akshay, much appreciated

I tried another way as well



def factorial(n):

If (n==1 or n==0):

return 1

else:

return(n*factorial(n-1))



num=5;

print('Factorial of',num, 'is', factorial(num))

Good to know! Happy learning!