PythonPrintable

Python Cheat Sheet

Printing, numbers, strings, formatting, loops, collections, functions, files, dates, classes, generators, decorators, regex, testing and APIs. The Python you'll use, on one printable page.

Back to the Python tutorial

Output & comments

SyntaxWhat it doesLesson
print("Hi")Show textIntroduction
print("Total:", n)Show several values with spacesIntroduction
# noteComment, ignored by PythonIntroduction
python app.pyRun a script from the terminalIntroduction

Variables & types

SyntaxWhat it doesLesson
name = "Ada"Store a valueVariables
str int float boolText, whole, decimal, True/FalseVariables
type(x)Check the typeVariables
int("5") float("2.5") str(9)Convert typesVariables
input("Ask? ")Read text from the userVariables
f"{price:.2f}"f-string with two decimalsVariables

Numbers & formatting

SyntaxWhat it doesLesson
7 // 2 7 % 2 2 ** 3Floor division, remainder, powerNumbers
x += 1Update a variableNumbers
round(x, 2) abs(x)Round, distance from zeroNumbers
math.ceil(x) math.sqrt(x)Round up, square rootNumbers
random.randint(1, 6)Random whole numberNumbers
f"{x:.2f}" f"{n:,}"2 decimals, thousands separatorString Formatting
f"{r:.1%}"PercentageString Formatting
f"{s:<10}" f"{s:>10}" f"{s:^10}"Align in a widthString Formatting
f"{value=}"Debug printString Formatting

Strings

SyntaxWhat it doesLesson
s[0] s[-1] s[1:4]Index and sliceStrings
s.upper() s.lower() s.title()Change caseStrings
s.strip() s.replace("a", "b")Trim spaces, replace textStrings
s.split(",") ", ".join(items)Split into list, join into stringStrings
"x" in s s.find("x")Search inside textStrings
r"C:\path"Raw string, backslashes keptStrings

Conditions & loops

SyntaxWhat it doesLesson
== != > < >= <=Compare valuesif/else
if x: elif y: else:Branch on conditionsif/else
and or notCombine conditionsif/else
for item in items:Visit each itemLoops
for i in range(1, 11):1 to 10Loops
while n > 0:Repeat while trueLoops
break continueLeave loop / skip a passLoops

Lists

SyntaxWhat it doesLesson
nums = [3, 1, 2]Create a listLists
nums.append(4)Add to the endLists
nums.remove(3) nums.pop()Remove by value / remove lastLists
nums[1:3]SliceLists
sum() max() min() sorted()Work with number listsLists

Dictionaries, tuples & sets

SyntaxWhat it doesLesson
d = {"a": 1}Create a dictionaryDictionaries
d["a"] d.get("b", 0)Read a value / read safelyDictionaries
for k, v in d.items():Loop over keys and valuesDictionaries
t = (1, 2) x, y = tTuple and unpackingTuples & sets
s = {1, 2} set()Set of unique itemsTuples & sets
a | b a & b a - bUnion, intersection, differenceTuples & sets

Functions & comprehensions

SyntaxWhat it doesLesson
def greet(name):Define a functionFunctions
return valueSend a result backFunctions
def f(size="M"):Default parameterFunctions
[x * 2 for x in nums]List comprehensionComprehensions
[x for x in nums if x > 0]Filter with a comprehensionComprehensions
sorted(items, key=lambda i: i[1])Sort with a keyComprehensions

Errors & files

SyntaxWhat it doesLesson
try: ... except ValueError:Handle an errorErrors
else: finally:Run on success / alwaysErrors
raise ValueError("msg")Report a problemErrors
with open("f.txt", encoding="utf-8") as f:Open a file safelyFiles
"r" "w" "a"Read, overwrite, appendFiles
json.dump(data, f) json.load(f)Save / load JSONFiles

Modules & classes

SyntaxWhat it doesLesson
import math from random import randintImport codeModules
python -m venv .venvCreate a virtual environmentModules
pip install requestsInstall a packageModules
class Dog: def __init__(self, name):Define a classClasses
rex = Dog("Rex")Create an objectClasses
class Puppy(Dog): super().__init__()Inherit and extendInheritance

