What You Will Learn
Beginner
- All comparison operators
- and, or, not with truth tables
- Short-circuit evaluation
Comparison Operators
Terminalpython
5 == 5 # True
5 != 3 # True
5 > 3 # True
5 < 3 # False
5 >= 5 # True
5 <= 4 # False
# String comparison (alphabetical)
"apple" < "banana" # True
"apple" == "apple" # TrueLogical Operators - Truth Tables
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
Short-Circuit Evaluation
Short-circuit
Python evaluates and left-to-right and stops at the first False. For or, it stops at the first True. This is useful for safe checks.Terminalpython
# Safe division - avoids ZeroDivisionError
x = 0
if x != 0 and 10 / x > 1: # x != 0 is False, so 10/x is never evaluated
print("Safe!")
# Default values with or
name = input("Name: ") or "Anonymous"
# If input is empty (falsy), uses "Anonymous"Practical Exercise
Test: 5 > 3 and 2 < 8
Test: True or False
Test: not True
Try: 0 or "default" (returns default)
Key Takeaways
- 6 comparison operators: == != > < >= <=
- and: both True. or: either True. not: inverts.
- Short-circuit: and stops at False, or stops at True.
- Use or for default values: x = input() or 'default'.
- Strings compare alphabetically.
Comments
Comments
Post a Comment