Python
Programming Language Guide
A comprehensive reference: syntax, data structures, OOP, files, exceptions, comprehensions,
decorators, concurrency, and the standard library.
Paradigm Multi-paradigm: OOP, functional, procedural, scripting
Typing Dynamic, strong (duck typing)
Created by Guido van Rossum — first released 1991
Latest Python 3.12 / 3.13 (active development)
Runtime CPython (reference), PyPy, Jython, MicroPython
License PSF License (open source)
Use cases Web, data science, AI/ML, scripting, automation, finance
Table of Contents
1. Introduction & Philosophy
2. Installation & First Program
3. Variables, Types & Operators
4. Control Flow
5. Functions & Scope
6. Core Data Structures
7. Object-Oriented Programming
8. Comprehensions & Generators
9. Exception Handling
10. File I/O
11. Modules & Packages
12. Decorators
13. Concurrency Overview
14. Popular Libraries
15. Best Practices & Style Guide
Python Guide Page 1 of 7
1. Introduction & Philosophy
Python was created by Guido van Rossum and first appeared in 1991. It emphasises code readability
through significant whitespace, and its design is guided by the "Zen of Python" — 19 aphorisms that
capture the language's philosophy. Key tenets include: Beautiful is better than ugly, Explicit is better
than implicit, and Simple is better than complex. Python consistently ranks as one of the most popular
languages worldwide (IEEE Spectrum, TIOBE, Stack Overflow surveys).
2. Installation & First Program
Install Python from [Link] or use a package manager:
# Linux / macOS (Homebrew) brew install python3 # Windows — use the official installer
or: winget install [Link].3 # Verify python3 --version
Hello World:
# [Link] print("Hello, World!") # Run with: # python3 [Link]
3. Variables, Types & Operators
Python is dynamically typed — the interpreter infers types at runtime. Variables are simply names
bound to objects.
# Basic types x = 42 # int pi = 3.14159 # float c = 3 + 2j # complex name = "Alice" # str
flag = True # bool none = None # NoneType # Type checking print(type(x)) #
print(isinstance(x, int)) # True # Type conversion s = str(42) # "42" n = int("100") #
100 f = float("3.14")# 3.14
Arithmetic & Comparison Operators
Operator Meaning Example Result
+ Addition 3 + 4 7
- Subtraction 10 - 3 7
* Multiplication 3 * 4 12
/ True division 7 / 2 3.5
// Floor division 7 // 2 3
% Modulo 7 % 3 1
** Exponent 2 ** 8 256
== Equal 3 == 3 True
!= Not equal 3 != 4 True
and/or/not Logical x>0 and x<10 bool
Python Guide Page 2 of 7
4. Control Flow
# if / elif / else score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B"
else: grade = "C" # for loop with enumerate fruits = ["apple", "banana", "cherry"] for i,
fruit in enumerate(fruits): print(i, fruit) # while loop count = 0 while count < 5: count
+= 1 # break / continue / else on loop for n in range(10): if n == 3: continue if n == 7:
break else: print("loop completed") # match statement (Python 3.10+) point = (1, 0) match
point: case (0, 0): print("origin") case (x, 0): print(f"x-axis at {x}") case _:
print("elsewhere")
5. Functions & Scope
def add(a: int, b: int = 0) -> int: """Add two integers. b defaults to 0.""" return a + b
# *args collects positional; **kwargs collects keyword def show(*args, **kwargs):
print(args, kwargs) # First-class functions def apply(func, value): return func(value)
result = apply(lambda x: x**2, 5) # 25 # Closures def make_multiplier(n): def
multiply(x): return x * n return multiply double = make_multiplier(2) print(double(7)) #
14 # Type hints (PEP 484) from typing import Optional, List def greet(name: str) ->
Optional[str]: return f"Hello, {name}" if name else None
6. Core Data Structures
Structure Mutable Ordered Duplicates Syntax Best for
list Yes Yes Yes [1,2,3] Sequences, stacks, queues
tuple No Yes Yes (1,2,3) Immutable records
dict Yes Yes* Keys: No {"k":1} Key-value lookups
set Yes No No {1,2,3} Membership tests, dedup
frozenset No No No frozenset() Dict keys, set of sets
deque Yes Yes Yes deque([]) Fast append/pop both ends
# Common list operations nums = [3,1,4,1,5,9] [Link](2) # add to end [Link](0,
0) # insert at index [Link]() # in-place sort top3 = nums[-3:] # slice last 3 # Dict
operations d = {"a":1, "b":2} d["c"] = 3 # add key val = [Link]("z", 0) # safe get with
default for k, v in [Link](): print(k, v)
Python Guide Page 3 of 7
7. Object-Oriented Programming
class Shape: """Base class for geometric shapes.""" def __init__(self, colour: str =
"red"): [Link] = colour def area(self) -> float: raise NotImplementedError def
__repr__(self): return f"{self.__class__.__name__}(colour={[Link]!r})" class
Circle(Shape): import math def __init__(self, radius: float, **kw):
super().__init__(**kw) [Link] = radius def area(self) -> float: return 3.14159 *
[Link] ** 2 class Rectangle(Shape): def __init__(self, w, h, **kw):
super().__init__(**kw) self.w, self.h = w, h def area(self): return self.w * self.h #
Polymorphism shapes = [Circle(5), Rectangle(4, 6)] for sh in shapes: print(sh, "area =",
[Link]()) # Dataclass (Python 3.7+) from dataclasses import dataclass, field @dataclass
class Point: x: float y: float tags: list = field(default_factory=list) p = Point(1.0,
2.0) print(p) # Point(x=1.0, y=2.0, tags=[])
8. Comprehensions & Generators
# List comprehension squares = [x**2 for x in range(10) if x % 2 == 0] # Dict
comprehension word_len = {w: len(w) for w in ["hello", "world"]} # Set comprehension
uniq_lens = {len(w) for w in ["cat", "dog", "fish"]} # Generator expression (lazy,
memory-efficient) gen = (x**2 for x in range(1_000_000)) print(next(gen)) # 0 # Generator
function def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b fib =
fibonacci() print([next(fib) for _ in range(8)])
9. Exception Handling
try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except
(TypeError, ValueError): print("Type or value error") else: print("No exception
occurred") finally: print("Always runs") # Custom exception class
InsufficientFundsError(Exception): def __init__(self, amount, balance):
super().__init__(f"Need {amount}, have {balance}") [Link] = amount # Context
managers with open("[Link]", "r") as f: content = [Link]() # File auto-closed after
block
Python Guide Page 4 of 7
10. File I/O
# Read entire file with open("[Link]", "r", encoding="utf-8") as f: text = [Link]() #
Write file with open("[Link]", "w") as f: [Link]("Hello\n")
[Link](["line2\n", "line3\n"]) # Read line by line (memory efficient) with
open("[Link]") as f: for line in f: process([Link]()) # JSON import json data =
{"name": "Alice", "age": 30} with open("[Link]", "w") as f: [Link](data, f,
indent=2) with open("[Link]") as f: loaded = [Link](f) # CSV import csv with
open("[Link]", newline="") as f: reader = [Link](f) rows = list(reader) #
pathlib (modern path handling) from pathlib import Path p = Path("data") / "[Link]" if
[Link](): print(p.read_text())
11. Modules & Packages
# Import styles import math from os import path, getcwd from typing import List, Dict,
Optional # Create a package # mypackage/ # __init__.py # [Link] # models/ # __init__.py
# [Link] # Virtual environments python3 -m venv .venv source .venv/bin/activate # Unix
.venv\Scripts\activate # Windows # Install packages pip install requests numpy pandas pip
freeze > [Link] pip install -r [Link]
12. Decorators
import functools, time # Timing decorator def timer(func): @[Link](func) def
wrapper(*args, **kwargs): t0 = time.perf_counter() result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter()-t0:.4f}s") return result return
wrapper @timer def slow_sum(n): return sum(range(n)) # Built-in decorators class MyClass:
@staticmethod def util(): ... @classmethod def from_string(cls, s): return cls()
@property def value(self): return self._val @[Link] def value(self, v): self._val =
v
Python Guide Page 5 of 7
13. Concurrency Overview
Approach Module Best for GIL affected?
Threading threading I/O-bound tasks Yes
Multiprocessing multiprocessing CPU-bound tasks No (separate processes)
Async/Await asyncio High-concurrency I/O Yes (single thread)
Executors [Link] Simple thread/proc pools Depends
import asyncio async def fetch(url: str) -> str: # Simulate async I/O await
[Link](0.1) return f"data from {url}" async def main(): urls = ["[Link]
"[Link] results = await [Link](*[fetch(u) for u in urls]) print(results)
[Link](main())
14. Popular Libraries
Category Library Description
Numerics NumPy N-dimensional arrays, linear algebra, FFT
Data Pandas DataFrames, CSV/Excel/SQL I/O, groupby
Visualisation Matplotlib Plots, charts, figures
Visualisation Seaborn Statistical data visualisation
ML / AI scikit-learn Classical ML: SVM, trees, clustering
Deep learning PyTorch Tensors, autograd, neural networks
Deep learning TensorFlow Production ML, Keras high-level API
Web FastAPI Modern async REST APIs with type hints
Web Django Full-stack web framework, batteries included
HTTP Requests Human-friendly HTTP client
Testing pytest Powerful test framework with fixtures
CLI Click / Typer Command-line app building
Async HTTP aiohttp Async HTTP client/server
15. Best Practices & PEP 8 Style Guide
• Naming: snake_case for variables/functions, PascalCase for classes, UPPER_CASE for
constants.
• Line length: Max 79 characters for code, 72 for docstrings.
• Imports: One per line; stdlib → third-party → local, separated by blank lines.
• Docstrings: Write them for every public module, class, and function (PEP 257).
• Type hints: Use them for function signatures — improves readability and tooling.
• Virtual environments: Always isolate dependencies per project.
Python Guide Page 6 of 7
• Testing: Aim for high coverage with pytest; use fixtures and parametrize.
• Linting: Use flake8 or ruff, and format with black or autopep8.
• Security: Never store secrets in source code — use environment variables or vaults.
• Performance: Profile before optimising; use cProfile, then consider NumPy or Cython.
Python Guide Page 7 of 7