Python Cheat Sheets for Quick Reference and Learning
A version-aware Python cheat sheet for everyday syntax, data types, control flow, functions, errors, and files, with links to the official docs for details.

Python cheat sheet, checked against Python 3.14.7 documentation (review date: September 29, 2026): use this page to recall common syntax and tasks, then follow the linked official documentation when behavior or version details matter. A cheat sheet is a map, not a substitute for the tutorial or language reference. The Python Software Foundation documentation separates those resources, along with built-ins and the library reference. Open the Python 3.14.7 documentation.
1. Start Python and run a script
Use the interactive interpreter to try expressions, and a .py file for a program you want to save or run again. The command name depends on how Python was installed; on some systems it is python3 rather than python.

# Check which interpreter is available
python --version
python3 --version
# Start an interactive session
python
# Save as hello.py, then run it
print("Hello, Python")
# Run the file
python hello.py
In an interactive session, type an expression and press Enter to see its value. To leave, use exit() or the terminal’s end-of-input shortcut. If a command is not found, install Python or correct your PATH, then confirm the interpreter with python --version. For installation and usage details, start from Python setup and usage.
2. Syntax, comments, and indentation
Python uses indentation to group statements. Keep indentation consistent, conventionally four spaces per level. A colon introduces a suite such as the body of an if, loop, function, or class. Comments begin with #.
# This is a comment
name = "Ari"
if name:
print(f"Hello, {name}") # indented block
Indentation errors are syntax errors, not cosmetic warnings. Avoid mixing tabs and spaces. For the formal rules, use the language reference.
3. Variables, types, and conversions
Names refer to objects; assignment binds a name to a value. Python does not require a type declaration for ordinary variables.
| Kind | Example | Useful detail |
|---|---|---|
| Integer | count = 12 |
Whole numbers |
| Float | ratio = 0.75 |
Binary floating-point values |
| Boolean | ready = True |
Values are True and False |
| None | result = None |
Represents absence of a value |
| String | label = "draft" |
Text; immutable |
| List | items = ["a", "b"] |
Ordered, mutable sequence |
| Tuple | point = (3, 4) |
Ordered sequence, commonly used as fixed grouping |
| Dictionary | user = {"id": 7} |
Key-value mapping |
| Set | unique = {"a", "b"} |
Unique elements |
text = "42"
number = int(text) # 42
price = float("3.50") # 3.5
as_text = str(number) # "42"
# Inspect a value when debugging
print(type(price))
Conversions can fail: int("four") raises ValueError. Check or handle the input instead of assuming every string is numeric. See the built-in functions reference for conversion and inspection functions.
4. Strings and formatting
Strings can use single or double quotes. Use an f-string to interpolate expressions into readable output. Indexing starts at zero; a slice excludes its ending index.
name = "Sam"
message = f"Hello, {name}!"
word = "python"
first = word[0] # "p"
last_three = word[-3:] # "hon"
parts = "red,green,blue".split(",")
joined = " | ".join(parts)
Strings are immutable: operations produce a new string rather than changing the existing one. For extensive text processing, consult the string type documentation.
5. Lists, dictionaries, and common collection patterns
Use a list when order and edits matter, a tuple for a fixed ordered grouping, a dictionary for lookup by key, and a set when uniqueness or membership checks are central.
tasks = ["read", "write"]
tasks.append("review")
print(tasks[0])
print(tasks[-1])
print(tasks[1:])
scores = {"Mina": 91, "Lee": 84}
scores["Jo"] = 88
print(scores.get("Pat", 0)) # default if key is absent
seen = {"alpha", "beta"}
print("alpha" in seen)
Common mistakes include indexing beyond the end of a list (IndexError) and looking up a missing dictionary key with brackets (KeyError). Use get when a missing key should have a default, or handle the exception when absence is exceptional.
6. Conditions and loops
Use if/elif/else for branching. for iterates over items; while repeats while a condition remains true. range produces a sequence of integers whose stop value is excluded.
temperature = 18
if temperature < 0:
label = "freezing"
elif temperature < 20:
label = "cool"
else:
label = "warm"
for index, value in enumerate(["a", "b", "c"]):
print(index, value)
for n in range(1, 4):
print(n) # 1, 2, 3
remaining = 3
while remaining > 0:
remaining -= 1
break exits the nearest loop; continue skips to its next iteration. Prefer iterating over a collection directly instead of manually managing indexes unless the index is needed. A loop that never changes the condition of a while loop may run forever.
7. Functions
Define reusable behavior with def. Parameters can have defaults; return sends a value back to the caller. A function without an explicit return value returns None.
def rectangle_area(width, height=1):
"""Return the area of a rectangle."""
return width * height
area = rectangle_area(4, height=3)
print(area) # 12
Use keyword arguments when they make a call clearer. Avoid mutable objects such as lists as default parameter values: defaults are created once when the function is defined, which can cause later calls to share mutations. Learn more in the official tutorial’s function section.
8. Classes and instances
A class defines a kind of object; an instance holds data and can expose methods. self refers to the instance receiving a method call.
class Counter:
def __init__(self, start=0):
self.value = start
def increment(self):
self.value += 1
counter = Counter(2)
counter.increment()
print(counter.value) # 3
Use a class when state and related behavior belong together. For a short transformation or a small group of values, a function or built-in collection may be simpler. The tutorial’s classes chapter covers inheritance and other details.
9. Exceptions and error handling
Errors should be handled at the point where the program can make a sensible decision. Catch specific exception types; broad catches can hide programming mistakes.
raw = "27"
try:
quantity = int(raw)
except ValueError:
print("Enter a whole number")
else:
print(f"Quantity: {quantity}")
finally:
print("Input processing finished")
else runs if the try block succeeds; finally runs whether it succeeds or raises. Raise an exception when a function cannot fulfill its contract. See errors and exceptions.
10. Read and write files
Use a context manager so the file is closed even if an error occurs. Specify an encoding for text files to avoid depending on the machine’s default.
# Read UTF-8 text
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
# Write or replace UTF-8 text
with open("summary.txt", "w", encoding="utf-8") as file:
file.write("Done\n")
# Append a line
with open("summary.txt", "a", encoding="utf-8") as file:
file.write("Next step\n")
Modes matter: "w" replaces existing contents, while "a" appends. A missing input file raises FileNotFoundError; verify the working directory or use a deliberate path. For structured formats such as JSON or CSV, use the corresponding standard-library modules documented in the library reference.
11. Getting input and printing output
input reads a line of text and returns a string. Convert it before arithmetic, and handle invalid input if users can enter arbitrary text.
name = input("Name: ")
raw_age = input("Age: ")
try:
age = int(raw_age)
except ValueError:
print("Age must be a whole number")
else:
print(f"{name} is {age}")
12. How to choose and keep a cheat sheet current
A useful reference makes its version and update date visible, gives examples, and points to fuller explanations. Check these things before relying on a sheet:

