# Factorial help

#1

factorial

My code works, I just don't understand why it works. How can the function call itself and what exactly is happening in that process?

``````def factorial(x):
x = abs(x)

if x == 0:
return 1
else:
return x * factorial(x - 1)

print factorial(4)``````

#2

Hello!
I have the same question as you do.

``````def factorial(x):
if x == 1 or x == 0:
return 1
else:
while x >= 1:
return x * factorial(x - 1)
print factorial(3)
print factorial(4)
output was:
6
24
None``````

I did this, and it magically works!
But, if I were to change the code as:

``````        while x >= 1:
return x * (x - 1)
print factorial(3)
print factorial(4)
output was:
6
12
None``````

It returns returns the number multiplied by it's preceding number as can be seen above. I don't get why!

#3

A factorial means the number is multiplied my all the numbers preceding it (but zero). not just one.
factorial(5) = 5x4x3x2x1
factorial(-5) = invalid input
factorial(0) = 0
factorial(3) = 3x2x1
factoral(2) = 2x1

for functions call themselves see "recursive function" on google.

#4

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