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?
2 Answers 2
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.
3 Comments
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32https://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.
nonlocal state). Anyway I tried it in terminal, it works fine to me.