Python Cheat Sheet

Variables and Data Types

Python is dynamically typed. Variable types are inferred at runtime.

x = 5           # int
y = 3.14        # float
name = "Alice"  # str
is_active = True # bool

Type Conversion

Convert between types using built-in functions.

int("3")        # 3
str(42)         # '42'
float("2.5")    # 2.5
bool(0)         # False

Operators (Arithmetic, Comparison, Logical, Bitwise, Assignment)

Arithmetic

a + b, a - b, a * b, a / b, a % b, a ** b, a // b

Comparison

a == b, a != b, a > b, a < b, a >= b, a <= b

Logical

and, or, not

Bitwise

a & b, a | b, a ^ b, ~a, a << b, a >> b

Assignment

=, +=, -=, *=, /=, %=, //=, **=

String Manipulation

s = "hello"
s.upper(), s.lower(), s.capitalize()
s.replace("h", "H")
s.split("e")
"-".join(["a", "b"])

Input and Output

name = input("Enter your name: ")
print(f"Hello, {name}!")

Comments and Docstrings

# This is a single-line comment
"""
This is a
multi-line docstring
"""

Conditional Statements (if, elif, else)

x = 10
if x > 0:
    print("Positive")
elif x == 0:
    print("Zero")
else:
    print("Negative")

Loops (for, while)

for loop

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

while loop

count = 0
while count < 5:
    print(count)
    count += 1

Loop Control (break, continue, pass)

for i in range(5):
    if i == 3:
        break  # exits loop
    if i == 1:
        continue  # skips to next iteration
    print(i)

for j in range(3):
    pass  # placeholder

Comprehensions (List, Dict, Set)

List Comprehension

squares = [x**2 for x in range(5)]

Dictionary Comprehension

squares = {x: x**2 for x in range(5)}

Set Comprehension

unique = {x % 3 for x in range(10)}

Function Definition and Arguments

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

greet("Alice")
greet("Bob", "Hi")

Lambda Functions

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

map, filter, reduce

from functools import reduce

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x*x, nums))
evens = list(filter(lambda x: x%2 == 0, nums))
sum_all = reduce(lambda x, y: x + y, nums)

Decorators

def decorator(func):
    def wrapper():
        print("Before function")
        func()
        print("After function")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

Recursion

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

Lists

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.remove("banana")
print(fruits[0])

Tuples

coordinates = (10, 20)
print(coordinates[1])

Dictionaries

person = {"name": "Alice", "age": 30}
print(person["name"])
person["age"] = 31

Sets

unique_numbers = {1, 2, 3, 2}
unique_numbers.add(4)

Stacks and Queues (Using list/deque)

Stack with list

stack = []
stack.append(1)
stack.pop()

Queue with deque

from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.popleft()

Collections Module

Counter

from collections import Counter
c = Counter("hello")

defaultdict

from collections import defaultdict
d = defaultdict(int)
d["a"] += 1

namedtuple

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)

deque

from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0)

Importing Modules

import math
from math import sqrt
import os as operating_system

Standard Library Overview

Popular modules: math, random, datetime, os, sys, re

import datetime
now = datetime.datetime.now()

Creating and Using Packages

# Directory structure:
# mypackage/
# ├── __init__.py
# └── module.py

from mypackage import module
module.my_function()

Virtual Environments

python -m venv env
source env/bin/activate  # On Windows: envScriptsactivate
pip install -r requirements.txt

Reading and Writing Files

# Writing to a file
with open("example.txt", "w") as f:
    f.write("Hello, World!")

# Reading from a file
with open("example.txt", "r") as f:
    content = f.read()

Working with Context Managers (with)

with ensures proper acquisition and release of resources like files.

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

CSV and JSON Handling

CSV

import csv
with open("data.csv", newline="") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

JSON

import json

data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
parsed = json.loads(json_str)

try, except, finally

try:
    x = 1 / 0
except ZeroDivisionError as e:
    print("Cannot divide by zero:", e)
finally:
    print("Cleanup actions")

Raising Exceptions and Custom Exceptions

Raising Exceptions

raise ValueError("Invalid input")

Custom Exceptions

class MyError(Exception):
    pass

raise MyError("Something went wrong")

Classes and Objects

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

    def greet(self):
        print(f"Hello, my name is {self.name}")

p = Person("Alice")
p.greet()

Constructors (__init__)

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

Inheritance

class Animal:
    def speak(self):
        print("Generic sound")

class Dog(Animal):
    def speak(self):
        print("Bark")

Encapsulation and Polymorphism

class Base:
    def greet(self):
        print("Hello")

class Derived(Base):
    def greet(self):
        print("Hi")

# Polymorphism
for obj in [Base(), Derived()]:
    obj.greet()

Dunder Methods (__str__, __repr__, etc.)

class Book:
    def __init__(self, title):
        self.title = title

    def __str__(self):
        return f"Book: {self.title}"

    def __repr__(self):
        return f"Book('{self.title}')"

Iterators and Generators

Iterators

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

Generators

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for val in countdown(3):
    print(val)

Closures

def outer(x):
    def inner(y):
        return x + y
    return inner

add_five = outer(5)
print(add_five(3))

Context Managers

class MyContext:
    def __enter__(self):
        print("Enter")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exit")

with MyContext() as ctx:
    print("Inside block")

Type Hinting (PEP 484)

def greet(name: str) -> str:
    return "Hello " + name

Multithreading and Multiprocessing

Threading

import threading

def worker():
    print("Working")

thread = threading.Thread(target=worker)
thread.start()
thread.join()

Multiprocessing

from multiprocessing import Process

def worker():
    print("Working in another process")

process = Process(target=worker)
process.start()
process.join()

Asynchronous Programming (async/await)

import asyncio

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

asyncio.run(say_hello())

Useful Built-in Functions

len(), type(), range(), enumerate(), zip()
sorted(), reversed(), any(), all(), sum()

Common Standard Libraries

import math
math.sqrt(16)

import datetime
datetime.datetime.now()

import os
os.getcwd()

import sys
print(sys.version)

import re
re.match(r"d+", "123abc")

Command Line Arguments (argparse)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--name")
args = parser.parse_args()
print(f"Hello {args.name}")

List of Magic/Dunder Methods

__init__, __str__, __repr__, __len__, __getitem__,
__setitem__, __delitem__, __iter__, __next__, __contains__

Popular Third-Party Libraries

  • requests: HTTP requests
  • pandas: Data analysis
  • numpy: Numerical computations
  • matplotlib: Plotting graphs
  • flask: Web applications
import requests
response = requests.get("https://api.example.com")
print(response.json())