Python Cheatsheet - Command Reference
This reference is for developers who are new to Python or hop between projects, covering the syntax you reach for most when scripting, processing text and data, and automating small tasks. Unlike API listings, entries are grouped by real usage scenarios (environments, containers, file I/O, exceptions) so you can code directly. By the end you should be able to set up a venv, condense loops into comprehensions, read and write files and JSON safely, and contain runtime errors with try/except.
Virtual Environment & Package Management 8
python3 -m venv venvsource venv/bin/activatevenv\Scripts\activatedeactivatepip install packagepip install -r requirements.txtpip freeze > requirements.txtpip listData Types 7
list = [1, 2, 3]tuple = (1, 2, 3)dict = {"key": "value"}set = {1, 2, 3}str = "hello"type(obj)isinstance(obj, int)List Comprehension 5
[x*2 for x in range(10)][x for x in range(10) if x % 2 == 0]{x: x*2 for x in range(5)}{x for x in range(10) if x % 2 == 0}list(map(lambda x: x*2, [1,2,3]))File I/O 8
with open("file.txt", "r") as f: content = f.read() lines = f.readlines()with open("file.txt", "w") as f: f.write("content")with open("file.txt", "a") as f:import json; json.load(f)json.dump(data, f, indent=2)Exception 8
try: result = 10 / 0except ZeroDivisionError as e: print(f"Error: {e}")except Exception as e:else:finally:raise ValueError("msg")Built-in 8
len(obj)range(start, stop, step)enumerate(iterable)zip(list1, list2)sorted(iterable, key=None, reverse=False)filter(func, iterable)map(func, iterable)any(iterable) / all(iterable)Typical Use Case
For developers whose day job revolves around scripting and data processing: scaffold a fresh venv and install dependencies, compress tedious loops into comprehensions, clean CSV or log lines by field, and persist intermediate results with with + json. Whether patching together a scratch tool, running a one-off report, or writing a scheduled task, these are the commands reused most.
Command Examples
Generate an arithmetically spaced sequence in one line
[x*2 for x in range(10)]range(stop) 是左闭右开,stopping 值不包含;要从 1 数到 10 请写 range(1, 11)。
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Read and write a JSON file
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)ensure_ascii=False 才会保留中文可读,否则非 ASCII 字符会被写成 \uXXXX 转义;with 语句保证文件在出错或正常结束时都被正确关闭。
Read a traceback to find the exception source
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")先用精确的异常类型,等真正需要兜底时再用 except Exception 捕获,避免吞掉不该忽略的 KeyboardInterrupt。
Output
Error: division by zero
Create a virtual environment and install dependencies
python3 -m venv venv
source venv/bin/activate
pip install requests
pip freeze > requirements.txtWindows 下激活改用 venv\Scripts\activate;requirements.txt 应在每次添加依赖后重新导出保持一致。
Output
(venv) $
Common Pitfalls
- Do not install packages into system Python blindly: test against venv before applying someone else's requirements.txt to avoid polluting or conflicting with the system interpreter.
- range() is half-open (excludes the stop value); index off-by-one errors are the most common pitfall. Start from 1 with range(1, n + 1).
- Using open() outside a with block without closing, or overlooking that mode="w" truncates the file first, can destroy data — confirm the path and mode before writing.
- A bare except Exception also swallows KeyboardInterrupt (Ctrl+C); do not silence every error, log it or re-raise at least part of it.
Tips
- Always use the with statement for file operations to ensure proper closing, even on exceptions.
- List comprehensions are more concise and efficient than for loops, but use regular loops for complex logic.
- In Python 3, range() returns an iterator, not a list — saving memory.
FAQ
Is a virtual environment mandatory for Python?
Not strictly, but strongly recommended. pip install writes into the global site-packages by default, so multiple projects can conflict. Create an isolated environment with python -m venv .venv and activate it before installing dependencies to keep them project-local.
What is the difference between == and is in Python?
== compares whether two objects are equal in value; is compares whether two variables refer to the same object in memory. Results may coincide for small numbers and interned strings, but for mutable containers like list and dict, is is usually False — use == for value equality and is only for object identity or None checks.
List comprehension or generator expression — which should I use?
They share the same syntax; a generator just swaps the outer brackets for parentheses. A list comprehension builds the whole list eagerly in memory, good when results are traversed repeatedly or sliced; a generator yields items lazily, saving memory, ideal for a single pass over huge data or aggregations like sum/min/max.
Why is with open() recommended, and what happens if I forget to close a file?
with open(path) as f automatically calls f.close() when the block ends, even on exceptions, so the handle is never leaked. Manually calling open() without close() can leave the file locked and buffers unflushed — prefer with, and if managing manually always close in a finally block.
Should I catch every exception in Python?
A bare except that swallows everything is harmful because it hides real bugs. Catch specific types (ValueError, KeyError) or at least except Exception, then re-raise or log afterwards so failures stay visible and debuggable.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us