Py
Reference Guide

PythonCheatsheet

A curated reference for Python syntax and idioms. From variables to classes, list comprehensions to decorators. Designed for quick lookup and deeper understanding.

12 sections
Python 3.10+
01

Variables

Assignment and naming conventions

Basic Assignment

Python uses dynamic typing - no type declarations needed

1# Variables are created on assignment
2name = "Alice"
3age = 30
4price = 19.99
5is_active = True
6
7# Multiple assignment
8x, y, z = 1, 2, 3
9a = b = c = 0
10
11# Constants (by convention, uppercase)
12MAX_SIZE = 100
13PI = 3.14159
02

Data Types

Built-in types and type checking

Core Types

Python's fundamental data types

1# Numeric types
2integer = 42
3floating = 3.14
4complex_num = 3 + 4j
5
6# Text
7string = "Hello, World"
8
9# Boolean
10flag = True # or False
11
12# None (null equivalent)
13empty = None
14
15# Check type
16type(integer) # <class 'int'>
17isinstance(42, int) # True
03

Strings

Text manipulation and formatting

String Operations

Common string methods and f-strings

1text = "hello world"
2
3# Methods
4text.upper() # "HELLO WORLD"
5text.lower() # "hello world"
6text.title() # "Hello World"
7text.split() # ["hello", "world"]
8text.replace("o", "0") # "hell0 w0rld"
9text.strip() # Remove whitespace
10
11# f-strings (Python 3.6+)
12name = "Alice"
13age = 30
14f"Hello, {name}! You are {age}."
15
16# Slicing
17text[0:5] # "hello"
18text[-5:] # "world"
19text[::2] # "hlowrd"
04

Lists

Ordered, mutable sequences

List Operations

Creating and manipulating lists

1nums = [1, 2, 3, 4, 5]
2
3# Access and slice
4nums[0] # 1
5nums[-1] # 5
6nums[1:4] # [2, 3, 4]
7
8# Modify
9nums.append(6) # Add to end
10nums.insert(0, 0) # Insert at index
11nums.pop() # Remove last
12nums.remove(3) # Remove by value
13
14# Useful methods
15len(nums) # Length
16sum(nums) # Sum
17sorted(nums) # Sorted copy
18nums.reverse() # Reverse in place
19nums.index(2) # Find index
05

Dictionaries

Key-value mappings

Dictionary Operations

Creating and accessing dictionaries

1person = {
2 "name": "Alice",
3 "age": 30,
4 "city": "NYC"
5}
6
7# Access
8person["name"] # "Alice"
9person.get("age") # 30
10person.get("job", "N/A") # Default value
11
12# Modify
13person["email"] = "a@b.com"
14del person["city"]
15
16# Iterate
17person.keys() # dict_keys
18person.values() # dict_values
19person.items() # key-value pairs
20
21for key, value in person.items():
22 print(f"{key}: {value}")
06

Control Flow

Conditionals and loops

Conditionals & Loops

if/elif/else, for, while

1# Conditionals
2age = 18
3if age >= 21:
4 print("Adult")
5elif age >= 18:
6 print("Young adult")
7else:
8 print("Minor")
9
10# For loop
11for i in range(5):
12 print(i) # 0, 1, 2, 3, 4
13
14for item in ["a", "b", "c"]:
15 print(item)
16
17# While loop
18count = 0
19while count < 3:
20 print(count)
21 count += 1
22
23# Loop control
24# break - exit loop
25# continue - skip iteration
07

Functions

Defining and calling functions

Function Definitions

Parameters, return values, and lambdas

1# Basic function
2def greet(name):
3 return f"Hello, {name}!"
4
5# Default parameters
6def greet(name="World"):
7 return f"Hello, {name}!"
8
9# Multiple return values
10def get_stats(nums):
11 return min(nums), max(nums)
12
13low, high = get_stats([1, 2, 3])
14
15# *args and **kwargs
16def func(*args, **kwargs):
17 print(args) # Tuple
18 print(kwargs) # Dictionary
19
20# Lambda (anonymous function)
21square = lambda x: x ** 2
22square(5) # 25
08

Classes

Object-oriented programming

Class Definition

Classes, __init__, methods, inheritance

1class Person:
2 def __init__(self, name, age):
3 self.name = name
4 self.age = age
5
6 def greet(self):
7 return f"Hi, I'm {self.name}"
8
9 def __str__(self):
10 return f"Person({self.name})"
11
12# Create instance
13alice = Person("Alice", 30)
14alice.greet() # "Hi, I'm Alice"
15
16# Inheritance
17class Student(Person):
18 def __init__(self, name, age, grade):
19 super().__init__(name, age)
20 self.grade = grade
09

Comprehensions

Pythonic list/dict creation

Comprehension Syntax

Concise ways to create collections

1# List comprehension
2squares = [x**2 for x in range(10)]
3# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4
5# With condition
6evens = [x for x in range(10) if x % 2 == 0]
7# [0, 2, 4, 6, 8]
8
9# Dictionary comprehension
10squares_dict = {x: x**2 for x in range(5)}
11# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
12
13# Set comprehension
14unique = {x % 3 for x in range(10)}
15# {0, 1, 2}
16
17# Nested comprehension
18matrix = [[i*j for j in range(3)]
19 for i in range(3)]
10

File I/O

Reading and writing files

File Operations

Safe file handling with context managers

1# Reading a file
2with open("file.txt", "r") as f:
3 content = f.read() # Entire file
4 # or
5 lines = f.readlines() # List of lines
6
7# Writing to a file
8with open("file.txt", "w") as f:
9 f.write("Hello, World!")
10
11# Appending to a file
12with open("file.txt", "a") as f:
13 f.write("\nNew line")
14
15# Read line by line (memory efficient)
16with open("large.txt") as f:
17 for line in f:
18 process(line)
11

Exceptions

Error handling

Try/Except Blocks

Catching and handling errors

1try:
2 result = 10 / 0
3except ZeroDivisionError:
4 print("Cannot divide by zero")
5except Exception as e:
6 print(f"Error: {e}")
7else:
8 print("Success!") # Runs if no error
9finally:
10 print("Always runs")
11
12# Raising exceptions
13def validate(age):
14 if age < 0:
15 raise ValueError("Age cannot be negative")
16 return age
17
18# Common exceptions:
19# ValueError, TypeError, KeyError
20# IndexError, FileNotFoundError
12

Modules

Importing and organizing code

Import Statements

Using Python's module system

1# Import entire module
2import math
3math.sqrt(16) # 4.0
4
5# Import specific items
6from math import sqrt, pi
7sqrt(16) # 4.0
8
9# Import with alias
10import numpy as np
11import pandas as pd
12
13# Import all (avoid in production)
14from math import *
15
16# Useful standard library modules
17import os # Operating system
18import sys # System-specific
19import json # JSON parsing
20import datetime # Date and time
21import random # Random numbers
22import re # Regular expressions

Ready to practice?

Build muscle memory with interactive fill-in-the-blank exercises. Master Python syntax through repetition.

Start Practicing Python