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.
Output & comments
| Syntax | What it does | Lesson |
|---|---|---|
print("Hi") | Show text | Introduction |
print("Total:", n) | Show several values with spaces | Introduction |
# note | Comment, ignored by Python | Introduction |
python app.py | Run a script from the terminal | Introduction |
Variables & types
Numbers & formatting
| Syntax | What it does | Lesson |
|---|---|---|
7 // 2 7 % 2 2 ** 3 | Floor division, remainder, power | Numbers |
x += 1 | Update a variable | Numbers |
round(x, 2) abs(x) | Round, distance from zero | Numbers |
math.ceil(x) math.sqrt(x) | Round up, square root | Numbers |
random.randint(1, 6) | Random whole number | Numbers |
f"{x:.2f}" f"{n:,}" | 2 decimals, thousands separator | String Formatting |
f"{r:.1%}" | Percentage | String Formatting |
f"{s:<10}" f"{s:>10}" f"{s:^10}" | Align in a width | String Formatting |
f"{value=}" | Debug print | String Formatting |
Strings
| Syntax | What it does | Lesson |
|---|---|---|
s[0] s[-1] s[1:4] | Index and slice | Strings |
s.upper() s.lower() s.title() | Change case | Strings |
s.strip() s.replace("a", "b") | Trim spaces, replace text | Strings |
s.split(",") ", ".join(items) | Split into list, join into string | Strings |
"x" in s s.find("x") | Search inside text | Strings |
r"C:\path" | Raw string, backslashes kept | Strings |
Conditions & loops
Lists
Dictionaries, tuples & sets
| Syntax | What it does | Lesson |
|---|---|---|
d = {"a": 1} | Create a dictionary | Dictionaries |
d["a"] d.get("b", 0) | Read a value / read safely | Dictionaries |
for k, v in d.items(): | Loop over keys and values | Dictionaries |
t = (1, 2) x, y = t | Tuple and unpacking | Tuples & sets |
s = {1, 2} set() | Set of unique items | Tuples & sets |
a | b a & b a - b | Union, intersection, difference | Tuples & sets |
Functions & comprehensions
| Syntax | What it does | Lesson |
|---|---|---|
def greet(name): | Define a function | Functions |
return value | Send a result back | Functions |
def f(size="M"): | Default parameter | Functions |
[x * 2 for x in nums] | List comprehension | Comprehensions |
[x for x in nums if x > 0] | Filter with a comprehension | Comprehensions |
sorted(items, key=lambda i: i[1]) | Sort with a key | Comprehensions |
Errors & files
| Syntax | What it does | Lesson |
|---|---|---|
try: ... except ValueError: | Handle an error | Errors |
else: finally: | Run on success / always | Errors |
raise ValueError("msg") | Report a problem | Errors |
with open("f.txt", encoding="utf-8") as f: | Open a file safely | Files |
"r" "w" "a" | Read, overwrite, append | Files |
json.dump(data, f) json.load(f) | Save / load JSON | Files |
Modules & classes
| Syntax | What it does | Lesson |
|---|---|---|
import math from random import randint | Import code | Modules |
python -m venv .venv | Create a virtual environment | Modules |
pip install requests | Install a package | Modules |
class Dog: def __init__(self, name): | Define a class | Classes |
rex = Dog("Rex") | Create an object | Classes |
class Puppy(Dog): super().__init__() | Inherit and extend | Inheritance |
Arguments & dates
| Syntax | What it does | Lesson |
|---|---|---|
def f(*args, **kwargs): | Any number of arguments | Arguments & Scope |
f(*items, **options) | Unpack into a call | Arguments & Scope |
def f(a, *, key): | Keyword-only parameter | Arguments & Scope |
def f(items=None): | Safe default for a list | Arguments & Scope |
date.today() datetime.now() | Current date and time | Dates & Times |
d.strftime("%d %B %Y") | Date to text | Dates & Times |
datetime.strptime(s, "%d/%m/%Y") | Text to date | Dates & Times |
d + timedelta(days=7) (d2 - d1).days | Date arithmetic | Dates & Times |
Advanced Python
| Syntax | What it does | Lesson |
|---|---|---|
def f(x: int) -> str: | Type hints | Type Hints & Dataclasses |
@dataclass field(default_factory=list) | Data class with generated methods | Type Hints & Dataclasses |
yield value | Generator function | Iterators & Generators |
(x * 2 for x in data) | Generator expression | Iterators & Generators |
@functools.wraps(func) | Write a decorator | Decorators |
@lru_cache | Cache results | Decorators |
re.findall(r"d+", text) | Find all matches | Regular Expressions |
re.sub(r"s+", " ", text) | Replace by pattern | Regular Expressions |
re.fullmatch(pattern, text) | Validate input | Regular Expressions |
Testing & APIs
| Syntax | What it does | Lesson |
|---|---|---|
assert result == expected | Check a value in a test | Testing |
pytest -v | Run tests by name | Testing |
with pytest.raises(ValueError): | Expect an error | Testing |
@pytest.mark.parametrize(...) | One test, many cases | Testing |
requests.get(url, params=..., timeout=10) | Fetch from an API | Web APIs |
r.raise_for_status() r.json() | Check and read the response | Web APIs |
requests.post(url, json=data) | Send data | Web APIs |
Fundamentals
| Syntax or pattern | What it does | Lesson |
|---|---|---|
if condition: | Expressions produce values while statements perform actions. | Syntax and Statements |
# Explain the reason | A 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_b | True and False are boolean objects whose spellings begin with capitals. | Boolean Values and Expressions |
(a + b) * c | True 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 |
pass | pass performs no action but supplies the statement required by an otherwise empty block. | The pass Statement |
value is None | None represents the absence of a meaningful value. | The None Value |
left, right = right, left | Identifiers 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 / @property | An 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 pattern | What it does | Lesson |
|---|---|---|
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 .venv | venv creates a project environment with its own installed package set. | pip and Virtual Environments |
Professional Development
| Syntax or pattern | What it does | Lesson |
|---|---|---|
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.fixture | Fixtures 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.txt | pyproject.toml can describe a package and its declared dependencies using the chosen build tool. | Virtual Environments and Dependencies |
.venv/ and __pycache__/ in .gitignore | Git records selected source files rather than every generated environment artifact. | Git and Python Projects |
a == b versus a is b | A strong answer states a concept and demonstrates it with a small counterexample or trace. | Interview Questions and Answers |
Database and Web Track
| Syntax or pattern | What it does | Lesson |
|---|---|---|
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 TOKEN | Tokens 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 pattern | What it does | Lesson |
|---|---|---|
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 / hist | A line connects ordered observations to reveal changes along a meaningful sequence. | Line, Bar, Scatter and Histogram Charts |
DSA Track
| Syntax or pattern | What it does | Lesson |
|---|---|---|
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.next | A 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 set | A graph models entities and their connections, which may be directed or undirected. | Graphs and Graph Traversal |
choose, explore, undo | Express a problem as a current choice and a smaller remaining problem. | Recursive Problem Solving |
Machine Learning Track
| Syntax or pattern | What it does | Lesson |
|---|---|---|
features X, target y, baseline | Features are inputs and a target is the quantity or label a supervised model tries to predict. | Introduction to Machine Learning |
mean / median / multimode / pstdev | The 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 / KNeighborsClassifier | A 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 pattern | What it does | Lesson |
|---|---|---|
| Example selection | Choose an example that answers one concrete question with explicit inputs and outputs. | Python Examples Library |
| Challenge contracts | State input types, expected outputs and invalid input behavior before solving. | Python Coding Challenges |
| Focused practice | A focused problem isolates one concept so the learner can see what changed. | Python Practice Problems |
| Beginner exercises | Beginner tasks combine a few familiar operations with directly visible results. | Python Exercises by Difficulty |
| Topic selection | The Python quiz topic selector narrows the question bank to a chapter. | Python Quizzes by Chapter |
| Project scope | A beginner project needs a small explicit outcome that can be built from variables, conditions, loops and functions. | Beginner Python Projects |
| Module boundaries | Separate parsing, validation, business logic and presentation into understandable responsibilities. | Intermediate Python Projects |
| Architecture decisions | Advanced work defines interfaces and responsibilities according to the actual workload. | Advanced Python Projects |
| Foundation route | The 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. Useitems=Noneand create the list inside. - input() always returns a string. Convert with
int()orfloat()before doing maths.
Check yourself on anything you looked up twice with the Python quiz.
The Python lessons behind this cheat sheet
Beginner
- 1Python Introduction
- 2Python Syntax and Statements
- 3Python Comments
- 4Python The print() Function
- 5Python Variables and Data Types
- 6Python Naming and Multiple Assignment
- 7Python Numbers and Math
- 8Python Type Casting
- 9Python The None Value
- 10Python Strings
- 11Python String Formatting
- 12Python User Input with input()
- 13Python Boolean Values and Expressions
- 14Python Operators and Precedence
- 15Python if, elif and else
- 16Python The match Statement
- 17Python The pass Statement
- 18Python Loops
- 19Python Lists
Intermediate
- 20Python Dictionaries
- 21Python Tuples and Sets
- 22Python range() in Depth
- 23Python Arrays in Python
- 24Python Advanced Collection Methods
- 25Python Copying and Joining Collections
- 26Python Functions
- 27Python Function Arguments and Scope
- 28Python Recursion
- 29Python List Comprehensions
- 30Python Error Handling
- 31Python File Handling
- 32Python Modules and Packages
- 33Python Dates and Times
Advanced
- 34Python Classes and Objects
- 35Python Inheritance
- 36Python Magic Methods
- 37Python Class Methods and Properties
- 38Python Polymorphism and Inner Classes
- 39Python Type Hints and Dataclasses
- 40Python Iterators and Generators
- 41Python Iterators vs. Iterables
- 42Python Context Managers
- 43Python Decorators
- 44Python Regular Expressions
- 45Testing Python Code
- 46Working with Web APIs in Python
Files and Standard Library
- 47Python Read, Write, Create and Delete Files
- 48Python JSON Handling
- 49Python CSV Handling in Depth
- 50Python File and Directory Operations
- 51Python Built-in Functions Reference
- 52Python String and Collection Methods Reference
- 53Python Exception Types Reference
- 54Python Keywords and Glossary
- 55Python Standard Library Essentials
- 56Python Environment Variables and Configuration
- 57Python pip and Virtual Environments
Professional Development
- 58Python Debugging Python Programs
- 59Python Logging
- 60Python Unit Testing and pytest
- 61Python Mocking and Test Fixtures
- 62Python Code Style and PEP 8
- 63Python Type Checking and Type Hinting
- 64Python Virtual Environments and Dependencies
- 65Python Git and Python Projects
- 66Python Interview Questions and Answers
Database and Web Track
Data Science Track
DSA Track
Machine Learning Track
- 90Python Introduction to Machine Learning
- 91Python Mean, Median, Mode and Deviation
- 92Python Data Distribution and Percentiles
- 93Python Linear and Multiple Regression
- 94Python Logistic Regression
- 95Python Decision Trees and K-Nearest Neighbors
- 96Python Training and Testing Datasets
- 97Python Cross-Validation and Evaluation
- 98Python Clustering and K-Means