Python - Operators

Overview

Estimated time: 20–30 minutes

Use Python operators effectively and readably.

Learning Objectives

  • Use arithmetic, comparison, and assignment operators.
  • Use logical, membership, and identity operators.
  • Know operator precedence and use parentheses for clarity.

Prerequisites

Operator examples

a, b = 3, 5
print(a + b, a * b, a ** b)
print(a == b, a != b, a < b)
print((a < b) and (b < 10))
print("py" in "python")
print(a is a, a is not b)

Precedence

# Always add parentheses for readability
result = (a + b) * (a - b)

Common Pitfalls

  • Using is for value equality instead of identity (use == for values).
  • Forgetting that and/or return operands, not booleans.

Checks for Understanding

  1. When should you use is?
  2. What does "x" in "exam" evaluate to?
Show answers
  1. For identity comparisons (e.g., x is None).
  2. True

Exercises

  1. Write an expression that checks if a number is between 1 and 10 inclusive.
  2. Show how precedence can change a result without parentheses.