Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
def compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
…
How to Use Template Strings for Substitution in Python
This code shows how to use Python's Template class for safe string substitution, replacing placeholders like $name with actual values.
from string import Template
def format_user_message(name, role, company):
template = Template("Hello $name! We are glad to have you as our $role at $company.")
return template.substitute(name=name, role=role, company=company)
if __name__ == "__main__":
result = format_user_message("Alice", "Python Develo…
Extract Data by Type from a List in Python: Numbers and Strings
Loop through a mixed list to filter out numeric and string values into separate lists.
def extract_numbers(items):
"""Extract all numeric values from a mixed list."""
numbers = []
for item in items:
if isinstance(item, (int, float)) and not isinstance(item, bool):
numbers.append(item)
return numbers
def extract_strings(items):
"""Extract all string values from a…
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.
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…
How to Filter None Values from a Mixed List in Python
Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.
mixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]
filtered_list = [item for item in mixed_list if item is not None]
print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
How to Filter a List in Python with a Loop
Filter a list of numbers by a threshold using a for loop and append results to a new list, then print the filtered values and count.
ages = [34, 12, 45, 8, 67, 21, 18, 55, 3]
threshold = 18
adults = []
for age in ages:
if age >= threshold:
adults.append(age)
print("All ages:", ages)
print("Adults (18+):", adults)
print("Count of adults:", len(adults))
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.
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}")
How to Normalize a List of Numbers in Python
This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.
def normalize(data):
"""
Normalize a list of numeric values to the range [0, 1].
Returns a new list, leaving the original unchanged.
"""
if not data:
return []
min_val = min(data)
max_val = max(data)
# Handle the edge case where all values are identical
if min_val …
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.
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 …
Replace Negative Values in a List with Python
This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.
def replace_if_negative(values, replacement=0):
return [replacement if value < 0 else value for value in values]
if __name__ == "__main__":
numbers = [5, -3, 8, -1, 0, -7, 2]
result = replace_if_negative(numbers)
print(f"Original: {numbers}")
print(f"Replaced: {result}")
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 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 Document Python Functions with Google Style Docstrings
Document a Python function with a Google style docstring to describe arguments and return values clearly.
def calculate_rectangle_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle in meters.
width (float): The width of the rectangle in meters.
Returns:
float: The area of the rectangle in square meters.
…
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 Read Environment Variables in Python with Default Values
Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.
import os
database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
How to Return Multiple Values from a Python Function
This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.
def get_user_stats(name, score, level):
"""Return multiple values as a tuple."""
return name, score, level
if __name__ == "__main__":
result = get_user_stats("Alice", 95, 3)
print(result)
print(type(result))
# Unpacking into individual variables
player_name, player_score, player_level…
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 Validate Function Arguments in Python
Shows how to manually check argument types and values in a Python function, raising clear TypeError and ValueError messages.
def calculate_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle with manual type validation."""
if not isinstance(length, (int, float)) or isinstance(length, bool):
raise TypeError(f"length must be a number, got {type(length).__name__}")
if not isinstance(width, (int,…
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 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 Catch KeyError with a Default Value in Python Dictionaries
Safely retrieve dictionary values while catching KeyError and handling None values by returning a default.
def get_value(data, key, default=None):
"""
Safely get a value from a dictionary, returning a default if the key
is missing or the value is None.
"""
try:
value = data[key]
return value if value is not None else default
except KeyError:
return default
if __name__ == "_…
How to check for None and raise helpful errors in Python
A defensive function that explicitly validates data, keys, and values — raising descriptive ValueError and KeyError exceptions before returning a result.
def get_value(data, key):
if data is None:
raise ValueError("data cannot be None")
if key not in data:
raise KeyError(f"key '{key}' not found in data")
result = data[key]
if result is None:
raise ValueError(f"value for key '{key}' is None")
return result
if __name__ == "__…
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.