Always true when testing if string == various OR'ed alternatives

前端 未结 5 1642
时光取名叫无心
时光取名叫无心 2020-11-30 14:57

So the problem I am currently having is that my program always calls the \'md5cypher\' class which I have defined, even if the input is not in that list:

def         


        
相关标签:
5条回答
  • 2020-11-30 15:11

    if toe=='md5' or 'M' or 'm' or 'Md5' or 'MD5':

    will always be evaluated to

    if toe=='md5' or True or True or True or True :

    What you want is:

    if toe in ('md5', 'M', 'm', 'Md5', 'MD5'):
        print("Md5 Encryption Cypher")
        md5cypher()
    .
    .
    .
    
    0 讨论(0)
  • 2020-11-30 15:19

    You have a fundamental misunderstanding of how boolean operators work in python.

    You have to consider the operator precedences, and then your condition becomes

    if (toe=='md5') or ('M') or ('m') or ('Md5') or ('MD5'):
    

    which is equivalent to

    if (toe=='md5') or True:
    

    which of course is always true. A solution to your problem would be

    if toe.lower() in ('m', 'md5'):
    
    0 讨论(0)
  • 2020-11-30 15:31

    Literally, what you want to do is:

    if toe=='md5' or toe=='M' or toe=='m' or toe=='Md5' or toe=='MD5'
    

    - each part of the composite condition should be a standalone condition.

    But in Python you can do it in a more elegant way, as indicated in other answers:

    if toe in ('md5', 'M', 'm', 'Md5', 'MD5')
    
    0 讨论(0)
  • 2020-11-30 15:33

    That is because checking a character will always return True therefore ensuring the if statement will execute.

    0 讨论(0)
  • 2020-11-30 15:36

    In reality you're checking:

    if (toe=='md5') or 'M' or 'm' or....
    

    And since bool('M') is True, you will always succeed that check. Try this instead:

    if toe.lower() in ('md5', 'm'):
    
    0 讨论(0)
提交回复
热议问题