Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
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 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,…
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.