【问题标题】:Python not returning value to variable in functionPython没有将值返回给函数中的变量
【发布时间】:2020-01-23 04:54:57
【问题描述】:

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

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

这里代码的输出对于两个变量都是一样的。

【问题讨论】:

  • return 的声明永远不会到达distance。因为if-else 的两个路径都返回并且代码永远没有机会到达distance。可能您想返回 tuple 而不是标量?
  • 这里的距离永远不会返回,因为在你的 if 和 else 中你的和“如果每次都不匹配”它会转到 else,所以每次斜率空值都会被返回,所以你可以使用两个不同的等式一个斜率一个用于距离,或者您可以返回元组
  • @PWier 检查解决方案

标签: python function math output algebra


【解决方案1】:

如果您希望两者都是不同的函数调用,即slope=equation(1,3,2,1)distance=equation(1,3,2,1),请尝试第一种方法,如果您希望两者都在单行中调用,即slope, 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)

【讨论】:

  • 谢谢,这很有帮助。感谢您列出的两种方法,有助于我更好地理解代码。
【解决方案2】:

return 语句在遇到时从函数中退出。从函数返回一个元组。

def equation(x,y,x1,y1):
    # calculate slope and distance
    return slope, distance

slope,distance = equation(1,3,2,1)
print(slope)
print(distance)

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2023-03-06
    • 1970-01-01
    • 2023-03-11
    • 2014-07-23
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多