[Tutor] namespaces

Evert Rol evert.rol at gmail.com
Sun May 30 18:33:54 CEST 2010


  Hi Robert

> This code generates the message “UnboundLocalError: local variable 'doubles' referenced before assignment” (line: if d[0] == d[1] and doubles == 2:)
>  
> http://pastebin.com/mYBaCfj1  
>  
> I think I have a fair picture of what it means but I would be very happy if someone could explain the difference between the two variables h and doubles in the code. Why is one accessible from the function but not the other? I looked into rules for namespaces but I’m still confused. Below is another sample of the code

You assign a value to doubles in the roll() function, making Python think doubles is a local variable (which hasn't been assigned anything when you first use it, throwing the exception).
If you assign some value to h after the first line in roll() (eg, h = 6), you'd get the same exception, but then for h.
So, if you assign a value to a variable inside a function() and you want that variable to be the global one (instead of the implicitly assumed local one), you'll have to explicitly tell Python that: "global doubles" (probably on the first line in the function).
Since you hadn't assigned any value to h inside roll(), only used it, Python assumes it's the global one.

See also the second answer to this question: http://stackoverflow.com/questions/423379/global-variables-in-python

Hope that helps,

  Evert


>  
> Cheers, Robert
>  
> from random import *
>  
> h = 6
> doubles = 0 # current number of consecutive doubles
>  
> def roll():
>     d = [randint(1, h), randint(1, h)]
>     if d[0] == d[1] and doubles == 2:
>         doubles = 0
>         return 0
>     elif d[0] == d[1] and doubles < 2:
>         doubles += 1
>         return sum(d)
>     else:
>         return sum(d)
>  
> for n in range(10):
>     d = roll()
>     print d   
>  


More information about the Tutor mailing list