Python未将值返回到函数中的变量

2024-03-29 07:37:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我写的这段代码很难输出两点之间的斜率和距离

在python visualizer中查看它,它似乎能够计算值,但是,距离变量并没有保存它的值。它将被坡度的值覆盖

我很难理解我应该如何在函数定义中使用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)

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


Tags: 函数代码距离return定义defslopedistance
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)

如果希望两个函数调用都是不同的,即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)

相关问题 更多 >