Python Cheat Sheet - Quick Reference
Reference Appendix
This page works as the course appendix. It summarizes the main concepts in a compact format so you can come back whenever you need a quick syntax or pattern refresher.
Contents
- Getting started
- Variables and types
- Operators
- Control flow
- Loops
- Data structures
- Strings
- Functions
- Decorators
- Classes (OOP)
- Special methods
- Files
- Error handling
- Modules and imports
- Virtual environment
- Dates
- Generators
- Context managers
- Type hints
- Testing
- Project structure
Getting started
1# Your first program
2print("Hello world")
3
4# Comments
5# This is a single-line comment
6
7"""
8This is a multi-line
9comment
10"""
11
12# Variables (no type declaration needed)
13name = "Python"
14version = 3.12Variables and types
1# Basic types
2integer = 42 # int
3floating = 3.14 # float
4text = "Hello" # str
5boolean = True # bool
6null = None # NoneType
7
8# Check type
9type(integer) # <class 'int'>
10isinstance(42, int) # True
11
12# Conversions
13int("42") # str β int: 42
14str(42) # int β str: "42"
15float("3.14") # str β float: 3.14
16bool(1) # int β bool: True
17list("abc") # str β list: ['a', 'b', 'c']Operators
| Type | Operators | Example |
|---|---|---|
| Arithmetic | + - * / | 5 + 3 = 8 |
| Floor division | // | 7 // 2 = 3 |
| Modulo | % | 7 % 2 = 1 |
| Power | ** | 2 ** 3 = 8 |
| Comparison | == != < > <= >= | 5 > 3 β True |
| Logical | and or not | True and False β False |
| Membership | in not in | “a” in “abc” β True |
| Identity | is is not | x is None |
| Assignment | = += -= *= /= | x += 1 |
Control flow
1# if / elif / else
2if x > 0:
3 print("positive")
4elif x < 0:
5 print("negative")
6else:
7 print("zero")
8
9# Ternary operator
10result = "even" if x % 2 == 0 else "odd"
11
12# match (Python 3.10+)
13match command:
14 case "exit":
15 exit()
16 case "help":
17 show_help()
18 case _:
19 print("Unknown command")Loops
1# for with range
2for i in range(5): # 0, 1, 2, 3, 4
3 print(i)
4
5for i in range(2, 10, 2): # 2, 4, 6, 8
6 print(i)
7
8# for with iterables
9for char in "Python":
10 print(char)
11
12for item in [1, 2, 3]:
13 print(item)
14
15for key, value in dict.items():
16 print(f"{key}: {value}")
17
18# while
19while condition:
20 do_something()
21 if exit_flag:
22 break
23 if skip_flag:
24 continue
25
26# enumerate and zip
27for i, value in enumerate(my_list):
28 print(f"{i}: {value}")
29
30for a, b in zip(list1, list2):
31 print(a, b)
32
33# Comprehensions
34squares = [x**2 for x in range(10)]
35evens = [x for x in nums if x % 2 == 0]
36my_dict = {x: x**2 for x in range(5)}
37my_set = {x for x in nums if x > 0}Data structures
1# List: mutable, ordered, allows duplicates
2my_list = [1, 2, 3, 4, 5]
3my_list = list() # empty list
4
5# Access
6my_list[0] # first element
7my_list[-1] # last element
8my_list[1:3] # sublist [2, 3]
9
10# Modify
11my_list.append(6) # add to end
12my_list.insert(0, 0) # insert at position
13my_list.extend([7, 8]) # add multiple
14my_list.remove(3) # remove by value
15my_list.pop() # remove last
16my_list.pop(0) # remove by index
17my_list[0] = 99 # replace
18
19# Operations
20len(my_list) # length
21sorted(my_list) # sort (new list)
22my_list.sort() # sort in-place
23my_list.reverse() # reverse in-place
24my_list.index(value) # find index
25my_list.count(value) # count occurrences 1# Dictionary: mutable, key-value pairs
2my_dict = {"name": "Ana", "age": 25}
3my_dict = dict() # empty
4
5# Access
6my_dict["name"] # "Ana" (error if missing)
7my_dict.get("name") # "Ana" (None if missing)
8my_dict.get("x", "default") # default value
9
10# Modify
11my_dict["city"] = "Madrid" # add/update
12my_dict.update({"a": 1}) # update multiple
13del my_dict["age"] # delete
14my_dict.pop("name") # delete and return
15
16# Iterate
17my_dict.keys() # keys
18my_dict.values() # values
19my_dict.items() # pairs (key, value)
20
21for k, v in my_dict.items():
22 print(f"{k}: {v}") 1# Set: mutable, unordered, no duplicates
2my_set = {1, 2, 3}
3my_set = set() # empty
4
5# Modify
6my_set.add(4) # add
7my_set.remove(1) # remove (error if missing)
8my_set.discard(1) # remove (no error)
9
10# Set operations
11a | b # union
12a & b # intersection
13a - b # difference
14a ^ b # symmetric difference
15a.issubset(b) # is a in b?
16a.issuperset(b) # is b in a? 1# Tuple: immutable, ordered
2my_tuple = (1, 2, 3)
3my_tuple = tuple() # empty
4my_tuple = (1,) # single element (note the comma!)
5
6# Access (same as lists)
7my_tuple[0] # first element
8my_tuple[-1] # last
9my_tuple[1:3] # subtuple
10
11# Unpacking
12a, b, c = (1, 2, 3)
13first, *rest = (1, 2, 3, 4) # first=1, rest=[2,3,4]
14
15# Common uses
16# - Dictionary keys
17# - Multiple return values
18# - Data that shouldn't changeStrings
1# Creation
2text = "Hello World"
3text = 'Hello World'
4text = """Multiple
5lines"""
6
7# Common methods
8text.upper() # "HELLO WORLD"
9text.lower() # "hello world"
10text.capitalize() # "Hello world"
11text.title() # "Hello World"
12text.strip() # remove whitespace
13text.split() # ["Hello", "World"]
14text.split(",") # split by comma
15",".join(["a", "b"]) # "a,b"
16text.replace("a", "o") # replace
17text.startswith("Hello") # True
18text.endswith("ld") # True
19text.find("Wor") # 6 (index)
20text.count("o") # 2
21
22# f-strings (Python 3.6+)
23name = "Ana"
24age = 25
25f"My name is {name}"
26f"I am {age} years old"
27f"Next year: {age + 1}"
28f"Pi = {3.14159:.2f}" # "Pi = 3.14"
29f"{name:>10}" # right aligned
30f"{name:<10}" # left aligned
31f"{name:^10}" # centered
32
33# Indexing and slicing
34text[0] # 'H'
35text[-1] # 'd'
36text[0:5] # 'Hello'
37text[::2] # 'HloWrd'
38text[::-1] # reverseFunctions
1# Basic definition
2def greet(name):
3 """Docstring: function documentation."""
4 return f"Hello {name}"
5
6# Default parameters
7def power(base, exp=2):
8 return base ** exp
9
10power(3) # 9 (exp=2 by default)
11power(3, 3) # 27
12
13# Keyword arguments
14def create_user(name, age, city="Madrid"):
15 pass
16
17create_user("Ana", 25)
18create_user(age=25, name="Ana")
19
20# *args: variable positional arguments
21def add(*numbers):
22 return sum(numbers)
23
24add(1, 2, 3, 4) # 10
25
26# **kwargs: variable keyword arguments
27def info(**data):
28 for k, v in data.items():
29 print(f"{k}: {v}")
30
31info(name="Ana", age=25)
32
33# Lambda (anonymous functions)
34double = lambda x: x * 2
35add = lambda a, b: a + b
36
37# Functions as arguments
38my_list = [3, 1, 2]
39sorted(my_list, key=lambda x: -x) # [3, 2, 1]Decorators
1# Simple decorator
2def my_decorator(func):
3 def wrapper(*args, **kwargs):
4 print("Before function")
5 result = func(*args, **kwargs)
6 print("After function")
7 return result
8 return wrapper
9
10@my_decorator
11def greet(name):
12 print(f"Hello {name}")
13
14# Decorator with arguments
15def repeat(times):
16 def decorator(func):
17 def wrapper(*args, **kwargs):
18 for _ in range(times):
19 func(*args, **kwargs)
20 return wrapper
21 return decorator
22
23@repeat(3)
24def say_hello():
25 print("Hello")
26
27# Common decorators
28@staticmethod # method without self
29@classmethod # method with cls
30@property # getter
31@name.setter # setterClasses (OOP)
1class Person:
2 # Class attribute (shared)
3 species = "Human"
4
5 def __init__(self, name, age):
6 # Instance attributes (unique)
7 self.name = name
8 self.age = age
9
10 def greet(self):
11 return f"Hello, I'm {self.name}"
12
13 @staticmethod
14 def info():
15 return "I'm a person"
16
17 @classmethod
18 def from_dict(cls, data):
19 return cls(data["name"], data["age"])
20
21 @property
22 def is_adult(self):
23 return self.age >= 18
24
25# Usage
26p = Person("Ana", 25)
27p.greet() # "Hello, I'm Ana"
28p.is_adult # True (property)
29Person.species # "Human"
30
31# Inheritance
32class Student(Person):
33 def __init__(self, name, age, major):
34 super().__init__(name, age)
35 self.major = major
36
37 def greet(self): # Override
38 return f"Hello, I study {self.major}"Special methods
1class Vector:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def __str__(self):
7 """For print() and str()"""
8 return f"({self.x}, {self.y})"
9
10 def __repr__(self):
11 """For debugging"""
12 return f"Vector({self.x}, {self.y})"
13
14 def __add__(self, other):
15 """For + operator"""
16 return Vector(self.x + other.x, self.y + other.y)
17
18 def __eq__(self, other):
19 """For == operator"""
20 return self.x == other.x and self.y == other.y
21
22 def __len__(self):
23 """For len()"""
24 return 2
25
26 def __getitem__(self, index):
27 """For [] access"""
28 return (self.x, self.y)[index]| Method | Operator/Function |
|---|---|
| add | + |
| sub | - |
| mul | * |
| eq | == |
| lt | < |
| len | len() |
| str | str(), print() |
| iter | for … in |
Files
1# Read entire file
2with open("file.txt", "r", encoding="utf-8") as f:
3 content = f.read()
4
5# Read line by line
6with open("file.txt", "r") as f:
7 for line in f:
8 print(line.strip())
9
10# Write to file
11with open("file.txt", "w") as f:
12 f.write("Hello world\n")
13
14# Append to file
15with open("file.txt", "a") as f:
16 f.write("New line\n")
17
18# JSON
19import json
20
21# Read JSON
22with open("data.json", "r") as f:
23 data = json.load(f)
24
25# Write JSON
26with open("data.json", "w") as f:
27 json.dump(data, f, indent=2)
28
29# String β JSON
30json.loads('{"key": "value"}')
31json.dumps({"key": "value"})
32
33# CSV
34import csv
35
36with open("data.csv", "r") as f:
37 reader = csv.DictReader(f)
38 for row in reader:
39 print(row["column"])
40
41with open("data.csv", "w", newline="") as f:
42 writer = csv.writer(f)
43 writer.writerow(["col1", "col2"])
44 writer.writerow([1, 2])Error handling
1try:
2 result = 10 / 0
3except ZeroDivisionError:
4 print("Cannot divide by zero")
5except (TypeError, ValueError) as e:
6 print(f"Type or value error: {e}")
7except Exception as e:
8 print(f"Unexpected error: {e}")
9else:
10 print("Everything went fine")
11finally:
12 print("Always executes")
13
14# Raise exceptions
15def divide(a, b):
16 if b == 0:
17 raise ValueError("Divisor cannot be zero")
18 return a / b
19
20# Custom exceptions
21class MyError(Exception):
22 pass
23
24raise MyError("Something went wrong")Modules and imports
1# Import entire module
2import math
3math.sqrt(16)
4
5# Import with alias
6import numpy as np
7np.array([1, 2, 3])
8
9# Import specific elements
10from datetime import datetime, timedelta
11datetime.now()
12
13# Import all (not recommended)
14from math import *
15
16# Relative import (inside a package)
17from . import module # same level
18from .. import module # parent level
19from .subpackage import somethingVirtual environment
1# Create virtual environment
2python -m venv venv
3
4# Activate (Windows)
5venv\Scripts\activate
6
7# Activate (Linux/Mac)
8source venv/bin/activate
9
10# Deactivate
11deactivate
12
13# Install packages
14pip install package
15pip install package==1.0.0
16
17# Save dependencies
18pip freeze > requirements.txt
19
20# Install from file
21pip install -r requirements.txt
22
23# List installed packages
24pip listDates
1from datetime import datetime, date, time, timedelta
2
3# Current date and time
4now = datetime.now()
5today = date.today()
6
7# Create specific date
8dt = datetime(2024, 12, 25, 10, 30, 0)
9d = date(2024, 12, 25)
10
11# Format to string
12dt.strftime("%d/%m/%Y") # "25/12/2024"
13dt.strftime("%Y-%m-%d %H:%M") # "2024-12-25 10:30"
14
15# Parse string to date
16datetime.strptime("25/12/2024", "%d/%m/%Y")
17
18# Operations
19tomorrow = today + timedelta(days=1)
20last_week = today - timedelta(weeks=1)
21difference = date2 - date1 # timedelta
22
23# Format codes
24# %Y: year (2024) %m: month (12) %d: day (25)
25# %H: hour 24h %M: minutes %S: seconds
26# %A: weekday %B: month nameGenerators
1# Generator function
2def counter(n):
3 i = 0
4 while i < n:
5 yield i
6 i += 1
7
8for num in counter(5):
9 print(num) # 0, 1, 2, 3, 4
10
11# Generator expression (lazy)
12gen = (x**2 for x in range(10))
13next(gen) # 0
14next(gen) # 1
15
16# Convert to list
17list(gen) # consumes the rest
18
19# Common uses
20# - Process large files line by line
21# - Infinite sequences
22# - Memory savingsContext managers
1# Usage with 'with'
2with open("file.txt") as f:
3 content = f.read()
4# File is automatically closed
5
6# Create context manager with class
7class MyContext:
8 def __enter__(self):
9 print("Entering")
10 return self
11
12 def __exit__(self, exc_type, exc_val, exc_tb):
13 print("Exiting")
14 return False # Don't suppress exceptions
15
16with MyContext() as ctx:
17 print("Inside context")
18
19# With decorator (simpler)
20from contextlib import contextmanager
21
22@contextmanager
23def my_context():
24 print("Entering")
25 yield
26 print("Exiting")Type hints
1# Basic types
2def greet(name: str) -> str:
3 return f"Hello {name}"
4
5def add(a: int, b: int) -> int:
6 return a + b
7
8# Compound types
9from typing import List, Dict, Tuple, Optional, Union
10
11def process(items: List[str]) -> Dict[str, int]:
12 return {item: len(item) for item in items}
13
14def find(id: int) -> Optional[str]:
15 # Can return str or None
16 pass
17
18def accept(value: Union[int, str]) -> None:
19 # Accepts int or str
20 pass
21
22# Python 3.10+
23def new_syntax(items: list[str]) -> dict[str, int]:
24 pass
25
26# Classes as types
27class User:
28 pass
29
30def create_user(name: str) -> User:
31 return User()Testing
1import pytest
2
3# Basic test
4def test_add():
5 assert 1 + 1 == 2
6 assert add(2, 3) == 5
7
8# Test with expected exception
9def test_division_by_zero():
10 with pytest.raises(ZeroDivisionError):
11 1 / 0
12
13# Fixture (setup)
14@pytest.fixture
15def user():
16 return {"name": "Ana", "age": 25}
17
18def test_with_fixture(user):
19 assert user["name"] == "Ana"
20
21# Parametrize
22@pytest.mark.parametrize("input,expected", [
23 (2, 4),
24 (3, 9),
25 (4, 16),
26])
27def test_square(input, expected):
28 assert input ** 2 == expected
29
30# Run tests
31# pytest # all tests
32# pytest test_file.py # one file
33# pytest -v # verbose
34# pytest -k "name" # filter by nameProject structure
my_project/
βββ src/
β βββ my_package/
β βββ __init__.py # makes directory a package
β βββ core.py # main module
β βββ utils.py # utilities
βββ tests/
β βββ __init__.py
β βββ test_core.py
βββ docs/
βββ pyproject.toml # project configuration
βββ README.md # documentation
βββ LICENSE
βββ .gitignore
# Basic pyproject.toml
[project]
name = "my-package"
version = "1.0.0"
dependencies = ["requests>=2.28.0"]
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
# Install in development mode
pip install -e .