Reference library

Python Code Samples

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

36 matches
Strings & text easy

How to Check and Manipulate Strings in Python

Demonstrates core string inspection and transformation methods like case conversion, trimming, splitting, and membership checks on a sample string.

strings text-processing beginners
Python
text = "  Hello, Python Learners!  "

print(f"Original: '{text}'")
print(f"Lowercase: '{text.lower()}'")
print(f"Uppercase: '{text.upper()}'")
print(f"Title case: '{text.title()}'")
print(f"Stripped: '{text.strip()}'")
print(f"Length: {len(text)}")
print(f"Replace: '{text.replace('Python', 'Programming')}'")
print(f"S…
15 0 Open
Strings & text easy

How to Check if a String is Numeric in Python

This code provides a function to determine if a string represents a valid numeric value using Python's built-in float() conversion.

numeric validation strings
Python
def is_numeric(s):
    """Check if a string represents a valid numeric value."""
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

if __name__ == "__main__":
    test_cases = ["123", "-45.67", "3.14e10", "0x1A", "abc", "12.5.6", "  42  ", ""]
    for case in test_c…
13 0 Open
Strings & text easy

How to Convert Data to Strings in Python

Convert common data types like bytes, numbers, containers, and None to readable strings with a safe helper function.

strings conversion type-conversion
Python
def to_str(value):
    """Convert common types to a readable string, safe for beginners."""
    if isinstance(value, bytes):
        return value.decode("utf-8")
    if isinstance(value, (dict, list, tuple, set)):
        return str(value)
    if value is None:
        return ""
    return str(value)


if __name__ == …
11 0 Open
Strings & text easy

How to Swap Case of Every Character in Python

Swap uppercase to lowercase and lowercase to uppercase for every character in a string using Python's built-in swapcase() method.

string swapcase case conversion
Python
def swap_case(text):
    """
    Swap uppercase to lowercase and lowercase to uppercase 
    for every character in the given string.
    """
    return text.swapcase()

if __name__ == "__main__":
    sample = "Hello World! Python3.9"
    result = swap_case(sample)
    print(f"Input:  {sample}")
    print(f"Output: {r…
14 0 Open
Strings & text easy

Text Processor Functions for Beginners in Python

Demonstrates simple text-processing utilities: word counting, word reversal, whitespace normalization, and lowercase conversion using basic string methods.

text-processing string-methods word-count
Python
def count_words(text):
    """Return the number of words in a string."""
    return len(text.split())

def reverse_words(text):
    """Return the text with words in reverse order."""
    return ' '.join(text.split()[::-1])

def remove_extra_spaces(text):
    """Return text with extra whitespace collapsed to a single s…
13 0 Open
Lists & loops easy

Convert a List of Integers to a Comma-Separated String in Python

Convert a list of integers into a single comma-separated string using a generator expression and str.join.

join list comma
Python
def ints_to_comma_string(numbers):
    return ",".join(str(num) for num in numbers)

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    result = ints_to_comma_string(numbers)
    print(result)
15 0 Open
Lists & loops easy

How to Convert Data Types in Python Lists

Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.

type-conversion loops lists
Python
def convert_data(data):
    """Convert a mixed list of values to strings, ints, and floats."""
    result = []
    for item in data:
        if isinstance(item, (int, float)):
            result.append(str(item))
        elif isinstance(item, str):
            try:
                if '.' in item:
                    r…
13 0 Open
Lists & loops easy

How to Get the Union of Two Lists Without Duplicates in Python

Merge two lists and remove duplicate values using a set, then convert back to a list.

set union merge
Python
def union_without_duplicates(list1, list2):
    return list(set(list1 + list2))

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [3, 4, 5, 6]
    result = union_without_duplicates(list_a, list_b)
    print(f"Union of {list_a} and {list_b}: {result}")
13 0 Open
Lists & loops easy

How to Safely Convert a List of Strings to Integers in Python

Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.

list conversion int conversion error handling
Python
def safe_to_int(values):
    """Safely convert a list of strings to integers, skipping invalid entries."""
    result = []
    errors = []
    for value in values:
        try:
            result.append(int(value))
        except (ValueError, TypeError):
            errors.append(value)
    return result, errors


if …
13 0 Open
Functions & basics easy

How to Write a Normalize Function with Default Parameters in Python

Define a reusable normalize function with configurable default parameters for lowercase conversion, whitespace stripping, and punctuation removal.

functions default-parameters string-processing
Python
def normalize(text, lowercase=True, strip_whitespace=True, remove_punctuation=False):
    """Normalize a string based on configurable options."""
    if lowercase:
        text = text.lower()
    if strip_whitespace:
        text = text.strip()
    if remove_punctuation:
        text = ''.join(char for char in text if…
13 0 Open
Errors & debugging easy

Handle ValueError and ZeroDivisionError in Python with try except

Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.

try-except valueerror zerodivisionerror
Python
def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ValueError as e:
        print(f"ValueError caught: {e}")
        return None
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None
    return result

# Test cases
print(safe_divide…
12 0 Open
Errors & debugging easy

How to Catch ValueError in Python

Shows how to handle a ValueError with try-except so a bad int() conversion doesn't crash the script.

try-except valueerror error-handling
Python
try:
    number = int("not_a_number")
    print(f"Parsed successfully: {number}")
except ValueError as e:
    print(f"Error: {e}")
    print("Please provide a valid integer.")
print("Program continues running.")
16 0 Open
Errors & debugging easy

How to Handle ValueError in Python (try except)

Learn to catch ValueError and other exceptions with try-except blocks in Python using practical division and string-to-float conversion examples.

try-except valueerror error-handling
Python
def divide_numbers(a, b):
    """Divide two numbers and handle ValueError safely."""
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero!"
    except TypeError:
        return "Error: Both inputs must be numbers!"


def parse…
13 0 Open
Errors & debugging easy

Try Except ValueError in Python: Handle Conversion Errors

Catch ValueError exceptions when converting strings to integers or performing arithmetic, returning None on failure instead of crashing.

try-except valueerror exception
Python
def convert_to_int(value):
    try:
        return int(value)
    except ValueError as error:
        print(f"Conversion failed: {error}")
        print(f"Problem value was: {repr(value)}")
        return None


def divide_numbers(numerator, denominator):
    try:
        result = numerator / denominator
        retur…
13 0 Open
Files & data easy

Convert All Markdown Files in a Folder to HTML in Python

Batch convert every .md file in a folder to .html using the `markdown` library with the 'extra' extensions.

markdown html batch-conversion
Python
import os
import markdown
from pathlib import Path

def convert_md_folder_to_html(input_folder="markdown_files", output_folder="html_pages"):
    input_path = Path(input_folder)
    output_path = Path(output_folder)
    output_path.mkdir(exist_ok=True)
    
    for md_file in input_path.glob("*.md"):
        with open…
54 0 Open
Files & data easy

Convert CSV Files to JSON in Python

Convert a CSV file to a JSON file using Python's built-in csv and json modules.

csv json conversion
Python
import csv
import json

def csv_to_json(csv_filepath, json_filepath):
    """Convert a CSV file to a JSON file."""
    with open(csv_filepath, mode='r', newline='') as csv_file:
        reader = csv.DictReader(csv_file)
        data = [row for row in reader]

    with open(json_filepath, mode='w') as json_file:
      …
93 0 Open
Files & data easy

How to Convert CSV Column Types While Reading in Python

Read a CSV file and automatically convert column values to int, float, str, or bool based on type suffixes in the header names.

csv type-conversion file-io
Python
import csv
from pathlib import Path
from typing import Any

def read_csv_with_types(filepath: str) -> list[dict[str, Any]]:
    """Read CSV and convert column types based on header suffixes."""
    converters = {
        "int": int,
        "float": float,
        "str": str,
        "bool": lambda v: v.strip().lower(…
11 0 Open
Files & data easy

How to Convert Images Between Formats in Python

Use the Pillow library to open an image from one file format and save it to another, with error handling for missing files or conversion issues.

pillow image conversion file i/o
Python
from PIL import Image
import sys

def convert_image_format(input_path, output_path):
    try:
        img = Image.open(input_path)
        img.save(output_path)
        print(f"Converted {input_path} to {output_path}")
    except FileNotFoundError:
        print(f"Error: File {input_path} not found")
        sys.exit(…
39 0 Open
Files & data easy

How to Transcode a File from Latin-1 to UTF-8 in Python

Read a latin1-encoded text file and rewrite it as UTF-8 using Python's pathlib and encoding parameters.

encoding utf8 latin1
Python
from pathlib import Path

def transcode_to_utf8(input_path, output_path):
    """Read a latin1-encoded file and write it as UTF-8."""
    source = Path(input_path)
    target = Path(output_path)
    
    with source.open(encoding='latin1') as infile:
        content = infile.read()
    
    with target.open('w', encod…
12 0 Open
Dictionaries & sets easy

Convert Lists and Dictionaries to Sets in Python

Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.

dict set conversion
Python
def convert_to_dict(data):
    """Convert list of tuples or lists into a dictionary."""
    return dict(data)


def convert_to_set(data):
    """Convert list or dictionary into a set of its keys/values."""
    if isinstance(data, dict):
        return set(data.keys())
    return set(data)


def convert_collection(data…
14 0 Open
Dictionaries & sets easy

Convert namedtuple to dict with asdict in Python

Convert a namedtuple instance into an ordinary dictionary using the asdict function from the collections module's namedtuple utility.

namedtuple dict asdict
Python
from collections import namedtuple, asdict

def main():
    # Define a namedtuple for a person
    Person = namedtuple("Person", ["name", "age", "city"])
    person = Person(name="Alice", age=30, city="New York")
    
    # Convert namedtuple to dict
    person_dict = asdict(person)
    
    print("Original namedtuple…
12 0 Open
Dictionaries & sets easy

How to convert string values to int or float in Python dicts

Recursively convert string values in nested dicts and lists to ints or floats when possible, leaving other strings untouched.

dict type-conversion recursion
Python
def coerce_str_values(data):
    """Recursively convert string values that look like ints or floats."""
    if isinstance(data, dict):
        return {key: coerce_str_values(val) for key, val in data.items()}
    elif isinstance(data, list):
        return [coerce_str_values(item) for item in data]
    elif isinstance…
12 0 Open
Dictionaries & sets easy

Parse Env Vars into Typed Dict in Python

Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.

env-vars type-conversion dict
Python
import os
from typing import Any, Dict


def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
    """Parse a list of environment variable names into a typed dict.

    Each variable is parsed as:
    - bool: "true"/"false" (case-insensitive)
    - int: if it can be converted t…
13 0 Open
OOP & classes easy

How to Convert Data Types in Python with a Helper Class

This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.

oop classes data-conversion
Python
class DataConverter:
    """A beginner-friendly helper class for common data conversions."""
    
    def __init__(self, data):
        self.data = data
    
    def to_list(self):
        """Convert string data (comma-separated) to a list."""
        if isinstance(self.data, str):
            return [item.strip() for…
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.