1

Hi i am a beginner who is learning Python, i have stumbled across this example in a book and for some reason when i attempt the same code myself i am not receiving the same output? Please help...

def tester(start):
    state = start
    def nested(label):
        nonlocal state
        print(label, state)
        state += 1
    return nested

>>> F = tester(0)
>>> F('spam')
spam 0
>>> F('ham')
ham 1
>>> F('eggs')
eggs 2

My results are not incrementing + 1 each time i run the function, is there something wrong with the book?

Eric
  • 95,302
  • 53
  • 242
  • 374
thechrishaddad
  • 6,523
  • 7
  • 27
  • 33

2 Answers2

1

Works for me. Are you sure you're using python 3? nonlocal is a python 3 feature, and will not work in python 2.x.

Eric
  • 95,302
  • 53
  • 242
  • 374
  • How do you know if you are using python 3? i just run python interactively in my terminal by typing 'python'? or do you need to run it differently for python 3? i do have python 3.2 installed. – thechrishaddad Jun 11 '12 at 10:50
  • @user1265535: When you open up your Python Terminal, the first line has the version listed for eg. `Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32` – Christian Witts Jun 11 '12 at 10:51
  • yeah okay my bad it works in terminal now which is weird Thanks :) – thechrishaddad Jun 11 '12 at 10:55
0

https://stackoverflow.com/a/1261961/778858 sums it up. Basically python changed a lot from 2.~ to 3.0 >= and you end up with issues like this. Compare what it says at the start of the book with the version they are using and compare it to your own.

Community
  • 1
  • 1
jett
  • 1,276
  • 2
  • 14
  • 34