In Python, operators are symbols that perform operations on variables and values. An expression is a combination of variables, values, and operators that computes to a value. Operators are fundamental to writing logic in programming.
Types of Operators in Python:
- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, division, etc.
Operator | Name | Description | Example | Result |
---|---|---|---|---|
+ | Addition | Adds two operands | 5 + 3 | 8 |
- | Subtraction | Subtracts the second operand from the first | 5 - 3 | 2 |
* | Multiplication | Multiplies two operands | 5 * 3 | 15 |
/ | Division | Divides the first operand by the second | 5 / 2 | 2.5 |
% | Modulus | Returns the remainder of the division | 5 % 2 | 1 |
** | Exponentiation | Raises the first operand to the power of the second | 2 ** 3 | 8 |
// | Floor Division | Divides the first operand by the second and rounds down | 5 // 2 | 2 |
Examples:
a = 10
b = 3
addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.3333333333333335
modulus = a % b # 1
exponentiation = a ** b # 1000
floor_division = a // b # 3
Comparison Operators
Comparison operators are used to compare two values and return a boolean value (True
or False
).
Operator | Name | Description | Example | Result |
---|---|---|---|---|
== | Equal to | Returns True if both operands are equal | 5 == 3 | False |
!= | Not equal to | Returns True if both operands are not equal | 5 != 3 | True |
> | Greater than | Returns True if the first operand is greater than the second | 5 > 3 | True |
< | Less than | Returns True if the first operand is less than the second | 5 < 3 | False |
>= | Greater than or equal to | Returns True if the first operand is greater than or equal to the second | 5 >= 3 | True |
<= | Less than or equal to | Returns True if the first operand is less than or equal to the second | 5 <= 3 | False |
Examples:
a = 5
b = 3
equal = a == b # False
not_equal = a != b # True
greater_than = a > b # True
less_than = a < b # False
greater_equal = a >= b # True
less_equal = a <= b # False
Logical Operators
Logical operators are used to combine conditional statements. They are primarily used to evaluate multiple expressions together.
Operator | Name | Description | Example | Result |
---|---|---|---|---|
and | Logical AND | Returns True if both expressions are True | (5 > 3) and (3 > 1) | True |
or | Logical OR | Returns True if at least one of the expressions is True | (5 > 3) or (3 < 1) | True |
not | Logical NOT | Reverses the result of the expression; returns False if the expression is True | not(5 > 3) | False |
Examples:
a = True
b = False
and_operator = a and b # False
or_operator = a or b # True
not_operator = not a # False
Bitwise Operators
Bitwise operators perform operations on the binary representations of integers. They are typically used in low-level programming, such as working with device drivers or system kernels.
Operator | Name | Description | Example | Result |
---|---|---|---|---|
& | Bitwise AND | Performs a logical AND operation on each pair of corresponding bits | 5 & 3 | 1 (0101 & 0011 = 0001) |
` | ` | Bitwise OR | Performs a logical OR operation on each pair of corresponding bits | `5 |
^ | Bitwise XOR | Performs a logical XOR operation on each pair of corresponding bits | 5 ^ 3 | 6 (0101 ^ 0011 = 0110) |
~ | Bitwise NOT | Inverts all the bits in the operand (bitwise complement) | ~5 | -6 (NOT 0101 = 1010, which is -6 in 2’s complement) |
<< | Left Shift | Shifts the bits of the operand to the left by the specified number of positions | 5 << 1 | 10 (0101 << 1 = 1010) |
>> | Right Shift | Shifts the bits of the operand to the right by the specified number of positions | 5 >> 1 | 2 (0101 >> 1 = 0010) |
Examples:
a = 5 # 0101 in binary
b = 3 # 0011 in binary
bitwise_and = a & b # 1 (0001 in binary)
bitwise_or = a | b # 7 (0111 in binary)
bitwise_xor = a ^ b # 6 (0110 in binary)
bitwise_not = ~a # -6 (inverted bits of 0101 give 1010 in binary, which is -6 in two's complement)
left_shift = a << 1 # 10 (1010 in binary)
right_shift = a >> 1 # 2 (0010 in binary)
Assignment Operators
Assignment operators are used to assign values to variables. In addition to basic assignment, Python also provides compound assignment operators that combine an arithmetic operation with assignment.
Operator | Name | Description | Example | Result (after) |
---|---|---|---|---|
= | Assign | Assigns the value of the right operand to the left operand | a = 5 | a is 5 |
+= | Add and assign | Adds the right operand to the left operand and assigns the result to the left operand | a += 3 | a becomes 8 |
-= | Subtract and assign | Subtracts the right operand from the left operand and assigns the result to the left operand | a -= 3 | a becomes 2 |
*= | Multiply and assign | Multiplies the left operand by the right operand and assigns the result to the left operand | a *= 3 | a becomes 15 |
/= | Divide and assign | Divides the left operand by the right operand and assigns the result to the left operand | a /= 3 | a becomes 5.0 |
%= | Modulus and assign | Takes modulus using two operands and assigns the result to the left operand | a %= 3 | a becomes 2 |
**= | Exponent and assign | Raises the left operand to the power of the right operand and assigns the result to the left operand | a **= 3 | a becomes 125 |
//= | Floor divide and assign | Floor divides the left operand by the right operand and assigns the result to the left operand | a //= 3 | a becomes 5 |
&= | Bitwise AND and assign | Performs a bitwise AND operation between the two operands and assigns the result to the left operand | a &= 3 | a becomes 1 |
` | =` | Bitwise OR and assign | Performs a bitwise OR operation between the two operands and assigns the result to the left operand | `a |
^= | Bitwise XOR and assign | Performs a bitwise XOR operation between the two operands and assigns the result to the left operand | a ^= 3 | a becomes 4 |
<<= | Left shift and assign | Shifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result to the left operand | a <<= 1 | a becomes 10 |
>>= | Right shift and assign | Shifts the bits of the left operand to the right by the number of positions specified by the right operand and assigns the result to the left operand | a >>= 1 | a becomes 2 |
Examples:
a = 5
a += 2 # a becomes 7
a *= 3 # a becomes 21
a //= 2 # a becomes 10
a **= 2 # a becomes 100
Operator Precedence
Operator precedence determines the order in which operations are performed in an expression with multiple operators. Operators with higher precedence are executed before operators with lower precedence. If operators have the same precedence, their associativity (left-to-right or right-to-left) determines the order of operations.
Python Operator Precedence Table:
Precedence | Operator | Description |
---|---|---|
1 | () | Parentheses |
2 | ** | Exponentiation |
3 | +x , -x , ~x | Unary plus, Unary minus, Bitwise NOT |
4 | * , / , // , % | Multiplication, Division, Floor Division, Modulus |
5 | + , - | Addition, Subtraction |
6 | << , >> | Left Shift, Right Shift |
7 | & | Bitwise AND |
8 | ^ | Bitwise XOR |
9 | ` | ` |
10 | in , not in , is , is not , < , <= , > , >= , == , != | Comparisons, Membership, Identity |
11 | not | Logical NOT |
12 | and | Logical AND |
13 | or | Logical OR |
14 | if ... else | Conditional Expression (Ternary) |
15 | = , += , -= , *= , /= , %= , &= , ` | =, ^=, >>=, <<=, **=, //=, :=` |
Examples:
result = 2 + 3 * 4 # 14 (Multiplication before addition)
result = (2 + 3) * 4 # 20 (Parentheses change precedence)
result = 2 ** 3 ** 2 # 512 (Exponentiation is right-associative)
result = 2 + 3 * 4 > 15 and not False # True (Combines arithmetic, comparison, and logical operators)
Understanding operator precedence is crucial for writing correct and efficient expressions in Python. It’s always a good practice to use parentheses to make your expressions clear, especially when the default precedence rules might not align with your intentions.
Let’s delve deeper into the concept of operator precedence in Python, especially focusing on how expressions with multiple operators are evaluated.
Operator Precedence in Expressions
When you write an expression with multiple operators, Python determines the order in which the operations are performed based on operator precedence. Operators with higher precedence are executed before operators with lower precedence. If two operators have the same precedence, Python evaluates the expression based on their associativity—which can be left-to-right or right-to-left.
Associativity of Operators
- Left-to-Right Associativity: Most operators, including arithmetic, bitwise, and logical operators, are evaluated from left to right when they have the same precedence level.
- Right-to-Left Associativity: Operators like exponentiation (
**
) and assignment operators (=
,+=
, etc.) are evaluated from right to left.
Examples of Operator Precedence with Multiple Operators
Arithmetic Operators
Consider the following expression:
result = 2 + 3 * 4
- Step 1: Identify the operators and their precedence:
+
(Addition) has lower precedence than*
(Multiplication).
- Step 2: Evaluate the expression based on precedence:
- Multiplication (
*
) is performed first:3 * 4 = 12
. - Then, addition (
+
) is performed:2 + 12 = 14
.
- Multiplication (
- Final Result:
result = 14
.
Mixed Operators with Parentheses
result = (2 + 3) * 4
- Step 1: Identify the parentheses:
- Parentheses have the highest precedence, so the expression inside them is evaluated first.
- Step 2: Evaluate the expression:
- First, addition (
+
) inside the parentheses:2 + 3 = 5
. - Then, multiplication (
*
) outside the parentheses:5 * 4 = 20
.
- First, addition (
- Final Result:
result = 20
.
Exponentiation and Multiplication
result = 2 ** 3 ** 2
- Step 1: Identify the operators and their precedence:
- Both
**
operators have the same precedence and are right-associative.
- Both
- Step 2: Evaluate from right to left:
- First, the rightmost exponentiation:
3 ** 2 = 9
. - Then, the leftmost exponentiation:
2 ** 9 = 512
.
- First, the rightmost exponentiation:
- Final Result:
result = 512
.
Combining Arithmetic, Comparison, and Logical Operators
result = 2 + 3 * 4 > 15 and not False
Step 1: Identify the operators and their precedence:
*
(Multiplication) has higher precedence than+
(Addition).>
(Comparison) is evaluated after arithmetic operations.and
andnot
(Logical operators) have lower precedence but will be evaluated according to their own precedence rules.
Step 2: Evaluate the expression:
- First, multiplication:
3 * 4 = 12
. - Then, addition:
2 + 12 = 14
. - Next, comparison:
14 > 15 = False
. - Then, logical NOT:
not False = True
. - Finally, logical AND:
False and True = False
.
Final Result: result = False
.
Detailed Operator Precedence Table with Associativity
Here’s a table summarizing operator precedence and associativity:
Precedence | Operator | Description | Associativity |
---|---|---|---|
1 | () | Parentheses | N/A |
2 | ** | Exponentiation | Right-to-Left |
3 | +x , -x , ~x | Unary plus, Unary minus, Bitwise NOT | Right-to-Left |
4 | * , / , // , % | Multiplication, Division, Floor Division, Modulus | Left-to-Right |
5 | + , - | Addition, Subtraction | Left-to-Right |
6 | << , >> | Left Shift, Right Shift | Left-to-Right |
7 | & | Bitwise AND | Left-to-Right |
8 | ^ | Bitwise XOR | Left-to-Right |
9 | ` | ` | Bitwise OR |
10 | in , not in , is , is not , < , <= , > , >= , == , != | Comparisons, Membership, Identity | Left-to-Right |
11 | not | Logical NOT | Right-to-Left |
12 | and | Logical AND | Left-to-Right |
13 | or | Logical OR | Left-to-Right |
14 | if ... else | Conditional Expression (Ternary) | Right-to-Left |
15 | = , += , -= , *= , /= , %= , &= , ` | =, ^=, >>=, <<=, **=, //=, :=` | Assignment Operators |
Key Points to Remember
- Parentheses are your best friend when dealing with complex expressions. They override the default precedence and make your intentions clear.
- Right-to-Left associativity is uncommon and mainly found in operators like exponentiation and assignment.
- Left-to-Right associativity is the norm for most other operators, including arithmetic, bitwise, and logical operators.
Understanding operator precedence and associativity ensures that your expressions are evaluated as intended, avoiding unexpected results.