Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Functions: Definitions, Parameters, and Return Values

Tech Aug 8 18

In Python, a function is defined using the def keyword, followed by the function name and parentheses. The code block within the function is indented. It is best practice to include a docstring—a string literal that appears as the first statement in a function—to describe its purpose.

def send_notification():
    """Sends a system notification to the user."""
    print("Notification sent successfully.")

# Invoking the function
send_notification()

# Accessing the docstring
print(send_notification.__doc__)

Function Variants

Functions can be categorized based on their paramter requirements:

  1. Parameter-less Functions: These operate independently without requiring external input.
  2. Parameterized Functions: These require input data (arguments) to execute their logic, similar to a tool needing specific attachments to function.
  3. Stub Functions: These act as placeholders for future implementation. They typically contain a pass statement to avoid syntax errors.
# Stub function example
def process_data():
    """TODO: Implement data processing logic later."""
    pass

Definition Phase Behavior

During the definition phase, Python checks the syntax of the functon but does not execute the body. Logic errors or undefined variable references within the function body will only raise exceptions when the function is actually called.

def execute_task():
    """This function passes syntax check but fails at runtime."""
    print(undefined_variable)

# No error occurs here during definition
# Calling execute_task() would raise a NameError

Return Values

The return statement is used to exit a function and pass a value back to the caller. If no return statement is specified, or return is written without an expression, the function returns None.

Key Characteristics of Return

  1. Implicit None: A function returns None by default if no return value is provided.
  2. Termination: Execution of the function stops immediately upon hitting a return statement. Any code following return is ignored.
  3. Multiple Values: Python allows returning multiple values separated by commas. These values are automatically packed into a tuple.
def fetch_config():
    """Returns a tuple of configuration settings."""
    host = "localhost"
    # Returns multiple values as a tuple: (int, str, dict)
    return 8080, "active", {"timeout": 30}

settings = fetch_config()
print(settings)  # Output: (8080, 'active', {'timeout': 30})

Function Parameters

Parameters allow data to be passed into functions. They act as variables that are initialized during the function call.

Formal Parameters (Parameters)

These are the variables listed in the function definition. They act as placeholders for the values the function expects.

  • Positional Parameters: Required arguments that must be provided in the correct order.
  • Default Parameters: Parameters that assume a default value if no argument is passed. Default parameters must always follow positional parameters in the definition.
def build_profile(username, role="guest"):
    """Creates a user profile with a default role."""
    print(f"User: {username}, Role: {role}")

build_profile("alice")          # Uses default role
build_profile("bob", "admin")   # Overrides default role

Type Hinting

Python supports optional type hints to indicate the expected data types for parameters and return values. While these improve readability and tooling support, they are not enforced at runtime.

def calculate_area(radius: float) -> float:
    """Calculates the area of a circle."""
    return 3.14159 * (radius ** 2)

Actual Parameters (Arguments)

These are the actual values passed to the function during a call.

  • Positional Arguments: Values passed in order; the number of arguments must match the number of positional parameters.
  • Keyword Arguments: Values passed by explicitly naming the parameter. This allows passing arguments out of order. Keyword arguments must come after positional arguments.
def create_user(name, age, country):
    print(f"Name: {name}, Age: {age}, Country: {country}")

# Positional arguments
create_user("John", 25, "USA")

# Keyword arguments (order changed)
create_user(age=30, name="Dana", country="Canada")

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.