Functions in Python
Functions in Python

Functions in Python

A Function in Python is a block of code that consists of interrelated programming statements. A function encapsulates a specific task or a group of tasks within a single block. Python functions are defined to perform a computational, logical, or evaluative programming task.

We know that in Mathematics, a function is a binary relation between two sets that associates each element of the first set (input set) to exactly one element of the second set (output set). In other words, we provide an input to a function and it provides the output based on the input. Functions in Python are similar to mathematical functions. Here we can pass data, known as parameters, into a function that performs a task and returns the data as a result. However, programming functions are much more versatile and are of great importance in the world of programming.

Functions could be built-in (provided by programming language) or user-defined (defined by the user). In this article, we will discuss about user-defined functions.

How to define a function in Python?

A function is defined using def keyword. This keyword informs Python that we are defining a function.

Syntax –

def <function_name>(<parameters>):
    """docstring"""
    <statement(s)>
    return <expression>

As we can see in syntax, we need a function name followed by a colon to define a function. The name of the function could be any valid Python identifier. Colon (:) is the punctuation that denotes the end of the Python function header.

A docstring or Document string is a python string written inside the function to describe the function’s functionality. We write a docstring within triple quotes. To define a function, docstring, parameters, and a return statement are optional. We will read about parameters and return statements in further sections.

How to call a function in Python?

Once, we define a function we need to call it which means asking Python to execute that function. We can call the function from any part of a Python program or even inside the other functions. To call a function we simply need to provide the function name with appropriate arguments inside the parenthesis. Let’s see an example to understand this.

# function definition
def add(a, b):
    """
    The function to add two numbers
    Parameters:
        a: first number
        b: second number
    Returns:
        Sum of first and second number
    """
    print('Function to add two numbers')
    return a + b

num1 = 36
num2 = 44
# calling function 
result = add(num1, num2)
# addition of both the numbers
print("Result:", result)

Output:

Function to add two numbers
Result: 80

Parameters and Arguments

Parameters are the variables we define inside the parenthesis of the function definition. We may or may not define a function with default values in the function declaration.

Arguments are the values (or variables) that we provide inside the parenthesis when we call a function.

Both the terms parameter and argument are used for denoting the information that is passed to the function. However, we should understand that parameter is the variable that is part of the function’s signature (function declaration) and argument is the value (constant, variable, or object) that is passed to the function when it is called. For example,

# function definition with parameters rollno and name
def student(rollno, name):
    """
    Function to display roll number 
    and name of the student
    """
    print("Your roll number:", rollno)
    print("Your name:", name)

num = 125

# calling function with arguments num and "Shubham"
student(num, "Shubham")

Output:

Your roll number: 125
Your name: Shubham

In the above example, the variables rollno and name in the function definition are called parameters whereas the variable num and string “Shubham” are said to be arguments. Now let’s discuss types of arguments for functions in Python.

Default arguments

When we specify some default value to a parameter of a function we call it a default argument. A default argument assumes a default value if a value is not provided in the function call for that argument. Therefore, whenever we call a function without argument it takes the default value. For example,

# function definition
def compliment(name, quality = "good"):
    """
    Function to give compliment to a person
    """
    print(name, "is a", quality, "person.")
    print()

# calling function with two arguments
compliment("John", "hardworking")

# calling function with only one argument
compliment("Sheldon")

Output:

John is a hardworking person.

Sheldon is a good person.

Keyword arguments

In Python, we can also pass arguments as key = value pair. Here we specify the value of variables of the parameter explicitly. In this way order of arguments does not matter. We just need to provide the arguments and their values as the parameters. For example,

# function definition
def fullname(firstname, lastname):
    """
    Function to display full name of a person
    """
    name = firstname + " " + lastname
    print("Your full name is", firstname, lastname)

# calling function
name1 = fullname(firstname="Arjun", lastname="Kumar")

# calling function
name2 = fullname(lastname="Singh", firstname="Sandeep")

Output:

Your full name is Arjun Kumar
Your full name is Sandeep Singh

Variable-length arguments (Arbitrary arguments)

When we are defining a function there may some cases arise where we do not know exactly how many arguments, we are going to pass during a function call. In that case, we may have an arbitrary number of arguments. Here, specifying parameters in the function definition is not possible. Therefore, Python provides a solution. We just need to add an asterisk (*) before the parameter name in the function definition. It tells Python that the number of arguments are undefined.

In this way, the function will receive a tuple of arguments and can access its arguments as members of the python tuple. For example,

# function definition having multiple arguments
def average(*args):
    """
    Function to find average of all
    the numbers of argument
    """
    total = 0
    for num in args:
        # total of all numbers
        total = total + num
    avg = total/len(args)
    return avg

# function call with multiple arguments
avg = average(9, 6, 5, 8, 1)
print("Average of numbers =", avg)

Output:

Average of numbers = 5.8

We can also use this concept on keyword arguments. However, here we need to use double asterisks (**) before the parameter name in the function definition. For example,

# function definition
def details(**kwargs):
    """
    Function to display details of a student
    """
    for k, v in kwargs.items():
        print(k, "=", v)

# calling function with multiple key-value arguments
details(name='Thomas', age=21, gender='Male')

Output:

name = Thomas
age = 21
gender = Male

Return statement

When we want a function to produce a result and give an output, we use a return statement to return that value. Whenever a function encounters a return statement it exits from the function, returns the specified value and control goes back to the subsequent part of the function call.

Syntax return [expression]

The return statement may consist of a variable, an expression, or a constant value which is returned at the end of function execution. If no value is specified or no return statement is provided a None object is returned by default. Example,

# function with return statement
def multiply(x, y):
    """
    Function to return product of two numbers
    """
    return x * y

# function without return statement
def greet(name):
    """
    Function to greet a person
    """
    print("Hello", name)

# value returned by multiply() function
res = multiply(9, 3)
print("Value returned by multiply():", res)

# value returned by greet() function
nval = greet('Twinkle')
print("Value returned by greet():", nval)

Output:

Value returned by multiply(): 27
Hello Twinkle
Value returned by greet(): None
  • Kindly note that string “Hello Twinkle” is not returned by the function but it is printed by the function.

Can we define empty functions in python?

We cannot leave the function definition empty. We must have some statements inside the function definition. However, if we have a function definition with no content, we can put in a pass statement just after the function header to avoid errors. It will tell Python to ignore the function. For example,

# function definition of an empty function
def empty(a, b):
    pass

print("Statement before function call")
# function call
empty(4, 5)
print("Statement after function call")

Output:

Statement before function call
Statement after function call

What is the importance of functions in Python?

Functions are an essential part of any programming language. There are two main reasons for which functions are known to be highly useful.

i) Reusability

Let’s assume we are writing a program for which we need to perform a task multiple times in the program. For this, we will have to type the same code again and again. As our program grows larger the repetition of the same code increases. Well, we can repeat the same code using copy-paste method. But what if there are some minor modifications for the same task in each case. This way, the code becomes lengthier, less organized, and complex.

Here the better solution is to define a function for the repeated task. Now, whenever we need to perform the same task again, we just need to call the function. We can define the function with proper parameters so it can work for different versions of the same task without additional code. In this way, we can avoid repetition and make code reusable. We call this property Reusability.

ii) Modularity

There are various cases in programming where we need to perform a complex process within our program. We can divide this complex process further into smaller tasks and we can use functions to complete each task. Therefore, functions allow the complex problem to be broken into smaller sub-problems which breaks our program into smaller modules. Here, each module is a function that performs its task independently. This property is termed Modularity and it makes our code more organized and manageable.

Conclusion

In this article, we have discussed about user-defined functions in Python. We have read about defining a function and calling a function. We have also read about parameters and arguments, return statement and pass keyword. At last, we have discussed the importance of functions in Python programming. To learn more topics in python programming, you can read this article on list comprehension in python.

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code
Payment QR Code

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply