🐍 Variables & Data Types

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

Creating Variables

python
company = "TechCorp Egypt" # str employees = 250 # int revenue = 4_500_000.75 # float is_listed = True # bool print(company) print(type(employees)) # <class 'int'> print(type(revenue)) # <class 'float'>
Output
TechCorp Egypt <class 'int'> <class 'float'>

The 4 Basic Types

python
name = "Ahmed" # str — text in quotes age = 28 # int — whole number height = 1.75 # float — decimal number active = True # bool — True or False (capital!) # type() checks the type print(type(name)) # <class 'str'> print(type(active)) # <class 'bool'>

Type Conversion

python
text = "42" num = int(text) # "42" → 42 flt = float(text) # "42" → 42.0 back = str(num) # 42 → "42" b = bool(0) # 0 → False b2 = bool(1) # 1 → True print(num + 8) # 50 print(flt + 0.5) # 42.5 print(bool("")) # False — empty string is falsy print(bool("hello")) # True — non-empty is truthy
Output
50 42.5 False True
💡 Tip: Use type(x) to check what type a variable is. Use isinstance(x, int) to check if x is an integer.
🎯 TASK Practice: Variables & Data Types
Create variables for a product record: name, price, quantity, in_stock, rating. Print each with its type. Then calculate total value (price × quantity).
Starter code:
python
product_name = ??? # string price = ??? # float quantity = ??? # int in_stock = ??? # bool rating = ??? # float # Print each with type for var, val in [("name",product_name),("price",price),("qty",quantity)]: print(f"{var}: {val} — type: {type(val).__name__}") total_value = ??? print(f"Total value: {total_value:,}")

🐍 Numbers & Math

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

Integer vs Float

python
x = 10 # int — whole number y = 10.0 # float — decimal z = 10 / 3 # always float: 3.333... w = 10 // 3 # floor div: int: 3 print(type(x)) # int print(type(z)) # float print(round(z, 2)) # 3.33
Output
<class 'int'> <class 'float'> 3.33

Math Operations

python
import math print(math.sqrt(144)) # 12.0 print(math.ceil(4.1)) # 5 — round up print(math.floor(4.9)) # 4 — round down print(math.pi) # 3.14159... print(math.log(100, 10)) # 2.0 (log base 10) print(abs(-50)) # 50 — absolute value print(pow(2, 10)) # 1024 — power
Output
12.0 5 4 3.141592653589793 2.0 50 1024

Business Math Example

python
revenue = 2_500_000 cost = 1_750_000 vat_rate = 0.14 profit = revenue - cost margin = profit / revenue * 100 vat = revenue * vat_rate quarterly_avg = revenue / 4 print(f"Profit: {profit:>12,.0f} EGP") print(f"Margin: {margin:>11.1f}%") print(f"VAT: {vat:>12,.0f} EGP") print(f"Quarterly avg: {quarterly_avg:>12,.0f} EGP")
Output
Profit: 750,000 EGP Margin: 30.0% VAT: 350,000 EGP Quarterly avg: 625,000 EGP
🎯 TASK Practice: Numbers & Math
Calculate loan payments: principal = 500,000 EGP, annual rate = 12%, years = 5. Calculate monthly payment using the formula: M = P × r(1+r)^n / ((1+r)^n - 1)
Starter code:
python
import math principal = 500_000 annual_rate = 0.12 years = 5 monthly_rate = annual_rate / ??? n_payments = years * ??? # Formula: M = P * r*(1+r)^n / ((1+r)^n - 1) monthly_payment = principal * (monthly_rate * (1 + monthly_rate)**n_payments) / ((1 + monthly_rate)**n_payments - 1) total_paid = ??? total_interest = ??? print(f"Monthly payment: {monthly_payment:,.2f}") print(f"Total paid: {total_paid:,.2f}") print(f"Total interest: {total_interest:,.2f}")

🐍 Strings

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

String Creation

python
s1 = 'Single quotes' s2 = "Double quotes" s3 = """Triple quotes for multiple lines like this""" # Raw string (ignores backslashes) path = r"C:\Users\Ahmed\Documents" print(path) # C:\Users\Ahmed\Documents

Essential String Methods

