[Tutor] How can I make this run right?

Alan G alan.gauld at freenet.co.uk
Mon Aug 15 22:27:51 CEST 2005

>I put in a 4 and expected 24, and instead got 12. It is supposed to 
>give 4!
> not 4*3.

Thanks Nathan. It would be good to get that kind of detail when you 
the initial message. Your function didn't look like the usual 

FWIW here is my version :-)

def factorial(n):
   result = 1
   for x in range(2,n+1):
      result *= x
   return result

By avoiding while loops you avoid all the mess of trying to maintain
the counter - one of the most common causes of errors in programming!

For a different approach see the recursion topic in my tutor.


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list