Python Mastery: Beginner → Advanced
(Full Guide + Syntax)
Hinglish notes + crystal‑clear code examples. From zero to pro. Bookmark this.
0) Quick Start
Install & Run
● Check version: python --version (sometimes python3 --version)
● REPL: run python then type code and press Enter.
● Run a file: python app.py
Create venv (recommended per project):
python -m venv .venv
# activate
# Windows (cmd): .venv\Scripts\activate
# PowerShell: .venv\Scripts\Activate.ps1
# macOS/Linux: source .venv/bin/activate
python -m pip install --upgrade pip
● pip install requests
Help inside Python
help(str)
import this # The Zen of Python
Basic syntax rules
● Indentation = 4 spaces (no tabs mix). Blocks are defined by indents.
● Case-sensitive. value ≠ Value.
● Comments: # single line, docstrings: triple quotes inside defs/classes/modules.
● File encoding default UTF‑8.
1) Data Types (Built‑ins)
Numbers: int, float, complex, bool (bool ⊂ int)
x = 42 # int
pi = 3.14159 # float
z = 2 + 3j # complex
ok = True # bool
● Conversions: int("7"), float("7.5"), complex(2, 3)
Strings: str (immutable)
s = "Hello" # or 'Hello'
multiline = """line1\nline2"""
len(s) # length
s.upper(); s.lower(); s.title()
"lo" in s # membership
s[1:4] # slicing
f"Hi {s}!" # f-strings
● Raw strings: r"C:\\path\\file"
● Byte strings: b"abc" (type bytes), mutable: bytearray.
Containers
lst = [1, 2, 3] # list (mutable)
tpl = (1, 2, 3) # tuple (immutable)
rng = range(5) # 0..4
st = {1, 2, 3} # set (unique, unordered)
fs = frozenset({1, 2}) # immutable set
dct = {"a": 1, "b": 2} # dict (key → value)
● Common ops: len(), in, iteration for x in ...:
● Dict: keys must be hashable (immutable & __hash__).
None: absence of value. Only falsey by itself.
Truthiness: False, None, 0, 0.0, 0j, '', [], {}, set() are falsey; others truthy.
2) Operators & Expressions
● Arithmetic: + - * / // % **
● Comparisons: == != < <= > >= (chained: a < b < c)
● Boolean: and or not (short‑circuit)
● Bitwise: & | ^ ~ << >>
● Membership: in, Identity: is (object identity, not equality)
● Assignment: = += -= *= //= ...
● Walrus operator (3.8+): if (n := len(data)) > 0:
● Precedence: use parentheses when unsure.
3) Control Flow
if x > 0:
...
elif x == 0:
...
else:
...
match / case (3.10+): structural pattern matching
def describe(point):
match point:
case (0, 0):
return "origin"
case (x, 0):
return f"x-axis at {x}"
case (0, y):
return f"y-axis at {y}"
case (x, y):
return f"point {x},{y}"
Loops
for x in iterable:
...
while cond:
...
# controls
break # exit loop
continue# next iteration
else: # runs if loop wasn’t broken
...
4) Collections: Methods & Idioms
List
lst.append(x); lst.extend([1,2])
lst.insert(0, x); lst.pop(); lst.remove(x)
lst.sort(); sorted(lst, key=len, reverse=True)
Slicing & copies: lst2 = lst[:] (shallow copy); lst.copy()
Dict
ages = {"A": 20}
ages.get("B", 0)
ages.keys(); ages.values(); ages.items()
ages.setdefault("C", 99)
Set
A | B # union
A & B # intersection
A - B # difference
A ^ B # symmetric diff
Comprehensions
squares = [x*x for x in range(10) if x%2==0]
set_comp = {c.lower() for c in "AaBb"}
dict_comp = {x: x*x for x in range(5)}
gen_comp = (x*x for x in range(10))
5) Functions (First‑Class)
def greet(name: str = "World") -> str:
return f"Hello {name}!"
Parameters
def f(a, b=0, *args, c=1, **kwargs):
...
● Positional‑only: def f(x, /): ...
● Keyword‑only: def f(*, x): ...
● Default arg pitfall (mutable):
def bad(acc=[]): # DON’T
acc.append(1)
return acc
def good(acc=None):
if acc is None:
acc = []
acc.append(1)
return acc
Lambda & Higher‑Order
inc = lambda x: x+1
list(map(inc, [1,2,3]))
list(filter(lambda x: x%2, range(10)))
Scope & Closures (LEGB)
x = 10
def outer():
x = 20
def inner():
nonlocal x
x += 1
return x
return inner
6) Modules & Packages
# mypkg/__init__.py (can be empty)
# mypkg/tools.py
from mypkg import tools
import mypkg.tools as t
from mypkg.tools import helper as h
if __name__ == "__main__":
... # script entry point
● sys.path controls import search. Relative imports inside packages: from .tools
import helper.
Virtual Envs & pip
● Create/activate venv (see Quick Start). Install libs: pip install requests fastapi
pytest
● Freeze: pip freeze > requirements.txt
● Install from file: pip install -r requirements.txt
7) Exceptions & Error Handling
try:
risky()
except ValueError as e:
print(e)
except (TypeError, KeyError):
...
else:
... # runs if no exception
finally:
cleanup()
● Raise: raise RuntimeError("boom")
● Custom:
class AppError(Exception):
pass
● Context managers (with) ensure cleanup.
8) Context Managers
with open("data.txt", "w", encoding="utf-8") as f:
f.write("hello")
Create your own:
from contextlib import contextmanager
@contextmanager
def opened(path, mode="r"):
f = open(path, mode)
try:
yield f
finally:
f.close()
9) Iterators & Generators
● Iterator protocol: __iter__() returns iterator; iterator defines __next__()
def gen():
yield 1
yield 2
for x in gen():
...
# Delegation (3.3+)
def gen2():
yield from gen()
itertools gems: count, cycle, repeat, accumulate, chain, product,
permutations, combinations, groupby.
10) Decorators
import time, functools
def timing(func):
@functools.wraps(func)
def wrapper(*a, **k):
t0 = time.perf_counter()
try:
return func(*a, **k)
finally:
print(f"{func.__name__}: {time.perf_counter()-t0:.6f}s")
return wrapper
@timing
def work():
...
Decorators with args:
def retry(n=3):
def deco(fn):
@functools.wraps(fn)
def wrap(*a, **k):
for i in range(n):
try:
return fn(*a, **k)
except Exception as e:
last = e
raise last
return wrap
return deco
11) Classes & OOP
class User:
def __init__(self, name: str):
self.name = name
def greet(self):
return f"Hi {self.name}"
def __repr__(self):
return f"User(name={self.name!r})"
● Class vs instance attrs, properties:
class Product:
tax_rate = 0.18 # class attr
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, v):
if v < 0: raise ValueError
self._price = v
@classmethod
def with_tax(cls, price):
return price * (1 + cls.tax_rate)
@staticmethod
def rupees(x):
return f"₹{x:.2f}"
● Inheritance & super()
class A:
def hi(self): return "A"
class B(A):
def hi(self): return "B" + super().hi()
● Special (dunder) methods: __len__, __str__, __eq__, ordering via
functools.total_ordering.
Data Classes (3.7+)
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: int
y: int
Abstract Base Classes & Protocols
from abc import ABC, abstractmethod
from typing import Protocol
class Repo(ABC):
@abstractmethod
def get(self, id: int) -> object: ...
class SupportsClose(Protocol):
def close(self) -> None: ...
12) Typing (Type Hints)
from typing import Optional, Union, Iterable, Mapping, Literal, Any
def parse(v: Union[int, str]) -> int: ...
def find(name: str, data: Mapping[str, int]) -> Optional[int]: ...
Id = int | str # 3.10+
● Generics: from typing import TypeVar, Generic, Sequence
● TypedDict, Protocol, Self (3.11+), Annotated for metadata.
● Static checkers: mypy, pyright (run in editor/CI).
13) Files, Paths & Data Formats
Pathlib
from pathlib import Path
p = Path("data")/"file.txt"
text = p.read_text(encoding="utf-8")
p.write_text("hello", encoding="utf-8")
CSV / JSON
import csv, json
with open("data.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
with open("data.json", "w", encoding="utf-8") as f:
json.dump({"a": 1}, f, ensure_ascii=False, indent=2)
SQLite
import sqlite3
con = sqlite3.connect("app.db")
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS t(id INTEGER, name TEXT)")
cur.execute("INSERT INTO t VALUES (?, ?)", (1, "A"))
con.commit(); con.close()
Pickle (be cautious): only load trusted data.
14) Stdlib Power Tools
● collections: Counter, defaultdict, deque, namedtuple
● functools: lru_cache, partial, reduce, cached_property
● itertools: iteration building blocks
● heapq, bisect: priority queues & sorted insertion
● datetime, zoneinfo: timezone‑aware time
● re: regular expressions
● argparse: CLI parsing
● logging: structured logs
● subprocess, shutil, os, pathlib, sys
● statistics, math, decimal, fractions
Regex mini
import re
m = re.search(r"(\w+)@(\w+).(\w+)", "[email protected]")
if m: print(m.group(0), m.group(1))
Logging mini
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(message)s")
logging.info("hello")
15) Concurrency & Parallelism
Threading (I/O bound, GIL allows I/O overlap)
import threading
results = []
def fetch(i):
# do network I/O
results.append(i)
threads = [threading.Thread(target=fetch, args=(i,)) for i in range(5)]
[t.start() for t in threads]
[t.join() for t in threads]
concurrent.futures
from concurrent.futures import ThreadPoolExecutor, as_completed
with ThreadPoolExecutor(max_workers=10) as ex:
futs = [ex.submit(fetch, i) for i in range(20)]
for f in as_completed(futs):
print(f.result())
Multiprocessing (CPU bound)