python
name = " ahmed hassan " product = "Laptop Pro X 2024" # Cleaning print(name.strip()) # "ahmed hassan" print(name.strip().title()) # "Ahmed Hassan" print(product.upper()) # "LAPTOP PRO X 2024" print(product.lower()) # "laptop pro x 2024" # Searching print(product.find("Pro")) # 7 (index) print("Pro" in product) # True print(product.count("a")) # 2 print(product.startswith("Laptop")) # True # Modifying print(product.replace("2024","2025")) # "Laptop Pro X 2025" print(product.split(" ")) # ['Laptop','Pro','X','2024'] print("-".join(["a","b","c"])) # "a-b-c"
Output
ahmed hassan Ahmed Hassan LAPTOP PRO X 2024 laptop pro x 2024 7 True 2 True Laptop Pro X 2025 ['Laptop', 'Pro', 'X', '2024'] a-b-c

f-String Formatting

python
name = "Layla" sales = 125_000 rate = 0.085 print(f"Agent: {name}") print(f"Sales: {sales:,}") # 125,000 print(f"Rate: {rate:.1%}") # 8.5% print(f"Name: {name:>10}") # right-align print(f"Code: {42:05d}") # 00042
Output
Agent: Layla Sales: 125,000 Rate: 8.5% Name: Layla Code: 00042

Indexing & Slicing

python
text = "Python Data" # 0 1 2 3 4 5 6 7 8 9 10 ← positive index # -11-10-9-8-7-6-5-4-3-2-1 ← negative index print(text[0]) # 'P' — first character print(text[-1]) # 'a' — last character print(text[7:11]) # 'Data' — [start:stop] (stop NOT included) print(text[:6]) # 'Python'— from start to index 6 print(text[7:]) # 'Data' — from index 7 to end print(text[::2]) # 'Pto aa'— every 2nd character print(text[::-1]) # 'ataD nohtyP' — reversed string!
Output
P a Data Python Data Pto aa ataD nohtyP

Escape Characters

python
print("Line 1\nLine 2") # \n = new line print("Name:\tAhmed") # \t = tab (4 spaces) print("She said \"hello\"") # \" = literal double-quote print("C:\\Users\\Ahmed") # \\ = literal backslash print('It\'s easy') # \' = literal single-quote # Raw string r"..." ignores ALL escape characters path = r"C:\Users\Ahmed\Desktop\data.csv" print(path) # prints exactly: C:\Users\Ahmed\Desktop\data.csv
Output
Line 1 Line 2 Name: Ahmed She said "hello" C:\Users\Ahmed It's easy C:\Users\Ahmed\Desktop\data.csv

String Methods Reference

python
s = " Hello, World! " # ── Case ────────────────────────────── s.upper() # " HELLO, WORLD! " s.lower() # " hello, world! " s.title() # " Hello, World! " s.capitalize() # first char upper, rest lower s.swapcase() # flip every letter's case # ── Trim ────────────────────────────── s.strip() # "Hello, World!" — both sides s.lstrip() # left side only s.rstrip() # right side only # ── Search ──────────────────────────── s.find("World") # 9 — index of first match, -1 if missing s.index("World") # 9 — same but raises ValueError if missing s.count("l") # 3 — how many times it appears s.startswith(" ") # True s.endswith(" ") # True # ── Replace & Split ─────────────────── s.replace("World", "Python") # " Hello, Python! " s.split(",") # [' Hello', ' World! '] "_".join(["a","b","c"]) # "a_b_c" # ── Check Type ──────────────────────── "abc123".isalnum() # True — letters AND digits only "abc".isalpha() # True — letters only "123".isdigit() # True — digits only " ".isspace() # True — whitespace only "Hello".isupper() # False "hello".islower() # True
💡 Remember: Strings are immutable — methods always return a NEW string. The original is never changed. Always assign: name = name.strip().title()
🎯 TASK Practice: Strings
Clean and format a messy customer record: fix spacing, capitalize name, extract domain from email, and build a formatted profile card.
Starter code:
python
record = { "name": " ahmed ibrahim ", "email": "[email protected]", "phone": "010-1234-5678", "city": "CAIRO" } name = record["name"].???.???() email = record["email"] domain = email.split("@")[???] phone = record["phone"].replace("-","") city = record["city"].???() print(f"Name: {name}") print(f"Email: {email}") print(f"Domain: {domain}") print(f"Phone: {phone}") print(f"City: {city}")

🐍 Lists

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

Creating & Accessing

python
products = ["Laptop", "Phone", "Tablet", "Monitor"] prices = [12000, 6500, 4200, 8000] mixed = ["Ahmed", 28, True, 99.5] print(products[0]) # "Laptop" (first) print(products[-1]) # "Monitor" (last) print(products[1:3]) # ['Phone','Tablet'] print(products[:2]) # ['Laptop','Phone'] print(products[::2]) # ['Laptop','Tablet'] (every 2nd) print(len(products)) # 4
Output
Laptop Monitor ['Phone', 'Tablet'] ['Laptop', 'Phone'] ['Laptop', 'Tablet'] 4

Modifying Lists

python
cart = ["Milk", "Bread", "Eggs"] cart.append("Butter") # Add to end cart.insert(1, "Water") # Add at index 1 cart.remove("Bread") # Remove by value last = cart.pop() # Remove & return last first = cart.pop(0) # Remove & return first cart.extend(["Tea","Coffee"]) # Add multiple items cart.sort() # Sort in place print(cart)
Output
['Butter', 'Coffee', 'Tea', 'Water']

Useful List Functions

python
sales = [45000, 72000, 31000, 58000, 66000, 72000] print(sum(sales)) # 344000 print(max(sales)) # 72000 print(min(sales)) # 31000 print(sorted(sales)) # ascending print(sorted(sales, reverse=True)) # descending print(sales.count(72000)) # 2 — appears twice print(sales.index(31000)) # 2 — position of value print(list(reversed(sales)))# reversed list

Copying Lists

python
original = [1, 2, 3, 4, 5] # ❌ WRONG — both names point to the SAME list wrong_copy = original wrong_copy.append(99) print(original) # [1, 2, 3, 4, 5, 99] ← original changed! # ✅ Correct shallow copy — 3 ways (all equivalent) copy1 = original.copy() copy2 = original[:] copy3 = list(original) copy1.append(100) print(original) # [1, 2, 3, 4, 5, 99] ← original safe # ✅ Deep copy — use for lists that contain other lists import copy matrix = [[1, 2], [3, 4]] deep = copy.deepcopy(matrix) deep[0][0] = 999 print(matrix[0][0]) # 1 — original untouched
Output
[1, 2, 3, 4, 5, 99] [1, 2, 3, 4, 5, 99] 1

Joining & Combining Lists

python
a = [1, 2, 3] b = [4, 5, 6] # + operator — creates a NEW list combined = a + b print(combined) # [1, 2, 3, 4, 5, 6] # extend() — adds to existing list IN PLACE a.extend(b) print(a) # [1, 2, 3, 4, 5, 6] # * repetition repeated = [0] * 5 print(repeated) # [0, 0, 0, 0, 0] # zip() — pair two lists together names = ["Ahmed", "Sara", "Omar"] scores = [88, 95, 72] paired = list(zip(names, scores)) print(paired) # [('Ahmed', 88), ('Sara', 95), ('Omar', 72)] # enumerate() — get index AND value for i, name in enumerate(names, start=1): print(f"{i}. {name}")
Output
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [0, 0, 0, 0, 0] [('Ahmed', 88), ('Sara', 95), ('Omar', 72)] 1. Ahmed 2. Sara 3. Omar

List Methods Quick Reference

python
lst = [3, 1, 4, 1, 5, 9, 2, 6] lst.append(7) # add 1 item to end lst.insert(0, 0) # insert at index lst.extend([8, 9]) # add multiple items lst.remove(1) # remove first occurrence of value lst.pop() # remove & return last item lst.pop(0) # remove & return item at index lst.clear() # remove ALL items → [] lst.sort() # sort in-place (ascending) lst.sort(reverse=True) # sort descending lst.reverse() # reverse in-place lst.index(5) # find index of value (ValueError if missing) lst.count(1) # count occurrences of value lst.copy() # shallow copy
🔑 Key Rule: Methods like sort(), reverse(), append() modify the list in place and return None. Functions like sorted() and reversed() return a new object.
🎯 TASK Practice: Lists
Given a list of employee salaries, do the following: find min/max/avg, remove the highest and lowest, add 10% raise to all remaining, sort descending.
Starter code:
python
salaries = [8500, 12000, 9800, 7500, 15000, 11000, 8000] # 1. Stats print(f"Min: {min(salaries):,}") print(f"Max: {max(salaries):,}") print(f"Avg: {sum(salaries)/len(salaries):,.0f}") # 2. Remove highest and lowest salaries.remove(???) salaries.remove(???) # 3. 10% raise to all salaries = [??? for s in salaries] # 4. Sort descending salaries.???(reverse=True) print("After raise, sorted:", salaries)

🐍 Dictionaries

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

Creating & Accessing

python
employee = { "name": "Omar Tarek", "dept": "Sales", "salary": 9500, "active": True, "skills": ["Python", "Excel", "SQL"] } print(employee["name"]) # direct access print(employee.get("bonus", 0)) # safe access with default print(employee["skills"][0]) # nested access print("dept" in employee) # True — key exists?
Output
Omar Tarek 0 Python True

Modifying Dictionaries

python
product = {"name": "Laptop", "price": 12000, "stock": 50} # Add / Update product["color"] = "Silver" # New key product["price"] = 11500 # Update existing product.update({"stock": 45, "warranty": 2}) # Multiple # Remove del product["color"] # Delete key removed = product.pop("warranty") # Remove and return print(product) print("Removed:", removed)
Output
{'name': 'Laptop', 'price': 11500, 'stock': 45} Removed: 2

Looping & Methods

python
sales = {"Cairo": 450000, "Alex": 280000, "Giza": 195000} # Loop keys for city in sales: print(city) # Loop values for amount in sales.values(): print(f"{amount:,}") # Loop both for city, amount in sales.items(): print(f"{city:<10} → {amount:>10,}") # Dict comprehension doubled = {k: v*2 for k,v in sales.items()} print(doubled)

Nested Dictionaries

python
company = { "Cairo": { "manager": "Hoda", "staff": 45, "revenue": 850_000 }, "Alex": { "manager": "Karim", "staff": 28, "revenue": 420_000 } } # Access nested value print(company["Cairo"]["manager"]) # "Hoda" print(company["Alex"]["revenue"]) # 420000 # Add a new branch company["Giza"] = {"manager": "Sara", "staff": 20, "revenue": 310_000} # Loop through nested dict for branch, info in company.items(): print(f"{branch}: {info['staff']} staff — revenue {info['revenue']:,}") # Total revenue across all branches total = sum(b["revenue"] for b in company.values()) print(f"Total: {total:,}")
Output
Hoda 420000 Cairo: 45 staff — revenue 850,000 Alex: 28 staff — revenue 420,000 Giza: 20 staff — revenue 310,000 Total: 1,580,000

Dict Methods Reference

python
d = {"a": 1, "b": 2, "c": 3} d.keys() # dict_keys(['a', 'b', 'c']) d.values() # dict_values([1, 2, 3]) d.items() # dict_items([('a',1), ('b',2), ('c',3)]) d.get("a") # 1 — safe access d.get("z", 0) # 0 — default if key missing d.setdefault("d", 99) # adds "d":99 only if "d" doesn't exist d.update({"b": 20}) # update/add multiple keys d.pop("c") # remove key "c", return its value d.popitem() # remove & return last inserted (key, value) d.clear() # empty the dict → {} # Create dict from keys template = dict.fromkeys(["name","age","city"], None) print(template) # {'name': None, 'age': None, 'city': None} # Copy (shallow) original = {"x": 1, "y": 2} clone = original.copy() # Merge two dicts (Python 3.9+) merged = {"a": 1} | {"b": 2} print(merged) # {'a': 1, 'b': 2}
💡 Tip: Always use d.get("key", default) instead of d["key"] when the key might not exist — it avoids a KeyError.
🎯 TASK Practice: Dictionaries
Build an inventory system: create a dict of 5 products with price and stock. Calculate total inventory value, find the most expensive product, and update stock after selling 3 units of 'Laptop'.
Starter code:
python
inventory = { "Laptop": {"price": 12000, "stock": 10}, "Phone": {"price": 6500, "stock": 25}, "Tablet": {"price": 4200, "stock": 15}, "Monitor": {"price": 8000, "stock": 8}, "Keyboard":{"price": 450, "stock": 50}, } # Total inventory value total_value = sum(??? * ??? for item in inventory.values()) print(f"Total inventory value: {total_value:,}") # Most expensive product most_expensive = max(inventory, key=lambda x: inventory[x][???]) print(f"Most expensive: {most_expensive}") # Update stock after selling 3 Laptops inventory["Laptop"]["stock"] -= ??? print(f"Laptop stock: {inventory['Laptop']['stock']}")

