仅使用图形包定义欧氏函数距离
Defining euclidean function distance using graphics package only
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):
,所以你必须用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))
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):
,所以你必须用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))