Operators in Python
Operators are symbols that perform operations on variables and values. They are the building blocks of expressions and allow you to manipulate data, make comparisons, and control program logic. Python provides a rich set of operators for various programming needs.
What are Operators?
Python operators are categorized by their function: arithmetic for mathematical operations, comparison for value relationships, logical for boolean operations, and more. Understanding operators is essential for building expressions and controlling program flow.
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values. Python provides all standard mathematical operations plus some special ones.
# Basic arithmetic operators
a = 15
b = 4
print(f"Addition: {a} + {b} = {a + b}") # 19
print(f"Subtraction: {a} - {b} = {a - b}") # 11
print(f"Multiplication: {a} * {b} = {a * b}") # 60
print(f"Division: {a} / {b} = {a / b}") # 3.75
print(f"Floor Division: {a} // {b} = {a // b}") # 3
print(f"Modulus: {a} % {b} = {a % b}") # 3
print(f"Exponentiation: {a} ** {b} = {a ** b}") # 50625
# Working with different number types
x = 10.5
y = 3
print(f"Float division: {x} / {y} = {x / y}") # 3.5
print(f"Floor division: {x} // {y} = {x // y}") # 3.0
# Useful modulus examples
print("Even or odd check:")
for num in [7, 8, 9, 10]:
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
# Modulus for cycling
for i in range(8):
day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][i % 7]
print(f"Day {i}: {day}")Comparison Operators
Comparison operators compare two values and return a boolean result (True or False). They're essential for making decisions in your programs.
# Comparison operators
a = 10
b = 5
c = 10
print(f"Equal: {a} == {c} is {a == c}") # True
print(f"Not equal: {a} != {b} is {a != b}") # True
print(f"Greater: {a} > {b} is {a > b}") # True
print(f"Less: {a} < {b} is {a < b}") # False
print(f"Greater/equal: {a} >= {c} is {a >= c}") # True
print(f"Less/equal: {b} <= {a} is {b <= a}") # True
# String comparisons (lexicographic order)
name1 = "Alice"
name2 = "Bob"
name3 = "alice"
print(f"'{name1}' < '{name2}': {name1 < name2}") # True
print(f"'{name1}' == '{name3}': {name1 == name3}") # False (case sensitive)
print(f"Case-insensitive: {name1.lower() == name3.lower()}") # True
# List comparisons
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [1, 2, 4]
print(f"Lists equal: {list1 == list2}") # True
print(f"Lists different: {list1 == list3}") # False
# Chained comparisons
x = 5
print(f"1 < {x} < 10: {1 < x < 10}") # True
print(f"0 <= {x} <= 3: {0 <= x <= 3}") # False
age = 25
print(f"Adult check: {18 <= age < 65}") # TrueLogical Operators
Logical operators combine boolean values or expressions. They're crucial for complex conditional statements and decision-making logic.
# Logical operators
x = 10
y = 5
z = 15
# AND operator - both conditions must be True
print(f"x > y and x < z: {x > y and x < z}") # True
print(f"x > y and x > z: {x > y and x > z}") # False
# OR operator - at least one condition must be True
print(f"x > y or x > z: {x > y or x > z}") # True
print(f"x < y or x > z: {x < y or x > z}") # False
# NOT operator - reverses the boolean value
print(f"not (x > y): {not (x > y)}") # False
print(f"not (x < y): {not (x < y)}") # True
# Practical examples
age = 25
income = 50000
has_job = True
# Loan eligibility check
eligible = age >= 18 and income >= 30000 and has_job
print(f"Loan eligible: {eligible}") # True
# Complex conditions
temperature = 75
sunny = True
weekend = False
# Good day for outdoor activity
good_day = (temperature > 70 and sunny) or weekend
print(f"Good day for outdoors: {good_day}") # True
# Short-circuit evaluation
def expensive_function():
print("Expensive function called!")
return True
# AND short-circuit: if first is False, second isn't evaluated
result1 = False and expensive_function() # Won't call function
print(f"Result 1: {result1}")
# OR short-circuit: if first is True, second isn't evaluated
result2 = True or expensive_function() # Won't call function
print(f"Result 2: {result2}")
# De Morgan's Laws
a = True
b = False
print(f"not (a and b) == (not a) or (not b): {not (a and b) == (not a) or (not b)}")
print(f"not (a or b) == (not a) and (not b): {not (a or b) == (not a) and (not b)}")Assignment Operators
Assignment operators assign values to variables. Python provides compound assignment operators that combine an operation with assignment for cleaner, more efficient code.
# Basic assignment
x = 10
print(f"x = {x}")
# Compound assignment operators
x += 5 # x = x + 5
print(f"After x += 5: {x}") # 15
x -= 3 # x = x - 3
print(f"After x -= 3: {x}") # 12
x *= 2 # x = x * 2
print(f"After x *= 2: {x}") # 24
x /= 4 # x = x / 4
print(f"After x /= 4: {x}") # 6.0
x //= 2 # x = x // 2
print(f"After x //= 2: {x}") # 3.0
x %= 2 # x = x % 2
print(f"After x %= 2: {x}") # 1.0
x **= 3 # x = x ** 3
print(f"After x **= 3: {x}") # 1.0
# String assignment operators
message = "Hello"
message += " World" # Concatenation
print(f"Message: {message}") # "Hello World"
text = "Python"
text *= 3 # Repetition
print(f"Repeated text: {text}") # "PythonPythonPython"
# List assignment operators
numbers = [1, 2, 3]
numbers += [4, 5] # Extend list
print(f"Extended list: {numbers}") # [1, 2, 3, 4, 5]
# Multiple assignment
a, b, c = 1, 2, 3
print(f"a={a}, b={b}, c={c}")
# Swapping variables
a, b = b, a
print(f"After swap: a={a}, b={b}")
# Unpacking assignment
coordinates = (10, 20)
x, y = coordinates
print(f"x={x}, y={y}")
# Assignment with different types
scores = [85, 92, 78, 96]
total = sum(scores)
average = total / len(scores)
print(f"Average score: {average:.1f}")Membership Operators
Membership operators test whether a value exists in a sequence (string, list, tuple, etc.). They're invaluable for checking data presence and validation.
# Membership operators: in and not in
# String membership
text = "Python programming"
print(f"'Python' in text: {'Python' in text}") # True
print(f"'Java' in text: {'Java' in text}") # False
print(f"'java' not in text: {'java' not in text}") # True
# List membership
fruits = ["apple", "banana", "cherry", "date"]
print(f"'banana' in fruits: {'banana' in fruits}") # True
print(f"'grape' in fruits: {'grape' in fruits}") # False
# Tuple membership
colors = ("red", "green", "blue")
user_color = "green"
if user_color in colors:
print(f"{user_color} is a valid color")
else:
print(f"{user_color} is not a valid color")
# Dictionary membership (checks keys by default)
student_grades = {"Alice": 95, "Bob": 87, "Charlie": 92}
print(f"'Alice' in grades: {'Alice' in student_grades}") # True
print(f"'David' in grades: {'David' in student_grades}") # False
# Check if value exists in dictionary values
print(f"95 in grades.values(): {95 in student_grades.values()}") # True
# Set membership (very fast for large collections)
valid_ids = {1001, 1002, 1003, 1004, 1005}
user_id = 1003
if user_id in valid_ids:
print(f"User ID {user_id} is valid")
# Practical examples
def validate_email(email):
"""Simple email validation using membership operators."""
required_chars = ["@", "."]
forbidden_chars = [" ", ",", ";"]
# Check for required characters
for char in required_chars:
if char not in email:
return False, f"Missing required character: {char}"
# Check for forbidden characters
for char in forbidden_chars:
if char in email:
return False, f"Contains forbidden character: {char}"
return True, "Email format appears valid"
# Test email validation
emails = ["user@example.com", "invalid.email", "user @test.com"]
for email in emails:
valid, message = validate_email(email)
print(f"{email}: {message}")
# Range membership
number = 15
if number in range(10, 20):
print(f"{number} is between 10 and 19")
# Substring search with position
text = "The quick brown fox jumps over the lazy dog"
if "quick" in text:
position = text.find("quick")
print(f"Found 'quick' at position {position}")Python's membership operators are incredibly efficient! For sets and dictionaries, the 'in' operator uses hash table lookups, making membership testing extremely fast even for millions of items.
Operator Precedence
Operator precedence determines the order in which operations are performed when multiple operators appear in an expression. Understanding precedence helps you write correct expressions and avoid bugs.
# Operator precedence examples
# Arithmetic operations follow mathematical rules
result1 = 2 + 3 * 4 # Multiplication first: 2 + 12 = 14
result2 = (2 + 3) * 4 # Parentheses first: 5 * 4 = 20
print(f"2 + 3 * 4 = {result1}")
print(f"(2 + 3) * 4 = {result2}")
# Exponentiation has higher precedence than multiplication
result3 = 2 * 3 ** 2 # Exponentiation first: 2 * 9 = 18
result4 = (2 * 3) ** 2 # Parentheses first: 6 ** 2 = 36
print(f"2 * 3 ** 2 = {result3}")
print(f"(2 * 3) ** 2 = {result4}")
# Comparison and logical operators
x, y, z = 5, 10, 15
# Comparisons before logical AND
result5 = x < y and y < z # (5 < 10) and (10 < 15) = True and True = True
print(f"x < y and y < z: {result5}")
# NOT has higher precedence than AND/OR
a, b = True, False
result6 = not a or b # (not True) or False = False or False = False
result7 = not (a or b) # not (True or False) = not True = False
print(f"not a or b: {result6}")
print(f"not (a or b): {result7}")
# Assignment has lowest precedence
x = y = 10
x += y * 2 # x = x + (y * 2) = 10 + 20 = 30
print(f"x after x += y * 2: {x}")
# Precedence order (highest to lowest):
# 1. Parentheses ()
# 2. Exponentiation **
# 3. Unary +, -, not
# 4. Multiplication *, Division /, Floor division //, Modulus %
# 5. Addition +, Subtraction -
# 6. Comparison ==, !=, <, >, <=, >=, in, not in
# 7. Logical NOT
# 8. Logical AND
# 9. Logical OR
# 10. Assignment =, +=, -=, etc.
# Complex expression breakdown
complex_expr = 2 + 3 * 4 > 10 and not False or 5 < 3
# Step by step:
# 1. 3 * 4 = 12
# 2. 2 + 12 = 14
# 3. 14 > 10 = True
# 4. not False = True
# 5. True and True = True
# 6. 5 < 3 = False
# 7. True or False = True
print(f"Complex expression result: {complex_expr}")
# Best practice: use parentheses for clarity
clear_expr = ((2 + (3 * 4)) > 10) and ((not False) or (5 < 3))
print(f"Same expression with parentheses: {clear_expr}")
# Practical example: form validation
age = 25
email = "user@example.com"
agreed_terms = True
# Without parentheses (potentially confusing)
valid1 = age >= 18 and "@" in email and "." in email or agreed_terms
# With parentheses (much clearer)
valid2 = (age >= 18) and ("@" in email) and ("." in email) and agreed_terms
print(f"Validation result: {valid2}")Understanding operators is fundamental to Python programming. They enable you to perform calculations, make comparisons, combine conditions, and manipulate data effectively. As you progress, you'll use operators constantly to build complex expressions and control program logic.