🐍 Tuples & Sets

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

Tuples — Immutable Lists

python
# Tuple — ordered, CANNOT be changed coords = (25.2048, 55.2708) # Dubai coordinates rgb_red = (255, 0, 0) single = (42,) # Single item needs trailing comma! empty = () print(coords[0]) # 25.2048 print(len(rgb_red)) # 3 # Tuple unpacking lat, lng = coords print(f"Lat: {lat}, Lng: {lng}") # Useful: function returning multiple values def get_stats(data): return min(data), max(data), sum(data)/len(data) lo, hi, avg = get_stats([10, 20, 30, 40]) print(lo, hi, avg) # 10 40 25.0
Output
25.2048 3 Lat: 25.2048, Lng: 55.2708 10 40 25.0

Sets — Unique Values Only

python
# Set — unordered, NO duplicates cities = {"Cairo", "Alex", "Giza", "Cairo", "Alex"} print(cities) # {'Cairo', 'Alex', 'Giza'} — duplicates removed! print(len(cities)) # 3 # Set operations a = {1, 2, 3, 4, 5} b = {3, 4, 5, 6, 7} print(a | b) # Union: {1,2,3,4,5,6,7} print(a & b) # Intersection: {3,4,5} print(a - b) # Difference: {1,2} print(a ^ b) # Symmetric: {1,2,6,7} # Practical use: remove duplicates from list sales_ids = [101, 102, 101, 103, 102, 104] unique_ids = list(set(sales_ids)) print(sorted(unique_ids)) # [101, 102, 103, 104]

Tuple Methods & Patterns

python
scores = (88, 95, 72, 95, 60, 88, 95) # Only 2 methods print(scores.count(95)) # 3 — how many times 95 appears print(scores.index(72)) # 2 — index of first 72 # Tuples can be used as dict keys (lists cannot!) locations = { (30.0444, 31.2357): "Cairo", (31.2001, 29.9187): "Alexandria" } # Convert between tuple and list as_list = list(scores) # → mutable list as_tuple = tuple(as_list) # → back to tuple # Extended unpacking first, *middle, last = (1, 2, 3, 4, 5) print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5 # When to use Tuple vs List? # Tuple → fixed data that shouldn't change (coordinates, RGB, DB row) # List → data you'll modify (shopping cart, scores, names)
Output
3 2 1 [2, 3, 4] 5

Set Methods & Operations

python
tags = {"python", "data", "excel"} # Add & Remove tags.add("sql") # add one item tags.update(["pandas","numpy"]) # add multiple items tags.remove("excel") # remove — raises KeyError if missing tags.discard("java") # remove safely — no error if missing # tags.pop() # remove & return a random item # tags.clear() # empty the set → set() print(tags) # Membership check — MUCH faster than list! print("python" in tags) # True # Subset / Superset a = {1, 2, 3} b = {1, 2, 3, 4, 5} print(a.issubset(b)) # True — all of a is in b print(b.issuperset(a)) # True — b contains all of a print(a.isdisjoint({6, 7})) # True — no common elements # Frozen set — immutable set (can be used as dict key) frozen = frozenset([1, 2, 3]) print(frozen) # frozenset({1, 2, 3})
Output
{'python', 'data', 'sql', 'pandas', 'numpy'} True True True True frozenset({1, 2, 3})
🔑 Use Sets When: You need fast membership testing (in operator), deduplication, or mathematical set operations. Sets are unordered — you can't use indexing like s[0].
🎯 TASK Practice: Tuples & Sets
You have two lists of customer IDs: last month and this month. Use sets to find: new customers, lost customers, and loyal customers (in both).
Starter code:
python
last_month = [101,102,103,104,105,106] this_month = [103,104,105,106,107,108] last_set = set(???) this_set = set(???) new_customers = this_set - ??? # in this month only lost_customers = last_set - ??? # in last month only loyal = last_set & ??? # in both print(f"New customers: {sorted(new_customers)}") print(f"Lost customers: {sorted(lost_customers)}") print(f"Loyal: {sorted(loyal)}")

