[Tutor] Coin flip game

Alan Gauld alan.gauld at btinternet.com
Fri Feb 12 02:04:26 CET 2010


"Jones, Lawrence D" <lawrence.jones at imperial.ac.uk> wrote 

> My code is below. But can someone please explain to me 
> why the following variable has to be placed where it is 

Others have explained about variable creation and the fact 
you need to be inside the loop to get different results for 
each iteration.

                coin = random.randrange(2)

I just want to pick up on something you said.
You asked about the "variable".
The variable is "coin". It can go anywhere before the point 
of use, even the first line of your code. You could have done

coin = None 
or 
coin = 0 
and it would work just fine.

What needs to be inside the loop is the call to the 
randrange() function. That is what is simulating the coin flip.
So you need to distinguish the difference between variable 
creation (which in Python happens by means of the first 
assignment of a value)  and function application (where you 
call a function and assign its return value to a variable.) 
In your code you create the variable coin at the same time 
as you apply the function, but you could have done those 
two things separately and the code would still work.

It might seem like I'm splitting hairs but it starts to make 
a difference in some other cases, like this:

while True:
    coin = coin + someFunction()

This will raise an error because you are using the value 
of coin (on the right hand side) before it has been created. 
You need to write it like this:

coin = 0
while True
    coin = coin + someFunction()

It is very important in programming to be clear in your mind 
about these different concepts, especially when deciphering 
error messages.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list