Skip to content

Function in Python

Exploring the Power of Functions in Python: A Comprehensive Guide

In the realm of Python programming, functions stand as essential building blocks, allowing developers to encapsulate reusable blocks of code, enhance modularity, and streamline the overall structure of a program. In this comprehensive guide, we will delve into the fundamentals of functions in Python, exploring their syntax, use cases, and best practices.

Functions in Python

A function is a block of code that performs a specific task. Functions are used to make code more modular and reusable. For example, you might have a function that adds two numbers. Instead of writing the same code again, you can just call the function. You can also pass parameters to a function, which allows you to reuse the same code with different inputs. In this tutorial, you’ll learn how to define and call a function in Python. You’ll also learn about parameters and return values of functions in Python.

A top-down approach is used to define functions in Python. This means that you start with the main function and then define other functions as you go. This is different from other programming languages like C, where you define all the functions at the top of the program. In Python, you can define a function anywhere in the program, and you can call a function before it is defined. This is because Python reads the entire program before executing it.

Defining a Function in Python

In Python, you can define a function using the defdef keyword. The syntax for defining a function is as follows:

Syntax
def function_name(parameters):
    """docstring"""
    statement(s)
    return [expression] # Optional
Syntax
def function_name(parameters):
    """docstring"""
    statement(s)
    return [expression] # Optional
  • function_namefunction_name: The name of the function. It must follow the same rules as variable names.
  • parametersparameters: A comma-separated list of parameters. Each parameter consists of a name followed by a colon and a type annotation. The type annotation is optional.
  • docstringdocstring: An optional docstring that describes the function.
  • statement(s)statement(s): The body of the function. It consists of one or more statements.
  • returnreturn: An optional return statement. It is used to return a value from the function.
  • expressionexpression: An optional expression that is evaluated and returned by the function.
  • ::: A colon that marks the end of the function header. It is followed by an indented block of code. The indentation is used to indicate the scope of the function. All statements in the function body must be indented.

Example:

function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y

In this example, we define a function named addadd that takes two parameters xx and yy and returns their sum. The type annotation for the parameters and return value is optional. The docstring is also optional, but it is good practice to include it.

Calling a Function in Python

In Python, you can call a function using its name followed by parentheses. The syntax for calling a function is as follows:

Syntax
[variable] = function_name(arguments)
Syntax
[variable] = function_name(arguments)
  • variablevariable: An optional variable that stores the return value of the function.
  • function_namefunction_name: The name of the function.
  • argumentsarguments: A comma-separated list of arguments. Each argument consists of a value followed by a colon and a type annotation. The type annotation is optional.
  • ==: An optional assignment operator. It is used to assign the return value of the function to a variable.

Example:

function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)
function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)

Output:

command
C:\Users\Your Name> python function.py
15
command
C:\Users\Your Name> python function.py
15

In this example, we call the add()add() function with two arguments 55 and 1010. The function returns 1515, which is assigned to the variable resultresult. The value of resultresult is then printed to the console.

Parameters of a Function in Python

In Python, you can pass parameters to a function. The syntax for passing parameters to a function is as follows:

Syntax
def function_name(parameter1, parameter2, ...):
Syntax
def function_name(parameter1, parameter2, ...):
  • function_namefunction_name: The name of the function.
  • parameter1, parameter2, ...parameter1, parameter2, ...: A comma-separated list of parameters. Each parameter consists of a name followed by a colon and a type annotation. The type annotation is optional.
  • ,,: A comma that separates the parameters.

Example:

function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)
function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)

Output:

command
C:\Users\Your Name> python function.py
15
command
C:\Users\Your Name> python function.py
15

In this example, we define a function named addadd that takes two parameters xx and yy and returns their sum. We then call the function with two arguments 55 and 1010. The function returns 1515, which is assigned to the variable resultresult. The value of resultresult is then printed to the console.

Return Value of a Function in Python

In Python, you can return a value from a function using the returnreturn statement. The syntax for returning a value from a function is as follows:

Syntax
return [expression]
Syntax
return [expression]
  • returnreturn: The returnreturn keyword.
  • expressionexpression: An optional expression that is evaluated and returned by the function.

Example:

function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)
function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)

Output:

command
C:\Users\Your Name> python function.py
15
command
C:\Users\Your Name> python function.py
15

In this example, we define a function named addadd that takes two parameters xx and yy and returns their sum. We then call the function with two arguments 55 and 1010. The function returns 1515, which is assigned to the variable resultresult. The value of resultresult is then printed to the console.

Return values are optional in Python. If you don’t specify a return value, the function returns NoneNone. For example:

function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    print(x + y)
 
result = add(5, 10)
print(result)
function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    print(x + y)
 
result = add(5, 10)
print(result)

Output:

command
C:\Users\Your Name> python function.py
15
None
command
C:\Users\Your Name> python function.py
15
None

In this example, we define a function named addadd that takes two parameters xx and yy and prints their sum. We then call the function with two arguments 55 and 1010. The function prints 1515 to the console. The return value of the function is NoneNone, which is assigned to the variable resultresult. The value of resultresult is then printed to the console.

Multiple calls to a Function in Python

In Python, you can call a function multiple times. The syntax for calling a function multiple times is as follows:

Syntax
function_name(arguments)
function_name(arguments)
function_name(arguments)
Syntax
function_name(arguments)
function_name(arguments)
function_name(arguments)

Example:

function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result1 = add(5, 10)
result2 = add(10, 20)
result3 = add(20, 30)
print(result1)
print(result2)
print(result3)
function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result1 = add(5, 10)
result2 = add(10, 20)
result3 = add(20, 30)
print(result1)
print(result2)
print(result3)

Output:

command
C:\Users\Your Name> python function.py
15
30
50
command
C:\Users\Your Name> python function.py
15
30
50

In this example, we define a function named addadd that takes two parameters xx and yy and returns their sum. We then call the function three times with different arguments. The function returns the sum of the arguments, which is assigned to the variables result1result1, result2result2, and result3result3. The values of these variables are then printed to the console. This is how you can call a function multiple times in Python. A function can be called as many times as you want. This is the main advantage of using functions in Python.

Types of Functions in Python

In Python, there are two types of functions:

  • Built-in functions
  • User-defined functions

Built-in functions are functions that are provided by Python. They are used to perform common tasks such as printing text to the console, reading input from the user, and converting data types.

User-defined functions are functions that are defined by the user. They are used to perform specific tasks that are not provided by Python. For example, you might want to define a function that adds two numbers. This function can then be called from anywhere in the program.

Arguments of a Function in Python

In Python, you can pass arguments to a function. The syntax for passing arguments to a function is as follows:

Syntax
function_name(argument1, argument2, ...)
Syntax
function_name(argument1, argument2, ...)
  • function_namefunction_name: The name of the function.
  • argument1, argument2, ...argument1, argument2, ...: A comma-separated list of arguments. Each argument consists of a value followed by a colon and a type annotation. The type annotation is optional.
  • ,,: A comma that separates the arguments.

Example:

function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)
function.py
def add(x: int, y: int) -> int:
    """Adds two numbers"""
    return x + y
 
result = add(5, 10)
print(result)

Output:

command
C:\Users\Your Name> python function.py
15
command
C:\Users\Your Name> python function.py
15

In this example, we define a function named addadd that takes two parameters xx and yy and returns their sum. We then call the function with two arguments 55 and 1010. The function returns 1515, which is assigned to the variable resultresult. The value of resultresult is then printed to the console. Here, we are passing arguments to the function. The arguments are 55 and 1010. The function takes these arguments and returns their sum.

Pass by Reference vs Pass by Value in Python

In Python, the terms “pass by value” and “pass by reference” are often misunderstood because the concept is a bit nuanced. Python uses a mechanism that is more accurately described as “pass by object reference” or “call by object reference.” To understand this, let’s delve into how values are passed to functions in Python.

Pass by Value

In Python, values are passed to functions by value. This means that when you pass a value to a function, a copy of the value is created and passed to the function. The function then operates on this copy of the value. The original value is not modified. For example:

function.py
def update(x: int):
    """Updates the value of x"""
    x = 10
 
x = 5
update(x)
print(x)
function.py
def update(x: int):
    """Updates the value of x"""
    x = 10
 
x = 5
update(x)
print(x)

Output:

command
C:\Users\Your Name> python function.py
5
command
C:\Users\Your Name> python function.py
5

In this example, we define a function named updateupdate that takes a parameter xx and updates its value to 1010. We then call the function with the argument 55. The function updates the value of xx to 1010. However, the original value of xx is not modified. The value of xx is still 55. This is because the value of xx is passed to the function by value. A copy of the value is created and passed to the function. The function then operates on this copy of the value. The original value is not modified. This is how values are passed to functions in Python.

Pass by Reference

In Python, values are passed to functions by reference. This means that when you pass a value to a function, a reference to the value is passed to the function. The function then operates on this reference to the value. The original value is modified. For example:

function.py
def update(x: list):
    """Updates the value of x"""
    x[0] = 10
 
x = [5]
update(x)
print(x)
function.py
def update(x: list):
    """Updates the value of x"""
    x[0] = 10
 
x = [5]
update(x)
print(x)

Output:

command
C:\Users\Your Name> python function.py
[10]
command
C:\Users\Your Name> python function.py
[10]

