Comprehensive Python Cheat Sheet

Python Basics

Math Operators

Operator Operation Example
** Exponent 2 ** 3 = 8
% Modulus (remainder) 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3 * 3 = 9
- Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4
# Examples
2 + 3 * 6       # 20
(2 + 3) * 6     # 30
2 ** 8          # 256
23 // 7         # 3
23 % 7          # 2
(5 - 1) * ((7 + 1) / (3 - 1))  # 16.0

Augmented Assignment Operators

Operator Equivalent
var += 1 var = var + 1
var -= 1 var = var - 1
var *= 1 var = var * 1
var /= 1 var = var / 1
var //= 1 var = var // 1
var %= 1 var = var % 1
var **= 1 var = var ** 1
# Examples
greeting = 'Hello'
greeting += ' world!'  # 'Hello world!'

number = 1
number += 1            # 2

my_list = ['item']
my_list *= 3           # ['item', 'item', 'item']

Walrus Operator (Python 3.8+)

# Assignment expressions
print(my_var := "Hello World!")  # Hello World!
my_var = "Yes"
print(my_var)                    # Yes
print(my_var := "Hello")         # Hello

Data Types

Data Type Examples
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

String Operations

# Concatenation
'Alice' 'Bob'     # 'AliceBob'

# Replication
'Alice' * 5       # 'AliceAliceAliceAliceAlice'

Variables & Naming Rules

# Valid
var = 'Hello'
my_var = 'Hello'
my_var_2 = 'Hello'
_underscore = 'hidden'  # valid but discouraged

# Invalid
# 3var = 'no'     # starts with a number
# my variable = 'no spaces allowed'

Comments

# This is a single line comment

# This is a
# multiline comment

a = 1  # inline comment

Function Docstring

def foo():
    """
    This is a function docstring.
    Describe your function here.
    """

print() Function

print('Hello world!')          # Hello world!
print('Hello world!', 1)       # Hello world! 1

# end keyword (suppress newline/change end char)
for word in ['printed', 'with', 'dashes']:
    print(word, end='-')
# Output: printed-with-dashes-

# sep keyword (separator between items)
print('cats', 'dogs', 'mice', sep=',')  # cats,dogs,mice

input() Function

my_name = input('What is your name? ')
print(f'Hi, {my_name}')

len() Function

len('hello')           # 5
len(['cat', 3, 'dog']) # 3

# Testing emptiness (preferred over len check)
a = [1, 2, 3]
if a:  # True if list is not empty
    print("List is not empty!")

Type Conversion

# To string
str(29)        # '29'

# To int
int('11')      # 11

# To float
float('3.14')  # 3.14

Control Flow

If, Elif, Else

if condition:
    # do something
elif another_condition:
    # do something else
else:
    # fallback code

For Loop

for item in iterable:
    # do something with item

for i in range(5):
    print(i)  # 0 1 2 3 4

While Loop

while condition:
    # loop body
    # remember to update condition or break

Loop Controls

break     # exit the loop immediately
continue  # skip rest of current loop iteration and continue

Functions and Lambdas

Function Definition

def function_name(parameters):
    """
    Describe function behavior here.
    """
    # function body
    return value  # optional

Example

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!

Lambda Functions (Anonymous Functions)

square = lambda x: x ** 2
print(square(5))  # 25

# In function calls
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))

Data Structures

Lists (mutable, ordered)

my_list = [1, 2, 3, 'a', 'b']
my_list.append(4)
my_list[0] = 100
print(my_list)  # [100, 2, 3, 'a', 'b', 4]

Tuples (immutable, ordered)

my_tuple = (1, 2, 3)
print(my_tuple[1])  # 2
# my_tuple[1] = 5  # error: tuples are immutable

Sets (unordered, unique)

my_set = {1, 2, 3, 3}
my_set.add(4)
print(my_set)  # {1, 2, 3, 4}

Dictionaries (key-value pairs)

my_dict = {'name': 'Alice', 'age': 30}
print(my_dict['name'])  # Alice
my_dict['age'] = 31

Exceptions & Error Handling

try:
    # code that might raise exception
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Error: {e}")
else:
    print("No errors!")
finally:
    print("Always runs!")

Modules & Imports

# Import whole module
import math
print(math.sqrt(16))  # 4.0

# Import specific functions or variables
from math import sqrt, pi
print(sqrt(25))  # 5.0

# Import with alias
import numpy as np
print(np.array([1, 2, 3]))

Classes & Object-Oriented Programming

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound."

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

d = Dog("Buddy")
print(d.speak())  # Buddy says Woof!

File Handling

# Writing to a file
with open('file.txt', 'w') as f:
    f.write("Hello, file!\n")

# Reading from a file
with open('file.txt', 'r') as f:
    content = f.read()
    print(content)

Common Built-in Functions

