this image shows how every input results in execution in triangleCalc() function block我是Python的新手,在练习过程中我制作了此程序,它要求用户从圆形和三角形中选择两种形状之一。但是,每当我输入一个输入时,无论它是“ c”,“ t”,“ r”还是其他任何东西,都会执行计算三角形面积的函数。
'''
This is a Calculator program
which asks the user to select a shape
and then calculate its area based on given dimensions
'''
print ('Shape Area Calculator is now running')
def triangleCalc():
base = float(input('Enter Base of triangle: '))
height = float(input('Enter Height of triangle: '))
areaT = 0.5 * base * height
print ('The area of triangle is: ' + str(areaT))
def circleCalc():
radius = float(input('Enter radius of Circle: '))
areaC = 3.14159 * radius * radius
print ('The area of Circle is ' + str(areaC))
print('Which shape would you like to calculate the Area of?')
print('Enter C for Circle or T for Triangle')
option = input()
if option == 't' or 'T':
triangleCalc()
elif option == 'c'or 'C':
circleCalc()
else:
print ('Invalid Choice')
答案 0 :(得分:0)
对于初学者来说,这似乎是多余的,但是if option == 't' or 'T'
实际上应该写为if option == 't' or option == 'T'
。
在旁注中,字符串(如'T')在python中的值为True
。因此,option == 't' or 'T'
始终为True,而不考虑option == 't'
的计算结果。
答案 1 :(得分:0)
@ bstrauch24解释了我要添加的错误所在
如果您必须使用各种组合或输入,则每次比较都不好,那么请in
运算符
option = input()
if option in ['t','T']:
triangleCalc()
elif option in ['c','C']:
circleCalc()