我正在尝试创建一小段代码,使用毕达哥拉斯定理来计算三角形的斜边长度和与高度相反的角度。 为此,用户必须输入三角形的长度和宽度。 我想定义一个函数,以便整个事件可以作为更大程序的一部分进行调用。 这是代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18def 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("
The length of the hypotenuse is" +"%.1f" % hyp +" units")
print("
The size of the angle opposite the height and
adjacent to the width is" +"%.1f" % angle +" degrees to 1 decimal place")
input = input("Press enter to end the program
")
任何人都可以向我解释,当我打电话给它时,它会向我抛出这个错误:
1UnboundLocalError: local variable 'input' referenced before assignment
提前谢谢了
你用的是什么版本的python? 如果它的3.x以上只有input工作。不要将最后一行分配给变量(即第二个input语句。如果你还想要,请使用另一个变量
它是Python 3.3.2,所以我不能定义多个用户输入? 好的,我会在程序结束时尝试一下。
始终避免使用python keywords作为变量名。 input是一个关键字,它使得它成为variable名称的大选择
谢谢你的帮助,现在解决了。
在这里看到这一行:?
1input = ...
请看上面几行您调用input()函数的地方? 你混淆了编译器。 使用其他名称。
问题似乎是你的最后一行,你在那里为变量'input'赋值。 请参阅此前的SO问题:局部变量输入