global variables?

Hi!
I’m new to Python, but started learning it so I could use it in Blender.
Now I’ve got an error in my script and i could work it down to this:

Why does this work:

x=3

def test():
    print x

test()

And this doesn’t

x=3

def test():
    x += 1   # or x = x + 1
    print x

test()

I tried the official Python documentation, but couldn’t find anything related to my problem. Can anyone tell me what I’m doing wrong?

The error message is:
UnboundLocalError: local variable ‘x’ referenced before assignment

Is this possibly due to my setup? (e.g. OS, Version etc.)

Alex

x=3

def test():
global x
x += 1
print x

test()

The above will print ‘4’.

Why your first test() function worked, I don’t know, but it may be about the print statement itself (IIRC print is a bit of an oddity in python as far as language design goes).

Declare variables as global if you want to ensure they are global.

Thanks a lot! It solved the problem. And I think I’m getting a grip on this stuff.