Sponsored Reserved space — layout preview until AdSense is connected

Reference library

Python code samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

3 matches
Sponsored Reserved space — layout preview until AdSense is connected
Files & data medium

Parse JSON safely

Load JSON from a string and handle decode errors without crashing.

json parsing stdlib
Python
import json

payload = '{"name": "Ada", "skills": ["Python", "math"]}'

try:
    data = json.loads(payload)
    print(data["name"])
    print(", ".join(data["skills"]))
except json.JSONDecodeError as exc:
    print(f"Invalid JSON: {exc}")
3 0 Open
Errors & debugging easy

Try/except ValueError

Convert user input to int inside try/except and show a friendly message.

errors try-except input
Python
raw = "42"

try:
    value = int(raw)
    print(f"Parsed: {value}")
except ValueError:
    print(f"Could not parse {raw!r} as an integer.")
3 0 Open
Errors & debugging medium

Raise a clear custom error

Validate input early and raise ValueError with a helpful message.

errors raise validation
Python
def positive_only(n):
    """Return n if it is strictly positive."""
    if n <= 0:
        raise ValueError(f"Expected a positive number, got {n}")
    return n


print(positive_only(5))
try:
    positive_only(-1)
except ValueError as exc:
    print(exc)
3 1 Open

Browse by section

Each section groups closely related Python snippets.