Operators are the “action words” of Python. If variables and values are the data you store, operators are the instructions that tell Python what to do with that data—add it, compare it, check membership, and more.
This chapter will walk you through the most commonly used operators in Python, with small examples you can try immediately. Each example is followed by a clear explanation of what the code does, why the result is what it is, and common follow-ups you may want to try.
Arithmetic Operators
Arithmetic operators perform math on numbers. You’ve already seen + for addition; Python also provides subtraction, multiplication, division, and a few operators that are especially useful in programming.
Addition and subtraction (+, -)
Addition and subtraction behave as you’d expect:
print(10 + 5) # 15
print(10 - 5) # 5Explanation:
10 + 5evaluates the sum of the two integers and prints15. Python adds numeric literals in the same way you would on paper.10 - 5subtracts the second operand from the first and prints5.
Why this matters: These simple operators are the foundation for all numeric calculations in code. Try replacing the literals with variables or expressions (e.g., a + b * c) to see operator precedence in action.
Multiplication (*)
The multiplication operator is an asterisk *.
print(6 * 7) # 42Explanation:
6 * 7multiplies the two numbers and prints42. When one or both operands are floats (e.g.,6.0 * 7), the result will be a float.
Try this: Multiply variables, or use multiplication with floats to observe type changes.
Exponentiation (**)
Exponentiation raises a number to a power using **.
print(5 ** 2) # 25
print(2 ** 5) # 32Explanation:
5 ** 2computes 5 to the power of 2 and prints25.2 ** 5computes 2 to the power of 5 and prints32.
Context: Exponentiation is useful for calculations involving growth, bit shifts when powers of two are relevant, and mathematical formulas.
Division (/) returns a float
Division uses a forward slash /. In Python, regular division returns a floating-point number (a decimal), even when the result looks like a whole number.
print(20 / 5) # 4.0
print(20 / 6) # 3.3333333333333335Explanation:
20 / 5mathematically equals4, but Python prints4.0because/always yields a float.20 / 6results in a non-terminating decimal which Python prints as a floating-point approximation3.3333333333333335.
Why floats by default: Returning a float avoids accidentally losing fractional information. If you specifically need an integer quotient, use floor division //.
Floor division (//) for “whole number” division
Sometimes you want the quotient without the decimal part. That’s what floor division // does.
print(20 // 6) # 3
print(21 // 6) # 3Explanation:
20 // 6divides 20 by 6 and drops the fractional part, giving3.21 // 6similarly gives3because21/6is3.5and floor division truncates toward negative infinity (so it gives3).
Important nuance with negatives: For negative results, // behaves differently than simple truncation: -7 // 3 yields -3, not -2. Test negative cases to understand this fully.
Modulus (%) for the remainder
The modulus operator % gives the remainder after division.
print(20 % 6) # 2Explanation:
20 % 6computes the remainder when 20 is divided by 6. Since6 * 3 = 18and20 - 18 = 2, the modulus is2.
Common uses:
- Determining even/odd numbers:
number % 2 == 0checks for evenness. - Scheduling or cycling through indices:
i % ngives a repeating sequence0..n-1.
number = 14
print(number % 2 == 0) # True
for i in range(1, 11):
if i % 3 == 0:
print(i, "is divisible by 3")Explanation of the loop:
range(1, 11)produces numbers 1 through 10.i % 3 == 0checks whetherileaves no remainder when divided by 3; theprintexecutes only for those values.
[ Output showing modulus-based checks]
Operators with Strings
Operators aren’t limited to numbers. Python also supports a couple of useful operations on strings.
String concatenation with +
Using + with strings joins them together.
first = "Hello"
second = "World"
print(first + " " + second) # Hello WorldExplanation:
first + " " + secondconcatenates three strings: thefirstvariable, a single space, and thesecondvariable, producing the combined stringHello World.
Type rule reminder: + for strings requires both operands to be strings. Combining a string and a number directly raises a TypeError.
# print("Age: " + 25) # TypeError
print("Age: " + str(25)) # Age: 25Why str() or f-strings: Converting non-string types with str() or using f-strings (f"Age: {age}") is preferable because it’s readable and avoids type errors.
String repetition with *
Multiplying a string by a number repeats it.
print("Hi! " * 4) # Hi! Hi! Hi! Hi!Explanation:
- The
*operator for strings duplicates the string the specified number of times and concatenates the results. Here,"Hi! " * 4creates a single string withHi!repeated 4 times.
Use cases: Building simple separators, creating test data, or drawing ASCII art lines.
Comparison Operators
Comparison operators evaluate two values and return a Boolean: True or False.
Equality and inequality (==, !=)
== checks whether two values are equal.
print(True == True) # True
print(10 == 10) # True
print(10 == 11) # False!= checks whether two values are not equal.
print(10 != 11) # TrueExplanation:
==returnsTruewhen the values compared are equivalent in value. For built-in types this behavior is predictable, but for custom objects the class may define its own equality logic.!=is simply the logical inverse of==and is often used when you want to exclude a certain value.
Less-than and greater-than (<, <=, >, >=)
These operators compare numeric values (and also work with strings in alphabetic order, though you’ll use them most often with numbers).
print(4 < 5) # True
print(5 <= 5) # True
print(5 > 2) # True
print(5 >= 2) # TrueExplanation:
- These comparisons evaluate relationships between values. For strings, Python compares lexicographically (based on character codes), which can be surprising if you mix uppercase and lowercase letters.
Practical tip: When comparing floating point numbers for equality, small rounding errors can occur. For sensitive comparisons, check whether values are within a small tolerance (e.g., abs(a-b) < 1e-9).
A common beginner mistake is confusing assignment (=) with comparison (==). Use = to store a value in a variable, and == to compare values.
[Example showing = vs == in code]
Logical Operators (and, or, not)
Logical operators combine or flip Boolean values. They read like plain English, which makes them easier to remember.
and
With and, both sides must be True for the whole expression to be True.
print(True and True) # True
print(True and False) # FalseExplanation:
True and TruereturnsTruebecause both operands evaluate toTrue.True and FalsereturnsFalsebecause one operand isFalse.
or
With or, at least one side must be True.
print(True or False) # True
print(False or False) # FalseExplanation:
True or FalseisTruebecause one of the operands isTrue.False or FalseisFalsebecause neither operand isTrue.
not
not flips a Boolean value.
print(not True) # False
print(not False) # TruePractical note — short-circuit evaluation:
- Python evaluates
andandorwith short-circuiting. Forand, if the left operand is falsey, Python skips evaluating the right side because the expression cannot beTrue. Foror, if the left operand is truthy, Python skips the right side. Use this to write concise defaults, but avoid placing expensive operations on the skipped side if you rely on them.
Example in conditions:
age = 20
has_id = True
if age >= 18 and has_id:
print("Allowed")
else:
print("Not allowed")Explanation:
- The
ifstatement runs theprint("Allowed")only if bothage >= 18andhas_idareTrue. This pattern appears frequently in access checks and validations.
Membership Operators (in, not in)
Membership operators check whether a value exists inside a sequence (like a list, tuple, set, or string). They also return True or False.
Checking membership in lists
numbers = [1, 2, 3, 4, 5]
print(1 in numbers) # True
print(10 in numbers) # False
print(10 not in numbers) # TrueExplanation:
1 in numbersscans the list and returnsTruebecause1is an element.10 in numbersisFalsebecause10does not appear.10 not in numbersis the inverse check and returnsTrue.
Checking membership in strings
You can also search inside strings.
text = "my pet cat"
print("cat" in text) # True
print("dog" in text) # FalseExplanation:
"cat" in textisTruebecause the sequence of charactersc-a-tappears in the string.- Be careful: substring matching is character-based, not word-based. For example,
"cat" in "catatonic"returnsTrue, which may be undesirable if you intended to check for whole words.
[ Membership checks with list and string]
Identity Operators (is, is not)
Identity operators check whether two variables refer to the same object in memory, not whether they merely have the same value.
This is different from ==.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (values are the same)
print(a is b) # False (different objects)Explanation:
a == breturnsTruebecause both lists have the same contents.a is breturnsFalsebecauseaandbpoint to different list objects in memory.
Common idiom: Use is when checking for None:
value = None
if value is None:
print("No value yet")This is the recommended way to check for the absence of a value.
Operator Precedence
When you combine operators, Python follows a precedence order (similar to math). Multiplication happens before addition, and parentheses can force an order.
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20Explanation:
- In
2 + 3 * 4, multiplication runs first (3 * 4 = 12) and then addition makes14. - With parentheses,
(2 + 3)is evaluated first, producing5, and then5 * 4 = 20.
Advice: Use parentheses liberally to document your intended evaluation order. It improves readability and reduces bugs.
Practice
Type these into your Python environment and predict the result before running them:
print(17 % 5)
print(9 // 2)
print("na" * 4 + " Batman!")
print(10 / 2)
print(5 <= 5)
print(True and not False)
print("py" in "python")
x = None
print(x is None)What to observe:
- For
17 % 5, identify the remainder. - For
9 // 2, notice how floor division discards fractional parts. - For the string operations, see how repetition and concatenation interact.
x is Nonedemonstrates a canonical identity check.
Summary
Operators are how you tell Python to work with your data. Arithmetic operators handle math (including helpful tools like % for remainders), strings can be joined and repeated using + and *, and comparison/logical/membership operators help you make decisions by producing True or False. Identity operators, especially is None, are a clean way to check for “no value.”
In the next chapters, you’ll use these operators constantly inside conditions, loops, and real programs—so it’s worth practicing until the results feel natural.