In this example, we define a function named updateupdate that takes a parameter xx and updates its value to 1010. We then call the function with the argument [5][5]. The function updates the value of xx to 1010. The original value of xx is modified. This is because the value of xx is passed to the function by reference. A reference to the value is passed to the function. The function then operates on this reference to the value. The original value is modified. This is how values are passed to functions in Python.

In python, the primitive data types like intint, floatfloat, boolbool, strstr, etc. are passed by value. The non-primitive data types like listlist, dictdict, setset, etc. are passed by reference. This is because the primitive data types are immutable, while the non-primitive data types are mutable.

Order of Arguments in Python

In Python, the order of arguments is important. The arguments are passed to the function in the same order as they are defined in the function definition. For example:

function.py
def subtract(x: int, y: int) -> int:
    """Subtracts two numbers"""
    return x - y
 
result1 = subtract(5, 10)
result2 = subtract(10, 5)
print(result1)
print(result2)
function.py
def subtract(x: int, y: int) -> int:
    """Subtracts two numbers"""
    return x - y
 
result1 = subtract(5, 10)
result2 = subtract(10, 5)
print(result1)
print(result2)

Output:

command
C:\Users\Your Name> python function.py
-5
5
command
C:\Users\Your Name> python function.py
-5
5

In this example, we define a function named subtractsubtract that takes two parameters xx and yy and returns their difference. We then call the function with two arguments 55 and 1010. The function returns -5-5, which is assigned to the variable result1result1. We then call the function with two arguments 1010 and 55. The function returns 55, which is assigned to the variable result2result2. The values of these variables are then printed to the console. This is how you can pass arguments to a function in Python. The arguments are passed to the function in the same order as they are defined in the function definition.

Types of Arguments in Python

In Python, there are three types of arguments:

  • Positional arguments
  • Keyword arguments
  • Default arguments

We will discuss each of these in detail in the following sections.

Best Practices for Functions in Python

1. Descriptive Function Names:

Choose descriptive names that convey the purpose of the function. This enhances code readability and understanding.

function.py
# Avoid
def calc(a, b):
    return a + b
 
# Prefer
def add_numbers(x, y):
    return x + y
function.py
# Avoid
def calc(a, b):
    return a + b
 
# Prefer
def add_numbers(x, y):
    return x + y

2. Modularity:

Break down complex tasks into smaller, modular functions. Each function should have a single responsibility.

function.py
# Avoid
def process_data(data):
    # Complex code
    return result
 
# Prefer
def clean_data(data):
    # Code for data cleaning
    return cleaned_data
 
def analyze_data(data):
    # Code for data analysis
    return result
function.py
# Avoid
def process_data(data):
    # Complex code
    return result
 
# Prefer
def clean_data(data):
    # Code for data cleaning
    return cleaned_data
 
def analyze_data(data):
    # Code for data analysis
    return result

3. Use Return Wisely:

Return meaningful values or use NoneNone for functions without a specific result.

function.py
# Avoid
def print_greeting(name):
    print(f"Hello, {name}!")
 
# Prefer
def generate_greeting(name):
    return f"Hello, {name}!"
function.py
# Avoid
def print_greeting(name):
    print(f"Hello, {name}!")
 
# Prefer
def generate_greeting(name):
    return f"Hello, {name}!"

4. Document Your Functions:

Provide clear documentation using docstrings to explain the purpose, parameters, and return values of your functions.

function.py
def multiply(a, b):
    """
    Multiply two numbers.
 
    Parameters:
    a (float): The first number.
    b (float): The second number.
 
    Returns:
    float: The result of the multiplication.
    """
    return a * b
function.py
def multiply(a, b):
    """
    Multiply two numbers.
 
    Parameters:
    a (float): The first number.
    b (float): The second number.
 
    Returns:
    float: The result of the multiplication.
    """
    return a * b

5. Avoid Global Variables:

Minimize the use of global variables within functions. Pass necessary values as parameters.

function.py
# Avoid
total = 0
 
def add_to_total(value):
    global total
    total += value
 
# Prefer
def add_numbers(a, b):
    return a + b
function.py
# Avoid
total = 0
 
def add_to_total(value):
    global total
    total += value
 
# Prefer
def add_numbers(a, b):
    return a + b

Conclusion

Functions are fundamental to Python programming, offering a powerful mechanism for organizing and reusing code. By understanding their syntax, using parameters effectively, and adhering to best practices, you can create modular and maintainable code.

As you explore Python, experiment with different types of functions and discover how they contribute to code readability, flexibility, and efficiency. For more insights and practical examples, check out our tutorials on Python Central Hub!

Was this page helpful?

Let us know how we did