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 Assignmenta += 5a = a + 5
-=Subtraction Assignmenta -= 3a = a - 3
*=Multiplication Assignmenta *= 2a = a * 2
/=Division Assignmenta /= 4a = a / 4
//=Floor Division Assignmenta //= 3a = a // 3
%=Modulus Assignmenta %= 2a = a % 2
**=Exponent Assignmenta **= 2a = 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 to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 8False
<Less than2 < 4True
>=Greater than or equal to5 >= 5True
<=Less than or equal to3 <= 2False
⚠️ Common Mistake: = 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: Returns True only if both sides are True.
  • or: Returns True if 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")

Practice Quiz