Python Cheat Sheet: Syntax Reference on One Page - Python with AI tutorial chapter 48
Python

Python Cheat Sheet: Syntax Reference on One Page

Python with AI Tutorial · Chapter 48 of 48

This Python cheat sheet puts the syntax from all 48 chapters of the course on one page: variables, strings, collections, control flow, functions, classes, files and pandas basics. Each table shows the statement, a short business-flavoured example and the result, and links to the chapter that explains it. Bookmark it and keep it open while you write code with or without an AI assistant.

Variables and data types

Chapters: Variables, Data Types, Casting, Booleans.

Syntax Example Result / note
Assign revenue = 26150 int
Multiple assign qty, price = 4, 1100.0 int, float
Type check type(price) <class 'float'>
Cast int("42"), float("3.5"), str(7) 42, 3.5, ‘7’
Boolean paid = total > 0 True / False
Truthiness bool(""), bool([]), bool(0) all False
None discount = None "no value yet"
Constants (convention) VAT_RATE = 0.18 upper case, module level

Numbers and operators

Chapters: Numbers, Operators, Math.

Syntax Example Result
Arithmetic 7 / 2, 7 // 2, 7 % 2, 2 ** 10 3.5, 3, 1, 1024
Round round(314.7255, 2) 314.73
Compound assign total += 49.5 adds and stores
Comparison a == b, a != b, a >= b bool
Logic paid and not overdue, x or y bool
Membership "North" in regions bool
math module math.ceil(4.2), math.sqrt(16) 5, 4.0
Big numbers 1_000_000 underscores allowed

Strings and formatting

Chapters: Strings, String Formatting, Regex.

Syntax Example Result
f-string f"Total: {total:,.2f}" Total: 2,063.23
Padding f"{name:<10}{qty:>4}" left / right align
Debug form f"{qty=}" qty=4
Slice "INV-2026-0042"[4:8] ‘2026’
Case s.lower(), s.upper(), s.title() new string
Clean s.strip(), s.replace(",", "") new string
Split / join "a,b".split(","), ", ".join(items) list / string
Search s.startswith("INV"), s.find("-") bool / index or -1
Regex re.findall(r"\d{4}", s) list of matches

Lists, tuples and sets

Chapters: Lists, Tuples, Sets.

Syntax Example Result
Create sales = [4400, 2500, 1250] list (mutable)
Index / slice sales[0], sales[-1], sales[1:] 4400, 1250, [2500, 1250]
Add / remove sales.append(900), sales.pop(), sales.remove(2500) in place
Sort sorted(sales, reverse=True), sales.sort() new list / in place
Aggregate sum(sales), len(sales), max(sales) 8150, 3, 4400
Comprehension [s * 1.18 for s in sales if s > 2000] filtered new list
Tuple row = ("North", 46200); region, rev = row immutable, unpack
Set set(["N", "S", "N"]) {‘N’, ‘S’} unique
Set ops a | b, a & b, a - b union, intersection, difference
Enumerate / zip for i, s in enumerate(sales, 1), zip(a, b, strict=True) index pairs / parallel loop

Dictionaries

Chapter: Dictionaries.

Syntax Example Result
Create row = {"Region": "North", "Revenue": 46200} dict
Read row["Revenue"], row.get("Units", 0) 46200, 0 (no KeyError)
Write row["Units"] = 42 adds or updates
Delete del row["Units"], row.pop("Units", None) removes key
Loop for k, v in row.items(): key, value pairs
Views row.keys(), row.values() iterables
Comprehension {r: t * 1.1 for r, t in totals.items()} new dict
Counting Counter(words).most_common(3) from collections
Merge {**defaults, **overrides} or a | b right side wins

Control flow

Chapters: If Else, While Loops, For Loops.

Syntax Example Note
if / elif / else if n < 0: ... elif n == 0: ... else: ... colon + 4-space indent
Conditional expression label = "late" if days > 0 else "on time" one-line if
for for order in orders: over any iterable
range for i in range(1, 13): 1 to 12
while while balance > 0: needs an exit condition
break / continue if not text: continue; if text == "quit": break skip / leave loop
match match status: case "paid": ... case _: ... Python 3.10+
pass def todo(): pass placeholder

Functions, lambda and scope

Chapters: Functions, Lambda, Scope.

Syntax Example Note
Define def net(price, vat=0.18): return price * (1 + vat) default argument
Type hints def net(price: float, vat: float = 0.18) -> float: documentation, not enforced
Keyword call net(100, vat=0.05) clearer than positional
*args / **kwargs def log(*items, **options): tuple / dict inside
Return several return total, count; t, c = f() tuple unpacking
Lambda sorted(rows, key=lambda r: r["Revenue"]) one-expression function
Docstring """Return net price.""" first line of body
Scope local inside function; global x to write a module variable avoid global

Errors and exceptions

Chapters: Try Except, Debugging with AI.

Syntax Example Note
try / except try: float(s) except ValueError: ... catch specific types
Access error except KeyError as e: print(e) message in e
else / finally else: runs if no error; finally: always cleanup in finally
Raise raise ValueError("pct must be 0-100") your own checks
Custom error class BudgetError(Exception): pass subclass Exception
Debugger breakpoint() then p, n, c, q built-in pdb

Classes and inheritance

Chapters: Classes and Objects, Inheritance, Iterators and Generators.

Syntax Example Note
Class class Invoice: CapWords name
Constructor def __init__(self, number, total): self first
Attribute self.total = total per instance
Method def is_paid(self) -> bool: called as inv.is_paid()
String form def __str__(self): return f"Invoice {self.number}" used by print
Inherit class CreditNote(Invoice): reuse parent
Parent call super().__init__(number, -total) inside child __init__
Dataclass @dataclass class Row: region: str; revenue: float auto __init__, __repr__
Generator def rows(): yield row lazy iteration

Files, CSV and JSON

Chapters: File Handling, CSV, JSON.

Syntax Example Note
Read text with open("notes.txt", encoding="utf-8") as f: text = f.read() with closes the file
Write / append open("log.txt", "w"), open("log.txt", "a") w overwrites
Lines for line in f: memory friendly
pathlib Path("data") / "sales.csv", p.exists(), p.read_text() modern file paths
CSV read for row in csv.DictReader(f): row is a dict
CSV write csv.writer(f).writerow([...]) open with newline=""
JSON to text json.dumps(data, indent=2) string
JSON from text json.loads(text) dict / list
JSON file json.dump(data, f), json.load(f) no s = file objects

Modules, dates, input and the web

Chapters: Modules and pip, Dates, User Input, Requests and APIs.

Syntax Example Note
Import import math, from datetime import date, import pandas as pd alias with as
Install pip install requests in the terminal, inside a venv
Today date.today(), datetime.now() date / datetime
Format f"{d:%d %b %Y}" 05 Sep 2026
Parse datetime.strptime("2026-09-05", "%Y-%m-%d") string to datetime
Difference (due - today).days, d + timedelta(days=30) timedelta
Input age = int(input("Age: ")) always returns str
HTTP GET requests.get(url, params={...}, timeout=10).json() check raise_for_status()
Env variable os.environ["OPENAI_API_KEY"] never hard-code keys

pandas basics

Chapters: NumPy, pandas, pandas with Excel, Matplotlib.

Syntax Example Note
Load pd.read_csv("sales.csv"), pd.read_excel("sales.xlsx", sheet_name="Data") DataFrame
Inspect df.head(), df.info(), df.describe(), df.shape first look
Select df["Revenue"], df[["Region", "Revenue"]] Series / DataFrame
Filter df[df["Revenue"] > 10000], df.query("Region == 'North'") boolean mask
New column df["Margin"] = df["Revenue"] - df["Cost"] vectorised
Group df.groupby("Region")["Revenue"].sum() add .reset_index() for a table
Pivot df.pivot_table(index="Region", columns="Product", values="Revenue", aggfunc="sum") Excel-style pivot
Sort / missing df.sort_values("Revenue", ascending=False), df.dropna(), df.fillna(0) new DataFrame
Save df.to_excel("out.xlsx", index=False), df.to_csv("out.csv", index=False) openpyxl for xlsx
Chart df.plot(kind="bar"); plt.savefig("chart.png") matplotlib

AI APIs in one glance

Chapters: Call an AI API, Chatbot, Automate Excel with AI.

Task OpenAI Anthropic
Install pip install openai pip install anthropic
Client client = OpenAI() client = anthropic.Anthropic()
Call client.responses.create(model="gpt-5", input="...") client.messages.create(model="claude-sonnet-5", max_tokens=1024, messages=[...])
Text r.output_text m.content[0].text
System prompt instructions="..." system="..."
Usage r.usage.input_tokens m.usage.input_tokens
Try it with AI

Turn any row of these tables into a worked example in seconds.

Give me a runnable Python 3.12 example, under 10 lines, that demonstrates df.pivot_table(index="Region", columns="Product", values="Revenue", aggfunc="sum") on a small DataFrame of six sales rows, and show the exact printed output.
Tip: when an assistant’s code uses a method that is not in these tables, check the official documentation before running it. Hallucinated method names such as df.sum_by() or list.add() look plausible and fail immediately.
Try it with AI

Use the sheet as a quiz generator.

Using only the Python topics variables, strings, lists, dictionaries, loops, functions and pandas basics, write 10 short quiz questions with a one-line answer each. Mix syntax questions with "what does this print" questions using small business examples. Do not show the answers until I ask.

Common mistakes

  • Forgetting the colon after if, for, def and class, and mixing tabs with spaces.
  • Treating input() results as numbers without casting.
  • Expecting sorted() or df.sort_values() to change the original in place; both return a new object.
  • Using == to compare with None; write is None.
  • Opening files without encoding="utf-8" and getting garbled accents on Windows.

Related chapters

FAQ

Is this Python cheat sheet enough to learn Python?

No, it is a reference. Work through the 48 chapters for explanations and exercises, then use this page to look up syntax while you build the projects.

Which Python version does the cheat sheet cover?

Python 3.12. Everything here also runs on 3.10 and later, including match statements, the dict union operator and zip with strict=True.

Can I print the Python cheat sheet?

Yes. Use your browser’s print function; the tables are plain HTML and fit on a few A4 pages in landscape orientation.

Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.

Chapter 48 of 48 · Python with AI: all 48 chapters

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com