Python Cheatsheet — Complete Quick Reference
Python Cheatsheet — Complete Quick Reference
DodaTech
3 min read
Python syntax, built-in data structures, control flow, functions, classes, file I/O, and common patterns — condensed into one dense reference for everyday use.
Variables & Data Types
x = 10 # int (dynamic typing)
y = 3.14 # float
name = "Python" # str
is_ok = True # bool| Type | Example | Mutable |
|---|---|---|
int | 42 | — |
float | 3.14 | — |
str | "hi" | No |
list | [1, 2] | Yes |
tuple | (1, 2) | No |
dict | {"a": 1} | Yes |
set | {1, 2} | Yes |
Strings
s = f"Hello {name}" # f-string (3.6+)
s.upper(); s.lower(); s.strip()
s.split(","); ",".join(["a","b"])
s.startswith("H"); s.find("P")Lists
nums = [1, 2, 3]
nums.append(4); nums.pop(); nums.sort()
nums[0]; nums[-1]; nums[1:3] # slice
[x*2 for x in nums] # list comprehensionDicts
d = {"a": 1, "b": 2}
d.get("c", 0); d.keys(); d.values(); d.items()
for k, v in d.items(): ...Tuples & Sets
t = (1, 2) # immutable
s = {1, 2, 2, 3} # {1, 2, 3} — duplicates removed
s.add(4); s.remove(1); s & {2, 3}; s | {4, 5}Control Flow
if x > 0: ...
elif x == 0: ...
else: ...
for i in range(5): ...
while x > 0: ...
# match-case (3.10+)
match status:
case 200: ...
case _: ...Functions & Lambda
def add(a, b=0): return a + b
f = lambda x: x * 2
# *args, **kwargs
def log(*args, **kwargs): ...Classes
class Dog:
species = "Canine" # class var
def __init__(self, name): # constructor
self.name = name # instance var
def bark(self): return f"{self.name} says woof"File I/O
with open("file.txt", "r") as f:
content = f.read() # str
lines = f.readlines() # list[str]
# Modes: r, w, a, r+, rb, wbExceptions
try:
x = 1 / 0
except ZeroDivisionError:
print("can't divide by zero")
except Exception as e:
print(e)
finally:
cleanup()Imports
import math; math.sqrt(16)
from os import path; path.join("a","b")
from collections import defaultdict, CounterComprehensions
[x*2 for x in range(10) if x % 2 == 0] # list
{k: v*2 for k, v in d.items()} # dict
{x for x in nums if x > 0} # setSee the full Python tutorial series for deeper dives.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro