Home / Journal

Python (Part 3): Operators

Python (Part 3): Operators

In Part 2 we learned how to store values in variables. Storing them is only half the story — the real work begins when you start doing things with those values. That's what operators are for: they let you calculate, compare, and combine data.

If you followed the PHP series, this covers the same ground — but Python has a couple of operators PHP doesn't, and it spells a few of them differently. Let me walk you through the ones you'll use every day.

Arithmetic Operators

The usual math, with one twist — Python has two kinds of division:

print(10 + 3)    # 13    addition
print(10 - 3)    # 7     subtraction
print(10 * 3)    # 30    multiplication
print(10 / 3)    # 3.3333333333333335   true division
print(10 // 3)   # 3     floor division (drops the fraction)
print(10 % 3)    # 1     modulus (the remainder)
print(2 ** 10)   # 1024  exponent (2 to the power of 10)

Two things here trip up newcomers:

  • / always gives a float. Even 10 / 2 is 5.0, not 5. When you want a whole number, use floor division //, which throws away the fractional part — so 10 // 3 is 3.
  • % is the modulus — the remainder of a division — and ** is exponentiation. Modulus is more useful than it looks: n % 2 is 0 for even numbers and 1 for odd, which is the usual way to test even or odd.

Note: with negatives, // rounds down (toward negative infinity), not toward zero — so -10 // 3 is -4, not -3. The modulus follows the divisor's sign too, so -10 % 3 is 2. You won't hit this often, but it's worth knowing it differs from simply chopping off the decimals.

Assignment Operators

You met the basic = in Part 2. Each arithmetic operator also has a shortcut form that updates a variable in place:

x = 10
x += 5    # same as x = x + 5   → 15
x -= 3    # → 12
x *= 2    # → 24
x //= 5   # → 4
x **= 2   # → 16

These work on text too — += appends to a string (this is where PHP used .=):

name = "Coders"
name += " Republic"    # → "Coders Republic"

No ++ or --

A quick heads-up if you're coming from PHP, JavaScript, or C: Python has no ++ or -- operators. Writing x++ is a syntax error. To add or subtract one, use the augmented form:

count = 5
count += 1    # 6   (instead of count++)
count -= 1    # 5   (instead of count--)

Comparison Operators

These compare two values and hand back a booleanTrue or False, capitalized as we saw in Part 2. You'll lean on these constantly once we reach conditions:

print(5 == 5)     # True    equal
print(5 != 3)     # True    not equal
print(5 > 3)      # True
print(5 <= 5)     # True
print(5 == "5")   # False   different types are NOT equal

If you came from PHP, look at that last line. PHP's == would call 5 and "5" equal, and PHP adds a separate === for strict checks. **Python keeps it simple — there's only one ==, and it does not ignore types.** The number 5 and the string "5" are never equal, so there's no === to learn.

Python also lets you chain comparisons the way math does:

age = 25
print(18 <= age < 65)    # True  — reads like "18 ≤ age < 65"

That's cleaner than writing age >= 18 and age < 65.

Logical Operators

To combine several true/false tests, Python uses words, not symbols — and, or, and not (where PHP used &&, ||, and !):

age = 25
print(age > 18 and age < 65)    # True    both must be true
print(age < 18 or age > 65)     # False   at least one must be true
print(not age > 18)             # False   flips the result
  • and — true only if both sides are true.
  • or — true if either side is true.
  • not — flips true to false and back.

Membership and Identity

Two more that are very Pythonic and worth meeting now.

in checks whether a value appears inside a string or a list — it reads like plain English:

print("a" in "cat")       # True
print(3 in [1, 2, 3])     # True
print("z" not in "cat")   # True

is checks identity — whether two names point to the exact same object. Day to day, you'll mostly use it to test for None, Python's "no value" from Part 2:

result = None
print(result is None)    # True

Rule of thumb: use == to compare values, and is to check against None. (There's a deeper distinction between the two, but "use is for None" covers you for now.)

String Operators

We can reuse two of the arithmetic symbols on text:

first = "Coders"
last = "Republic"
print(first + " " + last)    # Coders Republic   (+ joins)
print("ab" * 3)              # ababab            (* repeats)

+ concatenates and * repeats — a quick way to, say, print a divider with "-" * 40.

A quick note on order

Like in math, operators have an order of precedence: ** runs first, then * / // %, then + -, then the comparisons, then and / or. When in doubt, reach for parentheses — they make your intent obvious and your code easier to read:

print(2 + 3 * 4)      # 14   (multiplication first)
print((2 + 3) * 4)    # 20   (parentheses first)

Note: ** is right-associative, so 2 ** 3 ** 2 means 2 ** (3 ** 2) = 512, not 64 — another reason to add parentheses when it matters.

To Be Continued…

You can now do arithmetic, compare values, and combine conditions — and you've seen where Python parts ways with PHP: two kinds of division, word-based logic, no ++, and a == that respects types. In Part 4 we'll put all of this to work in Conditional Statementsif, elif, and else — where your programs finally start making decisions. Stay tuned!

← All articles