Python (programming language)/Cheat sheet
Last edited by dave on 14/02/2026, 10:08:16 UTC
Python (programming language) / Cheat sheet
Contents
The cheat sheet of Python
Scope: Python 3.10+, scripting, packaging, typing, async, testing, and common stdlib patterns.
0. Quick Start
Verify Python:
python3 --version
Create virtual environment:
python3 -m venv .venv source .venv/bin/activate
Install package:
pip install requests
1. Project Layout (Common)
project/
├─ src/
│ └─ app/
│ └─ __init__.py
├─ tests/
├─ pyproject.toml
└─ README.md
2. Python Basics
Variables:
x = 10 name = "alice"
Multiple assignment:
a, b = 1, 2
3. Control Flow
If:
if x > 0: pass elif x == 0: pass
For:
for i in range(5): print(i)
While:
while condition: break
4. Functions
def add(a: int, b: int) -> int: return a + b
Defaults:
def greet(name="world"): print(name)
Keyword-only:
def f(*, debug=False): pass
5. Data Structures
List:
xs = [1, 2, 3]
Dict:
m = {"a": 1}
Set:
s = {1, 2, 3}
Tuple:
t = (1, 2)
6. Comprehensions
[x*x for x in range(5)] {x: x*x for x in range(5)}
Filtered:
[x for x in xs if x > 2]
7. Classes
class User: def __init__(self, name: str): self.name = name
8. Dataclasses
from dataclasses import dataclass @dataclass class User: id: int name: str
9. Exceptions
try: x = int("a") except ValueError: pass
Raise:
raise RuntimeError("oops")
10. File I/O
with open("file.txt") as f: data = f.read()
Write:
with open("file.txt", "w") as f: f.write("hi")
11. Modules & Imports
import math from pathlib import Path
Relative import:
from .utils import helper
12. Packaging (pyproject.toml)
Minimal:
[project] name = "myapp" version = "0.1.0" dependencies = ["requests"]
Install locally:
pip install -e .
13. Typing
def f(x: int) -> str: return str(x)
Collections:
list[int] dict[str, int]
Optional:
int | None
14. Async Programming
Coroutine:
async def fetch(): return 1
Run:
import asyncio asyncio.run(fetch())
Gather:
await asyncio.gather(a(), b())
15. JSON
import json json.dumps(obj) json.loads(s)
16. CLI Arguments
import argparse parser = argparse.ArgumentParser() parser.add_argument("--port", type=int) args = parser.parse_args()
17. Logging
import logging logging.basicConfig(level=logging.INFO)
18. Testing (pytest)
Run:
pytest
Example:
def test_add(): assert 1 + 1 == 2
19. Useful Stdlib Modules
Common:
- pathlib
- datetime
- subprocess
- itertools
- collections
- functools
- tempfile
- uuid
Example:
from pathlib import Path Path("file.txt").read_text()
20. Virtualenv Workflow
python3 -m venv .venv source .venv/bin/activate pip install -e . pytest
21. Quick Reference
python3 -m venv .venv pip install -e . pytest python main.py
Backlinks (3)
- General
- User
No backlinks yet.
- Redirects
No backlinks yet.
- Media
No backlinks yet.
- Categories
No backlinks yet.
Categories (0)
No categories assigned to this page.
Edit Level
> Signed In Users
Latest on Lounge
Join the conversation about the 'Python (programming language)/Cheat sheet' article →
No comments yet. Be the first to comment!