Fundamentals 5 min read

Defining Functions in Python: Syntax, Parameters, and Return Values

This article explains how to define functions in Python, covering the def syntax, various parameter passing methods—including positional, default, keyword, *args, and **kwargs—and how to return single or multiple values, illustrated with clear code examples and a comprehensive calculate_area demonstration.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Defining Functions in Python: Syntax, Parameters, and Return Values

Defining functions is a core skill in programming that allows code to be organized into reusable blocks. Python provides a simple yet powerful way to define functions using the def keyword, followed by a function name, an optional parameter list, and a function body.

Simple function example

def greet():
    print("Hello, world!")

greet()  # Output: Hello, world!

Parameter passing

Positional arguments are the most common; arguments are passed in the order defined.

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!

Default arguments allow a parameter to have a default value if none is provided.

def greet(name="world"):
    print(f"Hello, {name}!")

greet()         # Output: Hello, world!

greet("Bob")    # Output: Hello, Bob!

Keyword arguments let callers specify values by parameter name, removing the need to follow positional order.

def greet(first_name, last_name):
    print(f"Hello, {first_name} {last_name}!")

greet(last_name="Smith", first_name="John")  # Output: Hello, John Smith!

Variable‑length arguments using *args and **kwargs collect extra positional arguments into a tuple and extra keyword arguments into a dictionary.

def greet_everyone(*names):
    for name in names:
        print(f"Hello, {name}!")

greet_everyone("Alice", "Bob", "Charlie")

def greet_with_details(**details):
    for key, value in details.items():
        print(f"{key}: {value}")

greet_with_details(name="David", age=30)

Return values

A function can return a single value with return . If no return is specified, None is returned implicitly.

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

Functions can also return multiple values, which are actually returned as a tuple that can be unpacked.

def get_user_info():
    return "Alice", 25, "Engineer"

name, age, occupation = get_user_info()
print(name, age, occupation)  # Output: Alice 25 Engineer

Combined example

The following function integrates all the concepts above, demonstrating positional, *args, **kwargs, and return handling while calculating the area of a rectangle or a circle.

def calculate_area(shape, *dimensions, **options):
    """
    Calculate the area of a shape, supporting rectangle and circle.
    :param shape: shape name ('rectangle' or 'circle')
    :param dimensions: for rectangle provide two dimensions; for circle provide the radius.
    :param options: additional options, e.g., whether to print the result.
    :return: computed area
    """
    if shape == 'rectangle':
        length, width = dimensions
        area = length * width
    elif shape == 'circle':
        radius, = dimensions
        area = math.pi * radius ** 2
    else:
        raise ValueError("Unsupported shape")
    if options.get('print_result', False):
        print(f"The area of {shape} is {area:.2f}")
    return area

# Usage examples
calculate_area('rectangle', 10, 5, print_result=True)
calculate_area('circle', 7, print_result=True)

This tutorial provides a comprehensive overview of Python function definition, parameter handling, and return mechanisms, supported by practical code snippets.

PythonFunctionsParametersProgramming Basicsreturn values
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.