Python logoPython BEGINNER

Python

Essential Python reference covering syntax, data structures, functions, OOP, comprehensions, type hints, virtual environments, and the standard library.

10 min read
pythonprogrammingbasicssyntaxdata-typescontrol-flowfunctionsoop

Setup & Basics

Install Python, run scripts, and understand basic syntax.

Installation & Running Python

Install Python and run scripts from the command line.

bash
💡 Use python3 explicitly — "python" may point to Python 2 on some systems
⚡ The REPL is great for testing snippets — type exit() or Ctrl+D to quit
📌 On Windows, use "py" instead of "python3" as the launcher
🟢 Use "python3 -m" to run installed modules as scripts (e.g., http.server, venv)
installsetupcli

Variables & Data Types

Python variables are dynamically typed — no declaration keyword needed.

python
💡 Python is dynamically typed — variables can change type at any time
⚡ Use x, y = y, x to swap values — no temp variable needed
📌 Falsy values: None, 0, 0.0, empty string, empty list/dict/set, False
🟢 Use isinstance() over type() for type checking — it supports inheritance
variablestypesbasics

Strings & Formatting

String operations, methods, and formatting with f-strings.

String Operations

Common string methods and operations.

python
💡 Strings are immutable — methods return new strings, they don't modify in place
⚡ Use "in" for substring checks — it's more Pythonic than .find()
📌 .find() returns -1 if not found; .index() raises ValueError
🟢 Use s[::-1] to reverse a string with slicing
stringsmethods

String Formatting

Format strings with f-strings, .format(), and % operator.

python
💡 f-strings are the fastest and most readable — use them by default
⚡ Format specs: :.2f (2 decimals), :, (thousands), :>10 (right-align)
📌 Use r"..." raw strings for regex patterns and Windows file paths
🟢 f-strings can contain any valid Python expression inside the braces
stringsformattingf-strings

Control Flow

Conditionals, loops, match statements, and flow control keywords.

Conditionals

if/elif/else statements and ternary expressions.

python
💡 Python uses and/or/not instead of &&/||/!
⚡ Chained comparisons like 0 < x < 100 are valid and Pythonic
📌 Check empty collections with "if items:" — no need for len(items) > 0
🟢 The ternary syntax is: value_if_true if condition else value_if_false
conditionalsifternary

Loops

for and while loops with break, continue, and else clauses.

python
💡 Use enumerate() instead of range(len()) — it's cleaner and more Pythonic
⚡ zip() pairs elements from multiple iterables — stops at the shortest
📌 The else clause on a loop runs only if the loop did NOT hit a break
🟢 Use continue to skip an iteration, break to exit the loop entirely
loopsforwhilebreakcontinue

Match Statements

Structural pattern matching (Python 3.10+).

python
💡 match/case is structural pattern matching, not just a switch statement
⚡ Use | to match multiple values in one case (e.g., 500 | 502 | 503)
📌 The _ wildcard matches anything — use it as a default/fallback case
🟢 Add a guard with "if" after the pattern for conditional matching
matchpattern-matchingcontrol-flow

Data Structures

Lists, tuples, dictionaries, and sets — with comprehensions.

Lists

Ordered, mutable sequences with powerful methods.

python
💡 .sort() modifies in place and returns None — use sorted() for a new list
⚡ Use first, *rest = list to unpack the head and tail
📌 .remove() deletes by value; del and .pop() delete by index
🟢 Slicing never raises IndexError — out-of-range slices return empty lists
listsdata-structures

Dictionaries

Key-value mappings with fast lookups.

python
💡 Use .get(key, default) to avoid KeyError on missing keys
⚡ The | merge operator (3.9+) creates a new dict — |= merges in place
📌 Use .items() to iterate over key-value pairs, not just keys
🟢 .setdefault() gets a value or inserts a default — great for counting/grouping
dictionariesdata-structures

Tuples & Sets

Immutable sequences and unique unordered collections.

python
💡 Use tuples for fixed collections — they're faster and hashable (can be dict keys)
⚡ Create an empty set with set(), not {} — braces create an empty dict
📌 .discard() is silent on missing elements; .remove() raises KeyError
🟢 Sets are perfect for deduplication: list(set(items)) removes duplicates
tuplessetsdata-structures

Comprehensions

Concise syntax for creating lists, dicts, and sets.

python
💡 List comps are faster than equivalent for loops — use them for simple transforms
⚡ Generator expressions use () instead of [] — they're lazy and memory-efficient
📌 Read nested comps left-to-right: "for row in matrix for n in row"
🟢 The walrus operator := lets you assign and filter in one expression
comprehensionslist-compgenerators

Functions

Define functions with default args, *args, **kwargs, and lambda expressions.

Function Basics

Define functions with parameters, defaults, and return values.

python
💡 Use / to mark positional-only params, * to mark keyword-only params
⚡ Functions can return multiple values as a tuple — unpack with a, b = func()
📌 Default arguments are evaluated once — never use mutable defaults like def f(x=[])
🟢 Add docstrings as the first line in a function for documentation
functionsparametersreturn

*args, **kwargs & Unpacking

Accept variable arguments and unpack iterables into function calls.

