Python Operators - Complete Guide

Arithmetic Operators

Basic Mathematical Operations

Python provides operators for all standard mathematical operations. These operators work on numeric data types (integers, floats) and in some cases on other types like strings and lists.

# Basic arithmetic
x = 10
y = 3

print(x + y)    # Addition: 13
print(x - y)    # Subtraction: 7
print(x * y)    # Multiplication: 30
print(x / y)    # Division: 3.3333... (returns float)
print(x // y)   # Floor division: 3 (returns integer)
print(x % y)    # Modulus: 1 (remainder)
print(x ** y)   # Exponentiation: 1000 (x raised to power y)

Comparison Operators

Comparing Values

Comparison operators are used to compare values and return Boolean results (True or False). These operators form the foundation for decision-making in Python programs.

# Comparison operators
x = 10
y = 5

print(x == y)    # Equal to: False
print(x != y)    # Not equal to: True
print(x > y)     # Greater than: True
print(x < y)     # Less than: False
print(x >= y)    # Greater than or equal to: True
print(x <= y)    # Less than or equal to: False

# Chained comparisons
age = 25
print(18 <= age < 65)  # Check if age is between 18 and 65: True

Assignment Operators

Efficient Variable Updates

Assignment operators combine an arithmetic operation with assignment, providing a concise way to update variables. They're both more readable and more efficient than writing the operation separately.

# Basic assignment
x = 10

# Combined operators
x += 5      # Same as: x = x + 5, Now x is 15
x -= 3      # Same as: x = x - 3, Now x is 12
x *= 2      # Same as: x = x * 2, Now x is 24
x /= 6      # Same as: x = x / 6, Now x is 4.0 (note: becomes float)
x //= 2     # Same as: x = x // 2, Now x is 2.0
x **= 3     # Same as: x = x ** 3, Now x is 8.0
x %= 3      # Same as: x = x % 3, Now x is 2.0

# Works with strings too
message = "Hello"
message += " World"  # message becomes "Hello World"

Logical Operators

Combining Conditions

Logical operators allow you to combine multiple conditions to create complex expressions. Python uses the keywords and, or, and not instead of symbols used in some other languages.

# Logical operators
x = 10
y = 5

# and - True if both conditions are True
print(x > 5 and y < 10)    # True (both conditions are True)
print(x < 5 and y < 10)    # False (first condition is False)

# or - True if at least one condition is True
print(x > 5 or y > 10)     # True (first condition is True)
print(x < 5 or y > 10)     # False (both conditions are False)

# not - Inverts the boolean value
print(not x > 5)           # False (inverts True to False)
print(not x < 5)           # True (inverts False to True)

# Short-circuit evaluation
result = x > 0 and (x / 0)  # Would cause ZeroDivisionError, but second part is never evaluated

Bitwise Operators

Working with Binary Representations

Bitwise operators manipulate individual bits in integers. They're useful for working with flags, binary data, hardware interaction, and certain optimization techniques.

# Bitwise operators
a = 60    # Binary: 0011 1100
b = 13    # Binary: 0000 1101

# & (AND) - Sets bit to 1 if both bits are 1
print(a & b)       # 12 (Binary: 0000 1100)

# | (OR) - Sets bit to 1 if either bit is 1
print(a | b)       # 61 (Binary: 0011 1101)

# ^ (XOR) - Sets bit to 1 if only one bit is 1
print(a ^ b)       # 49 (Binary: 0011 0001)

# ~ (NOT) - Inverts all bits
print(~a)          # -61 (Binary: 1100 0011 with 2's complement)

# << (Left Shift) - Shifts bits left by specified number
print(a << 2)      # 240 (Binary: 1111 0000)

# >> (Right Shift) - Shifts bits right by specified number
print(a >> 2)      # 15 (Binary: 0000 1111)

# Practical example: Binary flags
READ = 1        # 0001
WRITE = 2       # 0010
EXECUTE = 4     # 0100

# Grant read and write permissions
permissions = READ | WRITE    # 3 (0011)

# Check if write permission exists
has_write = permissions & WRITE  # 2 (non-zero means True)

Identity and Membership Operators

Object Identity and Collection Membership

Identity operators check if two variables reference the same object in memory, while membership operators test if a value exists within a sequence (like a list, tuple, or string).

# Identity operators: is, is not
x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(x is z)      # True (x and z reference the same object)
print(x is y)      # False (x and y are equal but different objects)
print(x is not y)  # True (x and y are different objects)

# Comparing with None should always use 'is'
value = None
print(value is None)       # True (correct way)
print(value == None)       # True (works but not recommended)

# Membership operators: in, not in
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)        # True
print("mango" in fruits)        # False
print("mango" not in fruits)    # True

# Works with strings too
message = "Hello, World!"
print("World" in message)       # True
print("Python" in message)      # False

# And with dictionaries (checks keys)
person = {"name": "Alice", "age": 25}
print("name" in person)         # True
print("Alice" in person)        # False (not a key)
print("Alice" in person.values()) # True (in values)

Operator Precedence

Understanding Order of Operations

When expressions contain multiple operators, Python follows a specific order of operations to determine which operations are performed first. Knowing this precedence is essential for writing and debugging complex expressions.

Precedence Operator Description
1 ** Exponentiation
2 +x, -x, ~x Unary plus, minus, bitwise NOT
3 *, /, //, % Multiplication, division, floor division, modulus
4 +, - Addition, subtraction
5 >>, << Bitwise shifts
6 & Bitwise AND
7 ^ Bitwise XOR
8 | Bitwise OR
9 ==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, identity, membership
10 not Logical NOT
11 and Logical AND
12 or Logical OR
# Operator precedence examples
result1 = 10 + 3 * 2       # 16 (not 26) - multiplication before addition
result2 = (10 + 3) * 2     # 26 - parentheses override precedence

# Complex example
x = 5
y = 10
z = 2
result3 = x + y * z / (x - 3)   # 25.0 (evaluated as: 5 + ((10 * 2) / (5 - 3)))

# Logical operators precedence
result4 = True or False and False  # True (and has higher precedence than or)
result5 = (True or False) and False # False (parentheses change the order)

Special Operator Behaviors

Non-Standard Uses of Operators

Python operators can behave differently depending on the data types they operate on. Understanding these behaviors helps write more pythonic and expressive code.

# String multiplication
print("Hello" * 3)    # HelloHelloHello

# List multiplication
print([1, 2] * 3)     # [1, 2, 1, 2, 1, 2]

# String concatenation with +
print("Hello" + " " + "World")  # Hello World

# List concatenation with +
print([1, 2] + [3, 4])          # [1, 2, 3, 4]

# in with strings checks for substring
print("py" in "python")         # True

# Ternary operator (conditional expression)
age = 20
status = "adult" if age >= 18 else "minor"  # "adult"

# The 'walrus' operator := (Python 3.8+)
numbers = [1, 2, 3, 4, 5]
if (n := len(numbers)) > 3:
    print(f"List is long ({n} elements)")  # Assigns and tests in one step

Practice Exercises

Test Your Understanding

Try these exercises to reinforce your knowledge of Python operators.

Exercise 1: Predict the Output

# What will the following expressions evaluate to?
print(5 + 3 * 2)
print(5 > 3 and 10 < 20)
print(not True or False)
print(3 in [1, 2, 3, 4] and 5 not in [1, 2, 3, 4])
print(10 * "a" + 5 * "b")

Exercise 2: Fix the Expressions

# Each of these expressions has an error. Fix them:
# print(10 +* 5)
# print(True and False or)
# print(5 < > 3)
# print(10 = 10)
# print(5 in in [1, 2, 3, 4, 5])