Python operators: Difference between revisions
From wikinotes
(6 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
= | = Equality Greater/Less Than = | ||
< | <blockquote> | ||
<syntaxhighlight lang="python"> | |||
== / != # equal/not-equal | |||
is / is not # same /not-same instance | |||
>= / <= # greater/less than | |||
</ | </syntaxhighlight> | ||
</blockquote><!-- Equality Greater/Less than --> | |||
= | = bitwise operators = | ||
<blockquote> | |||
<syntaxhighlight lang="python"> | |||
x | y # bitwise or | |||
x ^ y # bitwise exclusive and | |||
x & y # bitwise and | |||
x << n # bitwise shift by n bits | |||
x >> n # bitwise shift by n bits | |||
~x # invert bits | |||
</syntaxhighlight> | |||
expressing binary in python | |||
<syntaxhighlight lang="python"> | |||
int('101', 2) # 4 in binary | |||
0b101 # 4 in binary | |||
bin(4) # 0b101 converts to binary | |||
</syntaxhighlight> | |||
bitwise operators manipulate binary digits. | |||
<syntaxhighlight lang="python"> | |||
0b100 | 0b010 | 0b001 == 0b111 # bitwise OR sets binary digit | |||
0b111 ^ 0b100 ^ 0b001 == 0b010 # bitwise EXCLUSIVE AND unsets binary digit | |||
0b111 & 0b100 == 0b100 # bitwise AND keeps '1' digits where '1' in both numbers. | |||
</syntaxhighlight> | |||
</blockquote><!-- bitwise operators --> |
Latest revision as of 01:06, 31 July 2021
Equality Greater/Less Than
== / != # equal/not-equal is / is not # same /not-same instance >= / <= # greater/less than
bitwise operators
x | y # bitwise or x ^ y # bitwise exclusive and x & y # bitwise and x << n # bitwise shift by n bits x >> n # bitwise shift by n bits ~x # invert bitsexpressing binary in python
int('101', 2) # 4 in binary 0b101 # 4 in binary bin(4) # 0b101 converts to binarybitwise operators manipulate binary digits.
0b100 | 0b010 | 0b001 == 0b111 # bitwise OR sets binary digit 0b111 ^ 0b100 ^ 0b001 == 0b010 # bitwise EXCLUSIVE AND unsets binary digit 0b111 & 0b100 == 0b100 # bitwise AND keeps '1' digits where '1' in both numbers.