🔄 If / Elif / Else

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

Making Decisions

python
score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print(f"Score: {score} → Grade: {grade}")
Output
Score: 85 → Grade: B

Comparison & Logical Operators

python
# Comparison: == != > < >= <= # Logical: and or not age = 25 income = 8000 is_vip = False # and — both must be True if age >= 21 and income >= 5000: print("Eligible for loan") # or — at least one True if age < 18 or income > 20000: print("Special rate") # not — reverses if not is_vip: print("Standard customer") # Chained comparisons if 18 <= age <= 65: print("Working age")
Output
Eligible for loan Standard customer Working age

Ternary (One-line if)

python
salary = 12000 level = "Senior" if salary > 10000 else "Junior" print(level) # Senior # Nested ternary (use sparingly) score = 75 grade = "A" if score>=90 else "B" if score>=80 else "C" if score>=70 else "F" print(grade) # C
💡 Tip: Python uses indentation (4 spaces) to define code blocks — this is required, not optional.
🎯 TASK Practice: If / Elif / Else
Build a loan eligibility checker: age 21-60, income >= 5000, credit score >= 650, no existing loans. Print eligibility and reason if rejected.
Starter code:
python
def check_loan(age, income, credit_score, has_loan): if ???: return False, "Age must be between 21 and 60" elif ???: return False, "Income below minimum (5000)" elif ???: return False, "Credit score too low (min 650)" elif ???: return False, "Existing loan must be cleared first" else: max_loan = income * 36 return True, f"Eligible! Max loan: {max_loan:,} EGP" approved, msg = check_loan(28, 8000, 700, False) print(f"Approved: {approved}") print(f"Message: {msg}")

🔄 For Loops

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

Basic For Loop

python
products = ["Laptop", "Phone", "Tablet", "Monitor"] for product in products: print(f"Processing: {product}") print(f"Done! {len(products)} products processed.")
Output
Processing: Laptop Processing: Phone Processing: Tablet Processing: Monitor Done! 4 products processed.

range() — Loop N Times

python
# range(stop) → 0 to stop-1 # range(start, stop) → start to stop-1 # range(start,stop,step)→ with step for i in range(1, 6): print(f"Month {i}: target = {i * 50000:,}") print("---") for i in range(10, 0, -2): # countdown print(i, end=" ")
Output
Month 1: target = 50,000 Month 2: target = 100,000 Month 3: target = 150,000 Month 4: target = 200,000 Month 5: target = 250,000 --- 10 8 6 4 2

enumerate() & zip()

python
months = ["Jan","Feb","Mar","Apr"] sales = [45000, 52000, 48000, 61000] targets = [50000, 50000, 55000, 60000] # enumerate — index + value for i, month in enumerate(months, 1): print(f"{i}. {month}") # zip — loop multiple lists together for month, sale, target in zip(months, sales, targets): status = "✅" if sale >= target else "❌" print(f"{month}: {sale:,} / {target:,} {status}")
Output
1. Jan 2. Feb 3. Mar 4. Apr Jan: 45,000 / 50,000 ❌ Feb: 52,000 / 50,000 ✅ Mar: 48,000 / 55,000 ❌ Apr: 61,000 / 60,000 ✅
🎯 TASK Practice: For Loops
Loop through a list of transactions. Calculate running total, flag transactions > 10000 as 'Large', count each category, and print a summary.
Starter code:
python
transactions = [ {"id":1,"amount":5000, "category":"Sales"}, {"id":2,"amount":15000,"category":"Sales"}, {"id":3,"amount":3000, "category":"Refund"}, {"id":4,"amount":12000,"category":"Sales"}, {"id":5,"amount":800, "category":"Refund"}, ] running_total = 0 category_counts = {} for t in transactions: running_total += t["amount"] flag = "Large" if t["amount"] > ??? else "Normal" cat = t["category"] category_counts[cat] = category_counts.get(cat, 0) + 1 print(f"ID {t['id']}: {t['amount']:>8,} | {flag:<7} | Running: {running_total:,}") print(f"\nCategories: {category_counts}")

🔄 While Loops

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

Basic While Loop

python
# while loop runs as long as condition is True count = 1 while count <= 5: print(f"Attempt {count}") count += 1 # IMPORTANT: update the condition! print("Done!")
Output
Attempt 1 Attempt 2 Attempt 3 Attempt 4 Attempt 5 Done!

break and continue

python
# Search for first sale over target sales = [3000, 7000, 2000, 15000, 9000, 4000] target = 10000 found = None i = 0 while i < len(sales): if sales[i] >= target: found = sales[i] break # Stop searching i += 1 print(f"First sale over {target:,}: {found:,}" if found else "None found") # Skip negatives values = [5, -3, 8, -1, 4, 7] total = 0 i = 0 while i < len(values): i += 1 if values[i-1] < 0: continue # Skip negatives total += values[i-1] print(f"Sum of positives: {total}")
Output
First sale over 10,000: 15,000 Sum of positives: 24

while True (Infinite Loop)

python
# Use for menus and retrying attempts = 0 max_attempts = 3 while True: attempts += 1 password = input(f"Password (attempt {attempts}/{max_attempts}): ") if password == "secret123": print("Access granted!") break elif attempts >= max_attempts: print("Account locked!") break else: print("Wrong password, try again.")
💡 Tip: Always make sure a while loop has a way to exit — otherwise you'll have an infinite loop that freezes your program!
🎯 TASK Practice: While Loops
Simulate a simple ATM: start with balance 10000 EGP. Loop to allow withdrawals. Reject if amount > balance or > 5000 per transaction. Exit when user enters 0.
Starter code:
python
balance = 10_000 transactions = 0 while True: print(f"\nBalance: {balance:,} EGP") amount = int(input("Withdraw (0 to exit): ")) if amount == ???: print(f"Thank you! {transactions} transactions made.") break elif amount > ???: print("Exceeds single transaction limit (5000)") continue elif amount > ???: print("Insufficient funds!") continue else: balance -= amount transactions += 1 print(f"Dispensing {amount:,} EGP")

🔄 Functions

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

Defining & Calling Functions

python
def calculate_tax(amount, rate=0.14): """Calculate VAT on an amount.""" tax = amount * rate total = amount + tax return total # Call with positional args print(calculate_tax(1000)) # 1140.0 (uses default 14%) print(calculate_tax(5000, 0.10)) # 5500.0 (uses 10%) # Call with keyword args print(calculate_tax(rate=0.05, amount=2000)) # 2100.0
Output
1140.0 5500.0 2100.0

*args and **kwargs

python
# *args — accept any number of positional arguments def total_sales(*amounts): return sum(amounts) print(total_sales(1000, 2000, 3000)) # 6000 print(total_sales(500, 750, 800, 1200)) # 3250 # **kwargs — accept any number of keyword arguments def create_report(**info): for key, value in info.items(): print(f" {key}: {value}") create_report(month="January", total=450000, growth="12%")
Output
6000 3250 month: January total: 450000 growth: 12%

Return Multiple Values

python
def analyze_sales(data): """Return multiple stats as a tuple.""" total = sum(data) avg = total / len(data) best = max(data) worst = min(data) return total, avg, best, worst sales = [45000, 72000, 31000, 58000, 66000] total, avg, best, worst = analyze_sales(sales) print(f"Total: {total:,} | Avg: {avg:,.0f} | Best: {best:,} | Worst: {worst:,}")
Output
Total: 272,000 | Avg: 54,400 | Best: 72,000 | Worst: 31,000
🎯 TASK Practice: Functions
Write 3 utility functions for a sales system: calculate_commission(sales, rate), apply_discount(price, pct), and format_report(name, data_dict). Use default parameters.
Starter code:
python
def calculate_commission(sales, rate=0.05): """Return commission amount.""" return ??? def apply_discount(price, pct=10): """Return price after discount.""" return ??? def format_report(name, data): """Print a formatted report.""" print(f"\n{'='*30}") print(f" Report: {name}") print(f"{'='*30}") for key, value in data.items(): if isinstance(value, (int, float)): print(f" {key:<15}: {value:>10,}") else: print(f" {key:<15}: {value:>10}") # Test all functions sales = 150_000 comm = calculate_commission(sales) disc = apply_discount(12000, 15) format_report("Q1 Summary", { "Total Sales": sales, "Commission": comm, "Discounted Price": disc, "Agent": "Ahmed" })

🔄 Lambda Functions

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

What is Lambda?

A lambda is a small anonymous function — perfect for short, one-time operations especially with sort() and filter().

python
# Regular function def double(x): return x * 2 # Equivalent lambda double = lambda x: x * 2 print(double(5)) # 10 # Lambda with multiple args add = lambda x, y: x + y print(add(3, 4)) # 7 # Lambda with condition classify = lambda x: "High" if x > 50000 else "Low" print(classify(72000)) # High
Output
10 7 High

Lambda with sorted() and map()

