我正在尝试创建一个函数,该函数使用其参数之一创建具有该参数名称的全局变量。当我尝试使用该函数并输入一个参数时,它只是说“名称‘矩阵’未定义”
def Gen2D(name, length):
name = [[0 for j in range(length)] for i in range(length)]
return(name)
Gen2D(Matrix, 12)
我希望这会导致变量名称为“Matrix”的 12 x 12 矩阵,但出现错误:“未定义名称‘Matrix’”
最佳答案
所以我不太了解这个问题的全局部分。
你可以这样做:
def Gen2D(length):
name = [[0 for j in range(length)] for i in range(length)]
return name
Matrix = Gen2D(12)
如果你真的想让它成为一个全局变量,你可以像这样在函数中实例化和更新一个全局变量:
def Gen2D(length):
global Matrix
# Updating the value of the global matrix variable (will be updated outside the function)
Matrix = [[0 for j in range(length)] for i in range(length)]
# Calling the function to update the global variable.
Gen2D(12)
关于python - 我可以使用函数参数来创建全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513849/