# Factorial

#1

Oops, try again. factorial(2) returned 1 instead of 2

``````def factorial(x):
if x == 0 :
return 1
else :
while x > 0 :
factorial = 1
factorial = factorial*x
x-=1
return factorial``````

#2

I suggest executing your code manually (that's with your own head) and compare what it's telling you to do to how you know that factorial is supposed to be computed

#3

Well i did execute it manually , and it should work ...
I did edit it a bit, my code became :

``````def factorial(x):
if x == 0 :
return 1
else :
while x > 0 :
factorial = 1
factorial = factorial*x
x =- 1  (Changed this part here )
return factorial``````

#4

Did you execute the code or what you know it should do?
Those are the two things you need to compare, so you need to look at both.

Let's add a print in the loop to see how factorial changes as the loop runs:

``````>>> factorial(100)
100``````

It looped once. How many times should it have looped for an argument of 100? What controls the number of iterations? Add more prints to find out what it did with the stuff that controls the loop.

In your first piece of code factorial takes on these values:

``````>>> factorial(5)
5
4
3
2
1``````

What should those values have been? Probably these:

``````5
20
60
120
120``````

#5

I really got no clue why its taking these values ...
It's probably something really obvious but I really cant find it xD

#6

Why wouldn't it get those values? What should have happened instead? Go look at the code that's responsible for what should have happened instead and find out exactly which operation isn't doing what you want. Use prints to find out what variables contain or what expressions evaluate to etc, and also for finding out what order it's happening in.

It's not very different from watching another person compute the factorial and checking if they are doing it right. Just observe and compare to what you would do.

Start somewhere in the middle of the process and find out if everything is as it should be at that time. Or even investigate each line by itself, see if it has the desired effect.

#7

Yea , thanks i found the mistake , but i need a new way to code it.

#8

Thanks for the help ionatan , you really helped out giving hints and not the solution , my final code for this was :
EDIT : Decided not to spoil for others

#9

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