Search code examples
pythonor-operator

usage of or operator in python


Please explain what is going on with the or operator here in python

>>>sen='abcdef'
>>>'a' in sen
True
>>>'v' or 'z' in sen
'v'
>>>('v' or 'z') in sen
False
>>>('v' or 'a') in sen
False
>>>('a' or 'v') in sen
True

The first output obviously makes sense. From the second output, I do not follow what is going on!


Solution

  • When you use the parenthesis, you tell the interpreter to interpret what's inside the parenthesis first. So let's go over the outputs, starting from the second one:

    >>>('v' or 'z') in sen
    

    What you did here is: ('v' or 'z') translates to v because it goes from left to right - They both evaluate to True, so if you would to write 'z' or 'v' it would evaluate to z. So you are checking if v is inside sen --> False.

    Moving on:

    >>>('v' or 'a') in sen --> is 'v' inside sen?
    False
    >>>('a' or 'v') in sen --> is 'a' inside sen?
    True