We can use these Python operators when we work with numeric
data types.
Operator | Description | Example Input | Example Output |
Unary Operator | |||
+ | Plus | +2 | 2 |
- | Minus | -2 | 2 |
-(-2) | 2 | ||
~ | Invesion | ~5 | 6 |
Binary Operator | |||
+ | Addition | 5+7 | 12 |
5+7.0 | 12.0 | ||
- | Subtraction | 5-2 | 3 |
5-2.0 | 3.0 | ||
* | Multiplication | 2.5*2 | 5.0 |
/ | Division | 5/2 | 2 |
5/2.0 | 2.5 | ||
% | Module (remainder) | 5%2 | 1 |
7.5%2.5 | 0.0 | ||
** | Power | 5**2 | 25 |
1.2**2.1 | 1.466 | ||
Binary Bitwise Operator | |||
& | AND | 5&2 | 0 |
11&3 | 3 | ||
| | OR | 5 | 2 | 7 |
11 | 3 | 11 | ||
^ | XOR (exclusive-or) | 5 ^ 2 | 7 |
11 ^ 3 | 8 | ||
Shifting Operators | |||
<< | Left bit-shift | 5 << 2 | 20 |
>> | Right bit-shift | 50 >> 3 | 6 |
- Unary bitwise inversion of a number x is defined as -(x+1)
- Number used in binary bitwise and shifting operator must be integer or long integers.
It
is important to notice what happens when we mix standard numeric types (adding
an integer and a floating point number, for example). If needed, Python first coerces
(converts) either of the numbers according to these rules (stopping as soon as
a rule is satisfied):
- If one of the numbers is a complex number, convert the other to a complex number too.
- If one of the numbers is a floating point number, convert the other to floating point.
- If one of the numbers is a long integer, convert the other to a long integer.
- No previous rule applies, so both are integers, and Python leaves them unchanged.
0 Comments