Table of Contents
- Introduction to Conditional Logic
- If Statement Basics
- If-Else Statements
- Else-If Ladders
- Nested If Statements
- Comparison Operators
- Logical Operators
- Ternary Operator
- Switch Statements
- Pattern Matching
- Common Patterns
- Best Practices
- Real-World Examples
Introduction to Conditional Logic
Conditional logic is the foundation of decision-making in programming. It allows programs to execute different code paths based on different conditions, making programs dynamic and responsive.
What Are Conditional Statements?
Conditional statements allow a program to make decisions and execute different code based on whether a condition is true or false.
# Real-world analogy """ Weather App Decision: IF it's raining: Take an umbrella ELSE IF it's sunny: Wear sunglasses ELSE: Go out normally """
Why Conditionals Matter
Importance of Conditionals: ├── Decision Making - Choose between different actions ├── Validation - Check if input is valid ├── Error Handling - Handle exceptional cases ├── Flow Control - Direct program execution ├── User Interaction - Respond to user choices └── Business Logic - Implement business rules
If Statement Basics
Simple If Statement
The most basic conditional statement executes code only when a condition is true.
# Python
age = 18
if age >= 18:
print("You can vote!")
print("You can drive!")
# Code continues here regardless
print("Program continues")
// JavaScript
let temperature = 25;
if (temperature > 30) {
console.log("It's hot outside!");
console.log("Stay hydrated!");
}
// Java
int score = 85;
if (score >= 60) {
System.out.println("You passed!");
System.out.println("Congratulations!");
}
// C
int x = 10;
if (x > 0) {
printf("x is positive\n");
}
Indentation and Code Blocks
# Python - Indentation is critical
if condition:
# These lines are indented
print("Inside if block")
print("Still inside if")
# This line is outside
print("Outside if block")
# Multiple statements require consistent indentation
if True:
print("First line")
print("Second line")
# All indented lines execute together
// JavaScript/C/Java - Curly braces define blocks
if (condition) {
console.log("Inside if block");
console.log("Still inside if");
}
console.log("Outside if block");
// Without braces, only one statement executes
if (condition)
console.log("This executes if true");
console.log("This ALWAYS executes!"); // Not part of if!
Common Pitfall: Single Statement vs Block
// JavaScript - Without braces
if (x > 5)
console.log("x is greater than 5");
console.log("This always runs!"); // Bug! Not part of if
// Always use braces for clarity
if (x > 5) {
console.log("x is greater than 5");
console.log("This only runs when condition is true");
}
If-Else Statements
Basic If-Else
If-Else provides an alternative path when the condition is false.
# Python
password = "secret123"
if password == "secret123":
print("Access granted!")
print("Welcome, user!")
else:
print("Access denied!")
print("Incorrect password.")
// JavaScript
let age = 16;
if (age >= 18) {
console.log("You can vote!");
console.log("You're eligible for driver's license");
} else {
console.log("You're too young to vote!");
console.log("Wait until you turn 18");
}
If-Else with Multiple Statements
# Python
score = 75
if score >= 60:
print("Congratulations!")
print("You passed the exam!")
print(f"Your score: {score}")
else:
print("Sorry, you failed.")
print("Better luck next time!")
print(f"Your score: {score} (needed 60)")
Visual Representation
If-Else Flowchart: ┌─────────────┐ │ Condition │ └──────┬──────┘ │ ┌───────┴───────┐ │ │ True False │ │ ▼ ▼ ┌─────────────┐ ┌─────────────┐ │ Execute │ │ Execute │ │ If block │ │ Else block │ └─────────────┘ └─────────────┘ │ │ └───────┬───────┘ ▼ Continue program
Else-If Ladders
Multiple Conditions
When you need to check multiple conditions in sequence, use else-if (elif in Python).
# Python - elif
score = 85
if score >= 90:
grade = "A"
message = "Excellent!"
elif score >= 80:
grade = "B"
message = "Good job!"
elif score >= 70:
grade = "C"
message = "Fair"
elif score >= 60:
grade = "D"
message = "Passing"
else:
grade = "F"
message = "Needs improvement"
print(f"Grade: {grade} - {message}")
// JavaScript - else if
let temperature = 25;
if (temperature > 30) {
console.log("It's hot!");
console.log("Stay hydrated!");
} else if (temperature > 20) {
console.log("It's warm");
console.log("Perfect weather!");
} else if (temperature > 10) {
console.log("It's cool");
console.log("Bring a jacket");
} else {
console.log("It's cold!");
console.log("Wear warm clothes");
}
// Java - else if
int dayOfWeek = 3;
if (dayOfWeek == 1) {
System.out.println("Monday");
} else if (dayOfWeek == 2) {
System.out.println("Tuesday");
} else if (dayOfWeek == 3) {
System.out.println("Wednesday");
} else if (dayOfWeek == 4) {
System.out.println("Thursday");
} else if (dayOfWeek == 5) {
System.out.println("Friday");
} else if (dayOfWeek == 6) {
System.out.println("Saturday");
} else if (dayOfWeek == 7) {
System.out.println("Sunday");
} else {
System.out.println("Invalid day");
}
Important: Order Matters
# Wrong order - The first true condition stops checking
score = 95
# Bad - Will always hit first condition
if score >= 60:
print("Passing")
elif score >= 90:
print("Excellent") # This never executes!
# Output: "Passing"
# Good - Check most specific first
if score >= 90:
print("Excellent")
elif score >= 80:
print("Good")
elif score >= 70:
print("Fair")
elif score >= 60:
print("Passing")
else:
print("Failing")
Nested If Statements
If Inside If
You can place if statements inside other if statements for more complex logic.
# Python
age = 25
has_license = True
if age >= 18:
print("You're old enough to drive")
if has_license:
print("And you have a license!")
print("You can drive legally")
else:
print("But you need to get a license first")
else:
print("You're too young to drive")
// JavaScript
let isLoggedIn = true;
let isAdmin = true;
let hasPermission = true;
if (isLoggedIn) {
console.log("User is logged in");
if (isAdmin) {
console.log("Admin user detected");
if (hasPermission) {
console.log("Admin has full access");
console.log("Can delete users, view logs");
} else {
console.log("Admin has limited access");
}
} else {
console.log("Regular user");
}
} else {
console.log("Please log in");
}
Deep Nesting - Handle with Care
# Deep nesting can become hard to read
if condition1:
if condition2:
if condition3:
if condition4:
print("Deeply nested")
else:
print("Level 4 false")
else:
print("Level 3 false")
else:
print("Level 2 false")
else:
print("Level 1 false")
# Better approach - combine conditions
if condition1 and condition2 and condition3 and condition4:
print("All conditions true")
elif condition1 and condition2 and condition3:
print("First three true")
elif condition1 and condition2:
print("First two true")
elif condition1:
print("First condition true")
else:
print("First condition false")
Comparison Operators
Numerical Comparisons
# Python - Numerical operators
a = 10
b = 20
if a == b: # Equal to
print("Equal")
if a != b: # Not equal to
print("Not equal")
if a > b: # Greater than
print("a > b")
if a < b: # Less than
print("a < b")
if a >= b: # Greater than or equal
print("a >= b")
if a <= b: # Less than or equal
print("a <= b")
// JavaScript - Similar operators
let x = 5;
let y = "5";
// Value equality
if (x == y) {
console.log("Values equal"); // True (type coercion)
}
// Strict equality (type + value)
if (x === y) {
console.log("Strictly equal"); // False (different types)
}
String Comparisons
# Python
name = "Alice"
if name == "Alice":
print("Hello Alice!")
if name != "Bob":
print("You're not Bob")
# Case-sensitive
if name.lower() == "alice":
print("Case-insensitive match")
// JavaScript
let username = "admin";
if (username === "admin") {
console.log("Welcome admin!");
}
// String comparison (lexicographic)
if ("apple" < "banana") {
console.log("apple comes before banana");
}
Boolean Comparisons
# Python
is_logged_in = True
is_premium = False
# Direct boolean check (most Pythonic)
if is_logged_in:
print("User is logged in")
# Explicit comparison (also valid)
if is_logged_in == True:
print("Also works, but redundant")
# Check for False
if not is_premium:
print("Not a premium user")
Logical Operators
AND Operator (&&)
All conditions must be true for the overall condition to be true.
# Python
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive")
else:
print("Cannot drive")
# Multiple conditions
score = 85
attendance = 90
if score >= 70 and attendance >= 80:
print("Student passes")
// JavaScript
let username = "admin";
let password = "secret123";
if (username === "admin" && password === "secret123") {
console.log("Login successful!");
}
OR Operator (||)
At least one condition must be true.
# Python
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("It's a weekday")
// JavaScript
let userRole = "editor";
let hasPermission = true;
if (userRole === "admin" || hasPermission) {
console.log("Access granted");
}
NOT Operator (!)
Reverses the truth value of a condition.
# Python
is_raining = False
if not is_raining:
print("It's not raining, go outside!")
# Common pattern
if not user_logged_in:
print("Please log in")
// JavaScript
let isComplete = false;
if (!isComplete) {
console.log("Task not yet complete");
}
Truth Tables
AND (&&) Truth Table: ┌─────────┬─────────┬─────────┐ │ A │ B │ A && B │ ├─────────┼─────────┼─────────┤ │ true │ true │ true │ │ true │ false │ false │ │ false │ true │ false │ │ false │ false │ false │ └─────────┴─────────┴─────────┘ OR (||) Truth Table: ┌─────────┬─────────┬─────────┐ │ A │ B │ A || B │ ├─────────┼─────────┼─────────┤ │ true │ true │ true │ │ true │ false │ true │ │ false │ true │ true │ │ false │ false │ false │ └─────────┴─────────┴─────────┘ NOT (!) Truth Table: ┌─────────┬─────────┐ │ A │ !A │ ├─────────┼─────────┤ │ true │ false │ │ false │ true │ └─────────┴─────────┘
Short-Circuit Evaluation
# Python - Stops at first false in AND
def expensive_check():
print("Expensive operation...")
return True
x = False
# expensive_check() never called because x is False
if x and expensive_check():
print("Both true")
# Stops at first true in OR
y = True
# expensive_check() never called because y is True
if y or expensive_check():
print("At least one true")
Combining Multiple Conditions
# Python - Complex conditions
age = 25
is_student = True
income = 30000
has_scholarship = False
# Complex eligibility check
if (age >= 18 and age <= 65) and (is_student or income < 50000) and not has_scholarship:
print("Eligible for financial aid")
else:
print("Not eligible")
# Use parentheses for clarity
if (age >= 18 and age <= 65) and \
(is_student or income < 50000) and \
not has_scholarship:
print("Eligible")
Ternary Operator
Basic Ternary (Conditional Expression)
A shorthand for simple if-else assignments.
# Python age = 18 status = "Adult" if age >= 18 else "Minor" print(status) # "Adult" # Multiple assignments is_raining = True weather = "Stay inside" if is_raining else "Go outside"
// JavaScript let score = 85; let grade = score >= 60 ? "Pass" : "Fail"; console.log(grade); // "Pass" // With multiple statements (use sparingly) let result = score >= 90 ? "Excellent" : score >= 80 ? "Good" : score >= 70 ? "Fair" : "Poor";
// Java int number = 10; String parity = (number % 2 == 0) ? "Even" : "Odd"; System.out.println(parity); // "Even"
When to Use Ternary
# Good - Simple assignments max_value = a if a > b else b discount = 0.1 if is_member else 0.05 # Bad - Complex logic (use if-else instead) result = (a if a > b else b) if (a > 0 and b > 0) else 0 # Too complex # Better with if-else if a > 0 and b > 0: result = a if a > b else b else: result = 0
Switch Statements
Traditional Switch (C, Java, JavaScript)
// Java switch statement
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
System.out.println(dayName); // "Wednesday"
// JavaScript switch
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("Red or green fruit");
break;
case "banana":
console.log("Yellow fruit");
break;
case "orange":
console.log("Orange citrus fruit");
break;
default:
console.log("Unknown fruit");
}
Python Match Statement (Python 3.10+)
# Python match statement (structural pattern matching)
def describe_number(num):
match num:
case 0:
return "Zero"
case 1:
return "One"
case 2:
return "Two"
case _:
return "Something else"
# Matching patterns
def process_command(command):
match command.split():
case ["quit"]:
print("Exiting program")
case ["hello", name]:
print(f"Hello, {name}!")
case ["add", x, y]:
print(f"Sum: {int(x) + int(y)}")
case _:
print("Unknown command")
Switch vs If-Else
Switch vs If-Else: Switch is better for: ├── Single variable with many possible values ├── When comparing to constants ├── When performance matters (jump table) └── Code readability with many cases If-Else is better for: ├── Complex conditions ├── Range checks ├── Boolean expressions └── When conditions vary
Pattern Matching
Advanced Pattern Matching (Python 3.10+)
# Python - Complex pattern matching
def analyze_data(data):
match data:
case []:
return "Empty list"
case [x]:
return f"Single element: {x}"
case [x, y]:
return f"Two elements: {x}, {y}"
case [x, *rest]:
return f"First: {x}, Rest length: {len(rest)}"
case {"name": name, "age": age}:
return f"Person: {name} is {age} years old"
case _:
return "Something else"
# Using match with classes
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def describe_point(point):
match point:
case Point(0, 0):
return "Origin"
case Point(0, y):
return f"On Y-axis at y={y}"
case Point(x, 0):
return f"On X-axis at x={x}"
case Point(x, y):
return f"Point at ({x}, {y})"
Common Patterns
Guard Clauses (Early Returns)
# Without guard clauses - nested ifs def process_user(user): if user: if user.is_active: if user.is_authenticated: if user.has_permission: return "Process user" else: return "No permission" else: return "Not authenticated" else: return "Account inactive" else: return "No user" # With guard clauses - cleaner def process_user(user): if not user: return "No user" if not user.is_active: return "Account inactive" if not user.is_authenticated: return "Not authenticated" if not user.has_permission: return "No permission" return "Process user"
Validation Patterns
# Input validation
def validate_form(data):
errors = []
if not data.get("name"):
errors.append("Name is required")
elif len(data["name"]) < 2:
errors.append("Name must be at least 2 characters")
if not data.get("email"):
errors.append("Email is required")
elif "@" not in data["email"]:
errors.append("Invalid email format")
if not data.get("age"):
errors.append("Age is required")
elif data["age"] < 18:
errors.append("Must be 18 or older")
if errors:
return {"valid": False, "errors": errors}
return {"valid": True, "data": data}
State Machines
# Simple state machine with if statements def traffic_light(current_state, car_present): if current_state == "red": if car_present: next_state = "green" else: next_state = "red" elif current_state == "green": next_state = "yellow" elif current_state == "yellow": next_state = "red" else: next_state = "red" return next_state
Best Practices
1. Keep Conditions Simple
# Bad if x > 0 and y > 0 and z > 0 and x < 100 and y < 100 and z < 100: pass # Good - Extract to named variables is_positive = x > 0 and y > 0 and z > 0 is_within_bounds = x < 100 and y < 100 and z < 100 if is_positive and is_within_bounds: pass # Or create a function def is_valid_coordinate(x, y, z): return (x > 0 and x < 100 and y > 0 and y < 100 and z > 0 and z < 100) if is_valid_coordinate(x, y, z): pass
2. Avoid Deep Nesting
# Bad - Too deep if condition1: if condition2: if condition3: if condition4: do_something() # Good - Flatten with early returns if not condition1: return if not condition2: return if not condition3: return if not condition4: return do_something()
3. Use Meaningful Variable Names
# Bad if x > 0: pass # Good if user_age >= MINIMUM_VOTING_AGE: pass
4. Consider All Cases
def get_discount(customer_type): # Always include default/else case if customer_type == "premium": return 0.20 elif customer_type == "regular": return 0.10 elif customer_type == "new": return 0.05 else: return 0.00 # Default case
5. Use Enums for Multiple Options
from enum import Enum class UserType(Enum): ADMIN = "admin" EDITOR = "editor" VIEWER = "viewer" def get_permissions(user_type): if user_type == UserType.ADMIN: return ["read", "write", "delete", "manage_users"] elif user_type == UserType.EDITOR: return ["read", "write"] elif user_type == UserType.VIEWER: return ["read"] else: return []
Real-World Examples
Example 1: Login System
class LoginSystem:
def __init__(self):
self.users = {
"alice": {"password": "secret123", "is_active": True, "role": "admin"},
"bob": {"password": "pass456", "is_active": True, "role": "user"},
"charlie": {"password": "123", "is_active": False, "role": "user"}
}
self.max_attempts = 3
def login(self, username, password):
# Guard clauses for validation
if not username or not password:
return {"success": False, "message": "Username and password required"}
if username not in self.users:
return {"success": False, "message": "User not found"}
user = self.users[username]
if not user["is_active"]:
return {"success": False, "message": "Account is deactivated"}
if user["password"] != password:
return {"success": False, "message": "Invalid password"}
# Success - check role
if user["role"] == "admin":
return {"success": True, "message": "Welcome admin!", "role": "admin"}
else:
return {"success": True, "message": f"Welcome {username}!", "role": "user"}
def change_password(self, username, old_password, new_password):
# Validate user exists
if username not in self.users:
return False
user = self.users[username]
# Check current password
if user["password"] != old_password:
return False
# Validate new password
if len(new_password) < 6:
return False
if new_password == old_password:
return False
# Update password
user["password"] = new_password
return True
Example 2: E-commerce Checkout
class CheckoutSystem:
def calculate_total(self, cart, user, coupon=None):
"""Calculate order total with discounts and shipping"""
subtotal = sum(item["price"] * item["quantity"] for item in cart)
# Apply coupon discount
discount = 0
if coupon:
if coupon["type"] == "percentage":
discount = subtotal * coupon["value"] / 100
elif coupon["type"] == "fixed":
discount = min(coupon["value"], subtotal)
# Apply user tier discount
if user.get("tier") == "gold":
discount += subtotal * 0.10 # 10% gold discount
elif user.get("tier") == "silver":
discount += subtotal * 0.05 # 5% silver discount
after_discount = subtotal - discount
# Calculate shipping
shipping = 0
if after_discount > 0:
if after_discount > 100:
shipping = 0 # Free shipping
elif after_discount > 50:
shipping = 5.99
else:
shipping = 9.99
# Add tax
tax_rate = 0.08 # 8% tax
tax = after_discount * tax_rate
total = after_discount + shipping + tax
return {
"subtotal": round(subtotal, 2),
"discount": round(discount, 2),
"shipping": round(shipping, 2),
"tax": round(tax, 2),
"total": round(total, 2)
}
Example 3: Game Logic
class GameCharacter:
def __init__(self, name, health, mana):
self.name = name
self.health = health
self.mana = mana
self.level = 1
self.experience = 0
self.is_alive = True
def take_damage(self, damage):
# Apply damage with armor reduction
if self.health <= 0:
return "Already dead"
# Critical hit chance
import random
if random.random() < 0.1: # 10% crit chance
damage *= 2
print("Critical hit!")
self.health -= damage
if self.health <= 0:
self.health = 0
self.is_alive = False
return f"{self.name} has been defeated!"
else:
return f"{self.name} took {damage} damage. Health: {self.health}"
def heal(self, amount):
if not self.is_alive:
return "Cannot heal a dead character"
self.health += amount
if self.health > 100:
self.health = 100
return f"{self.name} healed for {amount}. Health: {self.health}"
def cast_spell(self, spell_name, cost):
if not self.is_alive:
return "Dead character cannot cast spells"
if self.mana < cost:
return f"Not enough mana! Need {cost}, have {self.mana}"
self.mana -= cost
return f"{self.name} casts {spell_name}! Mana left: {self.mana}"
def level_up(self):
if self.experience >= 100 * self.level:
self.level += 1
self.experience -= 100 * (self.level - 1)
self.health = 100 # Full heal on level up
self.mana = 100
return f"{self.name} reached level {self.level}!"
return f"Need {100 * self.level - self.experience} more XP to level up"
Conclusion
Key Takeaways
- If statements are fundamental to decision-making in programs
- Always consider all paths - think about what happens when conditions are true AND false
- Keep conditions simple - complex conditions are hard to understand and debug
- Use appropriate patterns - guard clauses, early returns, validation
- Test edge cases - always test boundary conditions
When to Use What
| Construct | Best Use Case |
|---|---|
| Simple if | Single decision, one branch |
| if-else | Two mutually exclusive paths |
| else-if | Multiple mutually exclusive conditions |
| Nested if | Complex hierarchical decisions |
| Switch/match | Single variable with many specific values |
| Ternary | Simple conditional assignment |
Common Mistakes to Avoid
❌ Forgetting else cases ❌ Deep nesting without reason ❌ Complex conditions without parentheses ❌ Using == with floating point numbers ❌ Forgetting break in switch statements ❌ Not considering all possible inputs
Testing Conditions
Always test your conditions with:
- Normal cases
- Edge cases (minimum, maximum)
- Boundary values
- Invalid inputs
- Empty/null values
Conditional logic is the foundation of dynamic programs. Master it, and you'll be able to create responsive, intelligent applications!