Dev In The Mountain Header
A Developer In The mountains having fun

Operators in Python

Operators are special symbols that perform operations on values and variables. They're the building blocks of expressions and are essential for performing calculations, comparisons, and logical operations in Python.

Types of Operators

Python provides several types of operators:

  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Logical Operators
  4. Assignment Operators
  5. Bitwise Operators
  6. Membership Operators
  7. Identity Operators

Arithmetic Operators

Perform mathematical calculations.

a = 10
b = 3

# Basic arithmetic
print(a + b)   # 13 - Addition
print(a - b)   # 7  - Subtraction
print(a * b)   # 30 - Multiplication
print(a / b)   # 3.333... - Division (always returns float)

# Additional operators
print(a // b)  # 3  - Floor division (integer division)
print(a % b)   # 1  - Modulus (remainder)
print(a ** b)  # 1000 - Exponentiation (10^3)

# Precedence (same as math)
result = 2 + 3 * 4  # 14 (not 20)
result = (2 + 3) * 4  # 20 (use parentheses to control order)

Practical Arithmetic Examples

# Calculate circle area
import math
radius = 5
area = math.pi * radius ** 2
print(f"Circle area: {area:.2f}")

# Convert temperature
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")

# Check if number is even
number = 42
is_even = (number % 2 == 0)
print(f"{number} is even: {is_even}")

# Split bill
total = 150.00
people = 4
per_person = total / people
print(f"Each person pays: ${per_person:.2f}")

Comparison Operators

Compare two values and return True or False.

a = 10
b = 5

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

# Chaining comparisons
x = 5
print(1 < x < 10)  # True (x is between 1 and 10)
print(0 <= x <= 100)  # True

# Comparing strings (lexicographic order)
print("apple" < "banana")  # True
print("ABC" < "abc")  # True (uppercase < lowercase)

Logical Operators

Combine conditional statements.

# and, or, not
age = 25
has_license = True
has_insurance = False

# and - both must be True
can_drive = age >= 18 and has_license
print(f"Can drive: {can_drive}")  # True

# or - at least one must be True
needs_action = has_license or has_insurance
print(f"Has docs: {needs_action}")  # True

# not - negates the condition
print(not has_insurance)  # True

# Complex conditions
can_rent_car = age >= 25 and has_license and has_insurance
print(f"Can rent car: {can_rent_car}")  # False

# Short-circuit evaluation
# and stops at first False
# or stops at first True
result = False and expensive_function()  # expensive_function not called
result = True or expensive_function()  # expensive_function not called

Truth Tables

# AND truth table
print(True and True)    # True
print(True and False)   # False
print(False and True)   # False
print(False and False)  # False

# OR truth table
print(True or True)     # True
print(True or False)    # True
print(False or True)    # True
print(False or False)   # False

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

Assignment Operators

Assign values to variables.

# Basic assignment
x = 10

# Augmented assignment
x += 5   # x = x + 5 (now 15)
x -= 3   # x = x - 3 (now 12)
x *= 2   # x = x * 2 (now 24)
x /= 4   # x = x / 4 (now 6.0)
x //= 2  # x = x // 2 (now 3.0)
x %= 2   # x = x % 2 (now 1.0)
x **= 3  # x = x ** 3 (now 1.0)

# Multiple assignment
a = b = c = 0
print(a, b, c)  # 0 0 0

# Tuple unpacking
x, y, z = 1, 2, 3
print(x, y, z)  # 1 2 3

# Swap variables
a, b = 10, 20
a, b = b, a  # Swap
print(a, b)  # 20 10

Membership Operators

Test if a value is in a sequence.

# in and not in
fruits = ['apple', 'banana', 'cherry']

print('apple' in fruits)      # True
print('orange' in fruits)     # False
print('grape' not in fruits)  # True

# Works with strings
text = "Python Programming"
print('Py' in text)       # True
print('Java' not in text) # True

# Works with dictionaries (checks keys)
person = {'name': 'Alice', 'age': 25}
print('name' in person)   # True
print('email' in person)  # False

# Works with sets
numbers = {1, 2, 3, 4, 5}
print(3 in numbers)  # True

Identity Operators

Compare object identity (memory location).

# is and is not
a = [1, 2, 3]
b = [1, 2, 3]
c = a

# == checks value equality
print(a == b)  # True (same values)

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

# With immutable objects (strings, numbers)
x = 10
y = 10
print(x is y)  # True (Python caches small integers)

# None comparison (always use 'is')
value = None
print(value is None)      # Correct
print(value == None)      # Works but not preferred

# is not
print(a is not b)  # True

Bitwise Operators

Operate on binary representations.

# Work at bit level
a = 10  # 1010 in binary
b = 4   # 0100 in binary

print(a & b)   # 0  - AND: 0000
print(a | b)   # 14 - OR: 1110
print(a ^ b)   # 14 - XOR: 1110
print(~a)      # -11 - NOT (two's complement)
print(a << 1)  # 20 - Left shift: 10100
print(a >> 1)  # 5  - Right shift: 0101

# Practical use: flags
READ = 4    # 100
WRITE = 2   # 010
EXECUTE = 1 # 001

permissions = READ | WRITE  # Set read and write
print(permissions & READ)   # Check if readable (non-zero = True)

Operator Precedence

Order in which operators are evaluated.

# Precedence from highest to lowest:
# 1. ()  - Parentheses
# 2. **  - Exponentiation
# 3. *, /, //, %  - Multiplication, Division
# 4. +, -  - Addition, Subtraction
# 5. <, <=, >, >=, ==, !=  - Comparison
# 6. not  - Logical NOT
# 7. and  - Logical AND
# 8. or   - Logical OR

# Examples
result = 2 + 3 * 4  # 14 (not 20)
result = 2 ** 3 ** 2  # 512 (2^9, not 8^2)
result = 10 - 5 - 2  # 3 (left to right)

# Use parentheses for clarity
result = (2 + 3) * 4  # 20
result = 10 > 5 and 20 < 30  # True

# Complex expression
result = 5 + 3 * 2 ** 2 - 4 / 2
# = 5 + 3 * 4 - 2
# = 5 + 12 - 2
# = 15

Practical Examples

Example 1: Grade Calculator

# Calculate final grade
homework = 85
midterm = 78
final = 92

# Weighted average
grade = homework * 0.3 + midterm * 0.3 + final * 0.4
print(f"Final grade: {grade:.1f}")

# Letter grade
if grade >= 90:
    letter = 'A'
elif grade >= 80:
    letter = 'B'
elif grade >= 70:
    letter = 'C'
elif grade >= 60:
    letter = 'D'
else:
    letter = 'F'

print(f"Letter grade: {letter}")

Example 2: Age Validator

def validate_age(age):
    """Validate age with multiple conditions"""
    # Check type and range
    if not isinstance(age, int):
        return False, "Age must be an integer"
    
    if age < 0 or age > 120:
        return False, "Age must be between 0 and 120"
    
    # Categorize
    if age < 13:
        category = "child"
    elif 13 <= age < 20:
        category = "teenager"
    elif 20 <= age < 65:
        category = "adult"
    else:
        category = "senior"
    
    return True, f"Valid {category}"

# Test
print(validate_age(25))    # (True, 'Valid adult')
print(validate_age(-5))    # (False, 'Age must be between 0 and 120')
print(validate_age("25"))  # (False, 'Age must be an integer')

Example 3: Price Calculator

def calculate_price(base_price, quantity, discount_percent=0):
    """Calculate final price with discount"""
    subtotal = base_price * quantity
    discount = subtotal * (discount_percent / 100)
    tax_rate = 0.08
    tax = (subtotal - discount) * tax_rate
    total = subtotal - discount + tax
    
    return {
        'subtotal': subtotal,
        'discount': discount,
        'tax': tax,
        'total': total
    }

# Test
result = calculate_price(29.99, 3, 10)
print(f"Subtotal: ${result['subtotal']:.2f}")
print(f"Discount: ${result['discount']:.2f}")
print(f"Tax: ${result['tax']:.2f}")
print(f"Total: ${result['total']:.2f}")

Example 4: Login Validator

def validate_login(username, password, is_admin=False):
    """Validate login credentials"""
    # Check username
    valid_username = (len(username) >= 3 and 
                     username.isalnum())
    
    # Check password
    has_length = len(password) >= 8
    has_upper = any(c.isupper() for c in password)
    has_digit = any(c.isdigit() for c in password)
    valid_password = has_length and has_upper and has_digit
    
    # Final validation
    if not valid_username:
        return False, "Invalid username"
    
    if not valid_password:
        return False, "Password too weak"
    
    access_level = "Admin" if is_admin else "User"
    return True, f"Login successful ({access_level})"

# Test
print(validate_login("alice123", "Password1"))
print(validate_login("ab", "Password1"))
print(validate_login("alice123", "pass"))

Example 5: Number Range Checker

def check_ranges(number):
    """Check which ranges a number falls into"""
    results = []
    
    if 0 <= number <= 10:
        results.append("0-10")
    
    if 10 < number <= 50:
        results.append("11-50")
    
    if 50 < number <= 100:
        results.append("51-100")
    
    if number > 100:
        results.append("Over 100")
    
    if number % 2 == 0:
        results.append("Even")
    else:
        results.append("Odd")
    
    if number % 5 == 0:
        results.append("Multiple of 5")
    
    return results

# Test
print(f"25: {check_ranges(25)}")
print(f"50: {check_ranges(50)}")
print(f"120: {check_ranges(120)}")

Common Patterns

Pattern 1: Clamp Value to Range

def clamp(value, min_val, max_val):
    """Restrict value to range"""
    return max(min_val, min(value, max_val))

print(clamp(5, 0, 10))   # 5
print(clamp(-5, 0, 10))  # 0
print(clamp(15, 0, 10))  # 10

Pattern 2: Default Value

# Using or for default values
name = input("Enter name: ") or "Anonymous"

# Better: explicit check
name = input("Enter name: ")
name = name if name else "Anonymous"

Pattern 3: Conditional Assignment

# Ternary operator
age = 25
status = "adult" if age >= 18 else "minor"

# Multiple conditions
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"

Common Mistakes

Mistake 1: Using = Instead of ==

# WRONG: Assignment instead of comparison
x = 5
if x = 10:  # SyntaxError
    print("x is 10")

# CORRECT
if x == 10:
    print("x is 10")

Mistake 2: Integer Division in Python 2 vs 3

# Python 3 (current)
print(5 / 2)   # 2.5 (float division)
print(5 // 2)  # 2 (integer division)

# Python 2 (legacy)
# 5 / 2 would give 2 (integer division)

Mistake 3: Logical Operator Confusion

# WRONG: Doesn't work as expected
x = 5
if x == 3 or 4:  # Always True!
    print("x is 3 or 4")

# CORRECT
if x == 3 or x == 4:
    print("x is 3 or 4")

# Or use 'in'
if x in [3, 4]:
    print("x is 3 or 4")

Practice Exercises

Exercise 1: BMI Calculator

Calculate Body Mass Index: BMI = weight(kg) / height(m)² Categorize: Underweight, Normal, Overweight, Obese

Exercise 2: Leap Year Checker

Determine if year is leap year Rules: Divisible by 4, except century years (must be divisible by 400)

Exercise 3: Discount Calculator

Apply tiered discounts based on total amount $0-$50: 0%, $50-$100: 10%, $100+: 20%

Sample Solutions

Exercise 1:

def calculate_bmi(weight, height):
    bmi = weight / (height ** 2)
    
    if bmi < 18.5:
        category = "Underweight"
    elif bmi < 25:
        category = "Normal"
    elif bmi < 30:
        category = "Overweight"
    else:
        category = "Obese"
    
    return round(bmi, 1), category

weight = 70  # kg
height = 1.75  # meters
bmi, category = calculate_bmi(weight, height)
print(f"BMI: {bmi} ({category})")

Exercise 2:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

# Test
for year in [2000, 2020, 2021, 2024, 1900]:
    print(f"{year}: {is_leap_year(year)}")

Key Takeaways

  • Arithmetic operators: +, -, *, /, //, %, **
  • Comparison operators: ==, !=, >, <, >=, <=
  • Logical operators: and, or, not
  • Assignment operators: =, +=, -=, *=, etc.
  • Membership: in, not in
  • Identity: is, is not
  • Operator precedence matters - use parentheses for clarity
  • == compares values, is compares identity
  • Augmented assignment (+=) is more concise

What's Next?


Operators are the foundation of all expressions in Python. Master them to write efficient, readable code!

More places to find me
Mental Health
follow me on Mastodon