我正在尝试在类findDist()中分配变量,但是一旦它们被分配并且它移动到closeDist(),它就表示变量没有被赋值。
这是错误:"NameError: global name 'Dist1' is not defined"
以下是代码,任何解决方案?
n=int(0)
Pro1='alive'
Pro2='alive'
Pro3='alive'
Pro4='alive'
Pro5='alive'
Pro6='alive'
xYou = 1
yYou = 1
xPro1 = 3
yPro1 = 0
xPro2 = 2
yPro2 = 3
xPro3 = 1
yPro3 = 6
xPro4 = 5
yPro4 = 6
xPro5 = 6
yPro5 = 2
xPro6 = 8
yPro6 = 5
proDists = []
def findDist():
if Pro1 == 'alive':
Dist1 = (abs(xYou-xPro1)+abs(yYou-yPro1))
print(Dist1)
if Pro2 == 'alive':
Dist2 = (abs(xYou-xPro2)+abs(yYou-yPro2))
print(Dist2)
if Pro3 == 'alive':
Dist3 = (abs(xYou-xPro3)+abs(yYou-yPro3))
print(Dist3)
if Pro4 == 'alive':
Dist4 = (abs(xYou-xPro4)+abs(yYou-yPro4))
print(Dist4)
if Pro5 == 'alive':
Dist5 = (abs(xYou-xPro5)+abs(yYou-yPro5))
print(Dist5)
if Pro6 == 'alive':
Dist6 = (abs(xYou-xPro6)+abs(yYou-yPro6))
print(Dist6)
findClose()
def findClose():
proDists.extend((Dist1,Dist2,Dist3,Dist4,Dist5,Dist6))
print ("".join(proDists))
findDist()
答案 0 :(得分:4)
您需要将本地变量作为参数从调用函数发送:
def findDist():
if Pro1 == 'alive':
Dist1 = (abs(xYou-xPro1)+abs(yYou-yPro1))
print(Dist1)
if Pro2 == 'alive':
Dist2 = (abs(xYou-xPro2)+abs(yYou-yPro2))
print(Dist2)
if Pro3 == 'alive':
Dist3 = (abs(xYou-xPro3)+abs(yYou-yPro3))
print(Dist3)
if Pro4 == 'alive':
Dist4 = (abs(xYou-xPro4)+abs(yYou-yPro4))
print(Dist4)
if Pro5 == 'alive':
Dist5 = (abs(xYou-xPro5)+abs(yYou-yPro5))
print(Dist5)
if Pro6 == 'alive':
Dist6 = (abs(xYou-xPro6)+abs(yYou-yPro6))
print(Dist6)
findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6)
def findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6):
proDists.extend((Dist1,Dist2,Dist3,Dist4,Dist5,Dist6))
print ("".join(proDists))
答案 1 :(得分:0)
您可以使用global
声明轻松实现它。
def findDist():
global Dist1, Dist2, Dist3, Dist4, Dist5, Dist6
但是鼓励避免使用太多的全局变量。您可以将它们作为参数传递给findClose()
,而不是像karthikr所建议的那样:
findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6)
和
def findClose(Dist1, Dist2, Dist3, Dist4, Dist5, Dist6):
希望这有帮助!