PythonCheatsheet
A curated reference for Python syntax and idioms. From variables to classes, list comprehensions to decorators. Designed for quick lookup and deeper understanding.
Variables
Assignment and naming conventions
Basic Assignment
Python uses dynamic typing - no type declarations needed
1# Variables are created on assignment2name = "Alice"3age = 304price = 19.995is_active = True6 7# Multiple assignment8x, y, z = 1, 2, 39a = b = c = 010 11# Constants (by convention, uppercase)12MAX_SIZE = 10013PI = 3.14159Data Types
Built-in types and type checking
Core Types
Python's fundamental data types
1# Numeric types2integer = 423floating = 3.144complex_num = 3 + 4j5 6# Text7string = "Hello, World"8 9# Boolean10flag = True # or False11 12# None (null equivalent)13empty = None14 15# Check type16type(integer) # <class 'int'>17isinstance(42, int) # TrueStrings
Text manipulation and formatting
String Operations
Common string methods and f-strings
1text = "hello world"2 3# Methods4text.upper() # "HELLO WORLD"5text.lower() # "hello world"6text.title() # "Hello World"7text.split() # ["hello", "world"]8text.replace("o", "0") # "hell0 w0rld"9text.strip() # Remove whitespace10 11# f-strings (Python 3.6+)12name = "Alice"13age = 3014f"Hello, {name}! You are {age}."15 16# Slicing17text[0:5] # "hello"18text[-5:] # "world"19text[::2] # "hlowrd"Lists
Ordered, mutable sequences
List Operations
Creating and manipulating lists
1nums = [1, 2, 3, 4, 5]2 3# Access and slice4nums[0] # 15nums[-1] # 56nums[1:4] # [2, 3, 4]7 8# Modify9nums.append(6) # Add to end10nums.insert(0, 0) # Insert at index11nums.pop() # Remove last12nums.remove(3) # Remove by value13 14# Useful methods15len(nums) # Length16sum(nums) # Sum17sorted(nums) # Sorted copy18nums.reverse() # Reverse in place19nums.index(2) # Find indexDictionaries
Key-value mappings
Dictionary Operations
Creating and accessing dictionaries
1person = {2 "name": "Alice",3 "age": 30,4 "city": "NYC"5}6 7# Access8person["name"] # "Alice"9person.get("age") # 3010person.get("job", "N/A") # Default value11 12# Modify13person["email"] = "a@b.com"14del person["city"]15 16# Iterate17person.keys() # dict_keys18person.values() # dict_values19person.items() # key-value pairs20 21for key, value in person.items():22 print(f"{key}: {value}")Control Flow
Conditionals and loops
Conditionals & Loops
if/elif/else, for, while
1# Conditionals2age = 183if age >= 21:4 print("Adult")5elif age >= 18:6 print("Young adult")7else:8 print("Minor")9 10# For loop11for i in range(5):12 print(i) # 0, 1, 2, 3, 413 14for item in ["a", "b", "c"]:15 print(item)16 17# While loop18count = 019while count < 3:20 print(count)21 count += 122 23# Loop control24# break - exit loop25# continue - skip iterationFunctions
Defining and calling functions
Function Definitions
Parameters, return values, and lambdas
1# Basic function2def greet(name):3 return f"Hello, {name}!"4 5# Default parameters6def greet(name="World"):7 return f"Hello, {name}!"8 9# Multiple return values10def get_stats(nums):11 return min(nums), max(nums)12 13low, high = get_stats([1, 2, 3])14 15# *args and **kwargs16def func(*args, **kwargs):17 print(args) # Tuple18 print(kwargs) # Dictionary19 20# Lambda (anonymous function)21square = lambda x: x ** 222square(5) # 25Classes
Object-oriented programming
Class Definition
Classes, __init__, methods, inheritance
1class Person:2 def __init__(self, name, age):3 self.name = name4 self.age = age5 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 instance13alice = Person("Alice", 30)14alice.greet() # "Hi, I'm Alice"15 16# Inheritance17class Student(Person):18 def __init__(self, name, age, grade):19 super().__init__(name, age)20 self.grade = gradeComprehensions
Pythonic list/dict creation
Comprehension Syntax
Concise ways to create collections
1# List comprehension2squares = [x**2 for x in range(10)]3# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]4 5# With condition6evens = [x for x in range(10) if x % 2 == 0]7# [0, 2, 4, 6, 8]8 9# Dictionary comprehension10squares_dict = {x: x**2 for x in range(5)}11# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}12 13# Set comprehension14unique = {x % 3 for x in range(10)}15# {0, 1, 2}16 17# Nested comprehension18matrix = [[i*j for j in range(3)]19 for i in range(3)]File I/O
Reading and writing files
File Operations
Safe file handling with context managers
1# Reading a file2with open("file.txt", "r") as f:3 content = f.read() # Entire file4 # or5 lines = f.readlines() # List of lines6 7# Writing to a file8with open("file.txt", "w") as f:9 f.write("Hello, World!")10 11# Appending to a file12with 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)Exceptions
Error handling
Try/Except Blocks
Catching and handling errors
1try:2 result = 10 / 03except ZeroDivisionError:4 print("Cannot divide by zero")5except Exception as e:6 print(f"Error: {e}")7else:8 print("Success!") # Runs if no error9finally:10 print("Always runs")11 12# Raising exceptions13def validate(age):14 if age < 0:15 raise ValueError("Age cannot be negative")16 return age17 18# Common exceptions:19# ValueError, TypeError, KeyError20# IndexError, FileNotFoundErrorModules
Importing and organizing code
Import Statements
Using Python's module system
1# Import entire module2import math3math.sqrt(16) # 4.04 5# Import specific items6from math import sqrt, pi7sqrt(16) # 4.08 9# Import with alias10import numpy as np11import pandas as pd12 13# Import all (avoid in production)14from math import *15 16# Useful standard library modules17import os # Operating system18import sys # System-specific19import json # JSON parsing20import datetime # Date and time21import random # Random numbers22import re # Regular expressionsReady to practice?
Build muscle memory with interactive fill-in-the-blank exercises. Master Python syntax through repetition.
Start Practicing Python