【问题标题】:Why my code is not returning the value of hypotenuse?为什么我的代码没有返回斜边的值?
【发布时间】:2019-09-17 05:49:13
【问题描述】:

基本上,我需要计算直角三角形的斜边
首先,我的代码定义三角形是否正确,然后根据两侧的长度计算该三角形的斜边,但它没有返回我需要返回的 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)

【问题讨论】:

  • 是的。但是你没有用它做任何事情。也许你想做print(hypoteneuse(a1....))
  • 或者description, h = hypotenuse(...),如果你以后想要这些值的话。但是如果没有直角会导致错误...

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


【解决方案1】:

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

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

这是你使用后的样子:

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

如 cmets 中所述,您可以将其存储在变量中。

我强烈建议您在程序中添加“错误捕获”,以防用户输入字母而不是可以使用 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 时出现,并且会变得很容易理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2014-08-07
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多