我正在尝试使用另一个函数中的变量,但我不知道如何访问它。如果有必要的话,我不知道把global
放在哪里。
以下是我目前所拥有的:
#Defs
def getAngle1():
angle1 = eval(input("Please enter the first angle: "))
return angle1
def getAngle2():
angle2 = eval(input("Please enter the second angle: "))
return angle2
def getAngle3():
angle3 = eval(input("Please enter the third angle: "))
return angle3
def main():
getAngle1()
getAngle2()
getAngle3()
if angle1 == 90:
print ("This is a right triangle!")
elif angle2 == 90:
print ("This is a right triangle!")
elif angle3 == 90:
print ("This is a right triangle!")
else:
print ("This is not a right triangle.")
#Driver
main()
我得到这个错误:
Traceback (most recent call last):
File "C:/Documents and Settings/user1/My Documents/AZ_isitRightRevised.py", line 29, in <module>
main()
File "C:/Documents and Settings/user1/My Documents/AZ_isitRightRevised.py", line 20, in main
if angle1 == 90:
NameError: name 'angle1' is not defined
问题是getAngles
代码块在return angle1
之后停止执行。此外,只需调用getAngles()
,就不会将此函数返回的值存储在任何位置。
首先,让我们将getAngles
重写为:
def getAngles():
a1 = int(input("Please enter the first angle:"))
a2 = int(input("Please enter the second angle:"))
a3 = int(input("Please enter the third angle:"))
return (a1, a2, a3)
现在,在main
中,您可以执行以下操作:
def main():
angles = getAngles()
# rest of your code
# angles[0] is the first angle
# angles[1] is the second angle
# angles[2] is the third angle
现在,您可以访问所有三个角度。你可以做的是:
if 90 in angles: # if it's a right triangle
print("This is a right triangle!")
else: # otherwise...
print("This is not a right triangle.")