Python Functions

  • Post category:python
  • Reading time:12 mins read

Introduction

In Python, functions are reusable blocks of code that perform a specific task. They allow you to break down your program into smaller, modular components, making your code more organized, easier to understand, and easier to maintain. Functions help avoid redundancy by allowing you to reuse the same code multiple times without having to rewrite it.

Defining a Function

In Python, you can define a function using the def keyword followed by the function name and parentheses containing any parameters the function accepts. You will define the body of functions below the function definition.

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

Calling a Function

You can simply call a function by using its name followed by parentheses containing any arguments the function requires.

greet("Shivaay")

# Output
Hi Shivaay!!!

Parameters and Arguments

Parameters are variables listed inside the parentheses in the function definition. The values that you pass while calling a function is called arguments. In the example above, name is a parameter, and "Alice" is the argument passed to the greet function.

Function with return values

Functions can also return values using the return statement. This allows the function to compute a value and return it to the caller. Here is an example:

def sum(x, y):
    return x + y

Calling a Function with Return Value

You can capture the return value of a function by assigning it to a variable or using it in an expression.

result = sum(10, 10)
print("Result: ", result)

# Output
Result:  20

Function with Default Parameters

You can provide default values for parameters in a function. If a default value is provided, the function can be called without providing a value for that parameter.

def greet(name="Proedu.co"):
    print("Hello, " + name + "!")

When calling a function, you can use keyword arguments to specify the values of parameters by their names.

greet(name="Shivaay")
greet()

# Output
Hello, Shivaay!
Hello, Proedu.co!

Passing Arbitrary Arguments ( *args ) to a function

In Python, you can use *args as a parameter in a function definition to pass a variable number of arguments to the function. The *args parameter allows you to accept any number of positional arguments, and it collects these arguments into a tuple within the function. This is useful when you’re unsure about the number of arguments that will be passed to the function.

Here’s a basic example of using *args:

def my_function(*args):
    for arg in args:
        print(arg)


my_function(1, 2, 3, 4, 5)

# Output
1
2
3
4
5

In this example, *args allows the function my_function to accept any number of arguments. When the function is called with multiple arguments (1, 2, 3, 4, 5), they are collected into a tuple named args within the function, and the for loop iterates over this tuple, printing each argument.

You can also combine *args with other parameters in the function definition. However, *args must come after any positional parameters in the function signature.

def my_func(arg1, *args):
    final_string = arg1
    for arg in args:
        final_string += " " + arg
    return final_string

print(my_func("Hello", "Proedu.co"))
print(my_func("Hello", "Proedu.co", "!!!"))

# Output
Hello Proedu.co
Hello Proedu.co !!!

In this example, the function concatenate accepts a prefix string followed by any number of additional strings. The prefix is concatenated with all the additional strings passed as arguments using *args.

Using *args, you can create functions that are more flexible and can handle varying numbers of arguments, making your code more versatile and adaptable to different use cases.

Keyword Arguments

In Python, you can also use keyword arguments to pass values to a function. Keyword arguments are arguments preceded by identifiers (keywords) when calling a function. These keywords tell the function which parameter each argument should be assigned to, allowing you to pass arguments in any order.

Here’s a basic example of using keyword arguments:

def greet(name, age):
    print(f"Hello {name}. You are {age} years old.")

greet(name="Shivaay", age=6)
greet(age=6, name="Shivaay") # Passing arguments in a different order.

# Output
Hello Shivaay. You are 6 years old.
Hello Shivaay. You are 6 years old.

Keyword arguments are particularly useful when a function has many parameters, and you want to make it clear which argument corresponds to which parameter, regardless of their order.

You can also combine positional arguments with keyword arguments when calling a function. However, positional arguments must come before keyword arguments.

def greet_func(name, age):
    print("Hello {}! You are {} years old.".format(name, age))

greet_func("Shivaay", age=6)

# Output
Hello Shivaay! You are 6 years old.

Arbitrary Keyword Arguments ( **kwargs )

In Python, you can use **kwargs as a parameter in a function definition to pass a variable number of keyword arguments to the function. The **kwargs parameter allows you to accept any number of keyword arguments, and it collects these arguments into a dictionary within the function. This is useful when you want to handle named arguments of unknown quantity or names.

Here’s a basic example of using **kwargs:

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


kwargs_func(name="Shivaay", age=6, city="Haridwar")

# Output
name: Shivaay
age: 6
city: Haridwar

You can also combine **kwargs with other parameters in the function definition. However, **kwargs must come after any positional parameters and before any other keyword parameters in the function signature.

Using positional parameter with **kwargs

def kwargs_func(name, **args):
    print("Name: ",name)
    for key, value in args.items():
        print(f"{key}: {value}")


kwargs_func("Shivaay", age=6, city="Haridwar")

# Output
Name:  Shivaay
age: 6
city: Haridwar

Python Lambda functions

In Python, a lambda function is a small anonymous function defined using the lambda keyword. Lambda functions can have any number of parameters, but they can only have one expression. They are useful for creating short, simple functions without needing to define them using the def keyword.

The basic syntax of a lambda function is as follows:

lambda arguments: expression

Here’s a simple example of a lambda function that adds two numbers:

add_func = lambda x, y: x + y
print(add_func(10, 2))

# Output
12

In this example, lambda x, y: x + y defines a lambda function that takes two arguments x and y, and returns their sum.

Lambda functions can also be assigned to variables, passed as arguments to other functions, or used within list comprehensions.

Using Lambda Functions with Built-in Functions

Lambda functions are often used in combination with built-in functions like map(), filter(), and reduce(). These functions expect a function as their first argument, and lambda functions are a convenient way to define simple functions on-the-fly.

Example 1: Using Lambda with map()

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

# Output
[1, 4, 9, 16, 25]

In this example, map() applies the lambda function to each element of the numbers list, squaring each element.

Example 2: Using Lambda with filter()

numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  

# Output: 
[2, 4]

In this example, filter() uses the lambda function to filter out only the even numbers from the numbers list.

Example 3: Using Lambda with sorted()

fruits = ["apple", "banana", "cherry", "date"]
sorted_fruits = sorted(fruits, key=lambda x: len(x))
print(sorted_fruits)  

# Output: 
['date', 'apple', 'banana', 'cherry']

In this example, sorted() sorts the fruits list based on the length of each string, using a lambda function as the sorting key.

Lambda functions are a powerful tool for creating quick, one-off functions without the need for a formal function definition. However, they should be used judiciously and for simple tasks, as they can make the code less readable if overused.