首页 > 解决方案 > Python没有将值返回给函数中的变量

问题描述

我在编写这段代码时遇到了困难,它应该输出两点之间的斜率和距离。

在 python 可视化器中查看它,它似乎能够计算值,但是距离变量并没有保存它的值。它被斜率的值覆盖。

我无法理解我应该如何在函数定义中使用 return,因为这似乎是问题所在。

def equation(x,y,x1,y1):
  distance=math.sqrt(((x-x1)**2)+((y-y1)**2))
  if x!=x1 and y1!=y:
    slope=(y1-y)/(x1-x)
    return slope
  else:
    slope='null'
    return slope
  return distance
slope=equation(1,3,2,1)
print(slope)
distance=equation(1,3,2,1)
print(distance)

这两个变量的代码输出是相同的。

标签: pythonfunctionmathoutputalgebra

解决方案


如果您希望两者都是不同的函数调用 ieslope=equation(1,3,2,1)distance=equation(1,3,2,1),请尝试第一种方法,如果您希望两者都在单行中调用 ieslope, distance=equation(1,3,2,1)然后尝试第二种方法:

第一种方法

import math
def equation(x,y,x1,y1,var):
  if var == "slope":
    if x!=x1 and y1!=y:
      slope=(y1-y)/(x1-x)
      return slope
    else:
      slope='null'
      return slope
  elif var == "distance":
    distance=math.sqrt(((x-x1)**2)+((y-y1)**2))
    return distance
slope=equation(1,3,2,1,"slope")
print(slope)
distance=equation(1,3,2,1,"distance")
print(distance)

第二种方法

def equation(x,y,x1,y1):
  distance=math.sqrt(((x-x1)**2)+((y-y1)**2))
  if x!=x1 and y1!=y:
    slope=(y1-y)/(x1-x)
    return slope,distance
  else:
    slope='null'
    return slope,distance
slope, distance=equation(1,3,2,1)
print(distance)
print(slope)

推荐阅读