5. Python Operators
Python Operators
An operator is a symbol that tells Python to perform a specific operation on one or more values. You use operators constantly — every time you add two numbers, compare two values, or check whether something exists in a list, you are using an operator.
Python organises its operators into seven categories. Each category serves a distinct purpose, and knowing when to reach for each one is a core programming skill.
Arithmetic Operators
Arithmetic operators perform mathematical calculations. They work on integers and floats, and some of them behave in surprising ways that are worth understanding precisely.
- / always returns a float — even 10 / 2 returns 5.0, not 5
- // floor division truncates toward negative infinity — -7 // 2 gives -4, not -3
- % modulus is invaluable for checking even/odd: if n % 2 == 0 the number is even
- ** exponentiation: 2 ** 10 gives 1024 — useful in algorithms and cryptography
Assignment Operators
Assignment operators assign a value to a variable. The basic one is =. The rest are shorthand compound operators that modify a variable and reassign it in one step, keeping your code concise.
Comparison Operators
Comparison operators compare two values and always return a boolean — either True or False. They are the engine behind every decision your program makes.
A very common beginner mistake is using = (assignment) when they meant == (comparison). Writing if x = 10: is a SyntaxError in Python. Always use == inside conditions.
Logical Operators
Logical operators combine multiple boolean expressions into a single result. They let you express compound conditions like "the user is logged in AND has a premium account."
- and short-circuits: if the left side is False, Python does not even evaluate the right side
- or short-circuits: if the left side is True, Python skips the right side
- Short-circuit evaluation is not just an optimisation — it prevents crashes, e.g. checking x is not None and x.value > 0
Identity Operators
Identity operators check whether two variables point to the exact same object in memory — not just whether they hold equal values. This is a subtle but critical distinction.
Membership Operators
Membership operators check whether a value exists inside a sequence — a string, list, tuple, set, or dictionary. They return True or False.
Bitwise Operators
Bitwise operators operate directly on the binary (bit-level) representation of integers. While you will not use them in everyday scripts, they appear frequently in systems programming, networking, cryptography, and performance-critical code.
Left shift (<< n) multiplies a number by 2ⁿ. Right shift (>> n) divides by 2ⁿ. These are extremely fast operations at the hardware level.
Knowledge Check
Ready to test your understanding of 5. Python Operators?