Skip to content

Operators ​

βž• Arithmetic Operators ​

Basic Arithmetic ​

python
a = 10
b = 3

print(a + b)    # 13 (Addition)
print(a - b)    # 7  (Subtraction)
print(a * b)    # 30 (Multiplication)
print(a / b)    # 3.333... (Division)
print(a // b)   # 3  (Floor Division)
print(a % b)    # 1  (Modulus - remainder)
print(a ** b)   # 1000 (Exponentiation)

Operator Precedence ​

python
# Follows mathematical order of operations
result = 2 + 3 * 4    # 14 (not 20)
result = (2 + 3) * 4  # 20 (parentheses first)

# Precedence order (highest to lowest):
# 1. Parentheses ()
# 2. Exponentiation **
# 3. Multiplication *, Division /, Floor Division //, Modulus %
# 4. Addition +, Subtraction -

πŸ” Comparison Operators ​

python
a = 10
b = 20

print(a == b)   # False (Equal to)
print(a != b)   # True  (Not equal to)
print(a < b)    # True  (Less than)
print(a > b)    # False (Greater than)
print(a <= b)   # True  (Less than or equal to)
print(a >= b)   # False (Greater than or equal to)

Comparing Different Types ​

python
# String comparison (lexicographic order)
print("apple" < "banana")  # True
print("Apple" < "apple")   # True (uppercase comes first)

# List comparison (element by element)
print([1, 2, 3] < [1, 2, 4])  # True
print([1, 2] < [1, 2, 3])     # True (shorter list is smaller)

πŸ”— Logical Operators ​

Basic Logical Operations ​

python
# AND operator
print(True and True)    # True
print(True and False)   # False
print(False and True)   # False
print(False and False)  # False

# OR operator
print(True or True)     # True
print(True or False)    # True
print(False or True)    # True
print(False or False)   # False

# NOT operator
print(not True)         # False
print(not False)        # True

Logical Operators with Conditions ​

python
age = 25
has_license = True
has_experience = False

# AND - all conditions must be true
if age >= 18 and has_license and has_experience:
    print("Can drive professionally")

# OR - at least one condition must be true
if age >= 21 or has_experience:
    print("Can apply for senior position")

# NOT - reverses the condition
if not has_experience:
    print("Needs training")

🎯 Assignment Operators ​

Basic Assignment ​

python
x = 10          # Simple assignment

Compound Assignment ​

python
x = 10

x += 5          # x = x + 5  β†’ x = 15
x -= 3          # x = x - 3  β†’ x = 12
x *= 2          # x = x * 2  β†’ x = 24
x /= 4          # x = x / 4  β†’ x = 6.0
x //= 2         # x = x // 2 β†’ x = 3.0
x %= 2          # x = x % 2  β†’ x = 1.0
x **= 3         # x = x ** 3 β†’ x = 1.0

Multiple Assignment ​

python
# Assign same value to multiple variables
a = b = c = 0

# Assign different values to multiple variables
x, y, z = 1, 2, 3

# Swap variables
a, b = b, a

🏷️ Identity Operators ​

python
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a is b)      # False (different objects)
print(a is c)      # True (same object)
print(a is not b)  # True (different objects)

# For small integers and strings, Python may reuse objects
x = 5
y = 5
print(x is y)      # True (Python optimizes small integers)

πŸ“‹ Membership Operators ​

python
# in operator
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)      # True
print("grape" in fruits)      # False

# not in operator
print("grape" not in fruits)  # True

# Works with strings too
text = "Hello World"
print("World" in text)        # True
print("world" in text)        # False (case sensitive)

# Works with dictionaries (checks keys)
person = {"name": "Alice", "age": 30}
print("name" in person)       # True
print("Alice" in person)      # False (checks keys, not values)

πŸ”’ Bitwise Operators ​

python
a = 60  # 111100 in binary
b = 13  # 001101 in binary

print(a & b)    # 12 (AND)     - 001100
print(a | b)    # 61 (OR)      - 111101
print(a ^ b)    # 49 (XOR)     - 110001
print(~a)       # -61 (NOT)    - inverts all bits
print(a << 2)   # 240 (Left shift by 2)
print(a >> 2)   # 15 (Right shift by 2)

πŸš€ Practice Examples ​

Example 1: Calculator ​

python
def calculator(a, b, operation):
    if operation == '+':
        return a + b
    elif operation == '-':
        return a - b
    elif operation == '*':
        return a * b
    elif operation == '/':
        return a / b if b != 0 else "Cannot divide by zero"
    elif operation == '**':
        return a ** b
    else:
        return "Invalid operation"

print(calculator(10, 3, '+'))   # 13
print(calculator(10, 3, '**'))  # 1000

Example 2: Grade Evaluator ​

python
def evaluate_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

# Using logical operators for additional conditions
def can_graduate(gpa, credits, thesis_completed):
    return gpa >= 2.0 and credits >= 120 and thesis_completed

print(evaluate_grade(85))  # B
print(can_graduate(3.5, 125, True))  # True

Example 3: Membership Check ​

python
# Check if user input is valid
valid_commands = ['start', 'stop', 'pause', 'resume', 'quit']
user_input = input("Enter command: ").lower()

if user_input in valid_commands:
    print(f"Executing: {user_input}")
else:
    print("Invalid command")
    print(f"Valid commands: {', '.join(valid_commands)}")

Example 4: Number Properties ​

python
def analyze_number(num):
    properties = []
    
    # Check if even or odd
    if num % 2 == 0:
        properties.append("even")
    else:
        properties.append("odd")
    
    # Check if positive, negative, or zero
    if num > 0:
        properties.append("positive")
    elif num < 0:
        properties.append("negative")
    else:
        properties.append("zero")
    
    # Check if perfect square
    if num >= 0 and int(num ** 0.5) ** 2 == num:
        properties.append("perfect square")
    
    return properties

print(analyze_number(16))   # ['even', 'positive', 'perfect square']
print(analyze_number(-5))   # ['odd', 'negative']

🎯 Key Takeaways ​

  • Arithmetic operators perform mathematical calculations
  • Comparison operators compare values and return boolean results
  • Logical operators combine boolean expressions
  • Assignment operators assign and modify variable values
  • Identity operators check if variables refer to the same object
  • Membership operators test if a value exists in a sequence
  • Bitwise operators work with binary representations
  • Operator precedence follows mathematical rules
  • Use parentheses to control evaluation order

Continue to: Control Flow β†’

Released under the MIT License.