Question about the range of Python variables

Asked 2 years ago, Updated 2 years ago, 126 views

a=0
def vartest(a):
    a=1
    return a

print(vartest(a))

Why is it said that a is not defined when a=0 is cleared? Since a in the function and a outside of the function are different variables, we defined a=1 within the function with or without a=0a=1 print(a) when we run print(a)?

function python varaiables

2022-09-22 18:12

1 Answers

a=0
def vartest(a):
    a=1
    return a

print(vartest(a))
print(a)

Results:
1
0

The reason why the questioner's main question, a, is that there is no variable called a when vartest(a) is called. In other words, if you clear the globally set a = 0 and invoke vartest(a), of course, a is undefined because there is no variable a.

But furthermore, the above results tell you the important points when programming Python.

The questioner simply asked why the error occurred, but in fact, the more important question in the above question is why the value a is not 1 after the function call.

Explicit call by reference is not available on Python. Where explicit means that there is no operator like & in c.

However, Python selects and applies call by value or call by reference depending on the parameter type that is delivered.

Specifically, non-changeable objects such as int, float, and tuple are passed to call by value. That is, copy the value. Because only values are copied, the source object remains unchanged. In other words, even if you change to 1 in the example above, the original a object is still zero.

However, changeable objects such as list and dict are forwarded to call by reference. Since the reference is passed, if you change the addition or deletion after passing it from a function to a factor, the original object that was passed will also change.


2022-09-22 18:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.