Python Cheat Sheets

Python comprehensive cheat sheet

Getting Started

Hello World

print("Hello, World!")

Basic Commands

Comment
# Single line comment
Multiline Comment
""" Multiline Comment """
Variable Assignment
x = 5
Output
print(x)
Input
input("Enter something: ")

Getting Started Resources

Python.org Getting Started https://www.python.org/about/gettingsta…
W3Schools Python https://www.w3schools.com/python/
Real Python Tutorials https://realpython.com/

Data Types

Primitive Data Types

int
Integer (x = 1)
float
Floating point (y = 3.14)
str
String (s = "hello")
bool
Boolean (b = True)
list
List (l = [1,2,3])
tuple
Tuple (t = (1,2,3))
set
Set (s = {1,2,3})
dict
Dictionary (d = {"a": 1})

Type Checking

print(type(3.14))  # <class "float">
print(isinstance("a", str))  # True

Type Checking Resources

Python Type Checking Docs https://docs.python.org/3/library/typin…
Real Python: Type Checking in Python https://realpython.com/python-type-chec…

Type Conversion Functions

int()
int("5") -> 5
float()
float("3.14") -> 3.14
str()
str(5) -> "5"
list()
list("abc") -> ["a","b","c"]

Type Conversion Resources

Python Type Conversion Docs https://docs.python.org/3/library/funct…
Real Python: Type Conversion in Python https://realpython.com/python-type-conv…

Type Conversion Examples

int("5")  # 5
float("3.14")  # 3.14
str(5)  # "5"
list("abc")  # ["a","b","c"]

List Comprehensions

Simple List Comprehension

[x*x for x in range(5)]  # [0, 1, 4, 9, 16]

Conditional List Comprehension

[x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

Nested List Comprehension

matrix = [[1,2],[3,4]]
flattened = [num for row in matrix for num in row]  # [1,2,3,4]

List Comprehension Resources

Python List Comprehension Docs https://docs.python.org/3/tutorial/data…
Real Python: List Comprehensions in Python https://realpython.com/list-comprehensi…

Control Flow

if-elif-else

x = 10
if x > 5:
    print("Greater")
elif x == 5:
    print("Equal")
else:
    print("Smaller")

for Loop

for i in range(3):
    print(i)

for i in [1,2,3]:
    print(i)

while Loop

i = 0
while i < 3:
    print(i)
    i += 1

Loop Control Keywords

break
Exit the loop
continue
Skip to next iteration
pass
Do nothing (placeholder)

Loop Control Resources

Python Loop Control Docs https://docs.python.org/3/tutorial/cont…
Real Python: Loops in Python https://realpython.com/python-for-loop/

Functions

Function Definition

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

Default Arguments

def greet(name="World"):
    print(f"Hello, {name}")

*args and **kwargs

def func(*args, **kwargs):
    print(args)
    print(kwargs)

Function Attributes

__name__
Function name
__doc__
Function docstring

Function Resources

Python Functions Docs https://docs.python.org/3/tutorial/cont…
Real Python: Defining Functions https://realpython.com/defining-your-ow…

Lambda, map, filter, reduce

Lambda Function

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

map()

nums = [1, 2, 3]
squares = list(map(lambda x: x*x, nums))

filter()

nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))

reduce()

from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)

Object-Oriented Programming (OOP)

Class Definition

class Car:
    def __init__(self, brand):
        self.brand = brand
    def start(self):
        print(f"{self.brand} is starting")

OOP Terms

self
Reference to the instance
__init__
Constructor method
method
Function defined in a class

Inheritance

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Woof!")

Classmethod & Staticmethod

class Example:
    @staticmethod
    def static():
        print("Static method")
    @classmethod
    def cls(cls):
        print("Class method")

OOP Resources

Python OOP Docs https://docs.python.org/3/tutorial/clas…
Real Python: Object-Oriented Programming in Python 3 https://realpython.com/python3-object-o…

Decorators

Simple Decorator

def my_decorator(func):
    def wrapper():
        print("Before")
        func()
        print("After")
    return wrapper

Using @decorator

@my_decorator
def greet():
    print("Hello!")

Generators & Iterators

Generator Function

def counter():
    for i in range(3):
        yield i

Generator Features

yield
Returns a value and pauses the function
next()
Gets the next value
iter()
Returns an iterator

Iterator Protocol

it = iter([1,2,3])
print(next(it))  # 1

Generator Resources

Python Generators Docs https://docs.python.org/3/howto/functio…
Real Python: Generators in Python https://realpython.com/introduction-to-…

Generator Example

def counter():
    for i in range(3):
        yield i

Error Handling

try-except

try:
    x = 1 / 0
except ZeroDivisionError as e:
    print("Error:", e)

finally and else

