Operators are special symbols that perform computations on operands. Python categorizes operators into arithmetic, comparison, logical, bitwise, assignment, membership, and identity operators.
flowchart TD
A["Highest Precedence"] --> B["Parentheses ()"]
B --> C["Exponentiation **"]
C --> D["Unary Operators +x, -x, ~x"]
D --> E["Multiplicative *, /, //, %"]
E --> F["Additive +, -"]
F --> G["Bitwise Shifts <<, >>"]
G --> H["Bitwise AND &, XOR ^, OR |"]
H --> I["Comparison & Membership ==, !=, in, is"]
I --> J["Logical NOT, AND, OR"]
J --> K["Lowest Precedence: Assignment =, +=, -="]
from typing import List
def demonstrate_operators() -> None:
# Arithmetic & Floor Division
total_items = 27
batch_size = 5
full_batches = total_items // batch_size # 5
remainder = total_items % batch_size # 2
print(f"Batches: {full_batches}, Remainder: {remainder}")
# Bitwise Operations (Flags)
READ_PERMISSION = 1 << 0 # 1 (0001)
WRITE_PERMISSION = 1 << 1 # 2 (0010)
EXEC_PERMISSION = 1 << 2 # 4 (0100)
user_permissions = READ_PERMISSION | WRITE_PERMISSION # 3 (0011)
has_write = bool(user_permissions & WRITE_PERMISSION)
has_exec = bool(user_permissions & EXEC_PERMISSION)
print(f"Permissions Flag: {user_permissions} | Write: {has_write} | Exec: {has_exec}")
# Membership & Identity Operators
numbers: List[int] = [10, 20, 30]
print(f"20 in numbers: {20 in numbers}")
print(f"40 not in numbers: {40 not in numbers}")
if __name__ == "__main__":
demonstrate_operators()
-3 ** 2 evaluates to -9 because ** binds tighter than unary -. Use (-3) ** 2 for 9.10 <= x <= 50, which evaluates cleanly as (10 <= x) and (x <= 50).:=): Python 3.8+ introduced assignment expressions if (n := len(data)) > 10: to assign and evaluate in a single statement.Write a function is_bit_set(number: int, bit_position: int) -> bool using the bitwise AND (&) and left shift (<<) operators.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With