I do not understand how Or works in python I refer to the following code

3

Someone can help me because and how it works in python because I try to do it according to the documentation and it gives me different results

import operator
operator.or_(2,8)
10

operator.or_(8,2)
10

8 | 2
10

2 | 8
10

2 or 8
2

2 | 8
10

thanks

    
asked by NEFEGAGO 04.01.2019 в 16:04
source

1 answer

7

Logical operator or

  

expression or expression

The logical operator or returns false if and only if both expressions are false, otherwise returns true . Now, in Python (and in many languages) it is compared in the following way:

false = 0
true = 1

then if you put any number greater than 0 the interpreter will consider it as True . If you use the logical operator or for anything that is not Boolean unexpected things start to happen, for example when you put the sentence

2 or 8
2

in this case it returns the first value "True", for example:

False or 8
8

As a recommendation, use the logical operator or only in Boolean operations

Operator "or" bit by bit | or operator.or_(2,8) (bitwise)

  

number | number

the bitwise operator is designed to work normally with numbers, and basically compares bitwise numbers, as an example

2 es 0010
8 es 1000

then the bitwise comparison with the logic "or" (0 with 0 is 0, 1 with 0 is 1, 0 with 1 is 1 and 1 with 1 is 1) gives us the following

1010 

that in binary is equivalent to 10. As you can see, in bitwise operations the order of the operands is irrelevant, that is why:

2 | 8 = 8 | 2 = 10
    
answered by 04.01.2019 / 16:49
source