Python Cheat Sheet

Last Updated: November 21, 2025

Variables & Data Types

# Variables (dynamically typed)
name = "Alice"
age = 30
height = 5.7
is_student = True

# Type checking
type(name)  # <class 'str'>

# Type conversion
int("123")    # 123
str(123)      # "123"
float("3.14") # 3.14

Strings

s.upper()
Convert to uppercase
s.lower()
Convert to lowercase
s.strip()
Remove leading/trailing whitespace
s.split(delimiter)
Split string into list
s.replace(old, new)
Replace substring
f"Hello {name}"
F-string formatting (Python 3.6+)

Lists

# Create list
fruits = ["apple", "banana", "cherry"]

# Access elements
fruits[0]        # "apple"
fruits[-1]       # "cherry" (last item)
fruits[1:3]      # ["banana", "cherry"] (slicing)

# Modify list
fruits.append("orange")       # Add to end
fruits.insert(1, "mango")     # Insert at index
fruits.remove("banana")       # Remove by value
fruits.pop()                  # Remove and return last
fruits.pop(0)                 # Remove and return at index

# List operations
len(fruits)                   # Get length
"apple" in fruits             # Check membership
fruits.sort()                 # Sort in place
sorted(fruits)                # Return sorted copy

# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]

Dictionaries

# Create dictionary
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Access values
person["name"]           # "Alice"
person.get("name")       # "Alice"
person.get("job", "N/A") # "N/A" (default if key missing)

# Modify dictionary
person["age"] = 31       # Update value
person["job"] = "Engineer" # Add new key-value

# Dictionary methods
person.keys()            # Get all keys
person.values()          # Get all values
person.items()           # Get (key, value) pairs

# Dictionary comprehension
{x: x**2 for x in range(5)}

Control Flow

# If-elif-else
if age < 18:
    print("Minor")
elif age < 65:
    print("Adult")
else:
    print("Senior")

# For loop
for fruit in fruits:
    print(fruit)

for i in range(5):      # 0 to 4
    print(i)

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

Functions

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

# Default parameters
def greet(name="World"):
    return f"Hello, {name}!"

# Multiple return values
def get_coordinates():
    return 10, 20

x, y = get_coordinates()

# *args and **kwargs
def sum_all(*args):
    return sum(args)

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Lambda functions
square = lambda x: x**2
add = lambda x, y: x + y

File Operations

# Read file
with open("file.txt", "r") as f:
    content = f.read()

# Read line by line
with open("file.txt", "r") as f:
    for line in f:
        print(line.strip())

# Write file
with open("file.txt", "w") as f:
    f.write("Hello, World!")

# Append to file
with open("file.txt", "a") as f:
    f.write("New line")

Common Libraries

Library Purpose Import
os Operating system operations import os
sys System-specific parameters import sys
json JSON encoding/decoding import json
datetime Date and time operations import datetime
requests HTTP requests import requests
pandas Data analysis import pandas as pd
numpy Numerical computing import numpy as np

Exception Handling

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Error: {e}")
else:
    print("No errors occurred")
finally:
    print("This always executes")
💡 Pro Tip: Use list comprehensions instead of loops when possible for cleaner, more Pythonic code.
← Back to Programming Languages | Browse all categories | View all cheat sheets