如何在 if/elif 条件 (python) 中正确使用全局变量?
How to use correctly global variables inside if/elif conditions (python)?
我有这个代码:
当我更改变量值时,它会给我 NameError: name 'y' is not defined
我该如何解决?
def a():
if 5 == 5:
global x
x = 39
return True
elif 6 == 6:
global y
y = 3
return True
def b():
if x == 3:
print("ok")
elif y == 3:
print("no")
a()
b()
在您的代码中,y
从未定义:
一种修复方法是:
def a():
if 5 == 5:
global x
x = 39
if 6 == 6:
global y
y = 3
def b():
if x == 3:
print("ok")
elif y == 3:
print("no")
a()
b()
您在第一个 if 语句中返回 Ture 并且 y 的声明在 elif 语句中,这两件事阻止 y
被定义
def a():
check_1 = False
check_2 = False
if 5 == 5:
global x
x = 39
check_1 = True
if 6 == 6:
global y
y = 3
check_2 = True
return (check_1 and check_2)
def b():
if x == 3:
print("ok")
elif y == 3:
print("no")
a()
b()
会输出
no
我有这个代码: 当我更改变量值时,它会给我 NameError: name 'y' is not defined 我该如何解决?
def a():
if 5 == 5:
global x
x = 39
return True
elif 6 == 6:
global y
y = 3
return True
def b():
if x == 3:
print("ok")
elif y == 3:
print("no")
a()
b()
在您的代码中,y
从未定义:
一种修复方法是:
def a():
if 5 == 5:
global x
x = 39
if 6 == 6:
global y
y = 3
def b():
if x == 3:
print("ok")
elif y == 3:
print("no")
a()
b()
您在第一个 if 语句中返回 Ture 并且 y 的声明在 elif 语句中,这两件事阻止 y
被定义
def a():
check_1 = False
check_2 = False
if 5 == 5:
global x
x = 39
check_1 = True
if 6 == 6:
global y
y = 3
check_2 = True
return (check_1 and check_2)
def b():
if x == 3:
print("ok")
elif y == 3:
print("no")
a()
b()
会输出
no