Quick answer: Python basics are variables and types, strings and f-strings, lists, tuples, dictionaries and sets, if/for/while, functions, modules, exceptions and files. Advanced Python adds comprehensions, *args/**kwargs, classes and dataclasses, decorators, generators, context managers, type hints, match statements, async/await and the standard library's power tools (collections, itertools, functools, pathlib). This guide covers all of them with short, runnable examples for Python 3.10 and later.
Use it as a reference while you learn, or as a refresher before an interview or a new project.
Getting started
python3 --version
python3 -m venv .venv # create a virtual environment
source .venv/bin/activate # Linux/macOS (Windows: .venv\Scripts\activate)
pip install requests # install a package
pip freeze > requirements.txt # save dependencies
pip install -r requirements.txt # install from a file
python3 app.py # run a script
Variables and data types
name = "Asha" # str
age = 30 # int
price = 99.5 # float
active = True # bool
nothing = None # NoneType
big = 10_000_000 # underscores for readability
type(age) # <class 'int'>
isinstance(age, int) # True
int("42"), float("3.5"), str(42), bool(0) # conversions
x, y = 1, 2 # multiple assignment
x, y = y, x # swap
Operators
7 / 2 # 3.5 true division
7 // 2 # 3 floor division
7 % 2 # 1 remainder
2 ** 10 # 1024 power
a == b, a != b, a is None, "py" in "python"
and, or, not
Strings
s = "Hello, World"
len(s); s.upper(); s.lower(); s.title()
s.strip(); s.replace("World", "Python"); s.split(", ")
", ".join(["a", "b"]) # 'a, b'
s.startswith("He"); s.endswith("d"); s.find("o")
s[0]; s[-1]; s[0:5]; s[::-1] # indexing, slicing, reverse
name, total = "Asha", 1234.5
f"Hi {name}, you owe ₹{total:,.2f}" # 'Hi Asha, you owe ₹1,234.50'
f"{total=}" # 'total=1234.5' (debugging)
"""Multi-line
string"""
Lists
nums = [3, 1, 2]
nums.append(4); nums.extend([5, 6]); nums.insert(0, 0)
nums.remove(3); nums.pop(); nums.pop(0)
nums.sort(); nums.sort(reverse=True); sorted(nums) # sorted() returns a new list
nums.reverse(); nums.index(2); nums.count(2)
len(nums); min(nums); max(nums); sum(nums)
nums[1:3]; nums[-2:]; nums[::2]
first, *rest = [1, 2, 3] # unpacking
Tuples, sets and dictionaries
point = (10, 20) # tuple: immutable
x, y = point
tags = {"python", "api"} # set: unique, unordered
tags.add("web"); tags.discard("api")
a | b; a & b; a - b # union, intersection, difference
user = {"name": "Asha", "age": 30}
user["email"] = "asha@example.com"
user.get("phone", "N/A") # default if missing
user.keys(); user.values(); user.items()
user.pop("age"); "name" in user
merged = defaults | overrides # merge (3.9+)
for key, value in user.items():
print(key, value)
Conditions and loops
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
status = "adult" if age >= 18 else "minor"
for i in range(5): ... # 0..4
for i, item in enumerate(items, start=1): ...
for name, score in zip(names, scores): ...
while retries < 3:
retries += 1
if ok: break
else: continue
for item in items:
if item.is_target: break
else:
print("not found") # runs only if the loop didn't break
Comprehensions
squares = [n * n for n in range(10)]
evens = [n for n in nums if n % 2 == 0]
lookup = {u["id"]: u for u in users} # dict comprehension
unique_domains = {e.split("@")[1] for e in emails} # set comprehension
total = sum(n * n for n in range(10)) # generator expression (no list built)
Functions
def greet(name: str, greeting: str = "Hello") -> str:
"""Return a greeting."""
return f"{greeting}, {name}!"
greet("Asha"); greet(greeting="Hi", name="Ravi")
def total(*args, **kwargs):
print(args) # tuple of positional arguments
print(kwargs) # dict of keyword arguments
def connect(host, *, port=5432, ssl=True): ... # args after * are keyword-only
def scale(value, /, factor=2): ... # args before / are positional-only
square = lambda n: n * n
sorted(users, key=lambda u: u["age"])
Gotcha: never use a mutable default such as
def add(item, items=[]). Useitems=Noneand create the list inside the function.
Modules and packages
import math
from datetime import datetime, timedelta
from pathlib import Path
import numpy as np
if __name__ == "__main__": # code that runs only when the file is executed directly
main()
Exceptions
try:
value = int(user_input)
except ValueError as e:
print(f"Not a number: {e}")
except (TypeError, KeyError):
...
else:
print("No error")
finally:
cleanup()
class InsufficientStock(Exception):
pass
raise InsufficientStock("Only 5 units left")
raise RuntimeError("Save failed") from original_error # keep the cause
Working with files
from pathlib import Path
import json, csv
text = Path("notes.txt").read_text(encoding="utf-8")
Path("out.txt").write_text("hello", encoding="utf-8")
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("users.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(row["email"])
for path in Path("logs").glob("*.log"):
print(path.name, path.stat().st_size)
Classes and object-oriented programming
class Account:
bank = "QOify Bank" # class attribute
def __init__(self, owner: str, balance: float = 0):
self.owner = owner
self._balance = balance # "protected" by convention
@property
def balance(self) -> float:
return self._balance
def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("Amount must be positive")
self._balance += amount
@classmethod
def from_dict(cls, data: dict) -> "Account":
return cls(data["owner"], data.get("balance", 0))
@staticmethod
def is_valid_amount(amount) -> bool:
return amount > 0
def __repr__(self) -> str:
return f"Account({self.owner!r}, {self._balance})"
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.04):
super().__init__(owner, balance)
self.rate = rate
Dataclasses
from dataclasses import dataclass, field
@dataclass
class Product:
sku: str
name: str
price: float = 0.0
tags: list[str] = field(default_factory=list)
p = Product("SKU-1", "Widget", 199)
print(p) # Product(sku='SKU-1', name='Widget', price=199, tags=[])
Add frozen=True for immutable objects, or slots=True for lower memory use.
Advanced Python
Decorators
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
@timer
def build_report():
...
Generators and iterators
def read_large_file(path):
with open(path, encoding="utf-8") as f:
for line in f:
yield line.rstrip() # one line at a time, low memory
for line in read_large_file("big.log"):
...
def chunks(items, size):
for i in range(0, len(items), size):
yield items[i:i + size]
Context managers
from contextlib import contextmanager
@contextmanager
def opened_db(url):
conn = connect(url)
try:
yield conn
finally:
conn.close()
with opened_db(DB_URL) as conn:
conn.execute("SELECT 1")
Type hints
from typing import Optional, Literal, TypedDict, Callable
def find_user(user_id: int) -> dict | None: ...
Status = Literal["draft", "published"]
class UserDict(TypedDict):
id: int
name: str
Handler = Callable[[str], bool]
def first[T](items: list[T]) -> T: # generic function syntax (3.12+)
return items[0]
Type hints are not enforced at runtime, but tools such as mypy and pyright, and editors, use them to catch bugs early.
Structural pattern matching (match, 3.10+)
match command.split():
case ["go", direction]:
move(direction)
case ["pick", "up", item]:
pick_up(item)
case ["quit" | "exit"]:
quit_game()
case _:
print("Unknown command")
match event:
case {"type": "order", "amount": amount} if amount > 10_000:
flag_for_review(event)
case {"type": "order"}:
process(event)
The walrus operator
if (n := len(items)) > 10:
print(f"Too many items: {n}")
while (chunk := f.read(8192)):
process(chunk)
async / await
import asyncio
import httpx
async def fetch(client, url):
response = await client.get(url)
return response.status_code
async def main():
async with httpx.AsyncClient() as client:
results = await asyncio.gather(*(fetch(client, u) for u in URLS))
print(results)
asyncio.run(main())
Use async for many concurrent I/O tasks (HTTP calls, database queries). For CPU-heavy work, use multiprocessing or concurrent.futures.ProcessPoolExecutor.
The standard library's power tools
from collections import Counter, defaultdict, deque, namedtuple
Counter("mississippi").most_common(2) # [('i', 4), ('s', 4)]
groups = defaultdict(list); groups["dev"].append("Asha")
queue = deque(maxlen=100); queue.append(x); queue.popleft()
from itertools import chain, groupby, islice, combinations, product, batched
list(chain([1, 2], [3])) # [1, 2, 3]
list(combinations("abc", 2)) # [('a','b'), ('a','c'), ('b','c')]
list(batched(range(7), 3)) # [(0,1,2), (3,4,5), (6,)] (3.12+)
from functools import lru_cache, partial, reduce
@lru_cache(maxsize=None)
def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)
from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
tomorrow = now + timedelta(days=1)
now.strftime("%Y-%m-%d %H:%M")
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.info("Server started")
import os
os.environ.get("DATABASE_URL", "sqlite:///dev.db")
Testing with pytest
# test_pricing.py
import pytest
from pricing import apply_discount
def test_apply_discount():
assert apply_discount(100, 10) == 90
def test_invalid_discount():
with pytest.raises(ValueError):
apply_discount(100, 150)
@pytest.mark.parametrize("price,pct,expected", [(100, 0, 100), (200, 50, 100)])
def test_many(price, pct, expected):
assert apply_discount(price, pct) == expected
Run with pip install pytest then pytest -q.
Popular libraries by use case
| Use case | Libraries |
|---|---|
| Web APIs | FastAPI, Django, Flask |
| HTTP requests | requests, httpx |
| Data analysis | pandas, Polars, NumPy |
| Machine learning and AI | scikit-learn, PyTorch, LLM provider SDKs |
| Databases | SQLAlchemy, SQLModel, psycopg |
| Validation | Pydantic |
| Automation and scraping | Playwright, Beautiful Soup |
| CLI tools | Typer, Click, argparse |
Common gotchas
- Mutable default arguments are shared between calls.
- Copying lists:
b = ashares the list; usea.copy()orcopy.deepcopy(a). - Integer division:
/always returns a float; use//for whole numbers. - Floating point:
0.1 + 0.2 != 0.3; usedecimal.Decimalfor money. - Late binding in lambdas inside loops: capture the value with a default,
lambda x=x: x. - Indentation matters: use 4 spaces, never mix tabs and spaces.
Conclusion
Python rewards learning a small core well: data structures, functions, classes and exceptions. Add comprehensions, dataclasses, type hints and context managers to write cleaner code, then decorators, generators, match and async/await as your projects grow. Pair it with virtual environments, pytest and a few well-chosen libraries, and you have a language that scales from quick scripts to production APIs and AI systems.



