[Edu-sig] teaching Python

kirby urner kirby.urner at gmail.com
Sat Apr 24 03:00:07 CEST 2010


On Fri, Apr 23, 2010 at 3:24 PM, Mark Engelberg
<mark.engelberg at alumni.rice.edu> wrote:
> On Fri, Apr 23, 2010 at 11:46 AM, Bill Punch <punch at cse.msu.edu> wrote:
>> To round out the
>> top three, which are the ones that get even my best students, look at the
>> below:
>>
>> myVar = 27
>>
>> def myFun ():
>>     print myVar
>>     myVar += 1
>>     return myVar
>>
>> print myFun
>>
>> What happens when you run this?
>>
>
> To fully appreciate Bill's example, I think it's worth pointing out
> that this version would behave exactly as expected:
>
> myVar = 27
>
> def myFun ():
>    print myVar
> #    myVar += 1
>    return myVar
>
> print myFun()
>

Also, for contrast:

myVar = [27]

def myFun ():
	print myVar
        myVar[0]+=1
        return myVar

>>> myFun()
[27]
[28]

The above works because the we're not referencing an unbound local,
are instead mutating a global.  No need to declare myVar global as there
could be no other legal meaning.  Functions look outside the local
scope for bindings.

def myFun ():
	print myVar
        myVar = 1
        return myVar

The above crashes because the print references an unbound local.
It's a local because of the local binding (don't call it "rebinding")  --
can't be the same as the global in that case, so no sense asking
to print it before it has a
value.

def myFun ():
	global myVar
	print myVar
        myVar = 1
        return myVar

>>> myFun()
[32]
1

>>> myVar
1

The above works because the print statement accesses the global.
Said global is then rebound.  Of course the return is not required
for the change to occur at the global level.

def myFun ():
        myVar = 1
        print myVar
        return myVar

No problem.... local myVar is already bound when print is encountered.
The global myVar is unchanged.

myVar = [27]
[27]

def myFun ():
	print myVar
        myVar = []
        return myVar

The above crashes.  It's the binding of myVar to some object other than
what the global myVar already references that makes it a local to this
function's scope, not the fact that it's bound to a mutable.  Can't print a
local before the binding occurs.

Kirby


More information about the Edu-sig mailing list