User-Defined Functions in Python

Creating User-Defined Functions

The syntax for creating a user-defined function in Python is as follows:

code.python
def funcName(arg1, arg2,...):
    """docstring(optional, describes the function)"""
    statements
    return [expression]

def: Required. Marks the start of the function declaration.

funcName: Required. Name of the function (follows Python naming conventions: lowercase with underscores).

arg1, arg2,...: Optional. Argument list of the function. Arguments can have default values (e.g., num=1).

:: Required. Ends the function header.

docstring: Optional. A string literal that describes the function (accessed via __doc__).

statements: Statements to be executed in the function body (must be indented).

return: Optional. Exits the function and returns the value of the expression. If omitted, the function returns None.

Example 1: Create a function named add_one that takes an integer as input and returns the integer plus 1.

code.python
def add_one(num):
    """Return the input integer plus 1."""
    return num + 1

Example 2: Create a function named get_area that calculates the area of a rectangle (length × width).

code.python
def get_area(length, width):
    """Return the area of a rectangle(length × width)."""
    return length * width

Example 3: Create a function named judge_sign that determines whether an integer is positive, negative, or zero.

code.python
def judge_sign(num):
    """Return 'Positive', 'Negative', or 'Zero' based on the input integer."""
    if num > 0:
        return "Positive"
    elif num < 0:
        return "Negative"
    else:
        return "Zero"

Example 4: Create a function named greet with a default argument.

code.python
def greet(name="Guest"):
    """Return a greeting message. Default name is 'Guest'."""
    return f"Hello, {name}!"

Calling User-Defined Functions

User-defined functions in Python must be called explicitly in the code.

Examples:

code.python
# Call add_one
result1 = add_one(5)
print(result1)  # Output: 6
# Call get_area
result2 = get_area(3, 4)
print(result2)  # Output: 12
# Call judge_sign
result3 = judge_sign(-2)
print(result3)  # Output: Negative
# Call greet with default argument
result4 = greet()
print(result4)  # Output: Hello, Guest!
# Call greet with a custom argument
result5 = greet("Alice")
print(result5)  # Output: Hello, Alice!

Notes on Using User-Defined Functions

Indentation: The function body must be indented consistently (typically 4 spaces).

Default Arguments: Default arguments must be placed after non-default arguments. Example: def func(a, b=2) is valid; def func(a=1, b) is invalid.

Return Value: A function can return multiple values (as a tuple). Example:

code.python
def get_min_max(nums):
    return min(nums), max(nums)
min_val, max_val = get_min_max([1, 2, 3, 4])
print(min_val, max_val)  # Output: 1 4

Docstring: Adding a docstring improves code readability and allows others to understand the function’s purpose quickly.