Python Operators
In Python, operators are symbols that perform operations on variables and values.
Types
Arithmetic
- handle numeric calculations
- modulus operator
%returns the reminder of the division of two numbers - floor division operator
//performs division and rounds down to the nearest whole number- discards the decimal to provide an integer
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 3 + 5 | 8 |
| - | Subtraction | 7 - 2 | 5 |
| * | Multiplication | 4 * 6 | 24 |
| / | Division | 8 / 2 | 4.0 |
| % | Modulus | 10 % 3 | 1 |
| // | Floor Division | 15 // 4 | 3 |
| ** | Exponentation | 2 ** 3 | 8 |
Comparison
A comparison operator is used to compare two values.
| Operator | Name | Example |
|---|---|---|
| == | Equal | var1 == var2 |
| != | Not equal | var1 != var2 |
| > | Greater than | var1 > var2 |
| < | Less than | var1 < var2 |
| >= | Greater than or equal to | var1 >= var2 |
| ⇐ | Less than or equal to | var1 <= var2 |
Logical
- perform logical operations on Boolean values
and,or,not
Assignment
An assignment operator is used to assign a value to a variable.
| Operator | Example | Equivalent |
|---|---|---|
= | a = 12 | a = 12 |
+= | a += 7 | a = a + 7 |
-= | a -= 7 | a = a - 7 |
*= | a *= 7 | a = a * 7 |
/= | a /= 7 | a = a / 7 |
%= | a %= 7 | a = a % 7 |
//= | a //= 7 | a = a // 7 |
**= | a **= 7 | a = a ** 7 |
&= | a &= 7 | a = a & 7 |
|= | a |= 7 | a = a | 7 |
^= | a ^= 7 | a = a ^ 7 |
>>= | a >>= 7 | a = a >> 7 |
<<= | a << = 7 | a = a << 7 |
Membership
Membership operators are used to test whether a value or variable is a member of a sequence or collection.
inreturnsTrueif a value is found in the sequencenot inreturnsTrueif a value is not found in the sequence
Identity
Identity operators are used to compare the memory location of two objects.
- compare object identities
- Two kinds:
is- returns
Trueif both variables point to same object
- returns
is not- Returns
Trueif both variables do not point to the same object
- Returns
Bitwise
- manipulate bits in binary representations
&(bitwise AND)|(bitwise OR)^(bitwise XOR)~(bitwise NOT)<<(left shift)>>(right shift)
Operate Precedence
- Parentheses
(): Highest precedence - Exponentiation
**: Next highest - Multiplication, Division, Floor Division, Modulus
*, /, //, %: Same precedence, evaluated left to right - Addition and Subtraction
+,-: Same precedence, evaluated left to right - Bitwise Shift
<<,>>: Lower than arithmetic operations - Bitwise AND
&: Lower than shifts - Bitwise XOR
^: Lower than AND - Bitwise OR
|: Lowest precedence
- if same precedence, evaluate left to right