Python variable range problem

Asked 1 years ago, Updated 1 years ago, 120 views

I've been programming for years, and recently started learning Python. The code below works normally on Python 2.5 and 3.0 as I expected :

a, b, c = (1, 2, 3)

print(a, b, c)

def test():
    print(a)
    print(b)
    print(c)    # (A)
    #c+=1       # (B)
test()

If you unannotate the currently annotated line (B), the error UnboundLocalError: 'c' not assigned occurs on line (A). The variables a and b are output normally. This led to two questions:

The only reason I can come up with is that the region variable c is generated by c+=1, and even before the region variable is created, the region variable takes precedence over the global variable c. Of course, it doesn't seem to make sense to take away the range of variables before the local variable even exists.

Please give me an explanation.

scope python variable

2022-09-22 21:26

1 Answers

Python treats variables within a function differently based on whether or not the value of the variable is assigned within the function. If you assign a value to a variable within a function, it's basically treated as a regional variable, so if you unannotate line (B), you're going to refer to the value before the local variable c is assigned a value.

If you want to use the variable as a global variable,

global c

Write down in the first line of the function.

Also on Python 3,

nonlocal c

allows you to use variables in the nearest outer region (even if they are not global variables).


2022-09-22 21:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.