Python Cheat Sheet: Syntax, Collections, Functions, and Files
Introduction
Use this Python 3 cheat sheet when you need the syntax fast. Each section is a compact reference you can copy and adapt. For explanations and exercises, follow the Python lessons on this site.
Prerequisites
- Python 3.10 or newer installed
Step-by-Step Guide
Step 1: Variables, types, and operators
Python is dynamically typed. Use type() to inspect a value and convert with int(), float(), str(), and bool().
name = "Ada" # str
age = 36 # int
price = 9.99 # float
ok = True # bool
nothing = None # NoneType
x, y = 3, 4 # multiple assignment
x, y = y, x # swap
10 // 3 # 3 floor division
10 % 3 # 1 remainder
2 ** 10 # 1024 power
a == b # equal a is b # same object
and or not # logical operatorsStep 2: Strings
Strings are immutable. Use f-strings for formatting, and slicing for substrings.
s = "Hello, World"
f"{name} is {age} years old" # f-string
f"{price:.2f}" # 2 decimals -> 9.99
s.lower(); s.upper(); s.strip()
s.split(", ") # ['Hello', 'World']
"-".join(["a", "b", "c"]) # 'a-b-c'
s.replace("World", "Python")
s.startswith("He"); "World" in s
s[0]; s[-1]; s[0:5]; s[::-1] # index, last, slice, reverse
len(s)Step 3: Lists, tuples, sets, and dictionaries
Lists are ordered and mutable, tuples are ordered and immutable, sets hold unique values, and dicts map keys to values.
nums = [3, 1, 2]
nums.append(4); nums.extend([5, 6]); nums.insert(0, 9)
nums.remove(9); nums.pop(); nums.sort(); nums.reverse()
sorted(nums, reverse=True) # new list
point = (1, 2) # tuple
tags = {"a", "b"} # set
tags.add("c"); tags & {"a"} # union |, intersection &, difference -
user = {"name": "Ada", "age": 36}
user["email"] = "ada@example.com"
user.get("phone", "n/a") # safe lookup with default
for key, value in user.items():
print(key, value)
user.pop("age"); "name" in userStep 4: Control flow and comprehensions
Indentation defines blocks. Comprehensions build lists, sets, and dicts in one line.
if age >= 18:
print("adult")
elif age >= 13:
print("teen")
else:
print("child")
for i in range(3): # 0, 1, 2
print(i)
for i, item in enumerate(nums):
print(i, item)
while age < 40:
age += 1
squares = [n * n for n in range(10) if n % 2 == 0]
lookup = {n: n * n for n in range(5)}
unique = {n % 3 for n in range(10)}
match command: # Python 3.10+
case "start": ...
case "stop": ...
case _: ...Step 5: Functions and classes
Use type hints for readability. Dataclasses remove boilerplate for classes that mostly hold data.
def greet(name: str, punctuation: str = "!") -> str:
return f"Hello, {name}{punctuation}"
def total(*numbers, **options): # variable arguments
return sum(numbers)
square = lambda n: n * n
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int = 0
def is_adult(self) -> bool:
return self.age >= 18
u = User("Ada", 36)
print(u.is_adult())Step 6: Files, JSON, and errors
Use with so files close automatically, pathlib for paths, and try/except for errors.
from pathlib import Path
import json
text = Path("notes.txt").read_text(encoding="utf-8")
Path("out.txt").write_text("hello", encoding="utf-8")
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
with open("out.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
try:
value = int("abc")
except ValueError as error:
print("bad number:", error)
else:
print("ok")
finally:
print("always runs")
raise ValueError("something went wrong")Step 7: Environments and packages
Create a virtual environment for every project so dependencies stay separate.
python -m venv .venv
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
pip install requests
pip freeze > requirements.txt
pip install -r requirements.txt
python -m pytest # run tests
python script.pyFAQs
- Which Python version should I learn?
- Use a current supported Python 3 release. This sheet works on 3.10 or newer, and match statements need 3.10.
Summary
Keep this sheet open while you code: f-strings, slicing, list and dict methods, comprehensions, dataclasses, pathlib, try/except, and virtual environments cover most everyday Python.
Related tutorials
- Linux Command Line Cheat Sheet: Files, Permissions, Processes, and Networking
- Docker and kubectl Cheat Sheet: Containers, Images, Compose, and Kubernetes
- SQL Cheat Sheet: SELECT, Joins, Aggregates, and Data Changes
- Git Cheat Sheet: Everyday Commands, Branching, and Undoing Mistakes
- Langflow Cheat Sheet: Install, Components, API Calls, and Custom Components
Comments
Log in or create a free account to join the discussion.