Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

9 matches
Files & data easy

How to Fetch Weather Data from a Public API in Python

Fetches and parses weather data from a free public API using only the Python standard library.

api json weather
Python
import urllib.request
import json

def get_weather(city):
    base_url = f"https://wttr.in/{city}?format=j1"
    with urllib.request.urlopen(base_url) as response:
        data = json.loads(response.read().decode())
    current = data["current_condition"][0]
    temp = current["temp_C"]
    desc = current["weatherDesc…
91 0 Open
Dictionaries & sets easy

How to Parse Query String to Dict with Duplicate Keys in Python

Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.

query-string dict url-parsing
Python
from urllib.parse import parse_qs


def parse_query_to_dict(query_string):
    parsed = parse_qs(query_string, keep_blank_values=True)
    return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}


if __name__ == "__main__":
    query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
13 0 Open
Dictionaries & sets easy

How to Serialize a Dictionary to a Query String in Python

Convert a Python dictionary into a URL-encoded query string using the standard library's urllib.parse.urlencode function.

urllib query-string urlencode
Python
import urllib.parse

def dict_to_query_string(params):
    """Serialize a dictionary to a URL query string."""
    return urllib.parse.urlencode(params)

if __name__ == "__main__":
    data = {
        "name": "Alice Johnson",
        "age": 30,
        "city": "New York",
        "interests": ["coding", "hiking"]
   …
13 0 Open
Automation & scripting easy

How to Cross Post Markdown to dev.to API in Python

A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.

api dev.to markdown
Python
import json
from urllib import request, error


def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
    """
    Mock cross-posting of markdown content to the dev.to API.
    Returns the API response or an error message.
    """
    payload = json.dumps({
        "article": …
10 0 Open
Automation & scripting easy

How to Download a List of URLs to a Directory in Python

This script downloads a list of URLs into a specified directory, creating the folder if needed and keeping original filenames.

urllib download file-io
Python
import urllib.request
from pathlib import Path

def download_urls(url_list, directory):
    """Download each URL in url_list into directory, keeping original filenames."""
    save_dir = Path(directory)
    save_dir.mkdir(parents=True, exist_ok=True)
    
    for url in url_list:
        filename = url.rstrip('/').spl…
16 0 Open
Automation & scripting easy

How to generate website performance reports from HTTP requests in Python

Measure and report website load time, status code, and content size using Python's standard library.

http performance urllib
Python
import urllib.request
import time

def measure_website_load_time(url):
    """Measures total loading time of a website."""
    start_time = time.time()
    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            content = response.read()
            status_code = response.status
            …
38 0 Open
Automation & scripting easy

Post a message to a Slack webhook in Python

Send a message to a Slack webhook endpoint using the standard library's urllib.request, handling the POST request and response cleanly.

slack webhook urllib
Python
import json
from urllib import request

def post_to_slack(webhook_url: str, message: str) -> dict:
    payload = json.dumps({"text": message}).encode("utf-8")
    req = request.Request(
        webhook_url,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    wit…
10 0 Open
API design & gRPC easy

How to Prefix Python API URIs with a Version Slug

Build a versioned API endpoint by optionally adding a version prefix like v1 to the URL path using the stdlib urllib module.

api url urllib
Python
from urllib.parse import urlparse

BASE_URL = "https://api.example.com"

def build_uri(resource, version="v1"):
    """Mock a versioned API URI with an optional v1 prefix."""
    parsed = urlparse(BASE_URL)
    prefix = f"/{version}" if version else ""
    return f"{parsed.scheme}://{parsed.netloc}{prefix}/{resource.l…
11 0 Open
Microservices patterns easy

Retry idempotent GET requests in Python

A Python function that retries an idempotent GET request a fixed number of times with a delay between attempts, raising a RuntimeError only after all retries fail.

retry idempotent urllib
Python
import time
import urllib.error
import urllib.request
from http.client import HTTPException

def fetch_with_retry(url, max_retries=3, delay=1.0):
    for attempt in range(1, max_retries + 1):
        try:
            with urllib.request.urlopen(url, timeout=5) as response:
                return response.read().decode…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.