Python Operators¶
- Operators in Python are symbols used to perform operations on variables and values. Python supports a wide range of operators for different purposes, including arithmetic operations, comparison operations, logical operations, and more.
- For example, In the expression 3 + 2 = 5. Here, 3 and 2 are called operands and + is called operator.
- Arithmetic operators
- Comparison operators
- Assignment operators
- Logical operators
- Membership operators
- Identity operators
- Bitwise operators
Arithmetic Operators¶
| Name | Operator | Example | Description |
|---|---|---|---|
| Addition | + | x + y | Adds two numbers and returns the sum. |
| Subtraction | - | x - y | Subtracts the right operand from the left operand. |
| Multiplication | * | x * y | Multiplies two numbers. |
| Division | / | x / y | Divides the left operand by the right operand and returns a floating-point result. |
| Modulus | % | x % y | Returns the remainder after dividing the left operand by the right operand. |
| Exponentiation | ** | x ** y | Raises the left operand to the power of the right operand. |
| Floor division | // | x // y | Divides the left operand by the right operand and returns the largest integer less than or equal to the result. |
In [3]:
x = 5
y = 10
print("Addition :", x + y) # Output: Addition : 15
print("Subtraction :", x - y) # Output: Subtraction : -5
print("Multiplication :", x * y) # Output: Multiplication : 50
print("Division :", x / y) # Output: Division : 0.5
print("Modulus :", x % y) # Output: Modulus : 5
print("Exponentiation :", x ** y) # Output: Exponentiation : 9765625
print("Floor_division :", x // y) # Output: Floor_division : 0
Addition : 15 Subtraction : -5 Multiplication : 50 Division : 0.5 Modulus : 5 Exponentiation : 9765625 Floor_division : 0
Comparison(Relational) Operators¶
| Name | Operator | Example | Description |
|---|---|---|---|
| Equal | == | x == y | Returns True if both operands have equal values; otherwise returns False. |
| Not equal | != | x != y | Returns True if operands have different values; otherwise returns False. |
| Greater than | > | x > y | Returns True if the left operand is greater than the right operand. |
| Less than | < | x < y | Returns True if the left operand is less than the right operand. |
| Greater than or equal to | >= | x >= y | Returns True if the left operand is greater than or equal to the right operand. |
| Less than or equal to | <= | x <= y | Returns True if the left operand is less than or equal to the right operand. |
In [4]:
x = 10
y = 5
print("Equal :", x == y) # Output: Equal : False
print("Not equal:", x != y) # Output: Not equal: True
print("Greater than :", x > y) # Output: Greater than : True
print("Less than :", x < y) # Output: Less than : False
print("Greater than or equal to :", x >= y) # Output: Greater than or equal to : True
print("Less than or equal to :", x <= y) # Output: Less than or equal to : False
Equal : False Not equal: True Greater than : True Less than : False Greater than or equal to : True Less than or equal to : False
Assignment Operators¶
| Operator | Example | Same As | Description |
|---|---|---|---|
| = | x = 5 | x = 5 | Assigns the value on the right to the variable on the left. |
| += | x += 5 | x = x + 5 | Adds the right operand to the left operand and assigns the result to the left operand. |
| -= | x -= 5 | x = x - 5 | Subtracts the right operand from the left operand and assigns the result to the left operand. |
| *= | x *= 5 | x = x * 5 | Multiplies the left operand by the right operand and assigns the result to the left operand. |
| /= | x /= 5 | x = x / 5 | Divides the left operand by the right operand and assigns the floating-point result to the left operand. |
| %= | x %= 5 | x = x % 5 | Calculates the remainder when the left operand is divided by the right operand and assigns it to the left operand. |
| //= | x //= 5 | x = x // 5 | Performs floor division and assigns the integer result to the left operand. |
| **= | x **= 5 | x = x ** 5 | Raises the left operand to the power of the right operand and assigns the result to the left operand. |
| &= | x &= 5 | x = x & 5 | Performs bitwise AND between operands and assigns the result to the left operand. |
| |= | x|= 5 | x = x | 5 | Performs bitwise OR between operands and assigns the result to the left operand. |
| ^= | x ^= 5 | x = x ^ 5 | Performs bitwise XOR between operands and assigns the result to the left operand. |
| >>= | x >>= 5 | x = x >> 5 | Performs bitwise right shift and assigns the result to the left operand. |
| <<= | x <<= 5 | x = x << 5 | Performs bitwise left shift and assigns the result to the left operand. |
In [6]:
x = 5
print("= :", x) # Output: = : 5
x = 5
x += 10
print("+= :", x) # Output: += : 15
x = 5
x -= 1
print("-= :", x) # Output: -= : 4
x = 5
x *= 3
print("*= :", x) # Output: *= : 15
x = 5
x /= 2
print("/= :", x) # Output: /= : 2.5
x = 5
x %= 2
print("%= :", x) # Output: %= : 1
x = 5
x //= 2
print("//= :", x) # Output: //= : 2
x = 5
x **= 2
print("**= :", x) # Output: **= : 25
x = 5
x &= 2
print("&= :", x) # Output: &= : 0 (binary: 0101 & 0010 → 0000)
x = 5
x |= 2
print("|= :", x) # Output: |= : 7 (binary: 0101 | 0010 → 0111)
x = 5
x ^= 3
print("^= :", x) # Output: ^= : 6 (binary: 0101 ^ 0011 → 0110)
x = 5
x >>= 3
print(">>= :", x) # Output: >>= : 0 (binary right shift → 0000)
x = 5
x <<= 3
print("<<= :", x) # Output: <<= : 40 (binary left shift → 0101 → 0101000)
= : 5 += : 15 -= : 4 *= : 15 /= : 2.5 %= : 1 //= : 2 **= : 25 &= : 0 |= : 7 ^= : 6 >>= : 0 <<= : 40
Logical Operators¶
- It is used to combine conditional statements
| Operator | Description | Example |
|---|---|---|
| and | Returns True if both statements are true | x < 5 and x < 10 |
| or | Returns True if one of the statements is true | x < 5 or x < 4 |
| not | Reverse the result, returns False if the result is true | not(x < 5 and x < 10) |
In [ ]:
x = 7
print(x > 3 and x < 10) # Output: True (7 is greater than 3 AND less than 10)
print(x > 3 or x < 4) # Output: True (7 is greater than 3, so condition is True)
print(not(x > 3 and x < 10)) # Output: False (because (x > 3 and x < 10) is True, and not True → False)
True True False
- For arithmetic values, the and operator does not return a Boolean but instead returns the second operand if the first one is truthy; otherwise, it returns the first operand.
In [ ]:
print(7 and 13) # 13
13
- For arithmetic values, the or operator returns the first operand if it is truthy; otherwise, it returns the second operand.
In [ ]:
print(7 or 13) # 7
7
- For arithmetic values, the not operator returns False for any nonzero value and True for zero.
In [ ]:
print(not 5) # Non-zero value : False
print(not 0) # zero value : True
False True
Membership Operators¶
- It is used to test if a sequence is presented in an object
| Operator | Description | Example |
|---|---|---|
| in | Returns True if a sequence with the specified value is present in the object | x in y |
| not in | Returns True if a sequence with the specified value is not present in the object | x not in y |
In [ ]:
# returns True because a sequence with the value "Bus" is in the list
x = ["Train", "Bus"]
print("Bus" in x)
# returns True because a sequence with the value "Boat" is not in the list
print("Boat" not in x)
True True
Identity Operators¶
- It is used to determine whether two objects are not just equal in value, but are in fact the exact same instance stored at the same memory address.
| Operator | Description | Example |
|---|---|---|
| is | Returns True if both variables are the same object | x is y |
| is not | Returns True if both variables are not the same object | x is not y |
In [ ]:
a = ["Train", "Bus"]
b = ["Train", "Bus"]
c = a
# returns True because c is the same object as a
print(a is c)
# returns False because a is not the same object as b, even if they have the same content
print(a is b)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True because a is equal to b
print(a == b)
# returns False because c is the same object as a
print(a is not c)
# returns True because a is not the same object as b, even if they have the same content
print(a is not b)
# to demonstrate the difference betweeen "is not" and "!=": this comparison returns False because a is equal to b
print(a != b)
True False True False True False
Bitwise Operators¶
- Bitwise operators in Python allow you to manipulate individual bits of integers at a binary level. It always returns the result in decimal format.
| Operator | Name | Description | Example |
|---|---|---|---|
| & | AND | Sets each bit to 1 if both bits are 1 | x & y |
| | | OR | Sets each bit to 1 if one of two bits is 1 | x | y |
| ^ | XOR | Sets each bit to 1 if only one of two bits is 1 | x ^ y |
| ~ | NOT | Inverts all the bits | ~x |
| << | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off | x << 2 |
| >> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off | x >> 2 |
AND¶
5 = 101
3 = 011
-------
1 = 001
In [ ]:
print(5 & 3)
1
OR¶
5 = 101
3 = 011
-------
7 = 111
In [ ]:
print(5 | 3)
7
XOR¶
5 = 101
3 = 011
-------
6 = 110
In [ ]:
print(5 ^ 3)
6
NOT¶
Inverted 3 becomes -4:
3 = 0000000000000011
-4 = 1111111111111100
In [ ]:
print(~3)
-4
Signed right shift¶
- The >> operator moves each bit the specified number of times to the right.
- Empty holes at the left are filled with 0's.
If you move each bit 2 times to the right, 8 becomes 2:
8 = 1000
becomes
2 = 0010
In [ ]:
print(8 >> 2)
2
Zero fill left shift¶
- The << operator inserts the specified number of 0's (in this case 2) from the right and let the same amount of leftmost bits fall off.
If you push 00 in from the left:
3 = 0011
becomes
12 = 1100
In [ ]:
print(3 << 2)
12
Python Operator Precedence¶
- Operator precedence in Python refers to the order in which different operators are evaluated in an expression.
- Associativity defines the direction in which operators of the same precedence are evaluated. Most operators in Python are left-to-right associative, but some (like exponentiation and unary operators) are right-to-left associative.
- Understanding operator precedence is crucial for writing correct and predictable code. Python follows a specific set of rules to determine the order in which operators are evaluated. Here's a brief overview of operator precedence in Python, from highest to lowest precedence:
| Operator | Description | Associativity |
|---|---|---|
() |
Parentheses | N/A (evaluated first) |
** |
Exponentiation | Right-to-left |
+x -x ~x |
Unary plus, unary minus, and bitwise NOT | Right-to-left |
* / // % |
Multiplication, division, floor division, and modulus | Left-to-right |
+ - |
Addition and subtraction | Left-to-right |
<< >> |
Bitwise left and right shifts | Left-to-right |
& |
Bitwise AND | Left-to-right |
^ |
Bitwise XOR | Left-to-right |
\| |
Bitwise OR | Left-to-right |
== != > >= < <= is is not in not in |
Comparisons, identity, and membership operators | Left-to-right |
not |
Logical NOT | Right-to-left |
and |
Logical AND | Left-to-right |
or |
Logical OR | Left-to-right |
In [7]:
result = 2 + 3 * 4 # Multiplication has higher precedence, so 3 * 4 is evaluated first.
print(result)# result will be 14
result = (2 + 3) * 4 # Parentheses force addition to be evaluated first.
print(result)# result will be 20
result = 2 ** 3 ** 2 # Exponentiation is right-associative, so 3 ** 2 is evaluated first.
print(result)# result will be 512
# If two operators have the same precedence, the expression is evaluated based on Associativity.
# Addition + and subtraction - has the same precedence, and therefor we evaluate the expression from left to right based on Associativity:
print(5 + 4 - 7 + 3)
14 20 512 5