[Tutor] loop problem

alan.gauld@bt.com alan.gauld@bt.com
Tue, 11 Jun 2002 17:57:21 +0100


> 1.Multiply 1 by 2
> 2.Take the result and multiply by 2
> 3.So on and so on thirty times
> 4.Print the final result
> 

First, thanks for the well stated problem specification, 
it always helps :-)


> I tried this:
> 
  b = 1  # initialise b
> for i in range(1,31):
> 		b = i * 2   # replace this with

            b = b * 2

> 		print b

Should work.

Just use the range to count the number of iterations but the 
number to multiply is b not i. (Try renaming b to result and 
see if it becomes clearer - using variable names that match 
your problem statement is usally a good dea - check the 
chapter on Style.

BTW Your function just works out the 30th power of two so 
the same end result comes (faster) from:

print pow(2,30)

But that doesn't display intermediate values or teach you 
about loops ;-)

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld