I don't understand the Python global variable, so could you give me an answer?

Asked 1 years ago, Updated 1 years ago, 395 views

x = 0
def A():
    x = 10 # Local variable of A x
    def B():
        global x # Use the global variable outside of the current function
        Allocate 20 to the regional variable x of x = 20 # A

    B()
    print(x) # Local variable of A x output

A()
print(x)

I think the result will be 20, 20, If you print it out, 10, 20 comes out.

I have no idea! Is there a master who can explain it.

python global-variable

2023-06-07 05:27

1 Answers

Because x in the A function is not a global variable!

Declaring global x means a global variable.

If you want to use x in the A function in the subscope, you can use the nonlocal keyword


2023-06-10 19:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.