Python: Operators
Every operator Python provides, from basic arithmetic to the modern walrus operator, with clear examples for each.
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values. Python covers everything you would expect from a calculator, plus two extras that often surprise newcomers: floor division // and the exponentiation operator **.
Arithmetic Operator Reference
Seven operators cover every fundamental math operation you will need.
- + addition: 3 + 2 gives 5
- - subtraction: 10 - 4 gives 6
- * multiplication: 4 * 3 gives 12
- / true division: 7 / 2 gives 3.5 (always returns float)
- // floor division: 7 // 2 gives 3 (rounds down to nearest integer)
- % modulus: 17 % 5 gives 2 (the remainder after division)
- ** exponentiation: 2 ** 8 gives 256
Arithmetic Operators in Action
PythonRun this to see all seven operators produce their results.
Assignment Operators
The basic assignment operator = stores a value into a variable. Compound assignment operators combine an arithmetic operation with assignment into one step, which keeps code shorter and easier to scan when you are updating a running total, applying a discount, or building a string in a loop.
Compound Assignment Shortcuts
x += 5 is exactly equivalent to x = x + 5. The same pattern applies to all seven operators.
- = basic: x = 10
- += add and assign: x += 5 (same as x = x + 5)
- -= subtract and assign: x -= 3
- *= multiply and assign: x *= 2
- /= divide and assign (float): x /= 4
- //= floor divide and assign: x //= 3
- %= modulus and assign: x %= 7
- **= exponentiate and assign: x **= 2
Assignment Operators Step by Step
PythonWatch the value of x change with each compound assignment.
Comparison Operators
Comparison operators evaluate two values and always return a boolean: either True or False. They are the backbone of every conditional statement and loop condition you will ever write. Python also supports chaining comparisons, which reads naturally: 1 < x < 10 works exactly as you would expect in mathematics.
Comparison Operator Reference
Six operators for comparing numeric values, strings, and any other comparable type.
- == equal to: 5 == 5 gives True
- != not equal to: 5 != 4 gives True
- < less than: 3 < 7 gives True
- > greater than: 9 > 2 gives True
- <= less than or equal to: 5 <= 5 gives True
- >= greater than or equal to: 6 >= 10 gives False
- Chaining: 1 < x < 10 checks both conditions at once
Comparison Operators
PythonEach operator returns True or False, which drives if statements and loops.
Logical Operators
Logical operators combine multiple boolean expressions into one. Python uses the English words and, or, and not instead of symbols like &&, ||, and ! found in other languages. This makes conditions read like natural English sentences.
Short-circuit Evaluation
Python stops evaluating as soon as the result is certain, which can prevent runtime errors.
- and: both sides must be True for the result to be True
- or: at least one side must be True
- not: flips True to False and vice versa
- Short-circuit: False and ... never checks the right side
- Short-circuit: True or ... never checks the right side
- and/or return the actual value that decided the result, not just True/False
Logical Operators
PythonCombining conditions with and, or, and not.
Bitwise Operators
Bitwise operators work directly on the binary representation of integers, manipulating individual bits. They appear frequently in systems programming, cryptography, networking (IP masking), and performance-sensitive numeric code. If you are just starting out, you will not need these every day, but understanding them will make you a well-rounded developer.
Bitwise Operator Reference
All six bitwise operators treat integers as sequences of 0s and 1s.
- & AND: bit is 1 only when both corresponding bits are 1
- | OR: bit is 1 when at least one corresponding bit is 1
- ^ XOR: bit is 1 when exactly one of the two bits is 1
- ~ NOT: flips every bit (result is -(n+1) for positive n)
- << left shift: shifts bits left, multiplying by 2 for each shift
- >> right shift: shifts bits right, dividing by 2 for each shift
Bitwise Operators
PythonOperating on 60 (0b111100) and 13 (0b001101) to see how bits combine.
Identity Operators: is, is not
The is operator does not compare values; it checks whether two variables point to the exact same object in memory. Two objects can hold the same value but be stored at different memory addresses, in which case == returns True but is returns False. The classic use case is checking against the singleton values None, True, and False.
is vs ==
Always use == to compare values. Use is only when testing identity (most commonly: if x is None).
- is: returns True only if both names reference the same object in memory
- is not: returns True if the two names reference different objects
- Use is None, not == None (PEP 8 recommendation)
- Small integers (-5 to 256) are cached: a = 5; b = 5; a is b gives True
- Larger integers or strings are not cached, so is may give surprising results
Identity vs Equality
Pythonis tests memory address; == tests value.
Membership Operators: in, not in
Membership operators test whether a value exists inside a sequence such as a list, tuple, string, set, or dictionary. They return a boolean and work on any iterable. For strings, in checks for a substring. For dictionaries, it checks for the presence of a key, not a value.
in and not in
One of Python's most readable features: conditions that almost sound like English.
- in: returns True if the value is found in the sequence
- not in: returns True if the value is NOT found in the sequence
- Works with: lists, tuples, strings, sets, dict keys, ranges
- String substring check: "py" in "python" gives True
- Dict key check: "name" in {"name": "Ali"} gives True
Membership Operators
PythonTesting membership across strings, lists, and dictionaries.
Walrus Operator := (Python 3.8+)
The walrus operator := is officially called the assignment expression. Its name comes from the fact that := looks like a walrus face on its side. It lets you assign a value to a variable and use that value in the same expression, which removes the need for a separate assignment line before a condition. It is particularly useful inside while loops and list comprehensions.
When to Use the Walrus Operator
Added in Python 3.8, it reduces repetition where you assign and immediately test a value.
- Assign and test in one expression inside a while loop condition
- Avoid computing a value twice (once for the check, once for use)
- List comprehensions: filter and keep the computed result in one pass
- Not for every assignment: only use it where it genuinely reduces duplication
Walrus Operator :=
PythonAssign inside a condition to avoid repeating the computation.
Ternary / Conditional Expression
Python's ternary expression is a compact way to choose between two values based on a condition, all on a single line. The syntax reads left to right in a natural way: value_if_true if condition else value_if_false. Use it when the logic is simple enough to read comfortably on one line; for anything complex, a regular if-else block is clearer.
Ternary Expression Syntax
One line that replaces a three-line if-else, as long as the logic stays simple.
- Syntax: result = value_a if condition else value_b
- value_a is returned when condition is True
- value_b is returned when condition is False
- Can be used anywhere a value is expected: in print(), as a function argument, etc.
- Tip: avoid nesting ternary expressions; they become unreadable quickly
Ternary Expression
PythonReplace simple if-else blocks with a readable one-liner.
Operator Precedence
When an expression contains multiple operators, Python does not simply evaluate from left to right. It follows a strict precedence table, similar to the mathematical BODMAS/PEMDAS rule. Operators with higher precedence are evaluated first. When two operators share the same precedence, Python evaluates them left to right (except for ** which is right to left).
The safest approach is to use parentheses to make your intent explicit. Code that relies heavily on remembering precedence rules is harder to read and more prone to bugs.
Precedence Order (Highest to Lowest)
Parentheses always win. When in doubt, add them.
- 1. () parentheses - highest priority
- 2. ** exponentiation (right to left)
- 3. +x, -x, ~x unary operators
- 4. *, /, //, % multiplication and division
- 5. +, - addition and subtraction
- 6. <<, >> bitwise shifts
- 7. & bitwise AND
- 8. ^ bitwise XOR
- 9. | bitwise OR
- 10. ==, !=, <, >, <=, >=, is, is not, in, not in comparisons
- 11. not logical NOT
- 12. and logical AND
- 13. or logical OR - lowest priority
Operator Precedence Examples
PythonShowing how precedence changes results and how parentheses clarify intent.
Quiz - Test Your Knowledge
Put your operator knowledge to the test. Each question targets a specific concept from this tutorial. Take your time before selecting an answer.
Knowledge Check
1. What is the result of 17 // 5 in Python?
2. Which operator checks both value and type equality?
3. What does the walrus operator := do?
4. What is the result of not (5 > 3)?
5. Which operator checks if a variable points to the exact same object in memory?
6. What is 5 ** 3 in Python?
7. What does "py" in "python" return?
8. Which operator has the highest precedence in Python?