By the end of this lesson, you will be able to use Python's core operators to perform calculations, make decisions, and manipulate data efficiently.
What it is
Operators are special symbols or keywords that tell the Python interpreter to perform specific mathematical or logical manipulations. They act on values (operands) to produce a new value. The main categories include arithmetic for math, comparison for checking relationships, logical for combining conditions, assignment for storing values, membership for checking existence in collections, and bitwise for low-level binary operations.
Why it matters
- Data Processing: Arithmetic operators allow you to calculate totals, averages, and transformations.
- Control Flow: Comparison and logical operators drive
ifstatements and loops, enabling decision-making. - Efficiency: Membership operators (
in) provide a clean way to check lists or strings without manual iteration. - State Management: Assignment operators update variables concisely, reducing code verbosity.
Syntax or steps
Python follows standard precedence rules: parentheses first, then exponentiation, multiplication/division, addition/subtraction, comparisons, and finally logical operators. Assignment happens last. For example, x += 1 is shorthand for x = x + 1.
Example
# Arithmetic
a = 10
b = 3
print(a + b) # Addition: 13
print(a % b) # Modulus (remainder): 1
print(a // b) # Floor Division: 3
# Comparison & Logical
x = 5
y = 10
is_greater = x > y # False
is_equal = x == 5 # True
combined = (x > 0) and (y < 20) # True
# Membership
fruits = ["apple", "banana"]
has_apple = "apple" in fruits # True
# Bitwise
binary_val = 5 & 3 # Binary 101 AND 011 results in 001 (1)
This snippet demonstrates how different operator types interact with basic data. Note that // performs integer division, discarding the remainder, while % returns only the remainder. The and keyword requires both sides to be true, whereas & operates on individual bits.
Common mistakes
- Confusing
=and==: Using a single equals sign inside anifstatement causes a syntax error because it attempts assignment rather than comparison. - Integer Division Expectations: In Python 3,
/always returns a float. Use//if you strictly need an integer result. - Misusing
isvs==:==checks value equality, whileischecks object identity (memory address). Use==for comparing numbers or strings. - Precedence Errors: Neglecting parentheses can lead to unexpected results when mixing arithmetic and bitwise operators. Always group complex expressions explicitly.
When to use it
| Operator Type | Use Case | Alternative/Note |
|---|---|---|
Arithmetic (+ - * /) | Mathematical calculations | Use math module for advanced functions like square roots. |
Logical (and or not) | Combining boolean conditions | Avoid using bitwise & | for booleans unless performance-critical. |
Membership (in) | Checking list/string contents | Faster and more readable than writing a loop. |
Practice
Guided Exercise: Write a script that takes two integers, calculates their sum and product, and prints whether the sum is greater than the product.
Challenge: Create a list of numbers [1, 2, 3, 4, 5]. Use membership operators to check if 3 is present, and use bitwise AND to find which numbers share the least significant bit with 1.
Hint: Remember thatnum & 1 checks if a number is odd.
Quick check
Question: What is the output of print(7 // 2)?
Answer: 3. The floor division operator rounds down to the nearest whole number.
Summary
Python operators provide the fundamental building blocks for computation and logic. Mastering the distinction between arithmetic, logical, and bitwise operations ensures your code is both correct and efficient. Always prioritize readability by using explicit parentheses when combining multiple operator types.