Advanced Data Types and Collections

Namedtuples

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p.x, p.y)  # 11 22

Dataclasses (Python 3.7+)

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

p = Person('Alice', 30)
print(p.name, p.age)

Collections Module

from collections import Counter, defaultdict, deque

# Counter - count hashable objects
counts = Counter(['a', 'b', 'a', 'c', 'b', 'a'])
print(counts)  # Counter({'a': 3, 'b': 2, 'c': 1})

# defaultdict - default value for missing keys
d = defaultdict(int)
d['a'] += 1
print(d['a'])  # 1

# deque - double-ended queue (fast pops and appends)
q = deque([1, 2, 3])
q.appendleft(0)
print(q)  # deque([0, 1, 2, 3])

Decorators and Generators

Function Decorators

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

Generators and Yield

def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

for number in count_up_to(5):
    print(number)

Generator Expressions

squares = (x**2 for x in range(5))
print(next(squares))  # 0
print(list(squares))  # [1, 4, 9, 16]

Concurrency and Parallelism

Threading Basics

import threading

def worker():
    print("Worker thread")

t = threading.Thread(target=worker)
t.start()
t.join()

Multiprocessing Basics

from multiprocessing import Process

def worker():
    print("Process running")

p = Process(target=worker)
p.start()
p.join()

AsyncIO Basics

import asyncio

async def say_hello():
    await asyncio.sleep(1)
    print("Hello after 1 second")

async def main():
    await asyncio.gather(say_hello(), say_hello())

asyncio.run(main())

Regular Expressions

import re

pattern = r'\b\w{3}\b'  # words with exactly 3 chars
text = "The cat and dog ran."
matches = re.findall(pattern, text)
print(matches)  # ['The', 'cat', 'and', 'dog', 'ran']

# Common functions:
#   re.match() - check beginning of string
#   re.search() - search anywhere
#   re.findall() - all matches
#   re.sub() - substitution

Context Managers and the with Statement

# Using built-in context manager for file handling
with open('file.txt', 'r') as f:
    content = f.read()

# Custom context manager example
class ManagedResource:
    def __enter__(self):
        print("Resource acquired")
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        print("Resource released")

with ManagedResource() as r:
    print("Using the resource")

contextlib utilities

from contextlib import contextmanager

@contextmanager
def simple_manager():
    print("Acquire")
    yield
    print("Release")

with simple_manager():
    print("Inside the context")

Typing and Annotations

from typing import List, Optional, Union

def greet(name: str) -> str:
    return f"Hello, {name}"

def process_items(items: List[int]) -> int:
    return sum(items)

def foo(bar: Optional[str] = None) -> Union[str, None]:
    if bar:
        return bar.upper()
    return None

Python Standard Library Highlights

os and sys

import os, sys

print(os.getcwd())        # current working directory
print(sys.platform)       # platform info
print(os.listdir('.'))    # list files in cwd

datetime and time

import datetime, time

now = datetime.datetime.now()
print(now.isoformat())

time.sleep(1)  # sleep for 1 second

json and csv

import json, csv

data = {'name': 'Alice', 'age': 30}
json_str = json.dumps(data)
print(json_str)

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

Testing

unittest example

import unittest

def add(a, b):
    return a + b

class TestAdd(unittest.TestCase):
    def test_positive(self):
        self.assertEqual(add(1, 2), 3)

    def test_negative(self):
        self.assertEqual(add(-1, -1), -2)

if __name__ == '__main__':
    unittest.main()

Assertions

assert 2 + 2 == 4, "Math is broken!"

Package Management and Virtual Environments

# Install a package
pip install package_name

# List installed packages
pip list

# Create virtual environment (Python 3.3+)
python -m venv env_name

# Activate virtual environment
# Windows:
env_name\Scripts\activate
# macOS/Linux:
source env_name/bin/activate

# Deactivate virtual environment
deactivate

PyInstaller Cheat Sheet

Basic Usage

# Generate a single executable from a Python script
pyinstaller --onefile your_script.py

Common Options

--onefile            # Bundle everything into a single executable
--noconsole          # Do not open a console window (GUI apps)
--name NAME          # Specify the name of the executable
--icon ICON.ico      # Add an icon to the executable
--add-data "SRC;DEST" # Include additional files or folders
--clean              # Clean PyInstaller cache and remove temporary files

Example Command

pyinstaller --onefile --noconsole --name MyApp --icon myicon.ico my_script.py

Output

# Executable and related files are created in the `dist` directory
# Build files and cache are in the `build` directory

Common Idioms and Best Practices

List Comprehensions

squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)

Dictionary Comprehensions

square_map = {x: x**2 for x in range(5)}
print(square_map)

Using enumerate and zip

for i, val in enumerate(['a', 'b', 'c']):
    print(i, val)

