Operators and Expressions
Perform calculations and evaluate logic using Python arithmetic, comparison, logical, identity, and membership operators.
In types, you learned how Python classifies data into integers, floats, strings, and booleans. But data sitting passively in memory is not useful on its own. To build programs that solve problems, you need to calculate totals, compare choices, and evaluate conditions.
You do this using operators and expressions:
- Operator: A special symbol or keyword that represents an action (like
+,-,==, orand). - Operand: The values or variables the operator acts upon.
- Expression: Any combination of values, variables, and operators that evaluates down to a single result (e.g.,
10 * 5evaluates to50).
Python provides five main families of operators. Let’s master each one.
1. Arithmetic Operators
Arithmetic operators perform standard mathematical calculations:
| Operator | Name | Example | Result | Notes |
|---|---|---|---|---|
+ | Addition | 10 + 5 | 15 | Also concatenates strings ("a" + "b") |
- | Subtraction | 10 - 5 | 5 | |
* | Multiplication | 10 * 5 | 50 | Also repeats strings ("Ha" * 3 $\rightarrow$ "HaHaHa") |
/ | True Division | 10 / 4 | 2.5 | Always returns a float |
// | Floor Division | 10 // 4 | 2 | Rounds down to nearest whole number |
% | Modulo | 10 % 4 | 2 | Returns the remainder of division |
** | Exponentiation | 2 ** 3 | 8 | $2^3 = 2 \times 2 \times 2$ |
The Division Rule: / vs. //
One of Python’s greatest beginner-friendly features is that the standard division operator / always produces a float, even if the numbers divide evenly:
print(8 / 4) # 2.0 (float)
print(7 / 2) # 3.5 (float)
If you only want the whole integer quotient without any fractional decimals, use floor division (//):
print(7 // 2) # 3 (int)
print(10 // 3) # 3 (int)
The Modulo Operator (%): The Remainder Engine
The modulo operator (%) returns the leftover remainder after dividing:
print(17 % 5) # 2 (because 5 goes into 17 three times, leaving 2 left over)
Modulo has three essential real-world programming uses:
- Checking Even vs. Odd: If
x % 2 == 0, the number is even. Ifx % 2 != 0, it is odd. - Clock Arithmetic: Converting 27 hours into clock time (
27 % 24= 3 AM). - Cyclic Repetition: Rotating through players in a turn-based game (
turn % number_of_players).
2. Comparison (Relational) Operators
Comparison operators compare two values and always evaluate to a boolean (True or False):
| Operator | Meaning | Example | Evaluates To |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 10 > 20 | False |
< | Less than | 10 < 20 | True |
>= | Greater than or equal to | 15 >= 15 | True |
<= | Less than or equal to | 8 <= 5 | False |
current_temperature = 72
target_temperature = 68
is_too_warm = current_temperature > target_temperature
print("AC should activate:", is_too_warm) # True
CRITICAL WARNING:
=vs==
- Single equals (
=): Assignment. Used to store data into a variable (age = 25).- Double equals (
==): Comparison. Used to ask if two values are equal (age == 25). Confusing=and==is one of the most frequent beginner mistakes!
Python’s Secret Superpower: Chained Comparisons
In languages like JavaScript, C, or Java, checking if a number falls within a range requires awkward syntax: (x >= 10 && x <= 20).
In Python, you can write mathematical chained comparisons directly:
age = 24
# Elegant, clean, and perfectly readable:
if 18 <= age < 65:
print("Eligible for standard adult ticket.")
3. Logical Operators (and, or, not)
Logical operators allow you to combine multiple boolean expressions into sophisticated decision rules:
1. and (Both must be True)
Returns True only if both sides are True:
has_ticket = True
has_id = True
can_board = has_ticket and has_id
print(can_board) # True
2. or (At least one must be True)
Returns True if either side is True:
is_weekend = False
is_holiday = True
can_sleep_in = is_weekend or is_holiday
print(can_sleep_in) # True
3. not (Inverts truth value)
Flips True into False, and False into True:
is_raining = False
print(not is_raining) # True
Short-Circuit Evaluation
Python is smart: it evaluates logical statements from left to right and stops the instant the outcome is guaranteed:
- In
False and expensive_function(): Because the first part isFalse, the entire expression can never beTrue. Python skips executing the second part entirely! - In
True or expensive_function(): Because the first part isTrue, the entire expression is already guaranteed to beTrue. Python skips the second part!
4. Identity Operators (is vs ==)
Beginners often confuse is with ==. They do not mean the same thing:
==(Equality): Compares values (do the two objects contain the same data?).is(Identity): Compares memory address (are both variables pointing to the exact same object in RAM?).
list_a = [1, 2, 3]
list_b = [1, 2, 3]
# They hold the same values:
print(list_a == list_b) # True
# But they are two distinct lists created in different memory blocks:
print(list_a is list_b) # False
The Standard Rule for None
Whenever checking if a variable is None, always use is or is not, never ==:
# The professional Python standard:
response = None
if response is None:
print("No data received.")
if response is not None:
print("Data processed.")
5. Membership Operators (in and not in)
Membership operators test whether a specific item exists inside a sequence (like a text string or a collection):
# In strings:
email = "developer@python.org"
print("@" in email) # True
print(".gov" in email) # False
# In lists:
allowed_roles = ["admin", "editor", "moderator"]
user_role = "guest"
if user_role not in allowed_roles:
print("Access denied: insufficient privileges.")
6. Operator Precedence (Order of Operations)
When an expression contains multiple operators, Python follows standard mathematical rules of precedence (similar to PEMDAS):
- Parentheses:
( ... )(Always evaluated first) - Exponentiation:
** - Multiplication, Division, Remainder:
*,/,//,% - Addition, Subtraction:
+,- - Comparisons:
==,!=,<,>,<=,>= - Logical
not - Logical
and - Logical
or
Look at this calculation:
result = 10 + 2 * 5
print(result) # 20 (multiplication runs before addition!)
If you wanted addition to occur first, wrap it in parentheses:
result = (10 + 2) * 5
print(result) # 60
Engineering Best Practice: Do not make your teammates guess precedence rules for complex statements. Use parentheses liberally to make your intent crystal clear.
Summary Checklist
- True Division (
/): Always returns afloat. - Floor Division (
//): Rounds down to anint. - Modulo (
%): Yields the division remainder (great for even/odd checks). - Equality (
==): Compares values; distinct from assignment (=). - Chained Comparisons: Write
10 < x < 50naturally. - Identity (
is): Checks memory identity; always useis None. - Parentheses: When in doubt, wrap expressions in
()for clarity.
Now that you know how to operate on values, continue to type-casting to learn how to seamlessly convert data between strings, integers, floats, and booleans without triggering type errors.