python
employees = [ {"name": "Ahmed", "salary": 9500, "dept": "Sales"}, {"name": "Sara", "salary": 12000, "dept": "IT"}, {"name": "Omar", "salary": 8800, "dept": "Sales"}, {"name": "Layla", "salary": 15000, "dept": "IT"}, ] # Sort by salary by_salary = sorted(employees, key=lambda e: e["salary"]) for e in by_salary: print(f"{e['name']:<8} {e['salary']:,}") # Sort by dept then salary by_dept_sal = sorted(employees, key=lambda e: (e["dept"], e["salary"])) # map — apply function to all items salaries = [e["salary"] for e in employees] after_raise = list(map(lambda s: s * 1.10, salaries)) print(after_raise)
Output
Omar 8,800 Ahmed 9,500 Sara 12,000 Layla 15,000 [10450.0, 13200.0, 9680.0, 16500.0]
🎯 TASK Practice: Lambda Functions
Use lambda with sorted(), filter(), and map() to: sort products by price descending, filter only in-stock items, and apply 20% discount to expensive items (>10000).
Starter code:
python
products = [ {"name":"Laptop", "price":12000,"stock":5}, {"name":"Phone", "price":6500, "stock":0}, {"name":"Monitor", "price":8000, "stock":3}, {"name":"Tablet", "price":4200, "stock":8}, {"name":"Camera", "price":15000,"stock":2}, ] # Sort by price descending by_price = sorted(products, key=lambda p: ???, reverse=True) print("By price:", [p["name"] for p in by_price]) # Filter in-stock only in_stock = list(filter(lambda p: ???, products)) print("In stock:", [p["name"] for p in in_stock]) # Apply 20% discount to items over 10000 discounted = list(map(lambda p: {**p, "price": p["price"]*0.8} if p["price"] > ??? else p, products)) for p in discounted: print(f"{p['name']}: {p['price']:,}")

🔄 List Comprehensions

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

From Loop to Comprehension

python
# Traditional loop prices = [100, 250, 75, 400, 180] discounted = [] for p in prices: discounted.append(p * 0.9) # List comprehension — same result, 1 line discounted = [p * 0.9 for p in prices] print(discounted)
Output
[90.0, 225.0, 67.5, 360.0, 162.0]

With Conditions

python
sales = [45000, 28000, 72000, 15000, 58000, 31000] # Filter: only sales above 30000 high = [s for s in sales if s > 30000] # Transform: apply bonus to high performers only bonus = [s * 1.15 if s > 50000 else s for s in sales] # Both filter and transform big_bonus = [s * 1.20 for s in sales if s > 50000] print("High:", high) print("Bonus:", bonus) print("Big bonus:", big_bonus)
Output
High: [45000, 72000, 58000] Bonus: [45000, 28000, 82800.0, 15000, 66700.0, 31000] Big bonus: [86400.0, 69600.0]

Dict & Set Comprehensions

python
employees = [("Ahmed",9500),("Sara",12000),("Omar",8800)] # Dict comprehension salary_dict = {name: salary for name, salary in employees} print(salary_dict) # Filter in dict comprehension high_earners = {name: sal for name, sal in employees if sal > 9000} print(high_earners) # Set comprehension — unique departments records = [("Ahmed","Sales"),("Sara","IT"),("Omar","Sales"),("Layla","IT")] depts = {dept for _, dept in records} print(depts) # {'Sales', 'IT'}
Output
{'Ahmed': 9500, 'Sara': 12000, 'Omar': 8800} {'Ahmed': 9500, 'Sara': 12000} {'Sales', 'IT'}
🎯 TASK Practice: List Comprehensions
Use comprehensions to process sales data: create a list of formatted strings, a dict of name→annual salary, and filter employees earning above average.
Starter code:
python
employees = [ {"name":"Ahmed", "salary":9500, "dept":"Sales"}, {"name":"Sara", "salary":12000, "dept":"IT"}, {"name":"Omar", "salary":8800, "dept":"Sales"}, {"name":"Layla", "salary":15000, "dept":"IT"}, {"name":"Karim", "salary":7500, "dept":"HR"}, ] # List of formatted strings labels = [f"{e['name']} ({e['dept']}): {e['salary']:,}" for e in employees] # Dict: name → annual salary annual = {e["name"]: e["salary"] * ??? for e in employees} # Filter above average avg = sum(e["salary"] for e in employees) / len(employees) above_avg = [e["name"] for e in employees if e["salary"] > ???] for label in labels: print(label) print(f"\nAverage: {avg:,.0f}") print(f"Above average: {above_avg}")

🔄 Dict & Set Comprehensions

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

Dict Comprehensions

