upgrade
upgrade

🐍Intro to Python Programming

Python Operators

Study smarter with Fiveable

Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.

Get Started

Why This Matters

Operators are the verbs of Python—they're how you do things with your data. Every program you write will use operators to perform calculations, make decisions, and control program flow. When you're tested on Python fundamentals, you're being tested on whether you understand not just what operators do, but when to use each type. The difference between = and ==, or knowing when to reach for // instead of /, separates working code from broken code.

Think of operators as falling into distinct categories based on their purpose: performing math, assigning values, making comparisons, combining logic, checking identity, testing membership, and manipulating bits. Don't just memorize the symbols—know what problem each operator solves and what type of value it returns. That conceptual understanding will carry you through debugging, code reading, and writing efficient solutions.


Operators That Perform Math

Arithmetic operators handle numerical calculations. These operators work on numeric types and return numeric results—except division, which has some quirks you need to know.

Addition, Subtraction, and Multiplication (+, -, *)

  • Basic math operations—these work exactly as you'd expect from elementary school
  • Type consistency—operating on two integers returns an integer; include a float and you get a float back
  • String concatenation—the + operator also joins strings, demonstrating Python's operator overloading

Division Operators (/, //, %)

  • True division / always returns a float—even $$10 / 2$$ gives you $$5.0$$, not $$5$$
  • Floor division // returns the largest integer less than or equal to the result—useful when you need whole numbers only
  • Modulus % returns the remainder—essential for checking divisibility, cycling through values, or extracting digits

Exponentiation (**)

  • Raises a number to a power$$2 ** 3$$ returns $$8$$, equivalent to 232^3
  • Supports fractional exponents$$9 ** 0.5$$ returns $$3.0$$ (square root)
  • Right-associative evaluation$$2 ** 3 ** 2$$ equals $$512$$, not $$64$$, because it evaluates right-to-left

Compare: / vs. //—both divide numbers, but / always returns a float while // truncates toward negative infinity. If a problem requires counting whole items (like how many full boxes fit), reach for //.


Operators That Store Values

Assignment operators bind values to variable names. The key insight is that compound operators combine calculation and storage into a single, readable step.

Basic Assignment (=)

  • Binds a value to a namex = 5 creates a reference from x to the integer object 5
  • Right-to-left evaluation—the expression on the right is evaluated first, then assigned to the left
  • Chained assignment supporteda = b = c = 0 sets all three variables to zero

Compound Assignment (+=, -=, *=, /=, //=, %=, **=)

  • Combines operation with assignmentx += 3 is shorthand for x = x + 3
  • Improves readability—makes the intent clear that you're modifying an existing value
  • Works with all arithmetic operators—including //= for floor division and **= for exponentiation

Compare: x = x + 1 vs. x += 1—functionally identical for immutable types, but += is more concise and signals intent. For mutable types like lists, += modifies in place while x = x + [item] creates a new object.


Operators That Compare Values

Comparison operators evaluate relationships between values and return Boolean results. Every comparison resolves to either True or False, making these essential for conditional logic.

Equality Operators (==, !=)

  • == checks value equality—returns True if both sides have the same value
  • != checks inequality—returns True if values differ
  • Works across types cautiously1 == 1.0 is True, but "1" == 1 is False

Relational Operators (<, >, <=, >=)

  • Determine ordering< and > for strict comparisons, <= and >= when equality counts
  • Chainable in Python1 < x < 10 works as you'd expect mathematically
  • String comparison uses lexicographic order"apple" < "banana" is True based on character codes

Compare: == vs. is== checks if values are equal, while is checks if two names reference the same object in memory. Use == for value comparison; reserve is for identity checks (especially with None).


Operators That Combine Logic

Logical operators work with Boolean values to build complex conditions. Understanding short-circuit evaluation here will help you write both correct and efficient code.

The and Operator

  • Returns True only if both operands are True—otherwise returns False
  • Short-circuits left to right—if the first operand is False, Python never evaluates the second
  • Returns the determining value—technically returns the first falsy value or the last value if all are truthy

The or Operator

  • Returns True if at least one operand is True—only False when both are False
  • Short-circuits on first truthy value—useful for setting default values like name = user_input or "Guest"
  • Returns the determining value—the first truthy value encountered, or the last value if all are falsy

The not Operator

  • Negates a Boolean valuenot True returns False, not False returns True
  • Useful for readabilityif not found: reads more naturally than if found == False:
  • Converts truthy/falsy valuesnot 0 returns True, not "hello" returns False

Compare: and vs. or short-circuiting—and stops at the first False (why continue if one condition fails?), while or stops at the first True (why continue if one condition succeeds?). This matters when the second operand has side effects or is expensive to compute.


Operators That Check Identity and Membership

These operators test relationships between objects and collections. Identity checks memory location; membership checks containment.

Identity Operators (is, is not)

  • is checks object identity—returns True if both variables point to the exact same object in memory
  • Best used with Noneif x is None: is the Pythonic way to check for None values
  • Avoid for value comparison—small integers and interned strings can give misleading results due to Python's caching

Membership Operators (in, not in)

  • in tests for presence in a collection—works with strings, lists, tuples, sets, and dictionaries
  • Dictionary membership checks keys"name" in my_dict checks if "name" is a key, not a value
  • Efficient with sets—membership testing is O(1)O(1) for sets versus O(n)O(n) for lists

Compare: is vs. == with None—always use is None rather than == None. It's faster (identity check vs. value comparison) and avoids edge cases where objects define custom __eq__ methods.


Operators That Manipulate Bits

Bitwise operators work directly on the binary representation of integers. These are specialized tools—less common in everyday code but powerful for specific applications like flags, permissions, and low-level optimization.

Bitwise AND, OR, XOR (&, |, ^)

  • & (AND) returns 1 only where both bits are 1—useful for masking specific bits
  • | (OR) returns 1 where either bit is 1—useful for combining flags
  • ^ (XOR) returns 1 where bits differ—useful for toggling and simple encryption

Bitwise NOT and Shifts (~, <<, >>)

  • ~ inverts all bits—for integer x, returns $$-(x+1)$$ due to two's complement representation
  • << left shift multiplies by 2n2^nx << 3 is equivalent to x×8x \times 8
  • >> right shift divides by 2n2^nx >> 2 is equivalent to x÷4x \div 4 (integer division)

Compare: << vs. * for powers of two—x << 3 and x * 8 produce the same result, but bit shifting is closer to hardware operations. In Python, readability usually wins, so use multiplication unless you're doing explicit bit manipulation.


Quick Reference Table

ConceptBest Examples
Basic math operations+, -, *, **
Division with different return types/ (float), // (integer), % (remainder)
Storing and updating values=, +=, -=, *=
Value equality testing==, !=
Ordering comparisons<, >, <=, >=
Combining Boolean conditionsand, or, not
Object identity checkingis, is not
Collection membershipin, not in
Binary manipulation&, `

Self-Check Questions

  1. What's the difference between / and //, and when would you choose floor division over true division?

  2. Which two operators both involve checking equality, but one checks value while the other checks memory location? When should you use each?

  3. Explain short-circuit evaluation: if x = False, what happens when Python evaluates x and some_function()? What about x or some_function()?

  4. Compare and contrast in when used with a list versus a dictionary. What does each check for?

  5. You need to check if a variable contains None. Write the Pythonic way to do this, and explain why == is discouraged for this comparison.