How to make a factorial function? why is mine wrong?


#1

def factorial(x):
while x>1:
x*= (x-1)
return x

print (factorial(3))


#2

lets run through the program:

while 3 > 1

which is true, so the loop will execute. First let get rid of the shorthand to better understand what is happening:

x = x * (x - 1)

now lets solve it:

x = 3 * (3 - 1)

which results in 6.

then we can do this again:

while 6 > 1

which is true, so:

x = 6 * (6 - 1)

so x = 30

so x will just endlessly increase, you have an infinity loop

we will need two variables: one variable to store the result of the multiplication (which will result in the factorial) and one variable which is constantly decreasing by one so the loop will end