3.4 Compound Assignment, Boolean, and Relational Operators (BT101CO)
This section covers operators that are essential for updating variables, comparing values, and building logical conditions. These form the building blocks of Decision Making in programming.
1. Augmented (Compound) Assignment Operators
These are shorthand ways to update a variable based on its current value. Instead of writing x = x + 5, you can simply write x += 5.
| Operator | Name | Example | Equivalent to |
|---|---|---|---|
+= | Addition Assignment | a += 5 | a = a + 5 |
-= | Subtraction Assignment | a -= 3 | a = a - 3 |
*= | Multiplication Assignment | a *= 2 | a = a * 2 |
/= | Division Assignment | a /= 4 | a = a / 4 |
//= | Floor Division Assignment | a //= 3 | a = a // 3 |
%= | Modulus Assignment | a %= 2 | a = a % 2 |
**= | Exponent Assignment | a **= 2 | a = a ** 2 |
2. Relational Operators (Comparison Tools)
Relational operators are the "questions" that Python asks to return a Boolean (True or False). They are used to compare two values.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 8 | False |
< | Less than | 2 < 4 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 3 <= 2 | False |
= vs ==
= is for Assignment (storing a value).
== is for Comparison (checking if values are equal).
Example: if age = 18: will cause a Syntax Error. Use if age == 18:
3. Logical Operators (Boolean Operators)
Sometimes a single comparison isn't enough. Logical operators allow you to combine multiple conditions.
and: ReturnsTrueonly if both sides are True.or: ReturnsTrueif at least one side is True.not: Inverts the result (True becomes False, False becomes True).
Example: Scholarship Eligibility
gpa = 3.8
attendance = 95
# Both conditions must be met
if gpa >= 3.5 and attendance >= 90:
print("Eligible for scholarship")