"or"导致"if"问题的情况



我在功能中的or条件上遇到麻烦。if语句无论是什么值choice,都将其评估为True。当我删除or时,if工作正常。

def chooseDim ():
    **choice = input ('Do you need to find radius or area? ')
    if choice == 'A' or 'a':**
        area = 0
        area = int(area)
        areaSol ()
    elif choice == 'R' or 'r':
        radSol ()
    else:
        print ('Please enter either A/a or R/r.')
        chooseDim ()

'a''评估为true,因此您需要正确构建if语句。

def chooseDim ( ):
**choice = input ('Do you need to find radius or area? ')
if choice == 'A' or choice == 'a':**
    area = 0
    area = int(area)
    areaSol ( )
elif choice == 'R' or choice == 'r':
    radSol ( )
else:
    print ('Please enter either A/a or R/r.')
    chooseDim ( )

有关or本身的答案是正确的。您实际上是在问"a"是否是正确的,它总是如此。但是还有一种替代方法:

if choice in 'Aa':

然后,再一次,没有什么错:

if choice.lower() == 'a':

在这种情况下仅使用in操作员会更容易:

if choice in ['A', 'a']: ...
if choice == 'A' or choice =='a':

相关内容

最新更新