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?

3
  • 2
    What output are you getting? Commented Jun 11, 2012 at 10:43
  • 1
    Are you sure you are not running that with Python 2.x? Commented Jun 11, 2012 at 10:45
  • @Keith it doesn't work at all in Python 2.x (throws error at nonlocal state). Anyway I tried it in terminal, it works fine to me. Commented Jun 11, 2012 at 10:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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
yeah okay my bad it works in terminal now which is weird Thanks :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.