22 min read
Comparison, Logical and Assignment Operators
Compare values (==, !=, <, >, <=, >=), combine conditions (and, or, not), and update variables with +=, -= and friends.
Comparison (Relational) Operators
| Comparison operators — each gives True or False | |||
|---|---|---|---|
Logical Operators
| Combining conditions (the same logic as AND, OR and NOT gates) | ||
|---|---|---|
Logical operatorsPython
age = 35day = "Sun"member = False print(age >= 18 and age < 60)print(day == "Sat" or day == "Sun")print(not member)Expected output
True True True
True and False as Numbers
Behind the scenes, True is 1 and False is 0. Python can also turn any number into True or False with bool(): 0 is False, and every other number is True — including negative numbers such as −1.
Logical values as numbersPython
print(True + True)print(5 > 3, int(5 > 3))print(bool(0), bool(7), bool(-1))Expected output
2 True 1 False True True
| Logical values in C (you may see these in exam questions) | |
|---|---|
Assignment and Compound Assignment
| Assignment operators | ||
|---|---|---|
A running total with +=Python
total = 0total += 280 # ricetotal += 450 # dhaltotal += 120 # breadprint("Subtotal:", total)total *= 0.9 # 10% offprint("After discount:", total)Expected output
Subtotal: 850 After discount: 765.0
Practice
A customer gets a gift if they spend over 5,000 AND are a member. Which condition is correct?
More lessons in Python Programming · Next: Input and Type Conversion · Previous: Arithmetic Operators
