Skip to content
PythonVariables and Basic Databeginner25 min read

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

Perform basic arithmetic
python
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
Output
13 7 30 3.3333333333333335 3 1 1000

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

Division and modulo by zero raise ZeroDivisionError. Do not assume that floor division always behaves like truncation toward zero for negative operands.
1. Arithmetic operators Reference
OperatorMeaningExample result
+Addition7 + 2 → 9
-Subtraction7 - 2 → 5
*Multiplication7 * 2 → 14
/True division7 / 2 → 3.5
//Floor division7 // 2 → 3
%Modulo7 % 2 → 1
Exponentiation2 ** 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

Compare values
python
score = 85
print(score >= 50)
print(score == 100)
print(score != 100)
print(0 <= score <= 100)
Output
True False True True

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

Do not confuse = with ==. Assignment changes which value a name refers to, while equality comparison evaluates to True or False.

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

Combine conditions
python
age = 22
has_id = True
print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)
Output
True True False

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

Do not assume and and or always return True or False. They return operands according to truthiness and short-circuit rules.

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

Update a running total
python
total = 10
total += 5
print(total)
total *= 2
print(total)
total -= 4
print(total)
Output
15 30 26

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

Augmented assignment is convenient for counters, totals, and repeated calculations. For mutable objects, remember that the operation may modify an existing object rather than create a separate one.

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

Make grouping explicit
python
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)
Output
14 20 512 64

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

When an expression contains several operators, do not rely on guesswork. Use parentheses to communicate the intended order of evaluation.

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

Check membership in lists and dictionaries
python
colors = ["red", "blue"]
profile = {"name": "Asha", "active": True}
print("red" in colors)
print("green" not in colors)
print("name" in profile)
print("Asha" in profile)
print("Asha" in profile.values())
Output
True True True False True

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

For dictionaries, key membership is the default. Use key in dictionary to check a key and value in dictionary.values() to check a value.

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

Equality is not identity
python
a = [1, 2]
b = [1, 2]
c = a
print(a == b)
print(a is b)
print(a is c)
result = None
print(result is None)
Output
True False True True

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

Use == to compare values and is to compare object identity. Do not rely on identity comparisons between numbers or strings simply because they appear to work in one Python session.

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

Trace a score validation expression
python
score = 78
passed = score >= 40 and 0 <= score <= 100
print(score >= 40)
print(0 <= score <= 100)
print(passed)
Output
True True True

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.

Incorrect Approach
script.py
python
Using / when floor division is required.
Correct Solution
script.py
python
Use // for floor division. Remember that -7 // 3 is -3 because the quotient is rounded down toward negative infinity.

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.

Incorrect Approach
script.py
python
Assuming modulo is always positive.
Correct Solution
script.py
python
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.

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.

Incorrect Approach
script.py
python
Using is to compare ordinary values.
Correct Solution
script.py
python
Use == for value equality and is for object identity. Use is None when checking whether a value is None.

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.

Incorrect Approach
script.py
python
Assuming and and or always return Boolean values.
Correct Solution
script.py
python
They can return one of their operands. They use truthiness and short-circuit evaluation to determine whether the right operand needs to be evaluated.

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.

Incorrect Approach
script.py
python
Forgetting operator precedence.
Correct Solution
script.py
python
Multiplication has higher precedence than addition, and exponentiation groups from the right. Use parentheses when grouping might be unclear.

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.

Incorrect Approach
script.py
python
Assuming membership in a dictionary checks its values.
Correct Solution
script.py
python
The in operator checks dictionary keys by default. Use value in dictionary.values() when you need to check 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.

Incorrect Approach
script.py
python
Confusing assignment with equality comparison.
Correct Solution
script.py
python
Use = to assign a value and == to compare 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.

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 //?
Answer:
/ performs true division. For ordinary integer and floating-point operands, it produces a float. // performs floor division and rounds the mathematical quotient down toward negative infinity.
Q2:How does Python calculate modulo with negative numbers?
Answer:
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. The quotient and remainder satisfy a == (a // b) * b + (a % b) for integers and nonzero b.
Q3:What is short-circuit evaluation?
Answer:
With and, Python stops evaluating once it encounters a falsy operand. With or, it stops once it encounters a truthy operand. The remaining expression is evaluated only when needed to determine the result.
Q4:What is the difference between == and is?
Answer:
== compares values for equality, whereas is checks whether two references point to the same object. Use == for ordinary value comparisons and is None when checking for None.
Q5:Do and and or always return Boolean values?
Answer:
No. They return one of their operands. For example, 0 or 5 returns 5, and 0 and 5 returns 0. Their evaluation decisions are based on truthiness.
Q6:What is operator precedence?
Answer:
Operator precedence determines how an expression is grouped when parentheses are absent. For example, multiplication is evaluated before addition, so 2 + 3 * 4 gives 14. Parentheses can explicitly control grouping.
Q7:What is the difference between assignment and augmented assignment?
Answer:
Assignment with = binds a name to a value. Augmented assignment, such as += or *=, combines an operation with assignment. For mutable objects, augmented assignment can modify the existing object in place.
Q8:How do membership operators work with dictionaries?
Answer:
The in and not in operators check dictionary keys by default. To check whether a value is present, use value in dictionary.values().
Q9:What is the difference between chained comparisons and logical operators?
Answer:
A chained comparison such as 0 <= score <= 100 checks a sequence of comparisons and evaluates the middle expression only once. Logical operators such as and and or combine truth values or other operands using short-circuit rules.
Q10:Why should is not be used to compare ordinary numbers or strings?
Answer:
is checks object identity, not value equality. Python may reuse some objects, so an identity comparison can appear to work for certain numbers or strings without being a reliable value comparison. Use == to compare values.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: