Explain it simply
Explain it simply
An operator is a small symbol or keyword that tells Python to do something with values. + asks for addition, > asks for a comparison and and joins conditions. Think of the buttons on a calculator: each one performs one kind of job.
Python sorts its operators into six groups by job: doing arithmetic, comparing, combining logic, updating a variable, checking whether something is in a collection, and checking whether two names point to the same object. When one expression contains many operators, you also need to know which runs first.
Problem → Why → Solution
The problem: the average comes out wrong
You want the average of three exam scores, 80, 90 and 70, so you add them and divide by 3. The answer should be 80, but the program prints 193.33, which is higher than any single score. There is no error, so nothing tells you what went wrong.
math_score = 80
english_score = 90
science_score = 70
average = math_score + english_score + science_score / 3
print(round(average, 2)) # 193.33, not 80.0Why is it wrong?
Operators have precedence, a fixed order of priority. / binds tighter than +, so Python first computes science_score / 3 (23.33) and only then adds 80 and 90, exactly as in school maths. Wrapping the sum in parentheses, (math_score + english_score + science_score) / 3, makes the addition happen first.
Core concept: six operator groups and precedence
| Group | Operators | Result |
|---|---|---|
| Arithmetic | + - * / // % ** | A number |
| Comparison | == != > < >= <= | True / False |
| Logical | and or not | An operand, or a bool for not |
| Assignment | = += -= *= /= //= %= **= | Updates a variable |
| Membership | in not in | True / False |
| Identity | is is not | True / False |
Arithmetic operators produce a new number, while comparison, membership and identity operators produce True or False. Many operators change meaning with the type: + adds numbers but joins strings and lists. in searches a list for an element, a string for a substring, and a dictionary for a key.
An augmented assignment such as c += 3 is shorthand for c = c + 3. It is most common inside loops, as in total += price. Python has no ++ operator like C or JavaScript, so you write count += 1.
== and is are not the same. == asks whether two values are equal, while is asks whether two names refer to the very same object in memory. [1, 2] == [1, 2] is True, but the two lists were created separately, so is gives False. Use is only for checks against singletons, as in x is None.
From highest to lowest, precedence runs: **, then * / // %, then + -, then comparisons together with in and is, then not, and, and finally or. ** groups from the right, so 2 ** 3 ** 2 is 512, and -2 ** 2 is -4 because ** applies before the minus sign. Other operators on the same level are evaluated left to right.
- Parentheses first
- Then **, then * / // %
- Then + -, then comparisons
- Then not, and, or last
When in doubt, add parentheses: they guarantee the order and help whoever reads the code.
General pattern
result = (left + right) * factor # arithmetic, grouped
is_valid = low <= value <= high # comparison
ok = condition_a and not condition_b # logical
counter += step # same as counter = counter + step
found = item in collection # membership
missing = value is None # identityOne line per group. Parentheses override precedence, += updates the variable on the left, in tests membership and is tests whether two names refer to one object.
Example: all six operator groups
This example tests each group in its own section. The final section covers the identity operator (is), and you will see a case where == is True while is is False. The arithmetic and logical sections overlap with the Numbers and Booleans lessons on purpose, so this one file works as a cheat sheet for every group.
# ===== 1. Arithmetic Operators =====
x = 10
y = 3
print("===== Arithmetic =====")
print(f"x + y = {x + y}") # 13
print(f"x - y = {x - y}") # 7
print(f"x * y = {x * y}") # 30
print(f"x / y = {x / y}") # 3.3333333333333335
print(f"x // y = {x // y}") # 3 (Floor Division)
print(f"x % y = {x % y}") # 1 (Modulus)
print(f"x ** y = {x ** y}") # 1000 (Exponentiation)
# ===== 2. Comparison Operators =====
print("\n===== Comparison =====")
a = 5
b = 10
print(f"a == b: {a == b}") # False
print(f"a != b: {a != b}") # True
print(f"a > b: {a > b}") # False
print(f"a < b: {a < b}") # True
# ===== 3. Logical Operators =====
print("\n===== Logical =====")
print(f"True and False: {True and False}")
print(f"True or False: {True or False}")
print(f"not True: {not True}")
# ===== 4. Assignment Operators =====
print("\n===== Assignment =====")
c = 5
c += 3 # c = c + 3
print(f"c += 3: {c}") # 8
c *= 2 # c = c * 2
print(f"c *= 2: {c}") # 16
# ===== 5. Membership Operators =====
print("\n===== Membership =====")
fruits = ["apple", "banana"]
print(f"'apple' in fruits: {'apple' in fruits}")
print(f"'mango' not in fruits: {'mango' not in fruits}")
# ===== 6. Identity Operators =====
print("\n===== Identity =====")
list_a = [1, 2]
list_b = [1, 2]
list_c = list_a
print(f"list_a == list_b: {list_a == list_b}") # same contents
print(f"list_a is list_b: {list_a is list_b}") # different objects
print(f"list_a is list_c: {list_a is list_c}") # same objectCode breakdown
- Line 9
print(f"x / y = {x / y}") # 3.3333333333333335/ returns a float, and the float approximation shows up as the trailing 5. // returns the int 3 instead.
- Lines 33-34
c += 3 # c = c + 3c goes from 5 to 8, and the following c *= 2 turns 8 into 16; each augmented assignment builds on c's current value.
- Line 42
print(f"'mango' not in fruits: {'mango' not in fruits}")not in is the opposite of in. It gives the same result as not ('mango' in fruits) but reads more naturally.
- Line 49
print(f"list_a == list_b: {list_a == list_b}") # same contentsBoth lists hold the same elements, so == is True.
- Lines 50-51
print(f"list_a is list_c: {list_a is list_c}") # same objectlist_b was created separately, so list_a is list_b is False, whereas list_c = list_a creates no new object, only a second name, so is returns True.
===== Arithmetic =====
x + y = 13
x - y = 7
x * y = 30
x / y = 3.3333333333333335
x // y = 3
x % y = 1
x ** y = 1000
===== Comparison =====
a == b: False
a != b: True
a > b: False
a < b: True
===== Logical =====
True and False: False
True or False: True
not True: False
===== Assignment =====
c += 3: 8
c *= 2: 16
===== Membership =====
'apple' in fruits: True
'mango' not in fruits: True
===== Identity =====
list_a == list_b: True
list_a is list_b: False
list_a is list_c: TrueTesting precedence yourself
Trying precedence in a Python shell sticks better than memorising a table. Predict each result below before running it. Pay special attention to -2 ** 2 versus (-2) ** 2, and to 10 - 4 - 3, which is evaluated left to right: grouping from the right would give 9, but Python returns 3.
print(2 + 3 * 4) # 14 (* before +)
print((2 + 3) * 4) # 20 (parentheses first)
print(2 ** 3 ** 2) # 512 (** groups from the right)
print(-2 ** 2, (-2) ** 2) # -4 4
print(10 - 4 - 3) # 3 (left to right)
print(1 + 2 == 3 and not 5 < 4) # TrueIn real projects
Where this shows up in real projects
Most business logic mixes several operator groups. A shopping cart accumulates total += price * quantity and then decides on free shipping with if total >= 50 and country in FREE_SHIPPING_COUNTRIES:. Pagination finds the number of pages with page_count = (total_items + per_page - 1) // per_page.
Membership tests appear everywhere: blocklists, allowed file extensions, supported languages. As data grows, in on a list gets slower because it checks elements one by one, whereas a lookup in a set or dict stays fast regardless of size. And is None appears in every piece of code that checks whether a function actually returned a result. Long-running scripts use % for progress reports, as in if i % 1000 == 0: print(i), so the log shows one line per thousand records instead of one per record.
Common mistakes
Common mistakes
1. Computing an average without parentheses
a + b + c / 3 divides only c by 3. Write (a + b + c) / 3, or use sum(scores) / len(scores). Whenever a result looks odd, suspect precedence first.
2. Using is to compare values
if name is "admin": may appear to work sometimes, but whether Python shares string objects in memory is an implementation detail, and since Python 3.8 it also triggers a SyntaxWarning. Use == for values and keep is for None, True and False.
3. Writing ++ or =+
count++ is a SyntaxError. Worse is count =+ 1, which raises no error at all: it means count = +1, so count is stuck at 1. Write count += 1.
4. Using && and ||
People coming from other languages often type if a > 0 && b > 0: and get a SyntaxError. Python's logical operators are the English keywords and, or and not, and ! only appears as part of !=.
Best practices
Best practices
- Add parentheses to mixed expressions so the intent is obvious.
- Use x is None / x is not None, and == for every other comparison.
- Store large collections you test with in frequently as a set.
Mini challenge
Mini challenge: leap years and a checkout
Combine several operator groups to write a leap-year check and a checkout function that accepts a coupon.
- is_leap(year): divisible by 4, except centuries, unless divisible by 400 (use % with and/or)
- checkout(prices, coupon): add with +=, and apply *= 0.9 when coupon is not None and is in ("SAVE10", "WELCOME")
- Check and print 2024, 1900, 2000 and 2023
- Print both the correct average and the buggy one without parentheses
def is_leap(year: int) -> bool:
# TODO: one return line using %, ==, !=, and, or
...
def checkout(prices: list[float], coupon: str | None) -> float:
total = 0.0
# TODO: add every price with +=
# TODO: if coupon is not None and is a known code, apply 10% off with *=
return round(total, 2)
# TODO: print is_leap for 2024, 1900, 2000, 2023
cart = [12.5, 7.5, 30.0]
# TODO: print checkout(cart, None) and checkout(cart, "SAVE10")
# TODO: print the correct average and the buggy one (no parentheses)Expected: The program prints: 2024: leap=True 1900: leap=False 2000: leap=True 2023: leap=False No coupon: 50.0 SAVE10: 45.0 Average price: 16.67 Buggy average: 30.0
Show hint
The leap-year condition is year % 4 == 0 and (year % 100 != 0 or year % 400 == 0). Without parentheses around the or part, and would run first and the result would be wrong.
Show solution
def is_leap(year: int) -> bool:
"""Divisible by 4, except centuries, unless divisible by 400."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def checkout(prices: list[float], coupon: str | None) -> float:
total = 0.0
for price in prices:
total += price
if coupon is not None and coupon in ("SAVE10", "WELCOME"):
total *= 0.9
return round(total, 2)
for year in (2024, 1900, 2000, 2023):
print(f"{year}: leap={is_leap(year)}")
cart = [12.5, 7.5, 30.0]
print(f"No coupon: {checkout(cart, None)}")
print(f"SAVE10: {checkout(cart, 'SAVE10')}")
print(f"Average price: {sum(cart) / len(cart):.2f}")
print(f"Buggy average: {cart[0] + cart[1] + cart[2] / 3}")Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- The six operator groups are arithmetic, comparison, logical, assignment, membership and identity.
- Precedence runs **, * / // %, + -, comparisons, not, and, or, and parentheses override it all.
- += is shorthand for x = x + ..., and Python has no ++.
- == compares values, is compares identity; use is for None.
The Python Tutorial — Python Software Foundation