我正在尝试创建一个使用其参数之一的函数来创建具有该参数名称的全局变量。当我尝试使用该函数并输入参数时,它只会显示“未定义名称'Matrix'”
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句