为什么我的程序没有比较if,elif,else语句中的返回值?

时间:2017-05-08 16:03:37

标签: python if-statement return

我遇到的问题是,即使M点比P点短M点,反之亦然,程序只打印它们是相同的距离。这可能是我的返回值的问题吗?还是用if,elif,else语句?

import math
print("This Program takes the coordinates of two points (Point M and N) and uses the distance formula to find which "
      "point is closer to Point P (-1, 2).")

x_P = -1
y_P = 2

def main():
    x_1 = int(input("Enter an x coordinate for the first point: "))
    y_1 = int(input("Enter an x coordinate for the first point: "))
    x_2 = int(input("Enter an x coordinate for the second point: "))
    y_2 = int(input("Enter an x coordinate for the second point: "))
    distance(x_1, y_1, x_2, y_2)
    distance1 = 0
    distance2 = 0
    if distance1 < distance2:
        print("Point M is closer to Point P.")
    elif distance1 > distance2:
        print("Point N is closer to Point P.")
    else:
        print("Points M and N are the same distance from Point P.")


def distance(x_1, y_1, x_2, y_2):
    distance1 = math.sqrt((x_P - x_1) ** 2 + (y_P - y_1) ** 2)
    distance2 = math.sqrt((x_P - x_2) ** 2 + (y_P - y_2) ** 2)
    return distance1, distance2


main()

2 个答案:

答案 0 :(得分:0)

您需要使用return值,而不是

distance(x_1, y_1, x_2, y_2)
distance1 = 0
distance2 = 0

你应该使用

distance1, distance2 = distance(x_1, y_1, x_2, y_2)

答案 1 :(得分:0)

distance(x_1, y_1, x_2, y_2)
distance1 = 0
distance2 = 0

你对distance()的调用没有任何东西可以应用返回值,所以它们基本上消失了。 distance()函数中的distance1和distance2是函数本身的命名空间的本地。即使它们不是,你也会用distance1 = 0和distance2 = 0语句覆盖它们。

轻松修复:

(distance1, distance2) = distance(x_1, y_1, x_2, y_2)

由于函数返回一个元组,只需在主命名空间中接受带有变量的元组。

哦,你的所有输入都要求x值。