Python 3 - Basic Operators
Python 3 - Basic Operators
Section titled “Python 3 - Basic Operators”Operators are special symbols or keywords in Python that perform operations on values. The values that operators act upon are called operands. For example, in the expression 5 + 3, + is the operator, and 5 and 3 are the operands.
Types of Operators
Section titled “Types of Operators”Python includes several categories of operators:
- Arithmetic Operators
- Comparison (Relational) Operators
- Assignment Operators
- Logical Operators
- Bitwise Operators
- Membership Operators
- Identity Operators
Let’s explore each type.
Python Arithmetic Operators
Section titled “Python Arithmetic Operators”These perform standard mathematical operations. Assume a = 10 and b = 3:
| Operator | Name | Description | Example (a=10, b=3) |
|---|---|---|---|
| + | Addition | Adds operands. | a + b is 13 |
| - | Subtraction | Subtracts right operand from left. | a - b is 7 |
| * | Multiplication | Multiplies operands. | a * b is 30 |
| / | Division | Divides left operand by right (result is always float). | a / b is 3.333... |
| % | Modulus | Returns the remainder of the division. | a % b is 1 |
| ** | Exponentiation | Raises left operand to the power of the right. | a ** b is 1000 |
| // | Floor Division | Divides and rounds down to the nearest whole number (integer). | a // b is 3. -10 // 3 is -4. |
#!/usr/bin/env python3a = 10b = 3print(f"a + b = {a + b}")print(f"a - b = {a - b}")print(f"a * b = {a * b}")print(f"a / b = {a / b}")print(f"a % b = {a % b}")print(f"a ** b = {a ** b}")print(f"a // b = {a // b}")print(f"-10 // 3 = {-10 // 3}") # Note floor division with negative numbersPython Comparison (Relational) Operators
Section titled “Python Comparison (Relational) Operators”These operators compare two values and return a Boolean result (True or False). Assume a = 10 and b = 20:
| Operator | Name | Description | Example (a=10, b=20) |
|---|---|---|---|
| == | Equal to | Checks if values are equal. | a == b is False |
| != | Not equal to | Checks if values are not equal. | a != b is True |
| > | Greater than | Checks if left operand is greater. | a > b is False |
| < | Less than | Checks if left operand is less. | a < b is True |
| >= | Greater than or equal to | Checks if left operand is greater or equal. | a >= b is False |
| <= | Less than or equal to | Checks if left operand is less or equal. | a <= b is True |
#!/usr/bin/env python3a = 10b = 20print(f"a == b: {a == b}")print(f"a != b: {a != b}")print(f"a > b: {a > b}")print(f"a < b: {a < b}")print(f"a >= b: {a >= b}")print(f"a <= b: {a <= b}")Python Assignment Operators
Section titled “Python Assignment Operators”These operators assign values to variables. The basic assignment operator is =. Combined operators perform an operation and assign the result in one step. Assume c = 10 initially for compound assignments:
| Operator | Example | Equivalent to |
|---|---|---|
| = | x = 5 | x = 5 |
| += | c += 5 | c = c + 5 (c becomes 15) |
| -= | c -= 3 | c = c - 3 (c becomes 7) |
| *= | c *= 2 | c = c * 2 (c becomes 20) |
| /= | c /= 4 | c = c / 4 (c becomes 2.5) |
| %= | c %= 3 | c = c % 3 (c becomes 1) |
| **= | c **= 3 | c = c ** 3 (c becomes 1000) |
| //= | c //= 3 | c = c // 3 (c becomes 3) |
#!/usr/bin/env python3c = 10print(f"Initial c: {c}")c += 5print(f"After c += 5: {c}")c //= 6print(f"After c //= 6: {c}")Python Logical Operators
Section titled “Python Logical Operators”These operators combine conditional statements and return True or False. Assume x = True and y = False:
| Operator | Description | Example (x=True, y=False) |
|---|---|---|
and | Returns True if both operands are true. | x and y is False |
or | Returns True if at least one operand is true. | x or y is True |
not | Reverses the logical state (True becomes False, False becomes True). | not x is False |
Logical operators use short-circuiting: and stops evaluating if the first operand is false; or stops if the first is true.
#!/usr/bin/env python3age = 25has_permission = False
if age >= 18 and has_permission: print("Access granted.")else: print("Access denied.")
if age < 18 or age > 65: print("Eligible for discount.")else: print("Standard price applies.")
print(f"Not has_permission: {not has_permission}")Python Membership Operators
Section titled “Python Membership Operators”These operators test if a value is present in a sequence (like lists, tuples, strings). Assume my_list = [1, 2, 3]:
| Operator | Description | Example (my_list = [1, 2, 3]) |
|---|---|---|
in | Returns True if the value is found in the sequence. | 2 in my_list is True |
not in | Returns True if the value is not found in the sequence. | 4 not in my_list is True |
#!/usr/bin/env python3my_list = [1, 2, 3, 'a', 'b']name = "Python"
print(f"Is 3 in my_list? {3 in my_list}")print(f"Is 'c' not in my_list? {'c' not in my_list}")print(f"Is 'th' in name? {'th' in name}")Python Identity Operators
Section titled “Python Identity Operators”These operators compare the memory locations of two objects, checking if they are the exact same object (not just if they have the same value).
| Operator | Description | Example |
|---|---|---|
is | Returns True if both variables point to the same object. | x is y |
is not | Returns True if variables point to different objects. | x is not y |
Use is with caution. For immutable types like integers (small ones) and strings, Python might reuse objects, leading to is returning True unexpectedly. It’s primarily used to check against singletons like None.
#!/usr/bin/env python3a = [1, 2, 3]b = [1, 2, 3]c = a
print(f"a == b: {a == b}") # True (Values are equal)print(f"a is b: {a is b}") # False (Different objects in memory)print(f"a == c: {a == c}") # True (Values are equal)print(f"a is c: {a is c}") # True (Point to the same object)
# Common use case for 'is'value = Noneif value is None: print("Value is None")
if value is not None: print("Value is not None")Python Bitwise Operators
Section titled “Python Bitwise Operators”These operators perform operations directly on the binary (bit) representation of integers. They are less common in general scripting but used in specific areas like low-level programming or data manipulation. Assume a = 60 (0011 1100) and b = 13 (0000 1101):
| Operator | Name | Description | Example (a=60, b=13) |
|---|---|---|---|
| & | Bitwise AND | Sets each bit to 1 if both corresponding bits are 1. | a & b is 12 (0000 1100) |
| | | Bitwise OR | Sets each bit to 1 if at least one corresponding bit is 1. | a | b is 61 (0011 1101) |
| ^ | Bitwise XOR | Sets each bit to 1 if only one corresponding bit is 1. | a ^ b is 49 (0011 0001) |
| ~ | Bitwise NOT (Complement) | Inverts all bits (0 becomes 1, 1 becomes 0). Result depends on signed representation. | ~a is -61 |
| << | Left Shift | Shifts bits left, filling with zeros (multiplies by 2^n). | a << 2 is 240 (1111 0000) |
| >> | Right Shift | Shifts bits right (divides by 2^n, discarding remainder). | a >> 2 is 15 (0000 1111) |
You can use the built-in bin() function to see the binary representation:
#!/usr/bin/env python3a = 60b = 13print(f"a = {a} ({bin(a)}), b = {b} ({bin(b)})")print(f"a & b = {a & b} ({bin(a & b)})")print(f"a | b = {a | b} ({bin(a | b)})")print(f"a ^ b = {a ^ b} ({bin(a ^ b)})")print(f"~a = {~a} ({bin(~a)}) # Note: Two's complement")print(f"a << 2 = {a << 2} ({bin(a << 2)})")print(f"a >> 2 = {a >> 2} ({bin(a >> 2)})")Python Operators Precedence
Section titled “Python Operators Precedence”When an expression contains multiple operators, Python follows a specific order of precedence to determine which operations are performed first. Parentheses () can be used to override this order.
The following table lists operators from highest precedence (executed first) to lowest:
| Precedence | Operator | Description |
|---|---|---|
| Highest | () | Parentheses |
** | Exponentiation | |
+x, -x, ~x | Unary plus, minus, bitwise NOT | |
*, /, //, % | Multiplication, division, floor division, modulus | |
+, - | Addition, subtraction | |
<<, >> | Bitwise shifts | |
& | Bitwise AND | |
^ | Bitwise XOR | |
| | Bitwise OR | |
in, not in, is, is not, <, <=, >, >=, !=, == | Comparisons, Membership, Identity | |
not x | Logical NOT | |
and | Logical AND | |
| Lowest | or | Logical OR |
Example:
#!/usr/bin/env python3result = 5 + 3 * 2 # Multiplication (*) has higher precedence than Addition (+)print(f"5 + 3 * 2 = {result}") # Output: 11
result = (5 + 3) * 2 # Parentheses override precedenceprint(f"(5 + 3) * 2 = {result}") # Output: 16
result = 10 / 2 + 3 # Division (/) has higher precedence than Addition (+)print(f"10 / 2 + 3 = {result}") # Output: 8.0