Skip to content

Python Code Snippets

This page collects short examples that are actually useful in day-to-day Python work.

items = ["api", "worker", "scheduler"]
for item in items:
print(item)
user = {
"name": "Ava",
"role": "admin",
"active": True,
}
print(user["name"])
from collections import Counter
values = ["python", "python", "api", "docs"]
counts = Counter(values)
print(counts)
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
import json
payload = {"status": "ok", "items": 3}
with open("output.json", "w", encoding="utf-8") as file:
json.dump(payload, file, indent=2)
try:
value = int("42")
except ValueError:
value = 0
print(value)
import os
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise RuntimeError("OPENAI_API_KEY is not set")
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)