How do I return the product of a while loop?

advertisements

I don't get the concept of loops yet. I got the following code:

x=0
while  x < n:
   x = x+1
   print x

which prints 1,2,3,4,5.

That's fine, but how do I access the computation, that was done in the loop? e.g., how do I return the product of the loop( 5*4*3*2*1)?

Thanks.

Edit:

That was my final code:

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


You want to introduce one more variable (total) which contains accumulated value of a bunch of actions:

total = 1
x = 1
while x <= 5:
   total *= x
   x += 1
   print x, total
print 'total:', total

Actually, more pythonic way:

total = 1
n = 5
for x in xrange(1, n + 1):
    total *= x
print total

Note, that the initial value of total must be 1 and not 0 since in the latter case you will always receive 0 as a result (0*1*.. is always equals to 0).