代码之家  ›  专栏  ›  技术社区  ›  Spencer Josephs

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

  •  0
  • Spencer Josephs  · 技术社区  · 10 年前
    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"
    

    我不知道我做错了什么

    1 回复  |  直到 10 年前
        1
  •  0
  •   Serge Ballesta    10 年前

    该错误可自行解释:

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