gpt4 book ai didi

python - 在 Python 的嵌套函数中使用全局变量

转载 作者:行者123 更新时间:2023-12-03 21:12:31 25 4
gpt4 key购买 nike

我读了这段代码(下面给出),我的理解是,如果一个变量在函数内被声明为全局变量,并且如果它被修改,那么它的值将改变 永久 .

x = 15
def change():
global x
x = x + 5
print("Value of x inside a function :", x)
change()
print("Value of x outside a function :", x)
输出:
Value of x inside a function : 20
Value of x outside a function : 20
但是下面的代码显示了不同的输出。
x 的值在 print("After making change: ", x) 内部怎么没有变化?仍然是 15
def add(): 
x = 15

def change():
global x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)

输出:
Before making changes:  15
Making change
After making change: 15
value of x 20

最佳答案

add , x不是全局变量;它是本地的 add .您也需要将其设为全局,以便 addchange指的是同一个变量

def add(): 
global x
x = 15

def change():
global x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)
或者您需要申报 xchange作为非本地的,而不是全局的。
def add(): 
x = 15

def change():
nonlocal x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)

关于python - 在 Python 的嵌套函数中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62838129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com