Python is a high‑level, dynamically typed, interpreted language known for its readability (PEP 20 “Zen of Python”), vast ecosystem, and “batteries‑included” standard library.
# Hello, world
print("Hello Py Universe 🚀")
Download from python.org (Windows/macOS) or use a system package manager:
# macOS — Homebrew
brew install python@3.12
# Windows — winget
winget install Python.Python.3.12
# Linux — APT
sudo apt install python3.12
Use venv
(built‑in) or virtualenv
for dependency isolation.
# create & activate
python3 -m venv .env
source .env/bin/activate # *NIX
.env\Scripts\activate.bat # Windows
pip
– default installer.pipx
– isolated CLI tool installer.poetry
/ pdm
– modern lock‑file‑based workflows.Type | Literals | Example |
---|---|---|
Boolean | True , False | a = True |
Integer | 42 , 0xFF | count = 1_000 |
Float | 3.14 , 1e‑3 | pi = 3.14159 |
String | "hi" , 'hi' | msg = "Hello" |
# Lists (mutable, ordered)
nums = [1, 2, 3]
# Tuples (immutable, ordered)
pt = (10, 20)
# Sets (unique members)
tags = {"python", "guide"}
# Dicts (key‑value)
user = {"id": 1, "name": "Ada"}
for n in nums:
if n % 2 == 0:
print(f"{n} is even")
else:
continue
while True:
break
def add(a: int, b: int) -> int:
"Return sum of a and b."
return a + b
def greet(name, *, punct="!"):
print(f"Hello {name}{punct}")
funcs = [abs, len]
for f in funcs:
print(f"Using {f.__name__}: {f(['hi'])}")
class Vector:
def __init__(self, x: float, y: float):
self.x, self.y = x, y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def magnitude(self) -> float:
return (self.x**2 + self.y**2)**0.5
class Animal: # base
def speak(self):
raise NotImplementedError
class Dog(Animal): # derived
def speak(self):
return "Bark!"
pets: list[Animal] = [Dog()]
for p in pets:
print(p.speak()) # dynamic dispatch
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
Every .py
file is a module; a folder with __init__.py
is a
package. Import styles:
import math
from pathlib import Path
import numpy as np
Use __all__
to declare public API, and take advantage of namespace
packages (no __init__.py
) in modern tooling.
try:
r = 1 / 0
except ZeroDivisionError as e:
print("Bad math:", e)
finally:
print("Cleanup")
class ConfigError(Exception):
"""Raised for invalid config."""
pdb
– console debugger (python ‑m pdb script.py
).breakpoint()
– built‑in hook (3.7+).# Reading
with open("data.txt") as f:
data = f.read()
# Writing
Path("out.txt").write_text("Hello")
# JSON
import json
blob = json.dumps({"ok": True}, indent=2)
# Pickle (⚠️ avoid untrusted data)
import pickle
payload = pickle.dumps(obj)
from threading import Thread
def worker(id):
print(f"Thread {id}")
th = Thread(target=worker, args=(1,))
th.start(); th.join()
from multiprocessing import Pool
with Pool() as p:
print(p.map(pow, [2,3,4], [5,5,5])) # [32, 243, 1024]
import asyncio, aiohttp
async def fetch_json(url):
async with aiohttp.ClientSession() as s:
async with s.get(url) as r:
return await r.json()
json_data = asyncio.run(fetch_json("https://api.github.com"))
unittest
– built‑in xUnit‑style.pytest
– minimalist, fixtures, -k
/-m
selectors.coverage.py
.ruff
, mypy
, pylint
.# tests/test_math.py
import pytest
from guide import add
def test_add():
assert add(2, 3) == 5
# pyproject.toml (minimal)
[project]
name = "awesome‑pkg"
version = "0.1.0"
dependencies = ["requests"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Build & publish:
pip install build twine
python -m build
twine upload dist/*
Module | Purpose |
---|---|
pathlib | OO path manipulation. |
datetime | Dates, times, time zones (3.9 zoneinfo). |
itertools | Lazily evaluated combinatorics. |
dataclasses | Boilerplate‑free data containers. |
typing | Type hints; 3.10 | union. |
ruff format
or black
.Books & Docs:
Practice portals: LeetCode, HackerRank, Exercism.