Operators in Python
Understand arithmetic, comparison, logical, assignment, membership, and identity operators through examples, dry runs, and practice.
In this lesson, you will learn
- ✓Use arithmetic operators to perform calculations.
- ✓Explain the difference between true division, floor division, and modulo.
- ✓Compare values using comparison operators and chained comparisons.
- ✓Combine conditions with and, or, and not.
- ✓Explain short-circuit evaluation and operand-returning behavior.
- ✓Use assignment and augmented-assignment operators correctly.
- ✓Apply operator precedence and parentheses to control expression grouping.
- ✓Distinguish membership from identity and equality.
1. Arithmetic operators
Arithmetic operators perform mathematical operations. The main arithmetic operators in Python are + for addition, - for subtraction, * for multiplication, / for true division, // for floor division, % for modulo, and ** for exponentiation.
For ordinary integer and floating-point operands, / returns a floating-point result. For example, 8 / 2 produces 4.0, not the integer 4. The // operator performs floor division: it rounds the mathematical quotient down toward negative infinity.
The modulo operator % returns the remainder associated with floor division. For a nonzero divisor, the remainder has the same sign as the divisor, or is zero. A useful relationship is a == (a // b) * b + (a % b), for integers a and nonzero b.
The exponentiation operator ** raises a number to a power. For example, 2 ** 3 evaluates to 8. Parentheses can make calculations easier to understand and help you explicitly control grouping.
Perform basic arithmetic
10 + 3 produces 13, while 10 - 3 produces 7. 10 * 3 produces 30. 10 / 3 performs true division and produces a floating-point result. 10 // 3 produces the floor quotient 3. 10 % 3 produces the remainder 1 because 10 = 3 * 3 + 1. 10 ** 3 calculates 10 raised to the third power, producing 1000.
Caution
| Operator | Meaning | Example result |
|---|---|---|
| + | Addition | 7 + 2 → 9 |
| - | Subtraction | 7 - 2 → 5 |
| * | Multiplication | 7 * 2 → 14 |
| / | True division | 7 / 2 → 3.5 |
| // | Floor division | 7 // 2 → 3 |
| % | Modulo | 7 % 2 → 1 |
| Exponentiation | 2 ** 3 → 8 |
2. Comparison operators
Comparison operators compare values and produce a Boolean result, True or False. The operators are == for equality, != for inequality, < for less than, <= for less than or equal to, > for greater than, and >= for greater than or equal to.
Use == when you want to know whether two values compare equal. A single = is assignment, not an equality comparison. For example, score = 85 assigns a value, while score == 85 evaluates a comparison.
Python also supports chained comparisons. The expression 0 <= score <= 100 checks whether score is at least 0 and at most 100. It is equivalent in meaning to 0 <= score and score <= 100, except that the middle expression is evaluated only once.
Comparisons between incompatible types are not always supported. For example, comparing an integer with a string using < raises TypeError in Python 3.
Compare values
85 is greater than or equal to 50, so the first result is True. 85 is not equal to 100, so score == 100 is False. 85 differs from 100, so score != 100 is True. The chained comparison checks both boundaries, and 85 is between 0 and 100 inclusive.
Caution
3. Logical operators: and, or, and not
Logical operators are commonly used to combine conditions. The and operator evaluates as truthy only when both operands are truthy. The or operator evaluates as truthy when at least one operand is truthy. The not operator reverses the truth value of its operand.
Python uses short-circuit evaluation for and and or. With and, Python does not evaluate the right operand when the left operand is falsy. With or, Python does not evaluate the right operand when the left operand is truthy.
Unlike comparison operators, and and or do not always return a Boolean object. They return one of their operands. The expression 0 or 5 returns 5, while 0 and 5 returns 0. Conditions such as if 0 or 5: still work because Python evaluates truthiness.
Use parentheses to make complicated conditions easier to read. They help show which comparisons belong together and reduce mistakes when several logical operators are combined.
Combine conditions
age >= 18 is True and has_id is True, so the and expression returns True. The second expression returns True because has_id is True, even though age < 18 is False. not reverses the truth value of has_id, so not True is False.
Caution
4. Assignment and augmented assignment
The = operator assigns a value to a name. For example, total = 10 binds the name total to the integer 10.
Augmented-assignment operators combine an operation with an assignment. Common examples include +=, -=, *=, /=, //=, %=, and **=. For example, total += 5 updates total using addition and assignment.
For immutable numeric values, x += 2 has the same resulting numeric value as x = x + 2. However, augmented assignment is not universally identical to the longer form for every object. Mutable objects such as lists can be modified in place by augmented assignment.
For a list, values += [3] commonly extends the existing list. This matters when another variable refers to the same list object.
Update a running total
total begins at 10. total += 5 changes its value to 15. total *= 2 changes its value to 30. total -= 4 changes its value to 26.
Note
5. Operator precedence and parentheses
Operator precedence determines how parts of an expression are grouped when parentheses are absent. For example, multiplication has higher precedence than addition, so 2 + 3 * 4 evaluates as 2 + (3 * 4).
Parentheses override the default grouping. The expression (2 + 3) * 4 performs addition first, producing 20.
Exponentiation groups from right to left. Therefore, 2 ** 3 ** 2 means 2 ** (3 ** 2), which equals 512.
Precedence rules also affect comparisons, logical operators, and other expression types. You do not need to memorize every rule immediately; use parentheses when they make the intended calculation clearer.
Make grouping explicit
Multiplication occurs before addition, so 2 + 3 * 4 gives 14. Parentheses force addition first, so (2 + 3) * 4 gives 20. Exponentiation groups from the right, so 2 ** (3 ** 2) equals 512. The final expression explicitly groups the first exponentiation, so 8 ** 2 equals 64.
Caution
6. Membership operators: in and not in
The in operator tests whether an item is present in a container or sequence. The not in operator tests whether the item is absent. These operators are useful for checking lists, tuples, sets, strings, and dictionaries.
For strings, membership checks whether a substring appears in the string. For dictionaries, membership checks keys, not values. To check dictionary values, use the values() view.
Membership behavior depends on the container. A list checks its elements, a set checks its members, and a dictionary checks its keys.
Check membership in lists and dictionaries
red is an element of the colors list. green is absent from the list, so green not in colors is True. name is a key in the profile dictionary. Asha is a dictionary value, not a key, so "Asha" in profile is False. profile.values() exposes the dictionary values, so "Asha" in profile.values() is True.
Caution
7. Identity operators: is and is not
The is operator checks object identity: whether two references point to the same object. The is not operator checks whether they refer to different objects.
The == operator checks equality instead. Two separate lists can contain the same elements and compare equal with == while still being different objects under is.
Use is None or is not None to check whether a value is None. Avoid using is to compare ordinary strings or numbers because object reuse and identity are not the same as value equality.
Equality is not identity
a and b contain equal elements, so a == b is True. The two list literals create separate list objects, so a is b is False. c is assigned the same object referenced by a, so a is c is True. result is None correctly checks whether result refers to the None singleton.
Caution
8. Dry run: evaluate an expression step by step
A dry run means tracing an expression or program manually to understand each intermediate value. For operators, write down the values, apply the relevant precedence rules, and then evaluate the final expression.
Trace a score validation expression
Step 1: score stores 78. Step 2: score >= 40 compares 78 with 40 and produces True. Step 3: 0 <= score <= 100 checks both range boundaries and produces True. Step 4: and combines the two truthy Boolean results, so passed becomes True. Step 5: the three print() calls display True on each line.
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Using / when floor division is required.
Why it happens: The / operator performs true division, while // performs floor division; they can produce different results, especially with negative operands.
Key takeaway: Use // for floor division. Remember that -7 // 3 is -3 because the quotient is rounded down toward negative infinity.
#2 Assuming modulo is always positive.
Why it happens: Python's modulo result follows the divisor's sign, so a negative operand can produce a negative or otherwise unexpected-looking remainder.
Key takeaway: For a nonzero divisor, Python’s modulo result has the divisor’s sign or is zero. For example, -7 % 3 is 2, while 7 % -3 is -2.
#3 Using is to compare ordinary values.
Why it happens: is tests whether two references point to the same object, not whether their values compare equal.
Key takeaway: Use == for value equality and is for object identity. Use is None when checking whether a value is None.
#4 Assuming and and or always return Boolean values.
Why it happens: and and or return one of their operands according to short-circuit rules; they are not restricted to returning True or False.
Key takeaway: They can return one of their operands. They use truthiness and short-circuit evaluation to determine whether the right operand needs to be evaluated.
#5 Forgetting operator precedence.
Why it happens: Operators have different precedence levels, so an expression may group differently than a learner expects; parentheses make intended grouping explicit.
Key takeaway: Multiplication has higher precedence than addition, and exponentiation groups from the right. Use parentheses when grouping might be unclear.
#6 Assuming membership in a dictionary checks its values.
Why it happens: The in operator on a dictionary checks its keys by default, not its values.
Key takeaway: The in operator checks dictionary keys by default. Use value in dictionary.values() when you need to check values.
#7 Confusing assignment with equality comparison.
Why it happens: The single equals sign assigns a value, while double equals compares values for equality.
Key takeaway: Use = to assign a value and == to compare values for equality.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is the difference between / and //?
Q2:How does Python calculate modulo with negative numbers?
Q3:What is short-circuit evaluation?
Q4:What is the difference between == and is?
Q5:Do and and or always return Boolean values?
Q6:What is operator precedence?
Q7:What is the difference between assignment and augmented assignment?
Q8:How do membership operators work with dictionaries?
Q9:What is the difference between chained comparisons and logical operators?
Q10:Why should is not be used to compare ordinary numbers or strings?
Key takeaways
- Arithmetic operators include +, -, *, /, //, %, and **.
- Floor division rounds toward negative infinity, while modulo follows Python’s quotient-and-remainder rules.
- Comparison operators evaluate to Boolean results and can be chained.
- and, or, and not use truthiness; and and or also use short-circuit evaluation.
- Augmented assignment combines an operation with assignment and can modify mutable objects in place.
- Operator precedence determines expression grouping; parentheses make intent clearer.
- in checks membership, and dictionary membership checks keys by default.
- == checks value equality, while is checks object identity.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: