jeudi 16 novembre 2017

one or the other in if statement

first we have this:

def some(a):
    if a is None or "*":
         print "*"
    else:
         print a

>>> some("*")
    *
>>> some("d")
    *

it failed but I couldn't give myself a good enough reason why it failed. Apparently it is because I wrote it wrong, a working version would be:

def some(a):
    if a is (None or "*"): # or write [ if a is None or a is "*" ]
         print "*"
    else:
         print a


   >>> some("*")
       *
   >>> some("d")
       d

Although it's almost intuitive enough to just write the correct version but I couldn't explain to myself why the first version failed.

so the question is, why the first version failed?

Aucun commentaire:

Enregistrer un commentaire