Learning Objectives: After this lesson, you'll learn to control program flow with if statements, master comparison and logical operators, and understand how Python evaluates boolean expressions.
Introduction to Conditional Logic
Programs need to make decisions based on different situations. Python uses conditional statements to execute different code paths depending on whether conditions are true or false.
Think of it like a flowchart in your daily life:
- If it's raining → take an umbrella
- If you're hungry → eat something
- If it's late → go to sleep
Basic If Statements
The simplest conditional statement is the if statement:
Loading Python runtime...
Key Points:
- The condition must evaluate to
TrueorFalse - Code inside the
ifblock is indented (usually 4 spaces) - If the condition is
False, the indented code is skipped
If-Else Statements
Use else to specify what happens when the condition is False:
Loading Python runtime...
If-Elif-Else Chains
For multiple conditions, use elif (else if):
Loading Python runtime...
Comparison Operators
Python provides several operators to compare values:
| 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 | 3 <= 3 | True |
>= | Greater than or equal | 5 >= 5 | True |
Loading Python runtime...
Logical Operators
Combine multiple conditions using logical operators:
| Operator | Meaning | Example | When True |
|---|---|---|---|
and | Both conditions true | a and b | Both a AND b are true |
or | At least one true | a or b | Either a OR b (or both) is true |
not | Opposite | not a | a is false |
Loading Python runtime...
Truthiness in Python
Python considers some values as "falsy" and others as "truthy":
Loading Python runtime...
Nested Conditions
You can put if statements inside other if statements:
Loading Python runtime...
Practical Examples
Example 1: User Authentication System
Loading Python runtime...
Example 2: Shipping Calculator
Loading Python runtime...
Practice Exercises
Exercise 1: Age Category Classifier
Loading Python runtime...
Exercise 2: Grade Calculator with Validation
Loading Python runtime...
Key Takeaways
✅ If statements control program flow based on conditions
✅ Indentation matters - Python uses indentation to group code blocks
✅ Comparison operators (==, !=, <, >, <=, >=) compare values
✅ Logical operators (and, or, not) combine conditions
✅ Truthiness - Empty containers and zero values are "falsy"
✅ elif chains handle multiple exclusive conditions
✅ Nested conditions allow complex decision trees
Connections: Conditional Logic Across Disciplines
🔗 Connection to Boolean Algebra and Logic
Conditional statements in programming are based on Boolean algebra, invented by George Boole in 1847:
Boolean Logic Fundamentals:
Truth Tables: AND (∧) OR (∨) NOT (¬) A B | A∧B A B | A∨B A | ¬A 0 0 | 0 0 0 | 0 0 | 1 0 1 | 0 0 1 | 1 1 | 0 1 0 | 0 1 0 | 1 1 1 | 1 1 1 | 1
Python Implementation:
# AND (both must be true) if age >= 18 and has_license: print("Can drive") # OR (at least one must be true) if is_weekend or is_holiday: print("No work today!") # NOT (inverse) if not is_raining: print("Go outside")
De Morgan's Laws (important logical equivalences):
# These are equivalent: not (A and B) == (not A) or (not B) not (A or B) == (not A) and (not B) # Example: not (is_sunny and is_warm) == (not is_sunny) or (not is_warm) # "Not both sunny and warm" = "Either not sunny OR not warm"
🔗 Connection to Digital Logic (Computer Hardware)
Your if statements eventually become logic gates in the CPU:
Logic Gates:
AND Gate: OR Gate: NOT Gate: A ──┐ A ──┐ A ──┐ ├─ Q ├─ Q ├─ Q B ──┘ B ──┘ │ └─ (inverts)
How Python conditions become hardware:
if (temp > 80) and (humidity > 60): print("Hot and humid") # Becomes: # 1. temp > 80 → Comparison circuit → True/False # 2. humidity > 60 → Comparison circuit → True/False # 3. AND gate combines both signals # 4. If output is 1 (True), execute print
🔗 Connection to Mathematics
Conditional logic appears throughout mathematics:
Piecewise Functions:
{ x² if x ≥ 0 f(x) = { { -x² if x < 0
Python Implementation:
def f(x): if x >= 0: return x ** 2 else: return -(x ** 2)
Set Theory:
Intersection (∩) = AND Union (∪) = OR Complement (') = NOT A ∩ B in Python: item in set_a and item in set_b A ∪ B in Python: item in set_a or item in set_b A' in Python: item not in set_a
🔗 Connection to Other Languages
Conditional statements exist in all languages with similar logic:
| Python | JavaScript | Java | C++ |
|---|---|---|---|
if age >= 18: | if (age >= 18) { | if (age >= 18) { | if (age >= 18) { |
elif age >= 13: | else if (age >= 13) { | else if (age >= 13) { | else if (age >= 13) { |
else: | else { | else { | else { |
and, or, not | &&, ||, ! | &&, ||, ! | &&, ||, ! |
Python's Advantage:
- More readable (
andvs&&) - No parentheses required around condition
- Cleaner syntax with colons and indentation
🔗 Connection to Real-World Decision Systems
Traffic Lights (Finite State Machine):
if light == "green": action = "go" elif light == "yellow": action = "slow down" elif light == "red": action = "stop" else: action = "error - check light"
Thermostat (Control System):
if current_temp < target_temp - 2: heater = "on" ac = "off" elif current_temp > target_temp + 2: heater = "off" ac = "on" else: heater = "off" ac = "off" # In desired range
Medical Diagnosis (Expert System):
if fever > 102 and has_cough and difficulty_breathing: recommendation = "Seek immediate medical attention" elif fever > 100 and has_cough: recommendation = "Rest and monitor symptoms" else: recommendation = "No immediate action needed"
🔗 Connection to Artificial Intelligence
Decision Trees: Conditional logic forms the basis of decision tree algorithms:
# Simple decision tree for weather prediction if humidity > 70: if temperature > 80: prediction = "Thunderstorm likely" else: prediction = "Cloudy" else: if temperature > 75: prediction = "Sunny" else: prediction = "Partly cloudy"
Rule-Based AI: Early AI systems were built entirely on if-then rules:
# Expert system rules if patient_temp > 103 and white_blood_count > 15000: diagnosis = "Severe infection - immediate treatment" elif patient_temp > 100 and white_blood_count > 11000: diagnosis = "Possible infection - monitor"
🔗 Connection to Future Python Topics
Short-Circuit Evaluation:
# Python evaluates left-to-right and stops when result is determined if expensive_check() or quick_check(): # If expensive_check() is True, quick_check() never runs! pass # Useful for avoiding errors: if user is not None and user.is_active: # Checks user exists before accessing is_active pass
Ternary Operator (Conditional Expression):
# Long form: if age >= 18: status = "adult" else: status = "minor" # Short form (ternary): status = "adult" if age >= 18 else "minor"
Match-Case (Python 3.10+):
# Modern alternative to long if-elif chains match status_code: case 200: message = "OK" case 404: message = "Not Found" case 500: message = "Server Error" case _: message = "Unknown"
🔗 Connection to Algorithm Complexity
Conditional logic affects performance:
# Bad: Redundant checks if x > 10: if x > 5: # Always true if x > 10! print("Greater than 5") # Good: Optimal ordering if x > 10: print("Greater than 10") elif x > 5: print("Between 5 and 10")
Binary Search relies on conditional logic:
def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 # Search right half else: right = mid - 1 # Search left half return -1 # Not found
🔗 Historical Context
Evolution of Conditional Logic in Programming:
- 1940s: Conditional jumps in machine code
- 1950s: IF statements in FORTRAN
- 1960s: Switch statements in ALGOL
- 1970s: Case statements in Pascal
- 1990s: Pattern matching in functional languages
- 2020s: Match-case in Python 3.10+
Boolean Algebra Timeline:
- 1847: George Boole publishes "The Mathematical Analysis of Logic"
- 1938: Claude Shannon shows Boolean algebra applies to electrical circuits
- 1947: Transistors enable logic gates
- Today: Billions of logic gates in every computer chip
Remember: Every time you write an if statement, you're using Boolean algebra invented 180 years ago, implemented in hardware logic gates, to make intelligent decisions in your programs!
Next Steps
In the next lesson, we'll learn about loops and iteration - how to repeat operations efficiently using for and while loops, and control loop execution with break and continue.
Ready to make your code repeat tasks automatically? The next lesson will show you the power of loops!