Quick Answer: Variables:
x = 10. Strings:f"Hello {name}". Lists:[1, 2, 3]. Dicts:{"key": "value"}. Loop:for item in list:. Function:def greet(name): return f"Hi {name}". File:with open("file.txt") as f: data = f.read().
Basics
# Variables (no type declaration needed)
name = "Sam"
age = 25
price = 19.99
is_active = True
# Print
print("Hello World")
print(f"Name: {name}, Age: {age}") # f-string (Python 3.6+)
# Input
user_input = input("Enter your name: ")
# Comments
# Single line comment
"""
Not a true comment -- this is a string literal.
When first in a module/class/function, it becomes a docstring.
"""
# Type checking
type(name) # <class 'str'>
isinstance(name, str) # True
Data Types
| Type | Example | Mutable |
|---|---|---|
int |
42 |
No |
float |
3.14 |
No |
str |
"hello" |
No |
bool |
True, False |
No |
list |
[1, 2, 3] |
Yes |
tuple |
(1, 2, 3) |
No |
dict |
{"a": 1} |
Yes |
set |
{1, 2, 3} |
Yes |
None |
None |
No |
# Type conversion
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
list("abc") # ['a', 'b', 'c']
bool(0) # False
bool(1) # True
Strings
s = "Hello World"
# Access
s[0] # 'H'
s[-1] # 'd'
s[0:5] # 'Hello'
s[6:] # 'World'
# Methods
s.lower() # 'hello world'
s.upper() # 'HELLO WORLD'
s.strip() # Remove whitespace from both ends
s.lstrip() # Remove from left
s.rstrip() # Remove from right
s.split() # ['Hello', 'World']
s.split(",") # Split by comma
s.replace("World", "Python") # 'Hello Python'
s.startswith("Hello") # True
s.endswith("World") # True
s.find("World") # 6 (index, -1 if not found)
s.count("l") # 3
s.isdigit() # False
s.isalpha() # False (has space)
s.title() # 'Hello World'
# Join
", ".join(["a", "b", "c"]) # 'a, b, c'
# F-strings (formatting)
name = "Sam"
age = 25
f"Name: {name}, Age: {age}"
f"Price: {19.99:.2f}" # 'Price: 19.99'
f"{'hello':>10}" # ' hello' (right-align)
f"{'hello':<10}" # 'hello ' (left-align)
f"{'hello':^10}" # ' hello ' (center)
f"{1000000:,}" # '1,000,000'
# Multi-line strings
text = """Line 1
Line 2
Line 3"""
# Raw strings (ignore escape sequences)
path = r"C:\Users\Sam\file.txt"
Lists
lst = [1, 2, 3, 4, 5]
# Access
lst[0] # 1
lst[-1] # 5
lst[1:3] # [2, 3]
# Modify
lst.append(6) # [1, 2, 3, 4, 5, 6]
lst.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6]
lst.extend([7, 8]) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
lst.remove(0) # Remove first occurrence of 0
lst.pop() # Remove and return last item
lst.pop(0) # Remove and return item at index 0
# Search
3 in lst # True
lst.index(3) # Index of first occurrence
lst.count(3) # Count occurrences
# Sort
lst.sort() # Sort in place
lst.sort(reverse=True) # Sort descending
sorted(lst) # Return new sorted list (doesn't modify original)
# Other
lst.reverse() # Reverse in place
lst.copy() # Shallow copy
len(lst) # Length
min(lst) # Minimum
max(lst) # Maximum
sum(lst) # Sum
# List comprehension
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, ...]
evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, ...]
Dictionaries
d = {"name": "Sam", "age": 25, "city": "LA"}
# Access
d["name"] # 'Sam'
d.get("name") # 'Sam'
d.get("phone", "N/A") # 'N/A' (default if key missing)
# Modify
d["email"] = "[email protected]" # Add/update
del d["city"] # Delete key
d.pop("age") # Remove and return value
# Methods
d.keys() # dict_keys(['name', 'email'])
d.values() # dict_values(['Sam', '[email protected]'])
d.items() # dict_items([('name', 'Sam'), ...])
d.update({"age": 26}) # Merge another dict
# Check
"name" in d # True
# Loop
for key, value in d.items():
print(f"{key}: {value}")
# Dict comprehension
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Tuples and Sets
# Tuples (immutable lists)
t = (1, 2, 3)
t[0] # 1
x, y, z = t # Unpacking: x=1, y=2, z=3
# Sets (unique values, unordered)
s = {1, 2, 3, 3, 3} # {1, 2, 3}
s.add(4)
s.remove(1)
s.discard(99) # Remove if exists (no error if missing)
# Set operations
a = {1, 2, 3}
b = {2, 3, 4}
a | b # Union: {1, 2, 3, 4}
a & b # Intersection: {2, 3}
a - b # Difference: {1}
a ^ b # Symmetric difference: {1, 4}
Control Flow
# If/elif/else
if x > 10:
print("big")
elif x > 5:
print("medium")
else:
print("small")
# Ternary
result = "even" if x % 2 == 0 else "odd"
# Match (Python 3.10+)
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Unknown")
Loops
# For loop
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
for item in ["a", "b", "c"]:
print(item)
for i, item in enumerate(["a", "b", "c"]):
print(f"{i}: {item}") # 0: a, 1: b, 2: c
for key, val in {"a": 1, "b": 2}.items():
print(f"{key}={val}")
# While loop
while x > 0:
x -= 1
# Break and continue
for i in range(10):
if i == 5:
break # Stop the loop
if i % 2 == 0:
continue # Skip to next iteration
print(i) # 1, 3
# Zip (loop over multiple lists)
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age}")
Functions
# Basic function
def greet(name):
return f"Hello, {name}!"
# Default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# *args (variable positional arguments)
def add(*args):
return sum(args)
add(1, 2, 3) # 6
# **kwargs (variable keyword arguments)
def info(**kwargs):
for key, val in kwargs.items():
print(f"{key}: {val}")
info(name="Sam", age=25)
# Lambda (anonymous function)
square = lambda x: x**2
square(5) # 25
# Map, filter, reduce
list(map(lambda x: x**2, [1, 2, 3])) # [1, 4, 9]
list(filter(lambda x: x > 2, [1, 2, 3])) # [3]
from functools import reduce
reduce(lambda a, b: a + b, [1, 2, 3]) # 6
# Type hints (optional, for documentation)
def greet(name: str, age: int) -> str:
return f"{name} is {age}"
Classes
class Person:
# Class variable
species = "Human"
# Constructor
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age
# Method
def greet(self):
return f"Hi, I'm {self.name}"
# String representation
def __repr__(self):
return f"Person('{self.name}', {self.age})"
# Create instance
p = Person("Sam", 25)
p.greet() # "Hi, I'm Sam"
p.name # "Sam"
# Inheritance
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def study(self):
return f"{self.name} is studying"
File I/O
# Read entire file
with open("file.txt") as f:
content = f.read()
# Read line by line
with open("file.txt") as f:
for line in f:
print(line.strip())
# Read all lines into list
with open("file.txt") as f:
lines = f.readlines()
# Write to file (overwrites)
with open("file.txt", "w") as f:
f.write("Hello\n")
# Append to file
with open("file.txt", "a") as f:
f.write("More text\n")
# Read/write JSON
import json
with open("data.json") as f:
data = json.load(f)
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read/write CSV
import csv
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"])
Error Handling
# Try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except (TypeError, ValueError) as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("No errors occurred")
finally:
print("Always runs")
# Raise exceptions
if age < 0:
raise ValueError("Age cannot be negative")
# Custom exception
class MyError(Exception):
pass
Common Modules
# OS and paths
import os
os.getcwd() # Current directory
os.listdir(".") # List directory
os.path.exists("file.txt") # Check if exists
os.path.join("dir", "file") # Join paths
os.makedirs("a/b/c", exist_ok=True)
os.environ.get("HOME") # Environment variable
# pathlib (modern alternative)
from pathlib import Path
p = Path("dir/file.txt")
p.exists()
p.read_text()
p.write_text("content")
list(Path(".").glob("*.py")) # Find Python files
# Datetime
from datetime import datetime, timedelta
now = datetime.now()
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2026-04-07", "%Y-%m-%d")
tomorrow = now + timedelta(days=1)
# Regular expressions
import re
re.search(r"\d+", "abc123") # Match object
re.findall(r"\d+", "a1b2c3") # ['1', '2', '3']
re.sub(r"\d+", "X", "a1b2c3") # 'aXbXcX'
# HTTP requests (install: pip install requests)
import requests
r = requests.get("https://api.example.com/data")
r.status_code # 200
r.json() # Parse JSON response
# Subprocess
import subprocess
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)
# System
import sys
sys.argv # Command-line arguments
sys.exit(1) # Exit with code
Virtual Environments
# Create virtual environment
python3 -m venv myenv
# Activate
source myenv/bin/activate # Linux/macOS
myenv\Scripts\activate # Windows
# Install packages
pip install requests flask
# Save dependencies
pip freeze > requirements.txt
# Install from requirements
pip install -r requirements.txt
# Deactivate
deactivate
One-Liners
# Swap variables
a, b = b, a
# Flatten nested list
flat = [x for sub in nested for x in sub]
# Remove duplicates (preserving order)
list(dict.fromkeys(lst))
# Reverse a string
s[::-1]
# Check if palindrome
s == s[::-1]
# Merge dictionaries (Python 3.9+)
merged = d1 | d2
# Find most common element
max(set(lst), key=lst.count)
# Read file into list of lines
lines = open("file.txt").read().splitlines()
# Simple HTTP server
# python3 -m http.server 8000
Related Guides
- Bash Cheat Sheet — shell scripting
- Git Cheat Sheet — version control
- Regex Cheat Sheet — pattern matching
- JSON Guide — working with JSON data
- Docker Cheat Sheet — containerize Python apps