Getting Started
5 snippetsYour first steps with Python basics
Hello World
print("Hello, World!")Comments
# Single line comment
"""Multi-line
comment"""User Input
name = input("Enter your name: ")Type Conversion
int("42") # str to int
str(42) # int to str
float("3.14")Check Type
type(variable) # <class 'int'>
isinstance(x, int) # True/FalseVariables & Data Types
10 snippetsDeclaring and using different data types
String
name = "John"Integer
age = 25Float
price = 19.99Boolean
is_active = TrueList
fruits = ["apple", "banana", "cherry"]Dictionary
person = {"name": "John", "age": 30}Tuple
coordinates = (10, 20)Set
unique = {1, 2, 3}None
value = NoneMultiple Assignment
a, b, c = 1, 2, 3
x = y = z = 0Operators
7 snippetsSymbols for calculations and comparisons
Arithmetic
5 + 3 # 8 (addition)
5 - 3 # 2 (subtraction)
5 * 3 # 15 (multiplication)
5 / 3 # 1.666... (division)
5 // 3 # 1 (floor division)
5 % 3 # 2 (modulus)
5 ** 3 # 125 (exponent)Comparison
5 == 5 # True (equal)
5 != 3 # True (not equal)
5 > 3 # True (greater)
5 < 3 # False (less)
5 >= 5 # True (greater or equal)
5 <= 3 # False (less or equal)Logical
True and False # False
True or False # True
not True # False
# Short-circuit evaluation
x and y # y if x is truthy
x or y # x if x is truthyAssignment
x = 5 # Assign
x += 3 # x = 8 (add)
x -= 2 # x = 6 (subtract)
x *= 2 # x = 12 (multiply)
x /= 3 # x = 4.0 (divide)
x //= 2 # x = 2.0 (floor)Identity
a = [1, 2]
b = a
c = [1, 2]
a is b # True (same object)
a is c # False (different object)
a is not c # TrueMembership
"a" in "abc" # True
2 in [1, 2, 3] # True
"x" not in "abc" # True
"key" in {"key": 1} # TrueBitwise
5 & 3 # 1 (AND: 101 & 011)
5 | 3 # 7 (OR: 101 | 011)
5 ^ 3 # 6 (XOR: 101 ^ 011)
~5 # -6 (NOT)
5 << 1 # 10 (left shift)
5 >> 1 # 2 (right shift)Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Loops
10 snippetsRepeating code blocks efficiently
For Range
for i in range(5):
print(i) # 0, 1, 2, 3, 4For Range Start/End
for i in range(2, 8):
print(i) # 2, 3, 4, 5, 6, 7For Range Step
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8For List
for fruit in fruits:
print(fruit)For Enumerate
for i, fruit in enumerate(fruits):
print(i, fruit)For Dict
for key, value in person.items():
print(key, value)While
while count < 10:
count += 1Break
for i in range(10):
if i == 5:
break # Exit loopContinue
for i in range(10):
if i == 5:
continue # Skip iterationElse in Loop
for i in range(5):
print(i)
else:
print("Done!") # Runs if no breakConditionals
5 snippetsMaking decisions in your code
If/Else
if x > 0:
print("positive")
elif x < 0:
print("negative")
else:
print("zero")Ternary
result = "yes" if condition else "no"Match (3.10+)
match status:
case 200:
print("OK")
case 404:
print("Not Found")
case _:
print("Unknown")Nested If
if x > 0:
if x > 10:
print("big positive")
else:
print("small positive")Multiple Conditions
if age >= 18 and age <= 65:
print("Working age")Comprehensions
6 snippetsConcise syntax for creating collections
List Comprehension
squares = [x**2 for x in range(10)]With Condition
evens = [x for x in range(10) if x % 2 == 0]Dict Comprehension
squares = {x: x**2 for x in range(5)}Set Comprehension
unique = {x % 3 for x in range(10)}Generator Expression
gen = (x**2 for x in range(10))Nested Comprehension
matrix = [[j for j in range(3)] for i in range(3)]Functions
5 snippetsBasic Function
def greet(name):
return f"Hello, {name}!"Default Args
def greet(name="World"):
return f"Hello, {name}!"Lambda
square = lambda x: x ** 2*args
def sum_all(*args):
return sum(args)**kwargs
def print_info(**kwargs):
for k, v in kwargs.items():
print(f"{k}: {v}")String Operations
6 snippetsF-string
f"Hello, {name}!"Split
"a,b,c".split(",") # ["a", "b", "c"]Join
",".join(["a", "b", "c"]) # "a,b,c"Strip
" hello ".strip() # "hello"Replace
"hello".replace("l", "x") # "hexxo"Slice
"hello"[1:4] # "ell"File I/O
3 snippetsRead File
with open("file.txt", "r") as f:
content = f.read()Write File
with open("file.txt", "w") as f:
f.write("Hello")Read Lines
with open("file.txt") as f:
lines = f.readlines()Error Handling
3 snippetsTry/Except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")Finally
try:
risky_operation()
except Exception as e:
print(e)
finally:
cleanup()Raise
raise ValueError("Invalid input")Classes & OOP
2 snippetsClass
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"Inheritance
class Puppy(Dog):
def play(self):
return f"{self.name} is playing!"Imports & Modules
3 snippetsImport
import osFrom Import
from datetime import datetimeAlias
import numpy as npDecorators
6 snippetsModify function behavior elegantly
Basic Decorator
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before")
result = func(*args, **kwargs)
print("After")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")Decorator with Args
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet():
print("Hi!")@property
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self._radius = max(0, value)@staticmethod
class Math:
@staticmethod
def add(a, b):
return a + b
Math.add(2, 3) # No instance needed@classmethod
class Person:
count = 0
@classmethod
def get_count(cls):
return cls.countfunctools.wraps
from functools import wraps
def decorator(func):
@wraps(func) # Preserves metadata
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapperDataclasses
5 snippetsSimplified class definitions for data
Basic Dataclass
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
p = Point(1.0, 2.0)Default Values
@dataclass
class User:
name: str
age: int = 0
active: bool = TrueFrozen (Immutable)
@dataclass(frozen=True)
class Config:
host: str
port: intField Options
from dataclasses import dataclass, field
@dataclass
class Item:
name: str
tags: list = field(default_factory=list)
_id: int = field(repr=False)Post Init
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
self.area = self.width * self.heightType Hints
7 snippetsAdd type annotations for better code
Basic Types
name: str = "John"
age: int = 30
price: float = 19.99
is_active: bool = TrueCollections
from typing import List, Dict, Set, Tuple
nums: List[int] = [1, 2, 3]
scores: Dict[str, int] = {"a": 1}
unique: Set[str] = {"x", "y"}
point: Tuple[int, int] = (1, 2)Optional
from typing import Optional
def find(id: int) -> Optional[str]:
return None # or return "found"Union
from typing import Union
def process(val: Union[int, str]) -> str:
return str(val)Callable
from typing import Callable
def apply(func: Callable[[int], int], x: int) -> int:
return func(x)TypeVar (Generics)
from typing import TypeVar, List
T = TypeVar('T')
def first(items: List[T]) -> T:
return items[0]Python 3.10+
# Simpler syntax in 3.10+
def greet(name: str | None = None) -> str:
return f"Hello, {name or 'World'}"
list[int] # Instead of List[int]Context Managers
4 snippetsResource management with 'with' statement
Class-based
class FileManager:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()@contextmanager
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
print(f"Elapsed: {time.time() - start:.2f}s")Multiple Contexts
with open("in.txt") as f_in, open("out.txt", "w") as f_out:
f_out.write(f_in.read())Suppress Errors
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove("temp.txt")Walrus Operator (3.8+)
4 snippetsAssignment expressions with :=
Basic Usage
# Assign and use in one expression
if (n := len(items)) > 10:
print(f"Too many: {n}")While Loop
while (line := file.readline()):
process(line)List Comprehension
# Avoid calling function twice
results = [y for x in data if (y := process(x)) is not None]Regex Match
import re
if (match := re.search(r'\d+', text)):
print(match.group())Common Standard Library
6 snippetsFrequently used built-in modules
json
import json
# Parse JSON
data = json.loads('{"name": "John"}')
# To JSON string
json_str = json.dumps(data, indent=2)
# File operations
with open("data.json") as f:
data = json.load(f)re (Regex)
import re
re.search(r'\d+', text) # First match
re.findall(r'\d+', text) # All matches
re.sub(r'\d+', 'X', text) # Replace
re.split(r'[,;]', text) # Splitcollections
from collections import defaultdict, Counter, deque
# Auto-initialize missing keys
d = defaultdict(list)
d['key'].append(1)
# Count occurrences
counts = Counter(['a', 'b', 'a'])
counts.most_common(2)
# Double-ended queue
dq = deque([1, 2, 3])
dq.appendleft(0)itertools
from itertools import chain, groupby, islice
# Flatten lists
list(chain([1,2], [3,4])) # [1,2,3,4]
# Take first n items
list(islice(range(100), 5)) # [0,1,2,3,4]pathlib
from pathlib import Path
p = Path("folder/file.txt")
p.exists() # Check existence
p.read_text() # Read file
p.parent # Parent directory
p.suffix # ".txt"
list(p.parent.glob("*.py")) # Find filesdatetime
from datetime import datetime, timedelta
now = datetime.now()
today = datetime.today().date()
# Parse string
dt = datetime.strptime("2024-01-15", "%Y-%m-%d")
# Format
dt.strftime("%B %d, %Y") # "January 15, 2024"
# Math
tomorrow = now + timedelta(days=1)