Assignment Operators?

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Mon Oct 6 23:37:36 CEST 2014


On Thursday, October 2, 2014 6:24:37 AM UTC-7, Didymus wrote:
> Hi All,
> 
> 
> 
>    I was wondering if someone could explain an assignment operator that I'm seeing in some code. As an example:
> 
> 
> 
> >>> errors = False
> 
> >>> errors |= 3
> 
> >>> errors 
> 
> 3
> 
> >>> errors |= 4
> 
> >>> errors
> 
> 7
> 
> 
> 
>    The '|=' operator, I read should be like a = a | b, but this appears to add the two numbers as long as it's more than the previous:
> 
> 
> 
> >>> errors |= 5
> 
> >>> errors
> 
> 7
> 
> 
> 
>    Is there anywhere I can read up more on this and the other assignment operators and what/how they work. I got this off 
> 
> 
> 
> http://rgruet.free.fr/PQR27/PQR2.7.html
> 
> 
> 
> 
> 
> I'm using:
> 
> % python
> 
> Python 2.7.5 (default, Sep 25 2014, 13:57:38) 
> 
> [GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
> 
> 
> 
> 
> 
>   Thanks for any help in advance.
> 
>    
> 
>      Tom

As others have said, the | operator is a bit-wise 'or', as opposed to a boolean 'or'.

False, when evaluated as an integer, converts to 0.  So False | 3 is equal to 3, and so your errors variable is now 3.

On the next step, you did | again with 4.  Now, | didn't ADD 3 and 4 like you think it did.  It did a bit-wise or.  3 in binary is 11.  4 in binary is 100.  OR them together and you get 111, which is 7.  The fact that the two numbers you chose have the same result whether you add them or 'or' them is a coincidence.

5 in binary is 101.  When you OR that with 111, you get 111, which is still 7.

If you're confused by this, read up on the binary number system and AND/OR/XOR/NAND logic.

-DJ



More information about the Python-list mailing list