</>
CompilerOnline
Open Interactive Editor

Python Functions

Declaring Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Functions help break down complex tasks into smaller, manageable, reusable modules, promoting the DRY (Don't Repeat Yourself) principle.

In Python, a function is defined using the def keyword, followed by the function name and parentheses containing any parameters. The body of the function must be indented.

Python functions are highly flexible. They support positional arguments, keyword arguments, default parameters (e.g., greeting="Hello"), and variable-length arguments using *args for tuples and **kwargs for dictionaries.

Docstrings

It is best practice to add a documentation string (docstring) as the first line of the function body using triple quotes. This helps other developers understand the function's purpose, arguments, and return types, and is automatically read by help tools.

Python also supports lambda functions, which are small, anonymous, single-expression functions. They are declared using the lambda keyword and are useful for short-lived operations like sorting or filtering collections.

Keyword and Default Arguments

Default arguments are parameters that assume a default value if no value is provided in the function call. Keyword arguments allow you to pass arguments in any order by specifying the parameter name, which prevents mistakes in functions with many parameters.

python
def introduce(name, role="Developer"):
    print(f"Name: {name}, Role: {role}")

introduce("Alice")
introduce("Bob", "Manager")
python
def greet(name, greeting="Hello"):
    """Return a customized greeting."""
    return f"{greeting}, {name}!"

message = greet("Bob", "Good morning")
print(message)
print(greet("Alice"))