Tutorial

Functions in Python

9 min read

Functions in Python are an essential building block programming language. They allow us to wrap up a chunk of code and give it a name, making it reusable and easier to understand. In Python, functions are no exception.

They are simple to use, and they can greatly improve the structure and readability of your code. Whether we are a beginner or experienced programmers, understanding how to use functions in Python is a critical skill.

In this article, we will dive into the basics of functions in Python, including how to define and call them, pass arguments, and return values. We’ll also cover some advanced topics such as lambda functions or anonymous functions and function closures.

Types of Functions in Python

In Python, there are several types of functions, including:

  • Built-in functions – These are the functions that are already available in Python and can be used without importing any module, such as print(), len(), etc.
  • User-defined functions – These are functions that the programmer creates to perform specific tasks. Such as a function to calculate the sum of two numbers.
  • Anonymous functions (lambda functions) – These are small, one-line functions that are defined using the lambda keyword. They are also known as throw-away functions as they are used for short-term tasks and are not meant to be reusable.
  • Higher-order functions – These are functions that take other functions as arguments and/or return functions as output.
  • Recursive functions – These are functions that call themselves to solve a problem by breaking it down into smaller sub-problems.
  • Generator functions – These are functions that generate a sequence of values and can be used in a for loop, making them more memory-efficient than traditional functions.

Function Declaration in Python

In Python, a function is declared using the def keyword, followed by the function name, a set of parentheses, and a colon. The code inside the function is indented and the function ends when the indentation returns to the previous level.

The general syntax for declaring a function in Python is as follows:

def function_name(arguments):
    # code inside the function
    return [expression]

The function name must be a valid Python identifier and the arguments, if any, are defined within the parentheses.

The return statement is used to return a value from the function, but it is optional. If the function doesn’t return a value, it is implicitly considered as returning None.

Calling a Function in Python

In Python, we can call a function by using its name followed by a set of parentheses.

The syntax for how to call a function in Python:

function_name(arguments)

Example of Python function call-

def greeting(name):
    print("Hello, " + name)

greeting("John")  
# Output: "Hello, John"

Here, we have defined a function greeting that takes a single argument name and prints a greeting message.

To call the function, we use the function name greeting followed by the argument “John” in parentheses. This will execute the code inside the function and print “Hello, John“.

Arguments in a Python Function

In Python, a function can take zero or more arguments.

The arguments are specified in the function definition between the parentheses following the function name.

The arguments can be used inside the function to perform the desired task.

There are three types of arguments in Python:

  1. Positional arguments – These are the most common type of arguments and are passed to the function in the same order as they are declared in the function definition.
  2. Keyword arguments – These are arguments passed to the function using the argument name and its value. The order of the keyword arguments does not matter.
  3. Default arguments – These are arguments that have a default value specified in the function definition. If a value is not provided for the argument, the default value will be used.

Example of arguments in Python function:

def print_info(name, age=20, city="New York"):
    print("Name:", name)
    print("Age:", age)
    print("City:", city)

print_info("John")
# Output:
# Name: John
# Age: 20
# City: New York

print_info("Jane", 25)
# Output:
# Name: Jane
# Age: 25
# City: New York

print_info("Jim", city="London")
# Output:
# Name: Jim
# Age: 20
# City: London

print_info("Jane", 25, "Paris")
# Output:
# Name: Jane
# Age: 25
# City: Paris

Here, the function print_info takes three arguments: name, age, and city.

The argument age has a default value of 20, and the argument city has a default value of “New York“. The default values are used for the other arguments when we call the function with a single argument.

When we call the function with two arguments, the first argument is used as the value for name and the second argument is used as the value for age.

When we call the function with the argument city=”London”, the default value for age is used, and the argument city is set to “London“.

In the final call, all the arguments are provided and the values are used in the order they are declared in the function definition.

Return Statement in a Function in Python

The return statement is used in a Python function to specify the value that the function returns.

A function can return a single value or multiple values as a tuple.

When a return statement is executed, the function terminates immediately and the specified value is returned to the caller.

Example of Python return statement in a function-

def square(x):
    return x * x

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

Here, the square function takes a single argument x and returns its square value using the return statement.

