仅使用图形包定义欧氏函数距离


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"

我不知道我做错了什么

错误是不言自明的:

pt1=Point(x,y)
NameError: name 'x' is not defined"

简单地说,你必须告诉 Python 什么是 x、y、x1 和 y1 变量。

函数声明只是def distance(pt1,pt2):,所以你必须用pt1pt2来表达所有变量,而不是相反。例如:

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:函数的名称不应用于变量的名称

如果你真的想使用图形包,你应该做:

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))

最新更新