UnboundLocalError:赋值前引用的局部变量.为什么输入函数时没有分配初始化的值



为什么输入函数时没有分配初始化的变量x和y?因为他们不在任何班级??

print("Start program")
x = 10
print(x)
y = 10
print(y)
def _return_string():
if type(x) == "<class 'int'>":
print("x is of type integer")
x = str(x)
else:
print("x is of type string")
if type(y) == "<class 'int'>":
print("y is of type integer")
y = str(y)
else:
print("y is of type string")
print("concatenate x and y:",x+y)
def _return_integer():
# x = 10
# y = 20
if type(x) == "<class 'str'>":
print("x is of type string")
x = int(x)
else:
print("x is of type integer")
if type(y) == "<class 'str'>":
print("y is of type string")
x = int(y)
else:
print("y is of type integer")
print("sum of x and y:",x+y)
_return_integer()

为什么输入函数时没有分配初始化值?

在函数内部更改或创建的任何变量都是局部变量,如果它尚未声明为全局变量。要告诉 Python,我们想要使用全局变量,我们必须使用关键字 "global" 明确声明这一点。

def _return_integer():
global x
global y
if type(x) == "<class 'str'>":
print("x is of type string")
x = int(x)
....

最新更新