DETAILED EXPLANATION OF FUNCTIONS IN PYTHON – 10

functions in python

OVERVIEW

In this blog post, you will learn,

  • What are functions?
  • How to create functions in python?
  • How to create function in different number of parameters?
  • How to create the functions with default arguments?
  • How to create the functions with *args and **kwargs?

What are functions?

A functions can be termed as the set of instructions that will not be executed until you will call that function. Functions also accepts the values which are termed as parameters. Functions also return the data that can be used further.

CREATE FUNCTIONS IN PYTHON

In python, a function is defined with the keyword def. Now let’s understand this by defining our first function and this function will print a greeting message.

def greet():
    print("Hello Everyone!!! Welcome to Innovate Yourself...")

Above is the function defined with name greet and on execution this will print a greeting message “Hello Everyone!!! Welcome to Innovate Yourself…”. On executing the script with only this code, you will not get anything in the output because the functions never execute anything until we call them.

To execute the function, call the function like shown below,

greet()

Now, on executing the script you will get the output as shown below.

Output:

Hello Everyone!!! Welcome to Innovate Yourself...

So, as you can see above now you have got the output when you have called the function. So this is the correct way to define the function and to call it to get the output.

CREATE FUNCTION IN DIFFERENT NUMBER OF PARAMETERS

Now let’s understand how can we define the function with the parameters. To understand that let’s define a function that will take two parameters as input and will perform the subtraction of two numbers.

def subtract(num1,num2):
    output = num1 - num2
    print(f"Subtraction of {num1} and {num2} is {output}")

subtract(5, 2)

In the above code you can see, we have defined a function that takes two parameters, i.e., num1 and num2 and will perform the subtraction of both the numbers and print its output. The output for the above code will be,

Output:

Subtraction of 5 and 2 is 3

This is what you will get if you will pass the values while calling the function. But what if you forgot to pass the values or you didn’t passed all the values? This is what you will get if you will not pass the arguments on function call,

def subtract(num1,num2):
    output = num1 - num2
    print(f"Subtraction of {num1} and {num2} is {output}")

subtract()
Output: 

Traceback (most recent call last):
  File "/Users/ashishsaini/Downloads/Fingerprint_v1/f2.py", line 67, in <module>
    subtract()
TypeError: subtract() missing 2 required positional arguments: 'num1' and 'num2'

create the functions with default arguments

So what should we do to handle this? We have an another concept(that is exception handling) for this, but right now we’ll use the default arguments to handle this. So what exactly default arguments are, the answer is to assign some by default values to the parameters while defining the functions. To understand this let’s use the same example to perform the subtraction.

def subtract(num1=5,num2=3):
    output = num1 - num2
    print(f"Subtraction of {num1} and {num2} is {output}")

subtract()
subtract(10, 5)

As per the above code you can see that we have the by default values for num1 and num2 as 5 and 3 respectively. So what it will do is that if you forgot to pass the values or you didn’t passed all the values on function call then instead of showing the error, the function will consider the default values and will give you the output based on them. Also if you will pass the arguments for the parameters then it will consider the passed values. Below is the output for the above code.

Output:

Subtraction of 5 and 3 is 2
Subtraction of 10 and 5 is 5
functions with default arguments

There is one more important thing that you should know about functions in python and that is the return function. What exactly a return function is and why do we need to know about it? To understand it let me explain it with an example, for this lets consider the above function and write the given code,

def subtract(num1=5,num2=3):
    output = num1 - num2
    print(f"Subtraction of {num1} and {num2} is {output}")

output=subtract()
print(output)

For the above code you will get the below output.

Output:

Subtraction of 5 and 3 is 2
None

From the above output you can see that we have got the out in first line but for the second line we have got the output as None. That simple means that your value is not getting stored in the variable output as a result you can’t use it further to perform any kind of calculation. So to store this value and to use it further you will have to use return function in the given way.

def subtract(num1=5,num2=3):
    output = num1 - num2
    return output

output1=subtract()
print("Output after return :", output1*5)

If you will execute the above code you will be able to store the value coming from the function and to perform the further calculation with the stored value. So this is the output that you will get for the above code,

Output:

Output after return : 10

create the functions with *args and **kwargs

First of all what exactly *args and **kwargs are? To understand this first of all I would like to call the above function in different ways like it is shown below,

From above images you can understand that if we are defining a function with limited set of parameters and with some defined keywords in that case we are limiting a function to only pass the arguments for that particular keyword and only that numbers of arguments. But what if we don’t wanna limit it, then how can we do that?

For handling that we have a new way to define a function in python that takes the parameter as *args or **kwargs for multiple arguments and multiple keyword arguments respectively. So what exactly these are and how to work on it. To understand this let’s take and example to except multiple values(it can be any numbers of values) and performs the addition of all the numbers. Below is the code to do it.

def addition(*args):
muliple_sum=sum(args)
print(f"Sum of all the entered numbers is {muliple_sum}")


addition(1,2,3,4,5,6,7,8)

In the above code you can see that there is just one parameter that is defined, i.e., *args. This simple defines that now your function will accept multiple arguments that you will pass and will give you all the values in tuple format, once we have got the values in tuple format we are just calling the sum function which is inbuilt in python and it will perform the addition of all the numbers that you will provide. Below is the output for the above code.

Output:

Sum of all the entered numbers is 36

But this function will only accept the values of you will pass the values without the keywords and if you will try to do so then it will generate an error. To handle the arguments with the keyword we use the **kwargs that will accept all the arguments(or values) with keyword and you can check it in the below code.

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


print_data(a=3, b=5, c=8, d=9)

In the above code we are passing the arguments with the keyword and when you pass the data in this way you will get the data of dictionary type. To demonstrate that we’ll be displaying all the data you will pass in the format defined. Output for the above code will be like,

Output:

key= a and value= 3
key= b and value= 5
key= c and value= 8
key= d and value= 9

So from the above example I hope you have got a clarity that what are function, why do you use them and how do you use that. You can also check out our video on functions for video demonstration,

Time to wrap up now. Hope you liked our content on FUNCTIONS IN PYTHON. See you in our next blog, thanks for reading our blog and do leave a comment below to help us improve the content to serve you all of our experience with you. Stay tuned with us for more python contents.

Also check out our other playlist Rasa ChatbotInternet of thingsDockerPython Programming, etc.
Become a member of our social family on youtube here.

Stay tuned and Happy Learning.

Ashish Saini
Ashish Saini

I am a software developer for Python/Machine Learning. Also, I’m Rasa Hero at Rasa. Also, I’m a youtuber where I regulary uploads the videos to help this generation learn about the technology just like they are playing games.

Leave a Reply