for a, b in zip([1,2,3], ['x','y','z']):
    print(a, b)

Pythonic EAFP (Easier to Ask Forgiveness than Permission)

try:
    value = my_dict['key']
except KeyError:
    value = 0

Error Types and Exception Hierarchy

# Common Exceptions:
#   Exception (base class)
#   ArithmeticError
#   ZeroDivisionError
#   IndexError
#   KeyError
#   ValueError
#   TypeError
#   ImportError
#   FileNotFoundError
#   IOError
#   RuntimeError

try:
    1 / 0
except ZeroDivisionError as e:
    print(f"Caught error: {e}")

Working with JSON and XML

JSON

import json

data = {'name': 'Bob', 'age': 25}
json_str = json.dumps(data)
print(json_str)

data_parsed = json.loads(json_str)
print(data_parsed['name'])

XML (using xml.etree.ElementTree)

import xml.etree.ElementTree as ET

xml_data = '''Alice30'''
root = ET.fromstring(xml_data)
print(root.find('name').text)  # Alice

Logging

import logging

logging.basicConfig(level=logging.INFO)
logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")

Command Line Argument Parsing

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Flask Cheat Sheet

Basic Flask App

from flask import Flask, request, render_template, redirect, url_for

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run(debug=True)

Routing and URL Parameters

@app.route('/user/<username>')
def show_user(username):
    return f'User: {username}'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Post {post_id}'

Request Methods and Forms

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        return f'Welcome, {username}!'
    return '''
        <form method="post">
            <input type="text" name="username">
            <input type="submit">
        </form>
    '''

Redirects and URL building

from flask import redirect, url_for

@app.route('/admin')
def admin():
    return redirect(url_for('home'))

Templates

# Use render_template to load HTML files from a `templates` folder
# Example:
return render_template('index.html', name='Alice')

Static files

# Place CSS, JS, images in `static` folder
# In templates: <link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet">

Requests Cheat Sheet

Basic GET Request

import requests

response = requests.get('https://api.github.com')
print(response.status_code)
print(response.text)

GET with Parameters

payload = {'q': 'python'}
response = requests.get('https://www.google.com/search', params=payload)
print(response.url)

POST Request

data = {'username': 'user', 'password': 'pass'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.json())

Headers and Cookies

headers = {'User-Agent': 'my-app/0.0.1'}
cookies = {'session_id': '123456'}

response = requests.get('https://example.com', headers=headers, cookies=cookies)

JSON Data

response = requests.get('https://api.github.com/users/octocat')
data = response.json()
print(data['login'])

Timeouts and Errors

try:
    response = requests.get('https://example.com', timeout=5)
    response.raise_for_status()
except requests.exceptions.Timeout:
    print("Timeout")
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e}")

BeautifulSoup Cheat Sheet

Parsing HTML

from bs4 import BeautifulSoup

html_doc = "<html><head><title>Test</title></head><body><p>Hello</p></body></html>"
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.title.string)  # Test

Finding Elements

soup.find('p')           # Finds first <p> tag
soup.find_all('a')       # Finds all <a> tags
soup.find(id='main')     # Find by id
soup.find(class_='btn')  # Find by class

Getting Attributes and Text

tag = soup.find('a')
link = tag['href']            # Get href attribute
text = tag.get_text()         # Get inner text

Navigating the Tree

soup.body.contents          # List of children
soup.body.children           # Iterator for children
soup.parent                  # Parent of a tag
soup.next_sibling            # Next sibling tag

Selenium Cheat Sheet

Setup and Basic Usage

from selenium import webdriver

driver = webdriver.Chrome()  # or Firefox(), Edge(), etc.
driver.get('https://www.google.com')

Finding Elements

element = driver.find_element('id', 'search')
elements = driver.find_elements('class name', 'item')

Interacting with Elements

element.send_keys('Selenium WebDriver')
element.click()

Waiting for Elements

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, 'result')))

Closing the Browser

driver.quit()    # Close all windows and stop the WebDriver
driver.close()   # Close current window

Jupyter Notebook Cheat Sheet

Running Cells

Cell Types

Magic Commands

# Line magics start with %
%timeit sum(range(1000))
%matplotlib inline

# Cell magics start with %%
%%writefile example.py
print("Hello world")

Useful Shortcuts

SQLAlchemy Cheat Sheet

Setup

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///example.db')
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

Define Models

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

Base.metadata.create_all(engine)

Create and Add Objects

new_user = User(name='Alice', age=30)
session.add(new_user)
session.commit()

Querying

# Get all users
users = session.query(User).all()

# Filtered query
young_users = session.query(User).filter(User.age < 25).all()

# Get one
user = session.query(User).filter_by(name='Alice').first()

Update and Delete

user = session.query(User).filter_by(name='Alice').first()
user.age = 31
session.commit()

session.delete(user)
session.commit()