python
# Basic dict comprehension squares = {x: x**2 for x in range(1, 6)} print(squares) # {1:1, 2:4, 3:9, 4:16, 5:25} # From two lists using zip cities = ["Cairo", "Alex", "Giza"] sales = [450000, 280000, 195000] sales_dict = {city: sale for city, sale in zip(cities, sales)} print(sales_dict) # Swap keys and values inverted = {v: k for k, v in sales_dict.items()} print(inverted) # Filter while building high_sales = {city: s for city, s in sales_dict.items() if s > 200000} print(high_sales)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25} {'Cairo': 450000, 'Alex': 280000, 'Giza': 195000} {450000: 'Cairo', 280000: 'Alex', 195000: 'Giza'} {'Cairo': 450000, 'Alex': 280000}

Nested Dict Comprehension

python
# Create a multiplication table table = {i: {j: i*j for j in range(1,4)} for i in range(1,4)} for row, vals in table.items(): print(f"{row}: {vals}") # Group employees by department employees = [ {"name":"Ahmed","dept":"Sales"}, {"name":"Sara", "dept":"IT"}, {"name":"Omar", "dept":"Sales"}, ] by_dept = {} for e in employees: by_dept.setdefault(e["dept"], []).append(e["name"]) print(by_dept)
Output
1: {1: 1, 2: 2, 3: 3} 2: {1: 2, 2: 4, 3: 6} 3: {1: 3, 2: 6, 3: 9} {'Sales': ['Ahmed', 'Omar'], 'IT': ['Sara']}
💡 Tip: Use dict comprehensions for transforming data — they're faster and more readable than building dicts in loops.
🎯 TASK Practice: Dict & Set Comprehensions
Given sales data, use comprehensions to: normalize sales (0-1 scale), create a rank dict, and group cities by performance tier (High/Medium/Low).
Starter code:
python
sales = {"Cairo":450000,"Alex":280000,"Giza":195000,"Aswan":90000,"Luxor":120000} max_s = max(sales.values()) min_s = min(sales.values()) # Normalize 0-1 normalized = {city: (s-min_s)/(max_s-min_s) for city, s in sales.items()} # Rank (1=highest) ranked = {city: rank+1 for rank,(city,_) in enumerate( sorted(sales.items(), key=lambda x: -x[1]) )} # Tier tiers = {city: "High" if s>300000 else "Medium" if s>150000 else "Low" for city, s in sales.items()} for city in sales: print(f"{city:<8} norm:{normalized[city]:.2f} rank:{ranked[city]} tier:{tiers[city]}")

🔄 File I/O

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

Writing & Reading Files

python
# Write with open("report.txt", "w", encoding="utf-8") as f: f.write("=== Q4 Sales Report ===\n") for city, amount in [("Cairo",450000),("Alex",280000)]: f.write(f"{city}: {amount:,}\n") # Read all at once with open("report.txt", "r", encoding="utf-8") as f: content = f.read() print(content) # Read line by line (memory efficient for large files) with open("report.txt", "r") as f: for line in f: print(line.strip())
Output
=== Q4 Sales Report === Cairo: 450,000 Alex: 280,000

CSV Files

python
import csv # Write CSV data = [ ["Name","Dept","Salary"], ["Ahmed","Sales",9500], ["Sara","IT",12000], ] with open("employees.csv","w",newline="",encoding="utf-8") as f: writer = csv.writer(f) writer.writerows(data) # Read CSV as dict with open("employees.csv","r",encoding="utf-8") as f: for row in csv.DictReader(f): print(f"{row['Name']:<10} {row['Dept']:<8} {int(row['Salary']):,}")
Output
Ahmed Sales 9,500 Sara IT 12,000

JSON Files

python
import json # Write JSON config = {"db":"postgresql","host":"localhost","port":5432} with open("config.json","w") as f: json.dump(config, f, indent=2) # Read JSON with open("config.json","r") as f: cfg = json.load(f) print(cfg["host"]) # localhost
💡 Tip: Always use encoding="utf-8" when working with text files to handle Arabic and other non-ASCII characters.
🎯 TASK Practice: File I/O
Write a complete file pipeline: save employee data as both CSV and JSON, then read the CSV back, filter high earners, and append a summary to a text report.
Starter code:
python
import csv, json employees = [ {"name":"Ahmed","dept":"Sales","salary":9500}, {"name":"Sara","dept":"IT","salary":12000}, {"name":"Omar","dept":"Sales","salary":8800}, {"name":"Layla","dept":"IT","salary":15000}, ] # Save as CSV with open("employees.csv","w",newline="") as f: writer = csv.DictWriter(f, fieldnames=["name","dept","salary"]) writer.writeheader() writer.writerows(employees) # Save as JSON with open("employees.json","w") as f: json.dump(employees, f, indent=2) # Read CSV and filter with open("employees.csv","r") as f: high = [r for r in csv.DictReader(f) if int(r["salary"]) > 10000] # Write summary report with open("summary.txt","w") as f: f.write(f"High earners (>{10000:,} EGP):\n") for r in high: f.write(f" {r['name']}: {int(r['salary']):,}\n") print(f"Saved {len(employees)} employees") print(f"High earners: {len(high)}")

🔄 Classes & OOP Basics

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

What is OOP?

Object-Oriented Programming organizes code into classes — blueprints for creating objects with data (attributes) and behavior (methods).

python
class Employee: """Represents a company employee.""" company = "TechCorp" # Class attribute (shared by all) def __init__(self, name, dept, salary): """Constructor — runs when creating object.""" self.name = name # Instance attributes self.dept = dept self.salary = salary def greet(self): return f"Hi, I'm {self.name} from {self.dept}." def give_raise(self, pct): self.salary *= (1 + pct/100) return self.salary # Create objects e1 = Employee("Ahmed", "Sales", 9500) e2 = Employee("Sara", "IT", 12000) print(e1.greet()) print(e2.greet()) print(e1.give_raise(10)) print(Employee.company) # class attribute
Output
Hi, I'm Ahmed from Sales. Hi, I'm Sara from IT. 10450.0 TechCorp
🎯 TASK Practice: Classes & OOP Basics
Create a BankAccount class with: balance, owner, deposit(), withdraw() (check funds), and statement() methods.
Starter code:
python
class BankAccount: def __init__(self, owner, initial_balance=0): self.owner = owner self.balance = initial_balance self.history = [] def deposit(self, amount): self.balance += amount self.history.append(f"+{amount:,}") return self.balance def withdraw(self, amount): if amount > self.balance: return "Insufficient funds" self.balance -= amount self.history.append(f"-{amount:,}") return self.balance def statement(self): print(f"\nAccount: {self.owner}") print(f"Balance: {self.balance:,} EGP") print(f"Transactions: {', '.join(self.history)}") acc = BankAccount("Ahmed", 10000) acc.deposit(5000) acc.withdraw(3000) acc.withdraw(20000) # Should fail acc.statement()

🔄 Inheritance & Methods

Unit 3 — Make decisions, repeat actions, write functions — the logic that makes programs smart.

Inheritance

python
class Animal: def __init__(self, name, sound): self.name = name self.sound = sound def speak(self): return f"{self.name} says {self.sound}!" class Dog(Animal): # Inherits from Animal def fetch(self): return f"{self.name} fetches the ball!" class Cat(Animal): def speak(self): # Override parent method return f"{self.name} says Meow (quietly)..." dog = Dog("Rex", "Woof") cat = Cat("Luna", "Meow") print(dog.speak()) # Inherited print(dog.fetch()) # Dog-specific print(cat.speak()) # Overridden
Output
Rex says Woof! Rex fetches the ball! Luna says Meow (quietly)...

super() and Special Methods

python
class Manager(Employee): def __init__(self, name, dept, salary, team_size): super().__init__(name, dept, salary) # Call parent __init__ self.team_size = team_size def __str__(self): # String representation return f"Manager {self.name} ({self.team_size} reports)" def __repr__(self): # Developer representation return f"Manager('{self.name}','{self.dept}',{self.salary})" def __len__(self): # len() support return self.team_size mgr = Manager("Layla","Sales",18000,8) print(mgr) # calls __str__ print(len(mgr)) # calls __len__ → 8
💡 Tip: Special methods (dunder methods) like __str__, __len__, __eq__ let your objects work with Python's built-in operations.
🎯 TASK Practice: Inheritance & Methods
Create a Product class and a DiscountedProduct subclass. Product has name, price, category. DiscountedProduct adds discount_pct and overrides price to return discounted price.
Starter code:
python
class Product: def __init__(self, name, price, category): self.name = name self.price = price self.category = category def __str__(self): return f"{self.name} ({self.category}): {self.price:,} EGP" def apply_vat(self, rate=0.14): return self.price * (1 + rate) class DiscountedProduct(Product): def __init__(self, name, price, category, discount_pct): super().__init__(name, price, category) self.discount_pct = discount_pct @property def discounted_price(self): return self.price * (1 - self.discount_pct/100) def __str__(self): return (f"{self.name}: {self.price:,} → " f"{self.discounted_price:,.0f} EGP ({self.discount_pct}% off)") p1 = Product("Laptop","Cairo",12000) p1 = Product("Laptop",12000,"Electronics") p2 = DiscountedProduct("Phone",6500,"Electronics",20) print(p1) print(p2) print(f"With VAT: {p1.apply_vat():,.0f}")