Python Cheat Sheet
Python is a popular programming language used for automation, scripting, backend web development, data analysis, and cybersecurity tooling. If you’re searching for a Python cheatsheet, Python syntax, or Python examples, this page is a fast reference for Python basics, lists, dictionaries, functions, comprehensions, file handling, error handling, typing, and asyncio—organized for quick scanning and copy‑paste use.
Quick Start
python --version
python -m venv .venv
# Linux/macOS
source .venv/bin/activate
# Windows PowerShell
.\.venv\Scripts\Activate.ps1
python app.py
python
>>> 2 + 2
4
>>> import this
python -c "import sys; print(sys.version)"
Python Basics
Variables & Naming
name = "Faruk"
count = 3
pi = 3.14159
is_ready = True
nothing = None
Numbers
a = 10
b = 3
a + b # 13
a - b # 7
a * b # 30
a / b # 3.333...
a // b # 3
a % b # 1
a ** b # 1000
Strings
s = "python"
s.upper() # "PYTHON"
s.title() # "Python"
s.replace("py", "Py")
s.startswith("py") # True
s.endswith("on") # True
len(s) # 6
f-strings (best default)
user = "Faruk"
n = 5
print(f"Hello {user}, you have {n} messages.")
print(f"{3.14159:.2f}") # 3.14
print(f"{42:08d}") # 00000042
Input / Output
name = input("Name: ")
print("Hi", name)
print("Hi " + name)
Data Types & Collections
Lists
nums = [1, 2, 3]
nums.append(4)
nums.extend([5, 6])
nums.insert(0, 0)
nums.pop() # removes last
nums[0] # 0
nums[-1] # last element
nums[1:4] # slicing
Tuples
point = (10, 20)
x, y = point
Sets
s = {1, 2, 3}
s.add(3) # no change
s.add(4)
2 in s # True
s | {5, 6} # union
s & {2, 4, 9} # intersection
s - {1, 4} # difference
Dictionaries
user = {"name": "Faruk", "role": "dev"}
user["name"] # "Faruk"
user.get("missing", "?") # "?"
user["active"] = True
for k, v in user.items():
print(k, v)
Dict trick: default values
counts = {}
for item in ["a", "b", "a"]:
counts[item] = counts.get(item, 0) + 1
# {'a': 2, 'b': 1}
Control Flow
if / elif / else
x = 10
if x > 10:
print("big")
elif x == 10:
print("ten")
else:
print("small")
for loops
for i in range(3):
print(i)
items = ["a", "b", "c"]
for idx, val in enumerate(items, start=1):
print(idx, val)
while loops
n = 3
while n > 0:
n -= 1
match / case (Python 3.10+)
status = 404
match status:
case 200:
msg = "OK"
case 404:
msg = "Not Found"
case _:
msg = "Other"
Functions
Define & Call
def add(a, b=0):
return a + b
add(2, 3) # 5
add(2) # 2
args and *kwargs
def log(*args, **kwargs):
print(args, kwargs)
log(1, 2, a=3, b=4)
Lambda
square = lambda x: x * x
square(5) # 25
Docstrings
def greet(name: str) -> str:
'''Return a friendly greeting.'''
return f"Hello, {name}"
Trick: unpacking as an API
from urllib.parse import urlencode
def build_url(base: str, **query) -> str:
return base + "?" + urlencode(query)
build_url("https://example.com", q="python", page=2)
Comprehensions
List Comprehension
squares = [x * x for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Dict & Set Comprehension
m = {x: x * x for x in range(5)}
unique_lengths = {len(w) for w in ["hi", "python", "ok", "python"]}
Generator Expression
total = sum(x * x for x in range(1000))
Readability rule
If the comprehension needs multiple conditions or nested loops, use a normal loop.
String Formatting & Text Processing
split / join
"one,two,three".split(",")
" ".join(["hello", "world"])
strip
" hi \n".strip()
Regex patterns (re)
import re
re.search(r"\d+", "id=123")
re.findall(r"[a-z]+", "a1b2c3")
re.sub(r"\s+", " ", "a b\nc")
Files & Paths
Read / Write (text)
from pathlib import Path
p = Path("notes.txt")
p.write_text("Hello\n", encoding="utf-8")
text = p.read_text(encoding="utf-8")
Directory scanning
from pathlib import Path
root = Path(".")
for path in root.rglob("*.py"):
print(path)
Trick: atomic file write
from pathlib import Path
import os
import tempfile
def atomic_write(path: Path, data: str) -> None:
path = Path(path)
with tempfile.NamedTemporaryFile(
"w",
delete=False,
dir=path.parent,
encoding="utf-8",
) as tmp:
tmp.write(data)
tmp_path = Path(tmp.name)
os.replace(tmp_path, path) # atomic on most OS/filesystems
atomic_write(Path("safe.txt"), "content\n")
Exceptions & Error Handling
try / except / else / finally
try:
x = int("10")
except ValueError as e:
print("bad input:", e)
else:
print("ok:", x)
finally:
print("done")
Custom exceptions
class AppError(Exception):
pass
raise AppError("Something went wrong")
Standard Library Essentials
collections
from collections import Counter, defaultdict, deque
Counter("banana")
dd = defaultdict(list)
dd["x"].append(1)
q = deque([1, 2, 3])
q.appendleft(0)
q.pop()
itertools
import itertools as it
list(it.chain([1, 2], [3, 4]))
list(it.islice(range(100), 5))
Type Hints (Typing)
from typing import Iterable, Optional, TypedDict
def mean(values: Iterable[float]) -> float:
values = list(values)
return sum(values) / len(values)
name: Optional[str] = None
class UserRow(TypedDict):
id: int
name: str
Asyncio (Async/Await)
import asyncio
async def fetch():
await asyncio.sleep(0.1)
return "ok"
async def main():
result = await fetch()
print(result)
asyncio.run(main())
Async trick: gather for concurrency
import asyncio
async def job(i: int) -> int:
await asyncio.sleep(0.1)
return i
async def main():
results = await asyncio.gather(*(job(i) for i in range(5)))
print(results)
asyncio.run(main())
Common Tricks (with examples)
Swap variables
a, b = 1, 2
a, b = b, a
Unpack and ignore values
a, _, c = (1, 2, 3)
Flatten a list (one level)
items = [[1, 2], [3, 4]]
flat = [x for row in items for x in row]
Dict merge (3.9+)
a = {"x": 1}
b = {"y": 2}
c = a | b
Safe dictionary access
user = {"name": "Faruk"}
user.get("role", "guest")