from graphics import*
def distance(pt1,pt2):
pt1=Point(x,y)
pt2=Point(x1,y1)
sqrt((x-x1) ** 2 + (y-y1) ** 2)
return distance
distance((100,50),(45,30))
File "/Users/tigersoprano/Documents/test.py", line 7, in <module>
distance((100,50),(45,30))
File "/Users/tigersoprano/Documents/test.py", line 3, in distance
pt1=Point(x,y)
NameError: name 'x' is not defined"
答案 0 :(得分:0)
错误是自我解释的:
pt1=Point(x,y)
NameError: name 'x' is not defined"
只是意味着你必须告诉python什么是x,y,x1和y1变量。
函数声明只是def distance(pt1,pt2):
,因此您必须以pt1
和pt2
表示所有变量,而不是相反。例如:
def distance(pt1,pt2):
x = pt1[0]
y = pt1[1]
x1 = pt2[0]
x2 = pt2[1]
dist = sqrt((x-x1) ** 2 + (y-y1) ** 2)
return dist
另请注意,Python不是Fortran:函数的名称不应该用于变量的名称
如果你真的想使用graphics包,你应该这样做:
def distance(pt1,pt2):
x = pt1.getX()
y = pt1.getY()
x1 = pt2.getX()
x2 = pt2.getX()
dist = sqrt((x-x1) ** 2 + (y-y1) ** 2)
return dist
d = distance(Point(100,50),Point(45,30))