Reference library

Python Code Samples

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

6 matches
Strings & text easy

How to Format Strings with Named Placeholders in Python

Format a template string using named placeholders with the str.format() method and a dictionary.

string format placeholders
Python
def format_named(template, data):
    """Format a template string using named placeholders."""
    return template.format(**data)


if __name__ == "__main__":
    template = "Hello {name}, you are {age} years old and live in {city}."
    data = {"name": "Alice", "age": 30, "city": "London"}
    result = format_named(t…
15 0 Open
Strings & text easy

How to Format a Float as Currency in Python

This code defines a function that converts a float to a string formatted as US currency with two decimal places and comma separators.

formatting currency f-string
Python
def format_currency(amount):
    return f"${amount:,.2f}"

if __name__ == "__main__":
    test_amounts = [1234.5, 0, 9999999.999, -42.867]
    for amount in test_amounts:
        print(f"{amount} -> {format_currency(amount)}")
13 0 Open
Strings & text easy

How to Round Numbers with f-strings in Python

Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.

f-string rounding formatting
Python
def main():
    # Values to format with expression-based rounding
    price = 19.995
    tax_rate = 0.0825
    distance = 1234.56789

    # Round inside the f-string expression using round()
    print(f"Price rounded to cents: ${round(price, 2)}")

    # Combine rounding with arithmetic inside the expression
    total…
12 0 Open
Lists & loops easy

Format Lists of Tuples into Numbered Lines in Python

This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.

enumerate formatting lists
Python
def format_students(students):
    formatted = []
    for i, student in enumerate(students, start=1):
        name, grade = student
        formatted.append(f"{i}. {name}: {grade}")
    return "\n".join(formatted)


if __name__ == "__main__":
    students = [
        ("Alice", 92),
        ("Bob", 85),
        ("Charl…
15 0 Open
Files & data easy

How to Build a Dated Backup Filename with Timestamp in Python

Generate unique backup filenames with a timestamp using Python's datetime module and f-strings.

datetime backup filenames
Python
from datetime import datetime

def build_backup_filename(base_name: str, extension: str = "bak") -> str:
    """Generate a dated backup filename with timestamp."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"{base_name}_{timestamp}.{extension}"

if __name__ == "__main__":
    backup_file = bu…
12 0 Open
Observability & SRE easy

How to Create a Deployment Environment Tag in Python

Generate a standardized deployment tag string by combining service and environment names with an f-string.

deployment observability f-string
Python
def mock_env_tag(service, environment):
    return f"{service}-{environment}"

if __name__ == "__main__":
    service = "api-gateway"
    environment = "production"
    tag = mock_env_tag(service, environment)
    print(f"Deployment tag: {tag}")
13 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.