W3docs

Introduction to Python Operators

Learn all Python operator types — arithmetic, comparison, assignment, logical, bitwise, identity, and membership — with examples and precedence rules.

Operators are the symbols and keywords that tell Python what action to perform on one or more values. Every meaningful Python expression — from x + 1 to if age >= 18 — relies on at least one operator. Python groups its operators into seven categories: arithmetic, comparison, assignment, logical, identity, membership, and bitwise. This chapter explains each category, shows when to use it, and highlights common gotchas.

Arithmetic Operators

Arithmetic operators perform mathematical calculations. Python provides seven of them:

OperatorNameExampleResult
+Addition17 + 522
-Subtraction17 - 512
*Multiplication17 * 585
/Division17 / 53.4
%Modulus (remainder)17 % 52
**Exponentiation2 ** 8256
//Floor division17 // 53

Two operators deserve extra attention:

  • / always returns a float in Python 3, even when dividing two integers (4 / 2 returns 2.0, not 2).
  • // (floor division) rounds the result toward negative infinity, not toward zero. So -7 // 2 is -4, not -3.
python— editable, runs on the server

Common use: checking even or odd

The modulus operator (%) is the standard way to test divisibility:

number = 42
if number % 2 == 0:
    print("even")
else:
    print("odd")
# Output: even

Comparison Operators

Comparison operators compare two values and always return True or False. They are used in conditions, while loops, and anywhere a Boolean result is needed.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal to5 >= 5True
<=Less than or equal to5 <= 4False
python— editable, runs on the server

Chaining comparisons

Python lets you chain multiple comparisons in one expression, which reads more naturally than in most other languages:

x = 7
print(1 < x < 10)   # True  — equivalent to (1 < x) and (x < 10)
print(0 < x < 5)    # False

Gotcha: == vs =

= is the assignment operator; == tests equality. Using = inside a condition is a SyntaxError in Python (unlike some other languages where it silently assigns).

Assignment Operators

Assignment operators store values in variables. The compound forms (+=, -=, …) combine an arithmetic or bitwise operation with assignment, making the code more concise.

OperatorEquivalent toExample
=x = 10
+=x = x + nx += 3
-=x = x - nx -= 3
*=x = x * nx *= 3
/=x = x / nx /= 3
//=x = x // nx //= 3
%=x = x % nx %= 3
**=x = x ** nx **= 3
&=x = x & nx &= 0b1111
|=x = x | nx |= 0b1000
^=x = x ^ nx ^= 0b0101
<<=x = x << nx <<= 1
>>=x = x >> nx >>= 1
python— editable, runs on the server

The walrus operator := (Python 3.8+)

The walrus operator assigns a value inside an expression. It is useful when you want to both evaluate and store a result without writing the expression twice:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Without walrus: compute length twice
if len(numbers) > 5:
    print(f"Long list: {len(numbers)} items")

# With walrus: assign once, use in condition and body
if (n := len(numbers)) > 5:
    print(f"Long list: {n} items")
# Output: Long list: 10 items

Logical Operators

Logical operators combine or invert Boolean expressions. Python uses English keywords rather than symbols (&&, ||, !).

OperatorMeaningExampleResult
andTrue if both sides are trueTrue and FalseFalse
orTrue if at least one side is trueTrue or FalseTrue
notInverts the Boolean valuenot TrueFalse
python— editable, runs on the server

Short-circuit evaluation

Python evaluates and and or lazily (left to right) and stops as soon as the result is determined:

  • False and <anything> — the right side is never evaluated.
  • True or <anything> — the right side is never evaluated.

This matters when the right-hand side has a side effect or could raise an error:

user_input = ""
name = user_input or "Anonymous"
print(name)   # Anonymous  (empty string is falsy, so "Anonymous" is returned)

Truthy and falsy values

Logical operators work with any value, not just True/False. Python treats 0, "", None, [], {}, and () as falsy; everything else is truthy.

See the Python Data Types chapter for a full list of falsy values per type.

Identity Operators

Identity operators test whether two variables point to the same object in memory, not just whether they hold equal values.

OperatorMeaning
isTrue if both variables reference the same object
is notTrue if they reference different objects
python— editable, runs on the server

When to use is vs ==

Use is only when you intentionally want to check object identity — most commonly when comparing to singletons:

value = None
if value is None:       # correct idiom
    print("No value provided")

# Never do: if value == None — works but is considered bad style

Python caches small integers (typically -5 to 256) and interned strings, so a is b may return True for two separately created small integers. Never rely on this behavior for integers or strings — use == for value equality.

Membership Operators

Membership operators test whether a value exists inside a sequence (list, tuple, string, set, or dictionary).

OperatorMeaning
inTrue if the value is found in the sequence
not inTrue if the value is not found
python— editable, runs on the server

Performance note

For lists and tuples, in checks every element sequentially (O(n)). For sets and dictionary keys, in uses a hash table and runs in constant time (O(1)). Prefer a set when you need many membership tests on a large collection.

Bitwise Operators

Bitwise operators work on the binary representation of integers, manipulating individual bits.

OperatorNameExampleResultNotes
&AND5 & 31Bit is 1 only if both bits are 1
|OR5 | 37Bit is 1 if either bit is 1
^XOR5 ^ 36Bit is 1 if bits differ
~NOT~5-6Inverts all bits; result is -(n+1)
<<Left shift5 << 110Shifts bits left (multiply by 2)
>>Right shift20 >> 25Shifts bits right (divide by 2)
python— editable, runs on the server

Why bitwise operators matter

In most everyday Python code you will not use bitwise operators directly, but they appear frequently in:

  • Flags and permissions — combining bitmasks to represent multiple options in a single integer.
  • Cryptography and hashing — XOR is a basic building block.
  • Efficient mathn << 1 is faster than n * 2 in performance-critical loops.
  • Working with binary protocols — parsing network packets or file headers.

Operator Precedence

When an expression mixes several operators, Python evaluates them in a fixed order (highest precedence first):

PriorityOperators
1 (highest)**
2+x, -x, ~x (unary)
3*, /, //, %
4+, -
5<<, >>
6&
7^
8|
9==, !=, <, >, <=, >=, is, is not, in, not in
10not
11and
12 (lowest)or
# Multiplication before addition (standard math rules apply)
print(2 + 3 * 4)      # 14, not 20

# Use parentheses to override
print((2 + 3) * 4)    # 20

# ** is right-associative: 2 ** 3 ** 2 = 2 ** (3**2) = 2**9
print(2 ** 3 ** 2)    # 512, not 64

# Comparisons before logical operators
print(2 + 3 > 4 and 10 % 3 == 1)  # True and True → True

When in doubt, use parentheses. They make precedence explicit and improve readability.

Summary

CategoryOperatorsPrimary use
Arithmetic+ - * / % ** //Math calculations
Comparison== != > < >= <=Conditions, filtering
Assignment= += -= *= /= //= %= **= &= |= ^= <<= >>=Store and update variables
Logicaland or notCombining Boolean conditions
Identityis is notSingleton checks (e.g. is None)
Membershipin not inSearching sequences and sets
Bitwise& | ^ ~ << >>Binary flags, low-level data

For related topics, see Python Variables, Python If...Else, and Python Data Types.

Practice

Practice
Which of the following categories does Python operators fall into?
Which of the following categories does Python operators fall into?
Was this page helpful?