Call functions

Defining Functions

A function in Python is defined using the def keyword, followed by the function name, parentheses (which may include parameters), and a colon. The function body contains the code to be executed.

Example:

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

Calling Functions

To call a function, you use the function name followed by parentheses. If the function requires parameters, you pass the arguments within the parentheses.

Example:

greet("Alice")

This will output: Hello, Alice!

Return Values

Functions can return values using the return statement. If no return statement is used, the function returns None by default.

Example:

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

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

Positional and Keyword Arguments

When calling a function, arguments can be passed by position or by keyword.

Example:

def display_info(name, age):
    print(f"Name: {name}, Age: {age}")

# Positional arguments
display_info("Alice", 30)

# Keyword arguments
display_info(age=30, name="Alice")

Default Arguments

Functions can have default parameter values. If an argument is not provided, the default value is used.

Example:

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

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

Variable-Length Arguments

Python allows functions to accept an arbitrary number of arguments using *args for positional arguments and **kwargs for keyword arguments.

Example:

def summarize(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

summarize(1, 2, 3, a=4, b=5)

Output:

Positional arguments: (1, 2, 3)
Keyword arguments: {'a': 4, 'b': 5}

Higher-Order Functions

Functions can be passed as arguments to other functions or returned from other functions.

Example:

def apply_function(func, value):
    return func(value)

def square(x):
    return x * x

result = apply_function(square, 5)
print(result)  # Output: 25

Lambda Functions

Lambda functions are small anonymous functions defined with the lambda keyword. They are used for short, throwaway functions.

Example:

multiply = lambda x, y: x * y
print(multiply(2, 3))  # Output: 6

Nested Functions

Functions can be defined within other functions, creating a closure. This is useful for encapsulating functionality.

Example:

def outer_function(msg):
    def inner_function():
        print(msg)
    return inner_function

my_func = outer_function("Hello, World!")
my_func()  # Output: Hello, World!

Recursion

A function can call itself, which is known as recursion. This is useful for problems that can be broken down into simpler, repetitive tasks.

Example:

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # Output: 120

Decorators

Decorators are a powerful feature that allows you to modify the behavior of a function or class. They are functions that return functions.

Example:

def decorator_function(original_function):
    def wrapper_function(*args, **kwargs):
        print(f"Wrapper executed before {original_function.__name__}")
        return original_function(*args, **kwargs)
    return wrapper_function

@decorator_function
def display():
    print("Display function ran")

display()

Output:

Wrapper executed before display
Display function ran

Understanding how to define and call functions in Python is essential for writing efficient and reusable code. Functions help to organize code logically, make it more readable, and reduce redundancy.