5. Factorial


To calculate the factorial of a non-negative integer x, just multiply all the integers from 1 through x. For example:
— factorial(4) would equal 4 * 3 * 2 * 1, which is 24.
— factorial(1) would equal 1.
— factorial(3) would equal 3 * 2 * 1, which is 6.


Define a function factorial that takes an integer x as input.

Calculate and return the factorial of that number.

I don't get how this is supposed to work or what I am meant to do.


From what you have typed or copied & pasted, it says to:

def factorial(x): #define function
    #write code to help calculate and return factorial
factorial(5) # call the function. You could also add the print method.

Hope this helps! :slight_smile:


I still don't understand how you are meant to do what it asked.
Thanks for the help anyway.


Okay, here is my suggested code:

def factorial(x): 
    result = x
    count = x-1
    while count > 0:
        result *= count
        count -= 1
    return result
print factorial(5)

The output will be 120 because 5! means 5 * 4 * 3 * 2 * 1


I thought my code here would work, but apparently it doesn't and I don't understand why, and any help would be much appreciated!

def factorial(x):
-----if factorial(1) and factorial (0):
----------return 1
----------return factorial(x)

It says: Oops, try again. factorial(1) resulted in an error: maximum recursion depth exceeded
What do they mean by this?


Check this out.

def factorial(x):
    if x==0:        #because factorial(0) is 1 
        return 1
        return factorial(x-1)*x


almost perfect, but the exercise asks for a positive interger, so add

if x % 1 == 0 and x > 0



Here is my code, it's short and efficient:
def factorial(x):
total = 1
for i in range(1, x+1):
total *= i
return total


x= int(raw_input ("Enter non-negitive number:"))

def factorial(x):
while y > 0:
y -=1
return n

print "Factorial for %d is %d:" %(x,factorial(x))


This worked for me

def factorial(x):
    while x>0:
    return total


That's what I really was looking for, thnx so much!!


@hermione311 You don't seem to understand what factorial is. Why don't you google the concept, and then read the instructions again? Here is a helpful link:

Factorial Functions


hey guys . help me modify the bold part so as to multiply it by the sum of the numbers before X

def factorial(x):
if x % 1 == 0:
return (x+0)***(x-1)**
return 1


def factorial(x):
    while x != 0:
        return factorial(x) * factorial(x - 1)
        if x == 0:
            return 1

Can you help me with this guys? I receive "Oops, try again. factorial(1) resulted in an error: maximum recursion depth exceeded" but don't really know how to modify the while loop to make this work.



simply outstanding,..!! worked


def factorial(x):
fact = 1
for i in range(1,x+1):
fact = fact * i
print fact
return fact



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.