Arguments & dates

SyntaxWhat it doesLesson
def f(*args, **kwargs):Any number of argumentsArguments & Scope
f(*items, **options)Unpack into a callArguments & Scope
def f(a, *, key):Keyword-only parameterArguments & Scope
def f(items=None):Safe default for a listArguments & Scope
date.today() datetime.now()Current date and timeDates & Times
d.strftime("%d %B %Y")Date to textDates & Times
datetime.strptime(s, "%d/%m/%Y")Text to dateDates & Times
d + timedelta(days=7) (d2 - d1).daysDate arithmeticDates & Times

Advanced Python

SyntaxWhat it doesLesson
def f(x: int) -> str:Type hintsType Hints & Dataclasses
@dataclass field(default_factory=list)Data class with generated methodsType Hints & Dataclasses
yield valueGenerator functionIterators & Generators
(x * 2 for x in data)Generator expressionIterators & Generators
@functools.wraps(func)Write a decoratorDecorators
@lru_cacheCache resultsDecorators
re.findall(r"d+", text)Find all matchesRegular Expressions
re.sub(r"s+", " ", text)Replace by patternRegular Expressions
re.fullmatch(pattern, text)Validate inputRegular Expressions

Testing & APIs

SyntaxWhat it doesLesson
assert result == expectedCheck a value in a testTesting
pytest -vRun tests by nameTesting
with pytest.raises(ValueError):Expect an errorTesting
@pytest.mark.parametrize(...)One test, many casesTesting
requests.get(url, params=..., timeout=10)Fetch from an APIWeb APIs
r.raise_for_status() r.json()Check and read the responseWeb APIs
requests.post(url, json=data)Send dataWeb APIs

Fundamentals