The returned value is assigned to the variable result, and the value of the result is printed.

It’s worth noting that a function can have multiple return statements, but only one of them will be executed. For example:

def find_max(a, b):
    if a > b:
        return a
    else:
        return b

result = find_max(5, 10)
print(result)  
# Output: 10

Here, the find_max function takes two arguments a and b, and returns the larger of the two values using the return statement.

The returned value is assigned to the variable result, and the value of the result is printed.

Note: It’s also possible for a function to return None if no value is specified in the return statement. In that case, the function terminates normally but returns nothing to the caller.

Anonymous or Lambda Functions in Python

In Python, Anonymous functions are functions that are defined without a name.

These functions are commonly referred to as Lambda functions. Lambda functions are defined using the lambda keyword, followed by a list of arguments, a colon or : and an expression that defines the operation performed by the function.

Example of an anonymous function in Python-

add = lambda x, y: x + y
print(add(5, 10))  
# Output: 15

Here, the lambda function takes two arguments x and y, and returns their sum.

The function is assigned to the variable add, and can be used just like any other function.

Lambda functions are often used as arguments to other functions, such as the map and filter functions, where a small operation is required to be performed on each element of a list.

Example:

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

Here, the map function applies the lambda function to each element of the numbers list and returns a new list with the square of each number.

Note: Lambda functions are a concise and powerful way to write small functions in Python, and can help make the code more readable and maintainable. However, it’s important to keep in mind that lambda functions should be used for simple operations only, as they become difficult to read and maintain for complex operations.

Function Closure in Python

In Python, a closure is a function object that remembers values in the enclosing scope even if they are not present in memory.

A closure, unlike a regular function, can capture and carry values from the enclosing scope even when the function is invoked outside that scope.

A closure is created by a nested function (the inner function), where the inner function references a value defined in the enclosing function (the outer function).

When the outer function returns, the reference to the inner function is still available, and the inner function retains access to the values in the enclosing scope.

Example of Python function closure-

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

closure = outer_function(10)
print(closure(5))  
# Output: 15

Here, the outer_function takes an argument x, and returns the inner_function. When the outer_function is invoked with x=10, it returns the inner_function which captures the value of x. When the returned inner_function is invoked with an argument y, it returns the sum of x and y.

Note: Python closures are useful in cases where we want to retain the state of a function even after it has returned. They can also be used to implement decorators, which is a way to modify the behavior of a function without changing its code.

Library Functions in Python

A library function in Python is a pre-written and pre-tested piece of code that can be used to perform a specific task.

Python has a large number of built-in library functions, also known as standard library functions, that can be used without having to write any code. These functions cover a wide range of tasks, from mathematical operations and string manipulation to working with files and the Internet.

Commonly used library functions in Python:

  • print() – The print() function is used to display output to the console.

Example of print function in Python-

print("Hello, World!")  
# Output: Hello, World!
  • len() – The len() function returns the length of a string, list, tuple, or any other iterable object.

Example of len function in Python-

string = "Hello, World!"
print(len(string))  
# Output: 13
  • sum() The sum() function returns the sum of a sequence of numbers.

Example of sum function in Python-

numbers = [1, 2, 3, 4, 5]
print(sum(numbers))  
# Output: 15
  • max() – The max() function returns the largest value in a sequence of numbers.

Example of max function in Python-

numbers = [1, 2, 3, 4, 5]
print(max(numbers))  
# Output: 5
  • sorted() – The sorted() function returns a sorted list from a given iterable object.

Example of sorted function in Python-

numbers = [3, 1, 4, 2, 5]
print(sorted(numbers))  
# Output: [1, 2, 3, 4, 5]

These are just a few examples of the many built-in library functions available in Python. By using library functions, we can save time and write more efficient code, as the functions are already tested and optimized for performance.

Conclusion

In conclusion, functions are a fundamental building block in the Python programming language. They provide a way to organize and reuse code, making it easier to write, maintain, and debug programs.

Breaking down complex problems into smaller, more manageable parts, and functions allow you to write clean, readable, and reusable code. By mastering functions in Python, we will become more productive and efficient programmers.

We will also be able to tackle even the most complex problems with ease.