🐍 Python for Everyone

← Back to all chapters

Chapter 3 of 27 Beginner 18 min read

Operators

You've used + already. Now let's meet the rest of the toolbox that lets your programs actually compute things.

An operator is a tiny symbol that does real work: + adds, > compares, and combines conditions. Every piece of logic you'll ever write — a discount calculation, a login check, a permission system — is built entirely out of these small pieces stacked together.
Sub-topic 1 of 4

1. Arithmetic & assignment operators

Picture the register at TechNaom Store ringing up a group order. Every line it prints — the subtotal, a discount, a split three ways — is just one of these operators at work.

Python has two division operators that behave differently — this single detail causes more beginner confusion than almost anything else in this chapter, so pay close attention to the example below.

arithmetic.py
order_total = 47   # dollars: today's group order at TechNaom Store
friends = 3         # how many friends are splitting the bill

print(order_total + 3)    # 50  — add a $3 delivery tip
print(order_total - 7)    # 40  — a $7 loyalty discount kicks in
print(order_total * 2)    # 94  — a friend orders the same amount again
print(order_total / friends)   # 15.666...  — splitting evenly, ALWAYS returns a float
print(order_total // friends)  # 15   — floor division, drops the remainder
print(order_total % friends)   # 2    — modulo, gives ONLY the remainder

bonus_multiplier = 2   # loyalty points double every tier you climb
tier = 3
print(bonus_multiplier ** tier)   # 8  — power: 2 to the power of 3
try_arithmetic.py
Click "Run Code" to see the output here.
47 // 3 and 47 % 3, visually
47 divided by 3  =  15  remainder  2
                    |              |
                    47 // 3        47 % 3
What is... floor division vs. modulo? // keeps the whole-number quotient, always rounding down (47 // 3 is 15). % keeps only the remainder left over (47 % 3 is 2 — the $2 left over that somebody still has to chip in). % is also the classic tool for "is this number even?" (n % 2 == 0) and for cycles and wraparounds.

Assignment operators combine an operation with storing the result back into the same variable — you already have a habit of writing i = i + 1; Python gives you a shortcut.

assignment.py
loyalty_points = 10
loyalty_points += 5    # same as: loyalty_points = loyalty_points + 5  -> 15
loyalty_points -= 3    # a redeemed reward costs 3 points          -> 12
loyalty_points *= 2    # a double-points weekend promo             -> 24
print(loyalty_points)
Go Deeper: no ++ or -- in Python

If you've used C, Java, or JavaScript, you might reach for loyalty_points++. Python doesn't have that operator at all — it was left out deliberately, partly because ++ in other languages secretly hides two different behaviors (increment-then-use vs. use-then-increment) that cause subtle bugs. In Python, you always write loyalty_points += 1 instead, which is completely unambiguous.

Quick recap
  • / always returns a float; // floor-divides (rounds down); % returns only the remainder.
  • ** is power: 2 ** 3 is 8.
  • +=, -=, *=, etc. combine an operation with reassignment.
  • Python has no ++ or -- operators.
Sub-topic 2 of 4

2. Relational & logical operators

Relational operators compare two values and always produce a boolean. Logical operators combine multiple boolean results into one final decision.

Back at TechNaom Store, the checkout page needs to decide whether a cart qualifies for free shipping — that decision is nothing more than a relational comparison combined with a logical operator.

relational.py
order_total = 62   # dollars, in the cart right now
is_member = True    # TechNaom+ subscribers get free shipping automatically

print(order_total >= 50)                   # True  — over the free-shipping threshold
print(order_total >= 50 and is_member)     # True  — BOTH must be true
print(order_total < 20 or is_member)       # True  — only ONE needs to be true
print(not is_member)                        # False — flips it
What is... a logical operator? and requires every condition to be true for the whole expression to be true. or only needs one condition to be true. not simply flips a boolean: True becomes False and vice versa.
Go Deeper: short-circuit evaluation

Python stops checking as soon as it knows the answer. In order_total >= 50 and is_member, if order_total >= 50 is already False, Python never even looks at is_member — the whole expression is already guaranteed False. This matters in real code: the checkout page can safely write cart_count != 0 and order_total / cart_count > 20 because Python won't attempt the division if cart_count is 0 (an empty cart), avoiding a crash.

Quick recap
  • Relational operators (>, <, >=, <=, ==, !=) always return a boolean.
  • and — every condition must be true.
  • or — at least one condition must be true.
  • not — flips a boolean.
Sub-topic 3 of 4

3. Bitwise operators

Every number is stored internally as bits (1s and 0s). Bitwise operators work directly on those bits. This sounds academic, but it's exactly how real permission systems (like Unix file permissions) and low-level flags work — and it's exactly how TechNaom Store decides what its own staff accounts are allowed to do. You'll build a full version of this in this chapter's project.

bitwise.py
alice_perms = 5   # binary: 101 -> view (4) + refund (1)
bob_perms = 6     # binary: 110 -> view (4) + edit (2)

print(alice_perms & bob_perms)   # 4   — AND: the permission they BOTH share (view)
print(alice_perms | bob_perms)   # 7   — OR: all permissions either one holds
print(alice_perms ^ bob_perms)   # 3   — XOR: the permissions where they DIFFER
print(alice_perms << 1)  # 10  — shift bits left (doubles the value)
print(alice_perms >> 1)  # 2   — shift bits right (halves it, rounding down)
What is... a bit flag? A bit flag uses individual bits of a single number to represent several independent yes/no switches at once. Instead of separate boolean variables for can_view, can_edit, and can_refund, TechNaom Store packs all three into one number and uses & (AND) to check one, and | (OR) to turn one on — this is exactly how Unix file permissions (read=4, write=2, execute=1) work under the hood.
Go Deeper: converting between number systems

Python can show you any integer in binary, octal, or hexadecimal with built-in functions: bin(5) gives '0b101', oct(5) gives '0o5', and hex(5) gives '0x5' — that's Alice's permission number from the example above, laid bare as raw bits. The prefixes (0b, 0o, 0x) tell Python (and you) which base you're reading, and you can write literals directly in any of these forms in your source code too.

Quick recap
  • & (AND), | (OR), ^ (XOR) operate bit by bit.
  • << and >> shift bits left/right (multiply/divide by powers of 2).
  • bin(), oct(), hex() show a number in another base.
Sub-topic 4 of 4

4. Special operators: is / in

Two more operators come up constantly in real Python code: is checks identity (same object in memory, the concept from Chapter 2), and in checks membership.

TechNaom Store uses both every day: in to validate a promo code against this week's active-codes string, and is to compare two variables that are supposed to point at the exact same record.

special_ops.py
customer_a_id = 42
customer_b_id = 42
print(customer_a_id is customer_b_id)   # True  — same small-int object (Chapter 2!)

valid_codes = "SAVE10 WELCOME20 FREESHIP"
print("WELCOME20" in valid_codes)       # True
print("EXPIRED5" not in valid_codes)    # True
What is... the difference between == and is? == asks "do these have the same value?" is asks "are these the exact same object in memory?" Two different pieces of text with identical contents are == but not always is. This distinction rarely matters day-to-day, but matters a lot once you start working with lists and objects in later chapters (Chapter 7 onward).
Quick recap
  • is / is not check identity (same object).
  • in / not in check membership (is this value inside this collection).
  • == checks value equality — not the same thing as is.
In the Real World

Points to Remember

← Chapter 2 Take the Quiz →