Why Python?
Python is built for readability and speed of development. It powers backend APIs, scripting, data engineering, and modern AI applications.
Simple & Readable
No semicolons or curly braces. Clean indentation defines structure.
AI & Web Ready
Huge ecosystem with FastAPI, PyTorch, LangChain, and automation tools.
Variables, Types & f-strings
Python dynamically infers variable types. Use f-strings for clean and fast string formatting.
# Dynamic variables
user_name = "Heremyas"
level = 42
xp_multiplier = 1.75
is_pro_member = True
# Type conversion
input_str = "100"
converted_int = int(input_str)
as_float = float(converted_int)
# Formatted f-string
summary = f"Student {user_name}: Lvl {level} ({xp_multiplier:.2f}x XP)"
print(summary)Core Types
- int: Integers (
10,-500) - float: Decimals (
3.14) - str: Text strings with methods like
.split() - bool:
TrueorFalse
Which creates a valid f-string with 2 decimal precision?
Lists, Tuples, Dicts & Sets
Store and transform data using Python's built-in collections and one-line comprehensions.
# Lists (ordered, mutable)
frameworks = ["FastAPI", "Django", "Flask"]
frameworks.append("PyTorch")
first_two = frameworks[:2] # Slicing: ['FastAPI', 'Django']
# Dictionaries (key-value hash map)
user = {
"id": 101,
"role": "Developer",
"skills": ["Python", "SQL"]
}
# Sets (unique items) & Tuples (immutable)
unique_tags = {"backend", "api", "backend"} # {'backend', 'api'}
coordinates = (14.5995, 120.9842) # Tuplenumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Filter even numbers & square them
squared_evens = [x**2 for x in numbers if x % 2 == 0]
# Output: [4, 16, 36, 64, 100]
# Dict comprehension: word lengths map
words = ["python", "fastapi", "svelte"]
word_lengths = {w: len(w) for w in words}
# Output: {'python': 6, 'fastapi': 7, 'svelte': 6}Conditionals, Loops & Pattern Matching
Control execution using if/elif/else, for-in loops with enumerate() / zip(), and match / case.
def handle_command(command: str | list[str]):
match command:
case "quit" | "exit":
return "Application shutting down..."
case ["load", filename]:
return f"Loading file: {filename}"
case ["move", x, y] if int(x) >= 0 and int(y) >= 0:
return f"Moving coordinates to ({x}, {y})"
case _:
return "Unknown command."items = ["Apple", "Banana", "Cherry"]
# enumerate() yields index and value
for idx, item in enumerate(items, start=1):
print(f"{idx}. {item}")
# zip() pairs items together
prices = [1.20, 0.80, 2.50]
for name, price in zip(items, prices):
print(f"{name}: ${price:.2f}")Functions, *args & Scope
Define reusable functions with default parameters, positional *args, and keyword **kwargs.
def create_profile(username: str, *badges: str, **metadata):
return {
"username": username,
"badges": list(badges),
"metadata": metadata
}
# Call with positional & keyword unpacking
res = create_profile(
"Alex",
"Early Adopter", "Pythonista",
tier="Pro",
streak=14
)Classes, Objects & Dataclasses
Model state and behavior with classes, inheritance, and clean Python @dataclass models.
class Account:
def __init__(self, owner: str, balance: float = 0.0):
self.owner = owner
self._balance = balance
def deposit(self, amount: float) -> float:
if amount > 0:
self._balance += amount
return self._balance
class SavingsAccount(Account):
def add_interest(self, rate: float = 0.05):
self._balance += self._balance * rate
return self._balancefrom dataclasses import dataclass, field
@dataclass
class CourseRoadmap:
slug: str
title: str
total_xp: int = 100
prerequisites: list[str] = field(default_factory=list)
def is_unlocked(self, completed: list[str]) -> bool:
return all(p in completed for p in self.prerequisites)
py_node = CourseRoadmap("python", "Python 3.14", 150)
print(py_node)Virtual Environments & Pip
Isolate dependencies using venv and install packages with pip.
python -m venv .venv
Creates an isolated runtime in your project.
source .venv/bin/activate
Windows: .venv\Scripts\activate
pip install pytest fastapi
Installs dependencies into your environment.
Context Managers, Decorators & Pytest
Handle resources safely with with open, wrap functions with decorators, and test with pytest.
import time
from functools import wraps
def timeit(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
duration = time.perf_counter() - start
print(f"{func.__name__}: {duration:.4f}s")
return result
return wrapper
# Safe File Context Manager
with open("data.json", "w", encoding="utf-8") as f:
f.write('{"status": "ok"}')# test_analytics.py
import pytest
def calculate_discount(price: float, rate: float) -> float:
if rate < 0 or rate > 1:
raise ValueError("Rate must be between 0 and 1")
return price * (1 - rate)
def test_calculate_discount_valid():
assert calculate_discount(100.0, 0.2) == 80.0
def test_calculate_discount_invalid():
with pytest.raises(ValueError):
calculate_discount(100.0, 1.5)Practice Live Code
Launch the in-browser Python sandbox to write and test code live.