test = 4
#start of def
def change():
test = 5
#end
change()
print test


Why doesn't it print 5? Can anyone explain this to me? Btw, test = 5 is indented, the forum won't let me indent for some reason

Member Avatar for Mouche

My code:

test = 4

def change():
    test = 5

print test
change()
print test

My output:

>>> 
4
4

Note: I used Python 2.6 here. I tried it with 3.1.1 (with correct syntax) and got the same result.

Ronnicus,
please put your code into code tags like this:

[code]
... your Python code here ...

[/code]

If your function changes a value you want to use, you have to use return. Here is your correct approcach ...

test = 4

def change():
    test = 5
    return test

print test  # 4
test = change()
print test  # 5
Member Avatar for Mouche

Oh my bad. I thought he was getting "5" for some reason.

Why do you have to use return? Couldn't it be a void method that sets test = 5? Why wouldn't that affect the actual value of test?

Member Avatar for Mouche

The test variable in the function is in a different scope. It is local to the function, so it does not affect the one outside of the function. It's also not good practice to make the test variable global so that it could be affected by the function. That can cause confusion when things get more complicated.

Why is the test in the function local? I meant to have it change the one outside, how would I do so without returning the variable?

Why is the test in the function local? I meant to have it change the one outside, how would I do so without returning the variable?

You'd do global test ,
which is a bad idea, since it is evidence for bad code structure.

Scopes make Python a clean and professional language, any other OO language has them, too.

If variables inside functions wouldn't be local, any code would be just loaded with hard to trace bugs!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.