Module 4 Quick Reference
Conditionals Cheat Sheet
Comparison Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
< | Less than | 3 < 5 | True |
> | Greater than | 5 > 3 | True |
<= | Less than or equal | 5 <= 5 | True |
>= | Greater than or equal | 7 >= 10 | False |
Remember: = is assignment, == is comparison!
if / elif / else Syntax
# Basic if if condition: # code runs if condition is True # if-else if condition: # runs if True else: # runs if False # if-elif-else if condition1: # runs if condition1 is True elif condition2: # runs if condition2 is True elif condition3: # runs if condition3 is True else: # runs if none above are True
Key rules: Colon : after every if/elif/else. Indent the block with 4 spaces. Only the first True branch runs in an elif chain.
Logical Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | Both must be True | True and False | False |
or | At least one True | True or False | True |
not | Reverses the value | not True | False |
Precedence: not → and → or (use parentheses to be clear)
Common Patterns
# Range check if 1 <= x <= 100: # Python supports chained comparisons! # Case-insensitive comparison if name.lower() == "alice": # Checking for valid input if user_input.isdigit(): # Guard clause (check failures first) if not logged_in: print("Please log in") elif not has_permission: print("Access denied") else: # do the actual work
Common Mistakes
| Mistake | Fix |
|---|---|
if x = 5: (assignment) | if x == 5: (comparison) |
Forgetting the colon : | Always end if/elif/else with : |
| Wrong indentation | Use exactly 4 spaces per level |
"5" == 5 (type mismatch) | int("5") == 5 |
"Yes" == "yes" (case) | "Yes".lower() == "yes" |
Short-Circuit Evaluation
# and: stops at first False if x != 0 and 10/x > 2: # Safe: won't divide if x is 0 # or: stops at first True if is_admin or is_owner: # Skips is_owner check if is_admin is True