- Version: Does it say which Python version it covers?
- Scope: Is it about core Python or a framework/library with its own release cycle?
- Explanation: Does it link to definitions for nuanced behavior?
- Format: Do you need a searchable web page, downloadable PDF, or print-friendly reference?
- Authority: Is the sheet official, or a third-party summary to verify against official documentation?
Python.org links to learning resources, books, and downloadable documentation formats, including typeset versions suitable for printing. See Python.org’s documentation resources. Real Python also provides a condensed sheet with a printable version; it is a third-party learning aid, so use official docs for definitive details: Real Python Python Cheat Sheet.
Do not assume a search result is current just because it is hosted on python.org. For example, the archived Python Quick Reference explicitly covers Python 1.3 and dates to 1995. It is historical material, not a current Python 3 guide.
13. Troubleshooting quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
python command not found |
Interpreter is not installed or not on PATH; command may be python3. |
Check installation and try python3 --version. |
IndentationError |
Block indentation is missing or inconsistent. | Align statements in the block and use spaces consistently. |
SyntaxError at an unexpected line |
Missing colon, quote, bracket, or earlier malformed expression. | Inspect the indicated line and the preceding line; delimiters often cause errors downstream. |
TypeError combining values |
Operation received incompatible types, such as text plus integer. | Convert intentionally with str, int, or another suitable conversion. |
ValueError during conversion |
Input is not valid for the requested type. | Validate or catch the specific exception and explain the expected input. |
IndexError |
Sequence index is outside its valid range. | Check length, use iteration, or handle the empty-sequence case. |
KeyError |
Dictionary key is absent. | Use get for optional keys or handle absence explicitly. |
FileNotFoundError |
Path is wrong or relative to a different working directory. | Check the current working directory and path; use an explicit path when appropriate. |
| Old syntax sheet disagrees with interpreter | Sheet targets another Python version or Python 2. | Confirm its version and date, then check Python 3.14.7 docs and “What’s New.” |
14. Or skip the browser setup
If you need a screenshot of your Python project’s documentation, rendered output, or a page used alongside your code, you can capture it with your own browser automation. That means managing a browser, waiting for the page, and deciding how to handle consent and overlays. Or use ScreenshotNeo, a website screenshot API and MCP server from Yorker Media. One GET request returns a PNG, JPEG, WebP, or PDF. See the API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://docs.python.org/3/ -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://docs.python.org/3/"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://docs.python.org/3/',
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, no card required.
15. Short FAQ
Is this sheet for Python 2?
No. It is a Python 3 reference aligned to the Python 3.14.7 documentation listed at review time. Always check the version shown on any sheet you find.
Should I learn from a cheat sheet alone?
No. Use it to recall syntax, then learn concepts in the official tutorial and resolve precise questions in the relevant reference.
Where can I get a printable reference?
Python.org offers downloadable documentation formats, including typeset versions. Real Python offers a printable third-party cheat sheet. Check the version and date before printing or relying on either.
Where should I look when a detail is missing here?
Start at the official docs landing page, then choose the tutorial, built-ins, library reference, or language reference that matches the question.