🐍 Type Conversion

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

Explicit Type Conversion

python
# str → number age_str = "28" age_int = int(age_str) # 28 age_flt = float(age_str) # 28.0 # number → str price = 12000 price_str = str(price) # "12000" formatted = f"{price:,}" # "12,000" # number → bool print(bool(0)) # False print(bool(100)) # True print(bool("")) # False print(bool("hi")) # True print(bool([])) # False print(bool([1])) # True
Output
False True False True False True

Safe Conversion with try/except

python
def safe_int(value, default=0): """Convert to int safely, return default if fails.""" try: return int(value) except (ValueError, TypeError): return default print(safe_int("42")) # 42 print(safe_int("hello")) # 0 (default) print(safe_int(None)) # 0 (default) print(safe_int("3.14")) # 0 (can't int() a float string!) # For float strings, use float() first print(int(float("3.14"))) # 3
Output
42 0 0 0 3

Converting Collections

python
# list ↔ tuple ↔ set my_list = [1, 2, 2, 3, 3, 4] my_tuple = tuple(my_list) # (1,2,2,3,3,4) my_set = set(my_list) # {1,2,3,4} — unique back = list(my_set) # [1,2,3,4] # string ↔ list text = "Hello" chars = list(text) # ['H','e','l','l','o'] back = "".join(chars) # "Hello" # range → list nums = list(range(1, 6)) # [1,2,3,4,5] print(nums)
🎯 TASK Practice: Type Conversion
Build a data type validator: given a list of raw input values (strings from a form), convert each to the correct type and handle errors gracefully.
Starter code:
python
raw_data = { "age": "28", "salary": "9500.50", "name": "Ahmed", "active": "true", "score": "bad_value" } def convert_field(key, value): if key == "age": return int(value) elif key == "salary": return float(value) elif key == "active": return value.lower() == ??? else: try: return float(value) except: return ??? result = {k: convert_field(k, v) for k, v in raw_data.items()} for k, v in result.items(): print(f"{k}: {v} ({type(v).__name__})")

🐍 Modules & Import

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

What is a Module?

A module is a Python file with reusable code. Python has thousands of built-in and third-party modules you can import.

python
# Different ways to import import math # Import entire module from math import sqrt, pi # Import specific items from math import sqrt as sq # Import with alias import numpy as np # Third-party with alias from datetime import date, datetime # Multiple items # Using imports print(math.sqrt(144)) # 12.0 print(sqrt(144)) # 12.0 (imported directly) print(sq(144)) # 12.0 (alias) print(pi) # 3.14159...
Output
12.0 12.0 12.0 3.141592653589793

Useful Built-in Modules

python
import os import sys import json import random from datetime import date, timedelta from collections import Counter, defaultdict # os — file system print(os.getcwd()) # Current directory print(os.listdir(".")) # Files in folder # datetime today = date.today() yesterday = today - timedelta(days=1) print(today, yesterday) # json — read/write JSON data = {"name": "Ahmed", "score": 95} json_str = json.dumps(data) # dict → JSON string back = json.loads(json_str) # JSON string → dict print(json_str) # Counter — count occurrences sales_regions = ["Cairo","Alex","Cairo","Giza","Cairo","Alex"] counts = Counter(sales_regions) print(counts) # Counter({'Cairo': 3, 'Alex': 2, 'Giza': 1})
🎯 TASK Practice: Modules & Import
Create your own module 'analytics.py' with 3 functions: calculate_growth(), format_currency(), and get_summary(). Then import and use it.
Starter code:
python
# analytics.py — create this file first def calculate_growth(old_value, new_value): """Calculate percentage growth.""" return (new_value - old_value) / old_value * ??? def format_currency(amount, currency="EGP"): """Format number as currency string.""" return f"{amount:,.2f} {currency}" def get_summary(data): """Return dict of summary stats.""" return { "count": len(data), "total": ???, "mean": sum(data)/len(data), "min": ???, "max": ??? } # main.py — import and use from analytics import calculate_growth, format_currency, get_summary sales = [45000, 52000, 48000, 61000, 72000] print(get_summary(sales)) print(format_currency(sum(sales))) print(f"Growth: {calculate_growth(sales[0], sales[-1]):.1f}%")

