Chapter 3: Operators
Master Python’s operators: arithmetic, comparison, logical, assignment, precedence, identity & membership.
Downloadchapter3.py
Objectives
- Perform calculations with arithmetic operators.
- Compare values using comparison operators.
- Combine Boolean expressions with logical operators.
- Use simple and augmented assignment operators.
- Understand operator precedence and associativity.
- Explore identity (
is
) and membership (in
) operators.
1. Arithmetic Operators
Basic mathematical operations:
Operator | Description | Example |
---|---|---|
+ | Addition | 2 + 3 # 5 |
- | Subtraction | 5 - 1 # 4 |
* | Multiplication | 4 * 3 # 12 |
/ | True division | 7 / 2 # 3.5 |
// | Floor division | 7 // 2 # 3 |
% | Modulus (remainder) | 7 % 2 # 1 |
** | Exponentiation | 2 ** 3 # 8 |
2. Comparison Operators
Evaluate relationships; result is True
or False
:
Operator | Description | Example |
---|---|---|
== | Equal to | 3 == 3 # True |
!= | Not equal to | 4 != 5 # True |
< | Less than | 2 < 5 # True |
> | Greater than | 5 > 2 # True |
<= | Less than or equal | 3 <= 3 # True |
>= | Greater than or equal | 4 >= 2 # True |
3. Logical Operators
Combine Boolean expressions:
and
:True
if both operandsTrue
or
:True
if at least one operandTrue
not
: invert a Boolean value
# 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):
**
(exponentiation)*, /, //, %
+, -
<, <=, >, >=
==, !=
not
and
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
- Compute
(3 + 5) * 2 ** 3 / 4 % 3
, print each intermediate step. - Write a Boolean expression to check if
n
is strictly between 1 and 10. - Demonstrate difference between
is
and==
with two identical lists. - Starting from
x = 5
, use augmented assignments to reachx = 120
.