try:
    x = 1
except:
    pass
else:
    print("No error!")
finally:
    print("Always runs")

Error Handling Resources

Python Error Handling Docs https://docs.python.org/3/tutorial/erro…
Real Python: Error Handling in Python https://realpython.com/python-exception…

Common Exceptions

ValueError
Raised when a function receives the wrong value type
TypeError
Raised when an operation is applied to an object of inappropriate type
KeyError
Raised when a dictionary key is not found

File I/O

Reading a File

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

Writing to a File

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

Reading Line by Line

with open("file.txt") as f:
    for line in f:
        print(line.strip())

File I/O Resources

Python File I/O Docs https://docs.python.org/3/tutorial/inpu…
Real Python: File I/O in Python https://realpython.com/read-write-files…

Modules & Packages

Importing Modules

import math
print(math.sqrt(16))

Modules Resources

Python Modules Docs https://docs.python.org/3/tutorial/modu…
Real Python: Modules in Python https://realpython.com/python-modules-p…

Importing Modules

import random
print(random.randint(1, 100))

Common Modules

os
Operating system interfaces
sys
System-specific parameters and functions
datetime
Date and time manipulation
itertools
Iterator building blocks
collections
High-performance container datatypes

Modules Resources

Python Modules Docs https://docs.python.org/3/tutorial/modu…
Real Python: Modules in Python https://realpython.com/python-modules-p…

Virtualenv & pip

pip Commands

pip install package
Install a package
pip uninstall package
Uninstall a package
pip list
List installed packages
pip freeze
Output installed packages in requirements format

Create Virtual Environment

python -m venv venv
source venv/bin/activate

Packaging & Environment Tools

pipenv https://pipenv.pypa.io/en/latest/
poetry https://python-poetry.org/
setuptools https://setuptools.pypa.io/en/latest/

Testing

Simple Test (unittest)

import unittest

class TestAdd(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

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

Testing Resources

unittest Docs https://docs.python.org/3/library/unitt…
pytest https://docs.pytest.org/en/stable/

Type Hints & Typing

Type Hints

def add(a: int, b: int) -> int:
    return a + b

Common Typing Types

List
List[int]
Dict
Dict[str, int]
Optional
Optional[str]
Union
Union[int, str]

Typing Resources

PEP 484 https://peps.python.org/pep-0484/
typing module https://docs.python.org/3/library/typin…

Dataclasses

Basic Dataclass

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

Dataclasses Resources

dataclasses Docs https://docs.python.org/3/library/datac…
Real Python: Dataclasses in Python https://realpython.com/python-data-clas…

Pathlib

Using Pathlib

from pathlib import Path
p = Path("file.txt")
print(p.exists())

Pathlib Resources

pathlib Docs https://docs.python.org/3/library/pathl…
Real Python: Pathlib in Python https://realpython.com/python-pathlib/

Logging

Basic Logging

import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")

Logging Resources

logging Docs https://docs.python.org/3/library/loggi…
Real Python: Logging in Python https://realpython.com/python-logging/

Argparse

Basic Argparse

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo")
args = parser.parse_args()

Argparse Resources

argparse Docs https://docs.python.org/3/library/argpa…

Asyncio

Basic Async Function

import asyncio

async def main():
    print("Hello")
    await asyncio.sleep(1)
    print("World")

asyncio.run(main())

Asyncio Resources

asyncio Docs https://docs.python.org/3/library/async…
Real Python: Asyncio in Python https://realpython.com/async-io-python/

Context Managers

with Statement

with open("file.txt") as f:
    data = f.read()

Context Managers Resources

Context Managers Docs https://docs.python.org/3/reference/dat…
Real Python: Context Managers in Python https://realpython.com/python-with-stat…

Custom Context Manager

from contextlib import contextmanager

@contextmanager
def my_cm():
    print("Enter")
    yield
    print("Exit")

with my_cm():
    print("Inside")

With Statement Resources

Real Python: Context Managers in Python https://realpython.com/python-with-stat…
Context Managers Docs https://docs.python.org/3/reference/dat…

Built-in Functions

Common Built-ins

len()
Get length of a sequence
sum()
Sum of elements
min(), max()
Minimum/maximum value
sorted()
Return a sorted list
enumerate()
Get index and value in a loop
zip()
Combine multiple iterables

Popular Libraries

Popular Libraries

NumPy https://numpy.org/
Pandas https://pandas.pydata.org/
Requests https://docs.python-requests.org/
Django https://www.djangoproject.com/
Flask https://flask.palletsprojects.com/
BeautifulSoup https://www.crummy.com/software/Beautif…
Matplotlib https://matplotlib.org/
itertools https://docs.python.org/3/library/itert…
dataclasses https://docs.python.org/3/library/datac…