🐍 Regular Expressions

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

What is RegEx?

Regular Expressions are patterns to search, validate, and clean text. Essential in data work for validating emails, extracting numbers, and fixing messy strings.

python
import re text = "Call: 010-1234-5678 or 011-9876-5432" phones = re.findall(r"\d{3}-\d{4}-\d{4}", text) print(phones) email = "[email protected]" valid = bool(re.match(r"^[\w.]+@[\w.]+\.[a-z]{2,}$", email)) print(valid)
Output
['010-1234-5678', '011-9876-5432'] True

Common Patterns

python
import re messy = "Cairo Alex Giza" clean = re.sub(r"\s+", " ", messy) # replace multiple spaces print(clean) row = "Ahmed,28;Cairo|Sales" parts = re.split(r"[,;|]", row) # split by multiple delimiters print(parts)
Output
Cairo Alex Giza ['Ahmed', '28', 'Cairo', 'Sales']
🎯 TASK Practice: Regular Expressions
Validate phone numbers (01x-xxxx-xxxx) and extract all prices (EGP amounts) from a text string.
Starter code:
python
import re phone = "010-1234-5678" text = "Laptop: 12000 EGP, Phone: 6500 EGP" phone_ok = bool(re.match(r"^01[0125]-\d{4}-\d{4}$", phone)) prices = re.findall(r"(\d+) EGP", text) print(f"Phone valid: {phone_ok}") print(f"Prices: {prices}")

🐍 Exception Handling

Unit 2 — Variables, data types, strings, lists, dictionaries, and more — the building blocks of every Python program.

try / except

python
# Basic structure try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") # Multiple exceptions try: value = int(input("Enter number: ")) result = 100 / value print(f"Result: {result}") except ValueError: print("Please enter a valid integer!") except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"Unexpected error: {e}")

else and finally

python
try: data = [1, 2, 3] print(data[0]) except IndexError as e: print(f"Error: {e}") else: print("No error — this runs if try succeeded!") finally: print("This ALWAYS runs — good for cleanup")
Output
1 No error — this runs if try succeeded! This ALWAYS runs — good for cleanup

Raising Exceptions

python
def set_salary(amount): if amount < 0: raise ValueError(f"Salary cannot be negative: {amount}") if amount > 1_000_000: raise ValueError(f"Salary seems too high: {amount:,}") return amount try: set_salary(-500) except ValueError as e: print(f"Invalid: {e}") # Custom exception class InsufficientStockError(Exception): pass def sell(stock, qty): if qty > stock: raise InsufficientStockError(f"Only {stock} units available") return stock - qty
🎯 TASK Practice: Exception Handling
Build a safe CSV reader function that handles: file not found, empty file, and invalid data types. Return a list of dicts or an error message.
Starter code:
python
import csv import os def safe_read_csv(filepath): """Safely read a CSV file and return list of dicts.""" try: if not os.path.exists(filepath): raise FileNotFoundError(f"File not found: {filepath}") with open(filepath, "r") as f: reader = csv.DictReader(f) data = list(reader) if not data: raise ValueError("File is empty") return {"status": "ok", "data": data, "rows": len(data)} except FileNotFoundError as e: return {"status": "error", "message": ???} except ValueError as e: return {"status": "error", "message": ???} except Exception as e: return {"status": "error", "message": f"Unexpected: {e}"} finally: print(f"Attempted to read: {filepath}") result = safe_read_csv("sales.csv") print(result["status"])