Syntax or patternWhat it doesLesson
if condition:Expressions produce values while statements perform actions.Syntax and Statements
# Explain the reasonA hash outside a string starts a comment extending to the end of the line.Comments
print(value, sep=" / ", end="\")print converts its arguments into text for display without changing their original types.The print() Function
input("Prompt: ")input displays a prompt and reads one line from standard input.User Input with input()
int(text)int, float, str and bool request values of a particular type.Type Casting
condition_a and condition_bTrue and False are boolean objects whose spellings begin with capitals.Boolean Values and Expressions
(a + b) * cTrue division, floor division, remainder and exponentiation have distinct numeric purposes.Operators and Precedence
match value: case pattern:match is structural pattern matching introduced in Python 3.10.The match Statement
passpass performs no action but supplies the statement required by an otherwise empty block.The pass Statement
value is NoneNone represents the absence of a meaningful value.The None Value
left, right = right, leftIdentifiers can use letters, digits and underscores but cannot begin with a digit or be a keyword.Naming and Multiple Assignment
range(start, stop, step)range includes its start and excludes its stop.range() in Depth
array("i", values)Lists store object references while array.array stores values of one supported basic type.Arrays in Python
return current + solve(smaller)A recursive function calls itself on a smaller problem.Recursion
mapping.update(other)append, extend, sort and reverse change the original list.Advanced Collection Methods
deepcopy(nested)Assignment gives another name to the same collection.Copying and Joining Collections
next(iterator, default)An iterable can provide an iterator through iter.Iterators vs. Iterables
def __repr__(self):Defined special methods connect classes with Python operations.Python Magic Methods
@classmethod / @propertyAn instance method receives self and operates on one object state.Class Methods and Properties
object.describe()Different objects can implement the same meaningful operation.Polymorphism and Inner Classes
with manager() as value:with pairs context entry with cleanup when leaving the block.Context Managers

Files and Standard Library

Syntax or patternWhat it doesLesson
path.open("x", encoding="utf-8")r reads existing text, w overwrites or creates, a appends and x creates exclusively.Read, Write, Create and Delete Files
json.loads(text) / json.dumps(value)JSON objects map to dictionaries, arrays to lists and null to None.JSON Handling
csv.DictReader(stream)CSV is a text format with rows and fields whose quoting rules can protect embedded delimiters.CSV Handling in Depth
Path(folder).glob("*.png")pathlib.Path expresses filesystem paths and joins components with the slash operator.File and Directory Operations
enumerate(values, start=1)type, isinstance, len and callable answer different questions about an object.Built-in Functions Reference
text.strip().casefold()String methods such as strip, split, replace and casefold return transformed text rather than mutating the original.String and Collection Methods Reference
except ValueError:ValueError indicates an unsuitable value while TypeError often indicates an unsupported operation or argument type.Exception Types Reference
keyword.iskeyword(name)Keywords such as if, class, return and import have defined grammatical roles.Python Keywords and Glossary
Counter(values)os provides operating system interfaces while sys describes the interpreter and its process context.Standard Library Essentials
os.getenv("SETTING", default)Environment variables are external string settings read through os.environ or os.getenv.Environment Variables and Configuration
python -m venv .venvvenv creates a project environment with its own installed package set.pip and Virtual Environments

Professional Development

Syntax or patternWhat it doesLesson
breakpoint()A small repeatable example gives an investigation a stable starting point.Debugging Python Programs
logger.info("Count: %s", count)DEBUG, INFO, WARNING, ERROR and CRITICAL distinguish kinds of operational messages.Logging
@pytest.mark.parametrize(...)A unit test checks an observable result for a controlled input.Unit Testing and pytest
@pytest.fixtureFixtures supply reusable test dependencies with a managed lifetime.Mocking and Test Fixtures
def meaningful_name(...):snake_case names normally identify functions and variables, while class names commonly use CapWords.Code Style and PEP 8
def total(values: list[float]) -> float:Type hints describe expected types for readers and static analysis tools.Type Checking and Type Hinting
python -m pip install -r requirements.txtpyproject.toml can describe a package and its declared dependencies using the chosen build tool.Virtual Environments and Dependencies
.venv/ and __pycache__/ in .gitignoreGit records selected source files rather than every generated environment artifact.Git and Python Projects
a == b versus a is bA strong answer states a concept and demonstrates it with a small counterexample or trace.Interview Questions and Answers

Database and Web Track

Syntax or patternWhat it doesLesson
cursor.execute(sql, parameters)MySQL Connector/Python is a separately installed database driver.Python MySQL Tutorial
collection.update_one(filter, {"$set": changes})MongoDB stores documents grouped into collections, and PyMongo is a Python driver.Python MongoDB Tutorial
db.execute(sql, parameters)INSERT adds rows while SELECT retrieves chosen columns and matching records.SQL CRUD with Python
closing(sqlite3.connect(path))A connection represents a database session while a cursor performs queries and reads results.Database Connections and Queries
requests.get(url, timeout=10)GET retrieves representations while POST commonly submits new data, with endpoint contracts defining exact behavior.HTTP Requests and REST APIs
Authorization: Bearer TOKENTokens or credentials identify a caller according to the API contract.API Authentication and Errors
self.end_headers()A handler inspects the request path and writes an HTTP response.A Simple Python Web Server
@app.get("/status")Flask provides an application object that registers routes and handles requests.Introduction to Flask

Data Science Track

Syntax or patternWhat it doesLesson
array.sum(axis=1)ndarray stores numeric values with a shape and dtype.NumPy Tutorial
frame.groupby("key")["value"].sum()A DataFrame organizes labeled columns and rows while a Series represents one labeled sequence.Pandas Tutorial
fig, ax = plt.subplots()A Figure holds the overall graphic while Axes hold plotting areas and their scales.Matplotlib Tutorial
pd.to_numeric(column, errors="coerce")Define expected columns, types and allowed values before transforming rows.Data Cleaning and Analysis
stdev(sample) / pstdev(population)Mean summarizes the arithmetic average while median identifies the middle sorted value.Statistics with Python
ax.plot / bar / scatter / histA line connects ordered observations to reveal changes along a meaningful sequence.Line, Bar, Scatter and Histogram Charts

DSA Track

Syntax or patternWhat it doesLesson
O(1), O(log n), O(n), O(n²)Complexity describes how work or memory grows with a defined input size.Time and Space Complexity
bisect_left(sorted_values, target)A linear search examines candidates in order until it finds a match or finishes.Linear and Binary Search
sorted(records, key=key_function)A key function defines the value used to compare records.Sorting Algorithms
list.pop() / deque.popleft()A stack removes the most recently added item first.Stacks and Queues
node = node.nextA linked node stores a value and a reference to the next node.Linked Lists
mapping[key]A hash maps a key to a numeric value used in locating a storage region.Hash Tables
inorder(left), node, inorder(right)A tree models parent and child relationships without cycles in its ordinary rooted form.Trees and Binary Search Trees
queue + visited setA graph models entities and their connections, which may be directed or undirected.Graphs and Graph Traversal
choose, explore, undoExpress a problem as a current choice and a smaller remaining problem.Recursive Problem Solving

Machine Learning Track

Syntax or patternWhat it doesLesson
features X, target y, baselineFeatures are inputs and a target is the quantity or label a supervised model tries to predict.Introduction to Machine Learning
mean / median / multimode / pstdevThe mean adds every observation while the median follows ordered position.Mean, Median, Mode and Deviation
np.percentile(values, 90)A distribution describes where values occur and how frequently, including skew and multiple clusters.Data Distribution and Percentiles
LinearRegression().fit(X_train, y_train)Linear regression expresses a numeric prediction as an intercept plus weighted feature contributions.Linear and Multiple Regression
model.predict_proba(X)Logistic regression commonly estimates probabilities for categorical outcomes.Logistic Regression
DecisionTreeClassifier / KNeighborsClassifierA decision tree partitions feature space through successive conditions.Decision Trees and K-Nearest Neighbors
train_test_split(X, y, ...)Training data fits a model while validation guides choices and final test data assesses the chosen procedure.Training and Testing Datasets
cross_val_score(pipeline, X, y, ...)Cross validation fits on training folds and evaluates on their held out counterparts.Cross-Validation and Evaluation
KMeans(n_clusters=k, n_init=10)Clustering groups observations by selected feature relationships without known target labels.Clustering and K-Means

Practice and Projects

Syntax or patternWhat it doesLesson
Example selectionChoose an example that answers one concrete question with explicit inputs and outputs.Python Examples Library
Challenge contractsState input types, expected outputs and invalid input behavior before solving.Python Coding Challenges
Focused practiceA focused problem isolates one concept so the learner can see what changed.Python Practice Problems
Beginner exercisesBeginner tasks combine a few familiar operations with directly visible results.Python Exercises by Difficulty
Topic selectionThe Python quiz topic selector narrows the question bank to a chapter.Python Quizzes by Chapter
Project scopeA beginner project needs a small explicit outcome that can be built from variables, conditions, loops and functions.Beginner Python Projects
Module boundariesSeparate parsing, validation, business logic and presentation into understandable responsibilities.Intermediate Python Projects
Architecture decisionsAdvanced work defines interfaces and responsibilities according to the actual workload.Advanced Python Projects
Foundation routeThe preserved twenty five lessons anchor the course, with new fundamental pages placed near their prerequisites.Study Plan and Learning Roadmap

How to use this Python cheat sheet

This Python cheat sheet collects the syntax you'll reach for most often, grouped in the same order as the course: output and comments, variables and types, numbers and formatting, strings, conditions, loops, collections, functions, errors, files, modules, classes, dates, type hints, generators, decorators, regular expressions, testing and web APIs. Each row links to the lesson that explains it in full, with examples and common mistakes.

Use it as a memory aid while you practise, not as a replacement for the lessons. When you can't remember whether it's split() or join() that belongs to the separator, or which file mode appends instead of overwriting, a quick look here saves a search. Type part of a method name into the filter box to jump straight to it, or print the page and keep it next to your keyboard while you work through the exercises.

Python gotchas worth remembering

  • Mutable default arguments are shared. def add(item, items=[]) reuses the same list on every call. Use items=None and create the list inside.
  • input() always returns a string. Convert with int() or float() before doing maths.

Check yourself on anything you looked up twice with the Python quiz.

The Python lessons behind this cheat sheet