Python Operators
Operators
Operators are special symbols (and a few keywords) that perform operations on values and variables — calculations, comparisons, logical checks, and more. The values an operator works on are called operands.
result = 20 + 30
In this statement, + is the operator, 20 and 30 are the operands, and = is the assignment operator that stores the result.
A First Example: The Addition Operator
The addition operator + is one of the most commonly used operators.
Example: Adding Two Numbers
result = 20 + 30
print("Addition result:", result)
Expected output:
Addition result: 50
The + operator adds two integers, and the result is stored in the variable result.
Example: Adding Variables and Values
Operators work with variables as well as literal values, which makes calculations flexible and reusable.
base_value = 120
increment = 80
total_one = base_value + increment
total_two = total_one + 300
total_three = total_two + total_two
print(total_one)
print(total_two)
print(total_three)
Expected output:
200
500
1000
Explanation:
base_valueandincrementstore numeric data.total_oneadds two variables:120 + 80 = 200.total_twoadds a variable and a constant:200 + 300 = 500.total_threeadds a variable to itself:500 + 500 = 1000.
Storing intermediate results in well-named variables makes code clearer and lets you reuse values across calculations.
Categories of Python Operators
Python groups operators by what they do:
| Category | Purpose | Examples | |
|---|---|---|---|
| Arithmetic | Perform mathematical calculations | +, -, *, /, %, **, // | |
| Assignment | Assign values to variables | =, +=, -=, := | |
| Comparison | Compare two values | ==, !=, >, <, >=, <= | |
| Logical | Combine conditions | and, or, not | |
| Identity | Check whether two names refer to the same object | is, is not | |
| Membership | Check whether a value is in a collection | in, not in | |
| Bitwise | Operate on the binary bits of integers | &, ` | , ^, ~, <<, >>` |
Each category is covered below.
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numbers.
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
+ | Addition | Adds two numbers | 18 + 6 | 24 |
- | Subtraction | Subtracts the right value from the left | 18 - 6 | 12 |
* | Multiplication | Multiplies two values | 18 * 6 | 108 |
/ | Division | Divides and always returns a float | 18 / 6 | 3.0 |
% | Modulus | Returns the remainder of a division | 18 % 6 | 0 |
** | Exponentiation | Raises a number to a power | 2 ** 3 | 8 |
// | Floor division | Divides and rounds down to a whole number | 18 // 6 | 3 |
Example: Using Arithmetic Operators
a = 18
b = 6
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Quotient:", a / b)
print("Remainder:", a % b)
print("Power:", a ** b)
print("Floor Result:", a // b)
Expected output:
Sum: 24
Difference: 12
Product: 108
Quotient: 3.0
Remainder: 0
Power: 34012224
Floor Result: 3
What to notice:
- Division with
/produces3.0— a float — even though 18 divides evenly by 6. - The remainder is
0because 6 divides 18 exactly. a ** bmeans 18⁶, which is 34,012,224.
Practical Uses of the Modulus Operator
The % operator is more useful than it first appears:
number = 17
print(number % 2 == 0) # Is the number even?
print(125 % 60) # Seconds left over after whole minutes
Expected output:
False
5
number % 2is0for even numbers and1for odd numbers.125 % 60is5, because 125 seconds is 2 minutes and 5 seconds.
Division Operators
Python has two division operators, each with a different purpose.
1. Standard Division (/)
- Always returns a floating-point value.
- Use it when you need the precise result.
value1 = 14
value2 = 3
result = value1 / value2
print("Standard division result:", result)
Expected output:
Standard division result: 4.666666666666667
2. Floor Division (//)
- Returns the largest whole number less than or equal to the exact result.
- In other words, it divides and then rounds down.
value1 = 14
value2 = 3
result = value1 // value2
print("Floor division result:", result)
Expected output:
Floor division result: 4
Floor Division With Negative Numbers
"Rounding down" means rounding toward negative infinity, not toward zero. This matters for negative numbers:
print(-14 // 3)
Expected output:
-5
The exact result is -4.67. The largest whole number less than or equal to it is -5, not -4.
Key difference:
/keeps the decimal part.//removes the decimal part by rounding down.
This distinction is important when working with loops, indexing, or any calculation that requires whole numbers, such as splitting items into pages:
total_items = 47
items_per_page = 10
full_pages = total_items // items_per_page
leftover = total_items % items_per_page
print("Full pages:", full_pages)
print("Items on last page:", leftover)
Expected output:
Full pages: 4
Items on last page: 7
Assignment Operators
Assignment operators store values in variables. Besides simple assignment (=), Python provides compound assignment operators that perform an operation and assign the result back to the same variable in one step.
| Operator | Purpose | Equivalent To | ||
|---|---|---|---|---|
= | Assign a value | a = 10 | ||
+= | Add and assign | a = a + 5 | ||
-= | Subtract and assign | a = a - 5 | ||
*= | Multiply and assign | a = a * 5 | ||
/= | Divide and assign | a = a / 5 | ||
%= | Modulus and assign | a = a % 5 | ||
//= | Floor divide and assign | a = a // 5 | ||
**= | Exponentiate and assign | a = a ** 5 | ||
&= | Bitwise AND and assign | a = a & 5 | ||
| ` | =` | Bitwise OR and assign | `a = a | 5` |
^= | Bitwise XOR and assign | a = a ^ 5 | ||
>>= | Right shift and assign | a = a >> 2 | ||
<<= | Left shift and assign | a = a << 2 |
Example: Using Assignment Operators
value = 20
value += 10
print("After addition:", value)
value -= 5
print("After subtraction:", value)
value *= 2
print("After multiplication:", value)
value //= 3
print("After floor division:", value)
Expected output:
After addition: 30
After subtraction: 25
After multiplication: 50
After floor division: 16
Explanation:
- Each operator updates the same variable.
- The operation is performed first, using the current value, and then the result is reassigned.
50 // 3is16(16.67 rounded down).
Compound operators reduce repetition and are widely used for counters and running totals:
total = 0
for price in [120, 80, 50]:
total += price
print(total)
Expected output:
250
Note: Python has no
++or--operators. Usecount += 1andcount -= 1instead.
The Walrus Operator (:=)
Python 3.8 introduced the assignment expression operator :=, nicknamed the walrus operator because := resembles the eyes and tusks of a walrus. It assigns a value to a variable as part of a larger expression, such as an if condition.
Without the Walrus Operator
data = [10, 20, 30, 40, 50]
length = len(data)
if length >= 4:
print("Total items:", length)
With the Walrus Operator
data = [10, 20, 30, 40, 50]
if (size := len(data)) >= 4:
print("Total items:", size)
Expected output (both versions):
Total items: 5
(size := len(data)) calculates len(data), stores it in size, and also returns it, so the comparison >= 4 can use it immediately. The parentheses are required here; without them, size would be assigned the result of len(data) >= 4.
Why use the walrus operator?
- It avoids calculating the same value twice.
- It makes some code more concise.
- It should be used carefully — in simple cases, a separate assignment line is often easier to read.
Comparison Operators
Comparison operators compare two values and always return a Boolean result: True or False. They are used in decision-making statements such as if and while.
| Operator | Description | Example |
|---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
Example: Using Comparison Operators
num_a = 12
num_b = 20
print("Equal:", num_a == num_b)
print("Not Equal:", num_a != num_b)
print("Greater Than:", num_a > num_b)
print("Less Than:", num_a < num_b)
print("Greater or Equal:", num_a >= num_b)
print("Less or Equal:", num_a <= num_b)
Expected output:
Equal: False
Not Equal: True
Greater Than: False
Less Than: True
Greater or Equal: False
Less or Equal: True
Each comparison checks one condition, and the Boolean result can be used directly in conditional logic.
Comparison operators also work with strings, which are compared alphabetically by character code:
print("apple" < "banana")
print("Zoo" < "apple")
Expected output:
True
True
The second result may be surprising: all uppercase letters come before all lowercase letters in character-code order.
Chaining Comparison Operators
Python supports chained comparisons, which let you check multiple conditions without repeating the variable.
value = 7
print(3 < value < 15)
Expected output:
True
This single line checks whether value lies between 3 and 15. It is equivalent to:
value = 7
print(value > 3 and value < 15)
Expected output:
True
Why use chained comparisons?
- More readable and concise
- Less repetition
- Natural for range validation, such as
0 <= score <= 100
Logical Operators
Logical operators combine multiple conditions into a single Boolean expression. They are commonly used in if, elif, and while statements.
| Operator | Meaning | Example |
|---|---|---|
and | True only when both conditions are true | a > 2 and a < 8 |
or | True when at least one condition is true | a < 3 or a > 10 |
not | Reverses the Boolean result | not (a == 5) |
Truth Table
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
Example: Using and
Check whether a number falls within a range.
number = 7
result = number > 1 and number < 10
print("Within range:", result)
Expected output:
Within range: True
Both conditions must be true. If either one fails, the result is False.
Example: Using or
Check whether a number is outside a range.
number = 7
result = number < 5 or number > 12
print("Outside range:", result)
Expected output:
Outside range: False
At least one condition must be true for the result to be True. Here, neither is true.
Example: Using not
Invert the result of a logical expression.
number = 7
result = not (number > 4 and number < 9)
print("Reversed result:", result)
Expected output:
Reversed result: False
The expression inside the parentheses is evaluated first (True), and not flips it to False.
Short-Circuit Evaluation
Python stops evaluating a logical expression as soon as the result is known:
- With
and, if the first condition isFalse, the second is never checked. - With
or, if the first condition isTrue, the second is never checked.
This is useful for avoiding errors:
items = []
if len(items) > 0 and items[0] == "pen":
print("First item is a pen")
else:
print("No pen found")
Expected output:
No pen found
Because len(items) > 0 is False, Python never evaluates items[0], which would otherwise raise an IndexError.
Identity Operators
Identity operators check whether two variables refer to the same object in memory, not just whether they contain equal values. This distinction is important for mutable objects such as lists, dictionaries, and custom objects.
| Operator | Description | Example |
|---|---|---|
is | True if both variables refer to the same object | a is b |
is not | True if the variables refer to different objects | a is not b |
Example: Using is
list_one = ["cat", "dog"]
list_two = ["cat", "dog"]
list_three = list_one
print(list_one is list_three)
print(list_one is list_two)
print(list_one == list_two)
Expected output:
True
False
True
Explanation:
list_three = list_onedoes not copy the list; it makeslist_threeanother name for the same list object. SoisreturnsTrue.list_twohas identical content but is a separate object, soisreturnsFalse.==compares only the values, solist_one == list_twoisTrue.
The practical consequence: a change made through list_three is also visible through list_one, because there is only one list.
Example: Using is not
colors_a = ["red", "blue"]
colors_b = ["red", "blue"]
print(colors_a is not colors_b)
Expected output:
True
Even though both lists contain the same elements, they are stored as separate objects, so is not returns True.
is vs ==
| Operator | What It Checks |
|---|---|
is | Whether both variables refer to the same object |
== | Whether the values are equal |
data_x = [10, 20, 30]
data_y = [10, 20, 30]
print("Value comparison:", data_x == data_y)
print("Identity comparison:", data_x is data_y)
Expected output:
Value comparison: True
Identity comparison: False
Rule of thumb:
- Use
==to compare values. - Use
isto compare identity — most commonly when checking forNone:if result is None:.
Caution: Do not use
isto compare numbers or strings. Python sometimes reuses objects for small values, soismay appear to work in one case and fail in another.
Membership Operators
Membership operators check whether a value exists in a collection or sequence, such as a list, tuple, set, dictionary, or string. The result is always True or False.
| Operator | Meaning | Example |
|---|---|---|
in | True if the value exists in the collection | item in collection |
not in | True if the value does not exist in the collection | item not in collection |
Example: Checking Membership in a List
items = ["pen", "pencil", "eraser"]
print("pencil" in items)
Expected output:
True
The expression checks whether "pencil" is one of the list's items. It is, so the result is True.
Example: Checking Non-Membership
items = ["pen", "pencil", "eraser"]
print("marker" not in items)
Expected output:
True
"marker" is not in the list, so not in returns True.
Membership With Strings
With strings, in checks for characters or substrings.
message = "Python Programming"
print("P" in message)
print("python" in message)
print("x" not in message)
Expected output:
True
False
True
String checks are case-sensitive, so "python" does not match "Python".
Membership With Dictionaries
With dictionaries, in checks the keys, not the values:
user = {"name": "Asha", "city": "Chennai"}
print("name" in user)
print("Asha" in user)
Expected output:
True
False
Membership operators are commonly used for validation, searching, and filtering data.
Bitwise Operators
Bitwise operators work directly on the binary representation of integers — the individual 1s and 0s. They are used in low-level programming, working with flags and permissions, network programming, and some algorithms.
| Operator | Name | Description | |
|---|---|---|---|
& | AND | Sets a bit to 1 only if both bits are 1 | |
| ` | ` | OR | Sets a bit to 1 if at least one bit is 1 |
^ | XOR | Sets a bit to 1 if the bits are different | |
~ | NOT | Inverts all bits | |
<< | Left shift | Shifts bits left, adding zeros on the right | |
>> | Right shift | Shifts bits right, discarding bits on the right (the sign is preserved) |
You can see the binary form of a number with bin(): bin(10) returns '0b1010'.
Example: Bitwise AND (&)
a = 10 # Binary: 1010
b = 4 # Binary: 0100
result = a & b
print(result)
Expected output:
0
1010 (10)
& 0100 (4)
----
0000 (0)
No position has a 1 in both numbers, so every bit of the result is 0.
Example: Bitwise OR (|)
a = 10 # Binary: 1010
b = 4 # Binary: 0100
result = a | b
print(result)
Expected output:
14
1010 (10)
| 0100 (4)
----
1110 (14)
A bit is 1 if either number has a 1 in that position.
Example: Bitwise XOR (^)
a = 10 # Binary: 1010
b = 4 # Binary: 0100
result = a ^ b
print(result)
Expected output:
14
A bit is 1 only where the two numbers differ. Because 10 and 4 never have a 1 in the same position, XOR gives the same result as OR here. With overlapping bits, the results differ — for example, 12 ^ 10 is 6, while 12 | 10 is 14.
Example: Bitwise NOT (~)
num = 5 # Binary: 0101
print(~num)
Expected output:
-6
~ flips every bit. Python represents negative integers using two's complement, so for any integer x, ~x equals -(x + 1). Therefore, ~5 is -6.
Example: Bit Shifting
value = 8 # Binary: 1000
print(value << 2)
print(value >> 1)
Expected output:
32
4
value << 2shifts the bits two places left (100000), which multiplies by 2²: 8 × 4 = 32.value >> 1shifts the bits one place right (100), which divides by 2 and rounds down: 8 ÷ 2 = 4.
Operator Precedence
Operator precedence determines the order in which operators are evaluated when an expression contains more than one operator. Understanding it prevents logical errors.
Parentheses Have the Highest Priority
Expressions inside parentheses are always evaluated first.
result = (8 + 2) - (8 + 2)
print(result)
Expected output:
0
Each parenthesized expression is calculated first (10 and 10), and then the subtraction is performed.
Multiplication Before Addition
Without parentheses, Python follows its precedence rules. Multiplication has higher priority than addition:
output = 50 + 4 * 5
print(output)
Expected output:
70
4 * 5 is evaluated first (20), and then 50 + 20 gives 70. To add first, use parentheses: (50 + 4) * 5 gives 270.
Precedence Order (Highest to Lowest)
| Precedence | Operators | Description | |
|---|---|---|---|
| 1 (highest) | () | Parentheses | |
| 2 | ** | Exponentiation | |
| 3 | +x, -x, ~x | Unary plus, unary minus, bitwise NOT | |
| 4 | *, /, //, % | Multiplication, division, floor division, modulus | |
| 5 | +, - | Addition and subtraction | |
| 6 | <<, >> | Bitwise shifts | |
| 7 | & | Bitwise AND | |
| 8 | ^ | Bitwise XOR | |
| 9 | ` | ` | Bitwise OR |
| 10 | ==, !=, >, >=, <, <=, is, is not, in, not in | Comparison, identity, membership | |
| 11 | not | Logical NOT | |
| 12 | and | Logical AND | |
| 13 | or | Logical OR | |
| 14 (lowest) | := | Assignment expression |
Left-to-Right Evaluation
When operators have the same precedence, Python evaluates them from left to right.
value = 10 + 6 - 8 + 2
print(value)
Expected output:
10
The steps are: 10 + 6 = 16, then 16 - 8 = 8, then 8 + 2 = 10.
One exception: exponentiation (**) is evaluated right to left:
print(2 ** 3 ** 2)
Expected output:
512
This is calculated as 2 ** (3 ** 2) = 2 ** 9 = 512, not (2 ** 3) ** 2 = 64.
A Precedence Trap: Negative Numbers and Powers
Because ** has higher precedence than unary minus, -2 ** 2 means -(2 ** 2):
print(-2 ** 2)
print((-2) ** 2)
Expected output:
-4
4
Tip
To improve readability and avoid mistakes:
- Use parentheses in complex expressions, even when they are not strictly required.
- Do not rely on readers memorizing the precedence table.
Common Mistakes
| Mistake | Example | Problem | |
|---|---|---|---|
Using = for comparison | if x = 5: | SyntaxError; use == | |
Expecting / to return an integer | 10 / 2 | Returns 5.0 | |
Using is to compare values | if name is "Asha": | Unreliable; use == | |
Using & or ` | instead ofand/or` | if a > 1 & b > 2: | Bitwise operators have different precedence and meaning |
Using ++ to increment | count++ | SyntaxError; use count += 1 | |
| Forgetting precedence | 50 + 4 * 5 expected to be 270 | Multiplication runs first |
Related Concepts
- Python Booleans — the
True/Falsevalues produced by comparisons - Python If Statements — using comparison and logical operators in conditions
- Python Numeric Data Types — how numbers behave in arithmetic
- Python Math — additional mathematical functions