Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Add Type Hints to Function Parameters and Return in Python
Add type hints to function parameters and return values in Python for clearer, more maintainable code using the typing module.
from typing import List, Optional, Dict
def average(numbers: List[float]) -> float:
return sum(numbers) / len(numbers)
def full_name(first: str, last: Optional[str] = "") -> str:
return f"{first} {last}".strip()
def build_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
us…
How to Count Items with Default Parameters in Python
Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.
def count_items(items, start=0, step=1):
"""Count items in a list with configurable start value and step."""
count = start
for item in items:
print(f"{count}: {item}")
count += step
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry"]
print("Default parameters (start=0…
How to Create Functions with Default Parameters in Python
This code defines two Python functions using default parameters to handle missing arguments gracefully, demonstrating how to work with optional inputs and keyword arguments.
def greet(name="Guest", greeting="Hello", punctuation="!"):
"""Generate a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def create_profile(username="anonymous", age=0, city="Unknown", active=True):
"""Create a user profile dictionary with default values."""
r…
How to Define a Function with Default Parameter Values in Python
This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.
def greet(name: str = "World", punctuation: str = "!") -> str:
"""Return a greeting message using default parameter values."""
message = f"Hello, {name}{punctuation}"
return message
if __name__ == "__main__":
# Call with no arguments – uses both defaults
print(greet())
# Call with one argume…
How to Group a List into Chunks in Python
Split a list into smaller groups of a fixed size using a reusable function with a default parameter.
def make_groups(numbers, group_size=2):
"""Splits a list into smaller groups of a given size."""
groups = []
for i in range(0, len(numbers), group_size):
groups.append(numbers[i:i + group_size])
return groups
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6, 7]
print("Default size…
How to Merge Lists in Python with Default Parameters
This Python function merges two lists using the + operator and demonstrates default parameters, allowing the second argument to be omitted.
def merge_lists(list1, list2=["default"]):
"""Merge two lists and return the combined result."""
return list1 + list2
if __name__ == "__main__":
# Example with default parameter
print("With default:", merge_lists([1, 2, 3]))
# Example with both arguments provided
print("With custom:", me…
How to Parse Function Parameters with Defaults in Python
Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.
def greet(name, greeting="Hello", punctuation="!"):
"""Greet a person with customizable greeting and punctuation."""
return f"{greeting}, {name}{punctuation}"
def describe_fruit(fruit, color="unknown", ripe=False):
"""Describe a fruit with optional attributes."""
status = "ripe" if ripe else "not ripe…
How to Sort a List of Numbers in Python with Default Parameters
Define a reusable sort function that uses a default parameter to sort a list of numbers in ascending or descending order.
def sort_numbers(numbers, reverse=False):
"""Sort a list of numbers in ascending or descending order."""
return sorted(numbers, reverse=reverse)
def main():
numbers = [5, 2, 9, 1, 7, 3]
# Default sort (ascending)
ascending = sort_numbers(numbers)
print(f"Ascending: {ascending}")
…
How to Use Default Parameter Values in Python Functions
Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
# Using defaults
print(greet("Alice"))
# Overriding first default
print(greet("Bob", "Hi"))
# Overrid…
How to Use Default Parameter Values in Python Functions
This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.
def greet(name, greeting="Hello", punctuation="!"):
message = f"{greeting}, {name}{punctuation}"
print(message)
if __name__ == "__main__":
greet("Alice")
greet("Bob", "Hi")
greet("Charlie", "Hey", "?")
How to Use Default Parameters in Python Functions
A beginner-friendly Python function that uses default parameters to compare two numbers with equal, greater, or less operations.
def compare(a, b, operation="equal"):
if operation == "equal":
return a == b
elif operation == "greater":
return a > b
elif operation == "less":
return a < b
else:
return f"Unknown operation: {operation}"
if __name__ == "__main__":
print(compare(5, 5))
print(com…
How to Use Default Parameters in Python Functions
Define a Python function with default parameters and call it using positional and keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Concatenate a greeting message with default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice")) # Uses both defaults
print(greet("Bob", "Hi")) # Uses default punctua…
How to Use Default Parameters in Python Functions
Create a simple function with default parameters to build flexible, reusable greetings in Python.
def greet(name, greeting="Hello", punctuation="!"):
"""Return a personalized greeting message."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charlie", greeting="Hey", punctuation="?"))…
How to Use Default Parameters with Python's Split Function
Create a reusable Python wrapper around str.split with sensible default parameters for delimiter and maxsplit, showing beginners how default arguments work.
def split_with_defaults(text, delimiter=" ", maxsplit=-1):
"""
Split a string into parts using a delimiter.
Default behavior: split on spaces, unlimited splits.
"""
parts = text.split(delimiter, maxsplit)
return parts
if __name__ == "__main__":
# Example usage with defaults and custom par…
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.
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…
How to use function defaults in Python
Define Python functions with default parameter values so callers can omit arguments and use sensible fallbacks.
def greet(name="Guest", greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def describe_pet(pet_name, animal_type="dog"):
"""Display information about a pet with a default animal type."""
print(f"I have a {animal_type…
Python Filter Function with Default Parameters for Beginners
Create a reusable filter function with default parameters to keep or exclude numbers above or below a threshold.
def filter_numbers(numbers, threshold=0, reverse=False):
"""Return numbers that pass the threshold filter.
Args:
numbers: list of numbers to filter
threshold: minimum value to keep (default 0)
reverse: if True, keep numbers below threshold (default False)
"""
if reverse:
…
Python Function Default Parameters Explained with Examples
Learn how to define Python functions with default parameter values and call them with fewer arguments than declared.
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
def calculate_area(length, width=1, unit="sq units"):
area = length * width
return f"Area: {area} {unit}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charl…
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.
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…
How to build a function calling schema dict in Python
Build an OpenAI-compatible function calling schema dictionary with a helper function that takes name, description, parameters, and required fields.
import json
from typing import Dict, Any, List, Optional
def build_function_schema(
name: str,
description: str,
parameters: Optional[Dict[str, Any]] = None,
required: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Build an OpenAI-compatible function calling schema dictionary."""
schema: …
Mock SSM Parameter Store Get Parameters by Path in Python
This code implements a simple mock of the AWS SSM Parameter Store get_parameters_by_path API, returning parameters under a given path with recursive and non-recursive options.
import json
class MockSSM:
def __init__(self, parameters):
self.parameters = parameters
def get_parameters_by_path(self, path, recursive=True):
result = []
for key, value in self.parameters.items():
if recursive:
if key.startswith(path):
…
How to Implement Pagination with Offset and Limit in Python
A mock API pagination pattern that parses page and per_page query parameters, computes offset and limit, and slices a list of items for a specific page.
def paginate(items, page, per_page):
offset = (page - 1) * per_page
return items[offset:offset + per_page]
def parse_query_params(query_string):
params = {}
if query_string:
for pair in query_string.split("&"):
key, value = pair.split("=")
params[key] = value
page …
Grid Search Hyperparameters in Python
Perform exhaustive grid search over hyperparameter combinations using itertools.product and a scoring function.
import itertools
def grid_search(param_grid, score_fn):
"""Perform exhaustive grid search over hyperparameter combinations."""
keys = param_grid.keys()
names = list(keys)
values = [param_grid[name] for name in names]
results = []
for combination in itertools.product(*values):
params =…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.