python - 为什么我的代码没有返回斜边的值?

标签 python python-3.x return return-value

基本上,我需要计算直角三角形的斜边
首先,我的代码定义三角形是否正确,然后根据两条边的长度计算该三角形的斜边,但它没有返回我需要作为本练习的任务返回的 h 值。 我不明白返回 h 有什么问题?
为什么代码没有返回它?

提前致谢

angle1 = input("what is a degree of the first angle? : ")
angle2 = input("what is a degree of the second angle? : ")
angle3 = input("what is a degree of the third angle? : ")

a1 = int(angle1)
a2 = int(angle2)
a3 = int(angle3)

length1 = input("what is a length of the first side? : ")
length2 = input("what is a length of the second side? : ")

l1 = int(length1)
l2 = int(length2)


def hypothenuse(a1, a2, a3, l1, l2):
    if a1 != 90 or a2 != 90 or a3 != 90:
        return ("\n sorry, but triangle sould be right -> one agle = 90 degrees")
    else:
        h = l1**2 + l2**2
        return ("The hypothenuse of this triangle is equal to:", h)

hypothenuse(a1, a2, a3, l1, l2)

最佳答案

您正在返回一个值。问题是你没有告诉 Python 显示它。

您可以使用 print() 显示变量、字符串、字节、整数和许多其他数据类型。 .

这就是您使用后的效果:

print(hypothenuse(a1, a2, a3, l1, l2))

正如评论中提到的,您可以将其存储在变量中。

我强烈建议您在程序中添加“错误捕获”,以防用户输入字母而不是可以使用 int() 转换为整数的内容

例如,如果在 angle1 下有人输入 a,您将得到:

>>> a1 = int(angle1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
>>>

防止这种情况的一种方法是“捕获”错误:

try:
    a1 = int(angle1)
except ValueError:
    print("Please enter an integer")

如果现在你对此感到陌生,请不要担心,当你学习 Python 时它就会出现,并且会变得足够容易理解。

关于python - 为什么我的代码没有返回斜边的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55889205/

相关文章:

python - Python 中的类继承问题

python - 使用 Django 将数千条记录插入 SQLite 表的有效方法是什么?

python - 比较Python中的浮点值

python - 类实例未通过 isinstance 检查

try 中的 pythonic 返回

function - 带返回的Powershell递归

javascript - 为什么程序返回未定义?

python - ubuntu 升级到 17.10(从 17.04 开始)时出现 psycopg2 导入错误

python - Tkinter Canvas 滚动条不跟随帧超过某个点

python-3.x - 无需用户输入即可向 Telegram 组发送消息