2.4 Operators
Definitions, purpose, and Python examples
Arithmetic Operators
Purpose: Perform mathematical calculations.
Examples include:
Examples include:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
- Exponentiation (**)
- Integer division (//)
- Modulus (%)
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)
Relational Operators
Purpose: Compare values and return True or False.
Examples include:
Examples include:
- Equal to (==)
- Not equal to (!=)
- Less than (<)
- Greater than (>)
- Less than or equal to (<=)
- Greater than or equal to (>=)
age = 18
print(age == 18)
print(age != 16)
print(age > 16)
print(age <= 21)
Boolean Operators
Purpose: Combine or invert conditions.
Examples include:
Examples include:
- and
- or
- not
age = 20
has_id = True
print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)
2.4.4–2.4.6 Using and interpreting operators in code
Interpreting Code Using Operators
Interpreting code means understanding what the logic produces.
Python example:
Python example:
numbers = [4, 6, 8]
total = numbers[0] + numbers[1]
print(total > numbers[2])
This checks whether the sum of the first two items is greater than the third.
Creating Code Using Operators
Operators are used to create decision‑making logic.
Python example:
Python example:
score = 70
if score >= 50:
print("Pass")
else:
print("Fail")
2.4.7 Debugging code using operators
Debugging Operator Errors
Debugging involves identifying incorrect logic or operators.
Incorrect code:
Corrected code:
Incorrect code:
age = 18
if age = 18:
print("Adult")
Problem: Assignment (=) used instead of comparison (==).
Corrected code:
if age == 18:
print("Adult")