🐍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.
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 - 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 name—
x = 5creates a reference fromxto the integer object5 - Right-to-left evaluation—the expression on the right is evaluated first, then assigned to the left
- Chained assignment supported—
a = b = c = 0sets all three variables to zero
Compound Assignment (+=, -=, *=, /=, //=, %=, **=)
- Combines operation with assignment—
x += 3is shorthand forx = 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—returnsTrueif both sides have the same value!=checks inequality—returnsTrueif values differ- Works across types cautiously—
1 == 1.0isTrue, but"1" == 1isFalse
Relational Operators (<, >, <=, >=)
- Determine ordering—
<and>for strict comparisons,<=and>=when equality counts - Chainable in Python—
1 < x < 10works as you'd expect mathematically - String comparison uses lexicographic order—
"apple" < "banana"isTruebased 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
Trueonly if both operands areTrue—otherwise returnsFalse - 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
Trueif at least one operand isTrue—onlyFalsewhen both areFalse - 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 value—
not TruereturnsFalse,not FalsereturnsTrue - Useful for readability—
if not found:reads more naturally thanif found == False: - Converts truthy/falsy values—
not 0returnsTrue,not "hello"returnsFalse
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)
ischecks object identity—returnsTrueif both variables point to the exact same object in memory- Best used with
None—if 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)
intests for presence in a collection—works with strings, lists, tuples, sets, and dictionaries- Dictionary membership checks keys—
"name" in my_dictchecks if"name"is a key, not a value - Efficient with sets—membership testing is for sets versus 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 integerx, returns$$-(x+1)$$due to two's complement representation<<left shift multiplies by —x << 3is equivalent to>>right shift divides by —x >> 2is equivalent to (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
| Concept | Best Examples |
|---|---|
| Basic math operations | +, -, *, ** |
| Division with different return types | / (float), // (integer), % (remainder) |
| Storing and updating values | =, +=, -=, *= |
| Value equality testing | ==, != |
| Ordering comparisons | <, >, <=, >= |
| Combining Boolean conditions | and, or, not |
| Object identity checking | is, is not |
| Collection membership | in, not in |
| Binary manipulation | &, ` |
Self-Check Questions
-
What's the difference between
/and//, and when would you choose floor division over true division? -
Which two operators both involve checking equality, but one checks value while the other checks memory location? When should you use each?
-
Explain short-circuit evaluation: if
x = False, what happens when Python evaluatesx and some_function()? What aboutx or some_function()? -
Compare and contrast
inwhen used with a list versus a dictionary. What does each check for? -
You need to check if a variable contains
None. Write the Pythonic way to do this, and explain why==is discouraged for this comparison.