Python Operators

Ka Kavitha V Updated 03 Oct 2026
17 min read ·Lesson 12 of 23

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_value and increment store numeric data.
  • total_one adds two variables: 120 + 80 = 200.
  • total_two adds a variable and a constant: 200 + 300 = 500.
  • total_three adds 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:

CategoryPurposeExamples
ArithmeticPerform mathematical calculations+, -, *, /, %, **, //
AssignmentAssign values to variables=, +=, -=, :=
ComparisonCompare two values==, !=, >, <, >=, <=
LogicalCombine conditionsand, or, not
IdentityCheck whether two names refer to the same objectis, is not
MembershipCheck whether a value is in a collectionin, not in
BitwiseOperate on the binary bits of integers&, `, ^, ~, <<, >>`

Each category is covered below.

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numbers.

OperatorNameDescriptionExampleResult
+AdditionAdds two numbers18 + 624
-SubtractionSubtracts the right value from the left18 - 612
*MultiplicationMultiplies two values18 * 6108
/DivisionDivides and always returns a float18 / 63.0
%ModulusReturns the remainder of a division18 % 60
**ExponentiationRaises a number to a power2 ** 38
//Floor divisionDivides and rounds down to a whole number18 // 63

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 / produces 3.0 — a float — even though 18 divides evenly by 6.
  • The remainder is 0 because 6 divides 18 exactly.
  • a ** b means 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 % 2 is 0 for even numbers and 1 for odd numbers.
  • 125 % 60 is 5, 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.

OperatorPurposeEquivalent To
=Assign a valuea = 10
+=Add and assigna = a + 5
-=Subtract and assigna = a - 5
*=Multiply and assigna = a * 5
/=Divide and assigna = a / 5
%=Modulus and assigna = a % 5
//=Floor divide and assigna = a // 5
**=Exponentiate and assigna = a ** 5
&=Bitwise AND and assigna = a & 5
`=`Bitwise OR and assign`a = a5`
^=Bitwise XOR and assigna = a ^ 5
>>=Right shift and assigna = a >> 2
<<=Left shift and assigna = 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 // 3 is 16 (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. Use count += 1 and count -= 1 instead.

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.

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= 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.

OperatorMeaningExample
andTrue only when both conditions are truea > 2 and a < 8
orTrue when at least one condition is truea < 3 or a > 10
notReverses the Boolean resultnot (a == 5)

Truth Table

ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

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 is False, the second is never checked.
  • With or, if the first condition is True, 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.

OperatorDescriptionExample
isTrue if both variables refer to the same objecta is b
is notTrue if the variables refer to different objectsa 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_one does not copy the list; it makes list_three another name for the same list object. So is returns True.
  • list_two has identical content but is a separate object, so is returns False.
  • == compares only the values, so list_one == list_two is True.

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 ==

OperatorWhat It Checks
isWhether 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 is to compare identity — most commonly when checking for None: if result is None:.

Caution: Do not use is to compare numbers or strings. Python sometimes reuses objects for small values, so is may 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.

OperatorMeaningExample
inTrue if the value exists in the collectionitem in collection
not inTrue if the value does not exist in the collectionitem 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.

OperatorNameDescription
&ANDSets a bit to 1 only if both bits are 1
``ORSets a bit to 1 if at least one bit is 1
^XORSets a bit to 1 if the bits are different
~NOTInverts all bits
<<Left shiftShifts bits left, adding zeros on the right
>>Right shiftShifts 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 << 2 shifts the bits two places left (100000), which multiplies by 2²: 8 × 4 = 32.
  • value >> 1 shifts 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)

PrecedenceOperatorsDescription
1 (highest)()Parentheses
2**Exponentiation
3+x, -x, ~xUnary 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 inComparison, identity, membership
11notLogical NOT
12andLogical AND
13orLogical 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

MistakeExampleProblem
Using = for comparisonif x = 5:SyntaxError; use ==
Expecting / to return an integer10 / 2Returns 5.0
Using is to compare valuesif name is "Asha":Unreliable; use ==
Using & or `instead ofand/or`if a > 1 & b > 2:Bitwise operators have different precedence and meaning
Using ++ to incrementcount++SyntaxError; use count += 1
Forgetting precedence50 + 4 * 5 expected to be 270Multiplication runs first
  • Python Booleans — the True/False values 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

0 Comments

Reviewed before they appear

No comments yet.

Python
Ask about this post
AI Ask about this post

Ask questions about Python Operators and get answers drawn from it.

Signed-in readers only.