Chapter 3: Operators

Master Python’s operators: arithmetic, comparison, logical, assignment, precedence, identity & membership.

Download chapter3.py

Objectives

1. Arithmetic Operators

Basic mathematical operations:

OperatorDescriptionExample
+Addition2 + 3 # 5
-Subtraction5 - 1 # 4
*Multiplication4 * 3 # 12
/True division7 / 2 # 3.5
//Floor division7 // 2 # 3
%Modulus (remainder)7 % 2 # 1
**Exponentiation2 ** 3 # 8

2. Comparison Operators

Evaluate relationships; result is True or False:

OperatorDescriptionExample
==Equal to3 == 3 # True
!=Not equal to4 != 5 # True
<Less than2 < 5 # True
>Greater than5 > 2 # True
<=Less than or equal3 <= 3 # True
>=Greater than or equal4 >= 2 # True

3. Logical Operators

Combine Boolean expressions:

# Examples
True and False   # False
True or False    # True
not True         # False
      

4. Assignment & Augmented Assignment

Store and update variable values:

# Standard assignment
x = 10

# Augmented assignment
x += 5    # x = x + 5 → 15
x *= 2    # x = x * 2 → 30
x %= 7    # x = x % 7 → 2
      

5. Precedence & Other Operators

Order of operations (highest → lowest):

  1. ** (exponentiation)
  2. *, /, //, %
  3. +, -
  4. <, <=, >, >=
  5. ==, !=
  6. not
  7. and
  8. or

Identity & membership:

# Identity
a = [1,2,3]
b = a
c = a[:]
a is b    # True
a is c    # False

# Membership
2 in a    # True
5 not in a  # True
      

Exercises

  1. Compute (3 + 5) * 2 ** 3 / 4 % 3, print each intermediate step.
  2. Write a Boolean expression to check if n is strictly between 1 and 10.
  3. Demonstrate difference between is and == with two identical lists.
  4. Starting from x = 5, use augmented assignments to reach x = 120.