Python 如何从用户处获取输入并根据输入调用函数?

Python 如何从用户处获取输入并根据输入调用函数?,python,function,if-statement,Python,Function,If Statement,我是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 Calcul

我是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')

对于刚开始编程的程序员来说,这似乎是多余的,但是如果option=='t'或't'实际上应该写成
if option=='t'或option=='t'


另一方面,在python中,字符串(如“T”)的计算结果为
True
。因此,无论
选项=='t'或't'
的计算结果是什么,它们都将始终为真。

正如@bstrauch24解释了您的错误所在,我想补充一下

如果您必须使用各种组合或输入,则每次比较都不好,然后在运算符中选择

option = input()
if option in ['t','T']:
    triangleCalc()
elif option in ['c','C']:
    circleCalc()

您可以引用一些代码,比如使用argparse:wow。这正好解决了我的问题,从过去的两个小时开始,我一直在为它挠头,谢谢!代码现在运行得非常好@bstrauch24