python
💡 *args becomes a tuple, **kwargs becomes a dict inside the function
⚡ Use *list and **dict to unpack when calling functions
📌 Parameter order: positional, *args, keyword defaults, **kwargs
🟢 The *args/**kwargs pattern is essential for decorators and wrapper functions
argskwargsunpacking

Lambda & Higher-Order Functions

Anonymous functions and built-in functions that take functions as arguments.

python
💡 Prefer list comprehensions over map/filter for readability
⚡ any() and all() short-circuit — great for validation checks
📌 sorted() always returns a new list; .sort() modifies in place
🟢 filter(None, items) removes all falsy values (None, 0, "", [])
lambdamapfilterhigher-order

Classes & OOP

Classes, inheritance, dataclasses, and special methods.

Class Basics

Define classes with __init__, instance methods, and class/static methods.

python
💡 Use @property to create computed attributes accessed without parentheses
⚡ @classmethod receives the class (cls) — great for alternative constructors
📌 @staticmethod receives neither self nor cls — it's just a namespaced function
🟢 Always define __repr__ for debugging — __str__ is for user-facing output
classesoopmethods

Inheritance & Dataclasses

Extend classes with inheritance and use dataclasses for data containers.

python
💡 Use super().__init__() to call the parent class constructor
⚡ Dataclasses auto-generate __init__, __repr__, and __eq__ from type annotations
📌 Use field(default_factory=list) for mutable defaults in dataclasses
🟢 @dataclass(frozen=True) makes instances immutable and hashable
inheritancedataclassesoop

Error Handling

Handle exceptions with try/except, raise errors, and define custom exceptions.

Try / Except / Finally

Catch and handle exceptions gracefully.

python
💡 Use specific exception types — bare "except:" catches everything including KeyboardInterrupt
⚡ The else block runs only when no exception occurs — great for success logic
📌 Use "raise" without arguments to re-raise the current exception
🟢 Custom exceptions should inherit from Exception, not BaseException
exceptionstryexcepterror-handling

File I/O

Read and write files, work with JSON, and use context managers.

File Operations & JSON

Read, write, and append files. Parse and write JSON data.

python
💡 Always use "with open(...)" — it automatically closes the file
⚡ json.load/dump work with files; json.loads/dumps work with strings
📌 Use pathlib.Path for cross-platform path handling — it's the modern approach
🟢 Read large files line-by-line with "for line in f:" to save memory
filesjsonio

Modules & Virtual Environments

Import modules, create packages, and manage dependencies with venv and pip.

Imports & Modules

Import standard library and custom modules.

python
💡 A module is just a .py file — a package is a directory with __init__.py
⚡ Use "from x import y" for specific items — avoids polluting the namespace
📌 Avoid "from x import *" in production — it makes it unclear where names come from
🟢 Use relative imports (from . import) inside packages, absolute imports elsewhere
importsmodulespackages

Virtual Environments & pip

Isolate project dependencies with virtual environments.

bash
💡 Always use a virtual environment per project — never install globally
⚡ Add venv/ and __pycache__/ to .gitignore
📌 pip freeze captures exact versions — use it to lock dependencies
🟢 On some systems, use pip3 instead of pip when not in a venv
venvpipvirtual-environments

Type Hints

Add type annotations for better code clarity and tooling support.

Type Annotations

Annotate function parameters, return types, and variables.

python
💡 Type hints are not enforced at runtime — they're for documentation and tooling
⚡ Use int | str (3.10+) instead of Union[int, str] — it's cleaner
📌 Use list[str] directly (3.9+) instead of importing List from typing
🟢 Run mypy or pyright to check types statically: mypy app.py
typestype-hintsannotations

Advanced Features

Decorators, generators, context managers, and the walrus operator.

Decorators

Wrap functions to add behavior without modifying the original.

python
💡 Always use @functools.wraps(func) to preserve the original function's metadata
⚡ @functools.lru_cache is a built-in memoization decorator — use it for expensive calls
📌 Stacked decorators apply bottom-up: the lowest decorator wraps first
🟢 The @decorator syntax is shorthand for: func = decorator(func)
decoratorsadvanced

Generators & Context Managers

Lazy iteration with yield and resource management with "with" statements.

python
💡 Generators are memory-efficient — they compute values on demand, not all at once
⚡ Use next() to get the next value from a generator manually
📌 Context managers guarantee cleanup — even if an exception occurs inside the block
🟢 Use @contextmanager from contextlib to create simple context managers with yield
generatorsyieldcontext-managerswith

Standard Library

Essential modules from the Python standard library.

Essential Modules

Most commonly used standard library modules.

python
💡 Counter is the fastest way to count occurrences — use it instead of manual loops
⚡ defaultdict(list) lets you append to missing keys without checking first
📌 Use pathlib.Path over os.path — it's more readable and cross-platform
🟢 strftime formats dates to strings; strptime parses strings to dates
stdlibcollectionsdatetimepathlibosre

Best Practices

Pythonic patterns and performance tips.

Pythonic Patterns

Write idiomatic Python code.

python
💡 EAFP (try/except) is more Pythonic than LBYL (check before acting)
⚡ Use _ as a throwaway variable for values you don't need
📌 "Explicit is better than implicit" — readability counts (PEP 20)
🟢 Run "import this" in the REPL to read The Zen of Python
best-practicespythonicpatterns