Cheatsheet: Python

Variables and Types

Basic variables

name = 'Alice'
age = 30
height = 1.72
is_active = True

Common collections

items = [1, 2, 3]
user = {'name': 'Alice', 'role': 'admin'}
unique_ids = {1, 2, 3}
coords = (10, 20)

Type checking and conversion

isinstance(age, int)
str(age)
int('42')
float('3.14')

Control Flow

if / elif / else

score = 88
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
else:
    grade = 'C'

for loop

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

while loop

count = 0
while count < 3:
    count += 1

list comprehension

squares = [x * x for x in range(6) if x % 2 == 0]

Functions

Function with default and keyword args

def greet(name, prefix='Hello'):
    return f'{prefix}, {name}'

greet('Alice')
greet('Bob', prefix='Hi')

Lambda and map/filter

nums = [1, 2, 3, 4]
doubled = list(map(lambda n: n * 2, nums))
even = list(filter(lambda n: n % 2 == 0, nums))

args and kwargs

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

Classes and Dataclasses

Simple class

class User:
    def __init__(self, name):
        self.name = name

    def hello(self):
        return f'Hi, {self.name}'

Dataclass

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

Imports and Modules

Import styles

import math
from datetime import datetime
from pathlib import Path as P

Useful standard library modules

json, pathlib, datetime, re, collections, itertools, statistics

Files and JSON

Read a text file

with open('input.txt', 'r', encoding='utf-8') as f:
    text = f.read()

Write a text file

with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('hello')

Read and write JSON

import json

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, indent=2)

Virtual Environment and Pip

Create and activate virtual environment

python3 -m venv .venv
source .venv/bin/activate

Install dependencies

pip install requests
pip install -r requirements.txt

Freeze dependencies

pip freeze > requirements.txt

See also: