[Tutor] Separating recursion, for loops, and while loops

alan.gauld@bt.com alan.gauld@bt.com
Thu Jan 23 12:15:57 2003


> the same thing (just for practice's sake) - one with a 'with' 
> loop, 

I assume you mean a while loop...

> a 'for' loop, and one with recursion. 

Good idea. Should be interesting.

> def loop_dice(rolls, sides):
>     while rolls > 0:
>         value=random.randint(1,sides)
>         rolls=rolls-1
>         print value
> 
> def for_dice(rolls, sides):
>     rolls=range(1,rolls)
>     for elem in rolls:

I think you mean
rolls = range(1,rolls+1)  # generates [1...10]

Or more pythonically:
rolls=range(rolls):  # generates [0...9]

Or evenb more pythonically:

for elem in range(rolls):

>         elem=random.randint(1,sides)
>         value=elem
>         total=value+total
>         #'local variable total referenced before assignment'

You are creating the variable using itself, whioch isn't 
possible. You need to do total=0 outside the loop.

> And one more thing - the first part, loop_dice, outputs 
> things on different lines - is there any way, without using 
> recursion, to add all the numbers together before printing them?

Either just add them inside the loop or create a list and 
then add the values later using reduce(operator.add, numbers)

But i'd think you might prefer to output the values on a single line by
sticking a comma after the print:

print value,   # comma suppresses the newline


> And if I am using recursion, same question - can I output add 
> the numbers together and output them? 

Same applies. In the return statement add instead of printing...
Or append to a list and then output the result at the end.


> Oh, and the 'for' statement wouldn't work when I would use 
> the input 'rolls' as a number - was that just in my imagination? 

You need to use range() coz the for loop in python is really 
a foreach loop and requires a sequence to work on. A number is 
not a sequence, range makes it into one...

> the following: string, tuple or list. Why would you 'iterate' 
> over a string 

To process each letter in turn - say to encrypt it?

> what in the world is a tuple?

Simply a collection of values that you can't change(in Python).

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/