Custom Functions in Python#

In this notebook, we’ll explore how to create and use custom functions in Python. Functions are reusable blocks of code that perform specific tasks, making our code more organized and efficient.

Let’s start by defining a simple function that greets a person by name.

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

print(greet("Alice"))
Hello, Alice!

Now, let’s create a function that takes multiple parameters and performs a calculation.

def calculate_rectangle_area(length, width):
    return length * width

print(calculate_rectangle_area(5, 3))
15

Functions can have default parameter values, which are used when the argument is not provided.

def power(base, exponent=2):
    return base ** exponent

print(power(3))      # Uses default exponent of 2
print(power(3, 3))   # Overrides default exponent
9
27

Functions can return multiple values as a tuple.

def min_max(numbers):
    return min(numbers), max(numbers)

result = min_max([1, 5, 3, 9, 2])
print(result)
(1, 9)

We can use *args to allow a function to accept any number of positional arguments.

def sum_all(*args):
    return sum(args)

print(sum_all(1, 2, 3))
print(sum_all(1, 2, 3, 4, 5))
6
15

Similarly, **kwargs allows a function to accept any number of keyword arguments.

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

print_info(name="Alice", age=30, city="New York")
name: Alice
age: 30
city: New York

Functions can be nested within other functions, allowing for more complex logic and encapsulation.

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

add_five = outer_function(5)
print(add_five(3))
8

Lambda functions are small, anonymous functions that can be used for simple operations.

square = lambda x: x**2
print(square(4))

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
16
[1, 4, 9, 16, 25]