使用用户输入定义Python函数

时间:2014-11-04 22:33:09

标签: python variables

我试图创建一小段代码,使用毕达哥拉斯'定理计算三角形的斜边长度和与高度相反的角度。为此,用户必须输入三角形的长度和宽度。我想定义一个函数,以便整个事件可以作为更大程序的一部分进行调用。这是代码:

def ex1() :
    from math import sqrt, atan, degrees
    print("""Hello, this is a program that will calculate the length of the
    hypotenuse of a triangle given the width and height of the triangle.
    It will also calculate the angle opposite the height and adjacent to the width.
    """)

    myWidth = float(input("Please input the width of the triangle: "))
    myHeight = float(input("Please input the height of the triangle: "))
    hyp = sqrt(((myWidth**2) + (myHeight**2)))
    angle = degrees(atan(myHeight/myWidth))
    print("\nThe length of the hypotenuse is " + "%.1f" % hyp + " units")
    print("\nThe size of the angle opposite the height and \nadjacent to the width is " + "%.1f" % angle + " degrees to 1 decimal place")
    input = input("Press enter to end the program\n")

任何人都可以向我解释,当我打电话给它时,它会向我抛出这个错误:

UnboundLocalError: local variable 'input' referenced before assignment

非常感谢提前

2 个答案:

答案 0 :(得分:2)

请在此处查看此行:?

input = ...

请参阅上面几行您调用input()函数的地方?你混淆了编译器。使用其他名称。

答案 1 :(得分:1)

问题似乎是你的最后一行,你在那里为变量'input'赋值。请参阅此前的SO问题:Local Variable Input