python - 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)
这两个变量的代码输出是相同的。
解决方案
如果您希望两者都是不同的函数调用 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)
推荐阅读
- swift - Swift HTTP 请求完成块无法正常工作
- swiftui - 如何在可扩展列表 SwiftUI 中移动元素
- mysql - 哪个是执行三重连接查询的最佳性能设置
- java - Apache Camel Spring Boot Java - 如何将动态值从休息路由传递到来自文件的路由?
- javascript - 使用功能组件中的 useState 反应无效的挂钩调用错误
- java - 在 redis sentinel 上使用 asyncRedisCommands 的 Redis 生菜设置
- c++ - 使 int 返回函数表现为左值和右值
- json - 为 Azure 资源创建复制循环
- flutter - 如何使用 Getx 修复 Flutter 中的导航栏悬停问题
- r - 了解有关箱线图的 ggplot2 文档中的数字