Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return the product of a while loop

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
like image 531
aaaa Avatar asked Jan 29 '26 12:01

aaaa


1 Answers

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).

like image 85
Vladimir Avatar answered Jan 31 '26 01:01

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!