⚙️

How to Write Functions in Python

PythonBeginner

Create reusable blocks of code with functions.

Code Example

Python
# Functions in Python
def greet(name, greeting="Hello"):
    """Greet someone with a custom message."""
    return f"{greeting}, {name}!"

# Basic call
print(greet("Alice"))
print(greet("Bob", "Hi"))

# Multiple return values
def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(f"\nMin: {lo}, Max: {hi}")

# Lambda functions
square = lambda x: x ** 2
print(f"\n5² = {square(5)}")

# *args and **kwargs
def flexible(*args, **kwargs):
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

flexible(1, 2, 3, name="test", value=42)

Explanation

Functions are defined with def. They can have default parameters, return multiple values, and accept variable arguments.

Related Tutorials