A function is very important in any programming language. The function will make your code more flexible and make it more readable. In this article, we will see what is Function in Python and how can we use them in different ways.
What is a Function
A function is just a block in which you write your code. Suppose you have written a piece of code in your program to do a certain activity. Now if you need to use the same activity at some other places then you will end up writing the same code again. We are just duplicating the same piece of code, again and again, making it difficult to manage, read and maintain. It would have been better if we have something which could allow us to use the same code without writing it again.
For that function come in the picture. The function provides the facility not to write the same code, again and again, you can reuse the same code anywhere in the program as much time you needed. So, basically, you write your piece of code once and reuse it anywhere in your program you want, making that piece of code more manageable. it will save you time and effort.
Let us see how to create the function or syntax of function in Python:
Syntax of the python function is as below:
#Syntax of python function def yourFunctionName(): #defining your function name print("First Program") #printing in the function
Here we use a def keyword to start function than we have to give the name to the function, here I have given function name as yourFunctionName .
Now I am creating a simple program that will print the hello world using the function.
def firstProgram(): print("Hello world") firstProgram() #calling the function #Output will be: Hello world
Now the question is how to use the function? To use the function we have to call the function. We have to use the function name with parameters. In the above program, you can see I am calling the function with the function name. My function name is firstProgram(). Here there is no argument or parameter so we don’t have to pass any argument. After calling the function, you will get the output Hello world.
Once you have created the function, you can use that function anywhere in the program by calling it with their name. For better understanding let us write another program.
#Program to add two numbers def add(): c=5 b=15 result=c+b print(result) add() #calling the function with its name #output: 20
Here I have created the program which will add the two number and give the sum of two numbers. I have used 2 variables, In variable c I stored 5 and in variable b, I stored 15. The addition of these two value is getting stored in the variable result. Then I am calling the function with its name. Here my function name is add(). After calling the function we are getting the result 20.
Function with argument and without Argument
Before starting this section, let’s see what is an argument, the argument is the value which we give to the function, and this value is used by the function. In the above program, you can see I have given fixed value to the variable which is 5 and 15. Suppose we want to take inputs from the user and then show the result by adding the numbers to the user, how can we achieve that? In that case, we have to use arguments with function. Now let us create a small program to understand the argument. for better understanding let us create the same addition program using argument.
def add(a,b): #function add with 2 arguments result=a+b print(result) add(5,15) #calling the function with its name and providing the values. # Output: 20
In the above program, we are using two-argument, you can use as many as you want or according to the requirement. My requirement is for two numbers, so I am using two-argument. Arguments are passed in brackets (a,b). You have to pass values from where you are calling the function. Now I will explain how the above program is working with arguments.
In the above program, I am using the function name add and in the bracket, I am passing the two arguments a and b as add(a,b). Here you can see the variable a and b don’t have actual value, these variables are blank. To perform the addition operation we have to give the value to these variables. Here you can see I am calling the function add(5,15) and giving the two value 5 and 15. These value will go to the function and get stored in variable a and b respectively. 5 will be stored in a and 15 will be stored in b. The sum of these two number will get stored in the variable result. So, in the example above at the time of calling the function, we are giving the value to the function.
These arguments are very helpful because you can pass any number as arguments. It will give the output based on the argument passed, means the output will never be fixed.
Now we will see another program in which we will see how to give different arguments and get the output based on arguments. I am creating the same add program so that we can understand the program easily.
def add(a,b): result=a+b print(result) #example with different argument add(5,15) #output: 20 add(10,20) #output:30 add(50,100) #output: 150
This way we have written one function that accepts parameter or argument and gives a different result based on the argument passed to the function. This makes the function dynamic in nature.
Till now we have learned about function with and without arguments. Now we will learn about Default arguments. In the default, arguments we can fix the value of argument/parameter and at the time of calling we can overwrite the value. Default arguments must be the last arguments in series. If you pass the value then it will overwrite otherwise it will take the default value which is fixed. If you have multiple arguments in a function, and you want to have multiple default arguments in your program, then you have to write them in continuity from the last argument. Let us first see a program with default argument and then we will see how can we have multiple default arguments.
#Function with single default argument def add(x,y=30): k=x+y print(k) add(23) #output: 53
Here you can see we are passing only one argument that is for x because y already have the value 30.
What if we give both values as we have already defined the value of y=30. See the example.
def add(x,y=30): k=x+y print(k) add(23,4) #Output:27
Now, we can see that we are passing the argument 23 and 4. Here 4 is overriding the default value 30. So if we pass the value then it will override otherwise it will keep the default value.
Python program for multiple arguments
def fact(n,y=3,t=5): #Multiple Arguments result=n+y+5 print(result) fact(5,2) #output:12
How to write a function that can take n number of argument
Python allows you to write functions that can accept n numbers of the parameter. In this case, the number of parameters or arguments is not defined. You can decide at the time of calling the function, on how many parameters you have to pass. See an example below:
def add(*x): k=sum(x) #using default sum function of python print(k) add(2,3,4) #output will be 9
Here you can pass as many parameters you want. Here the number of parameters is not fixed. To add the number we are using sum() function, the sum is the default function of python which will add the number passed as an argument.
Important point: Python supports recursive functions, but avoid creating and using the recursive function in python because it may create memory issues.
Example of recursive function
def fact(n): if n == 1: return n else: return n*fact(n-1) #Output:6
Lambada Function in Python
Python allows creating an anonymous function using lambada keyword. Lamda functions are generaaly small functions and can be written in one line. Lambda functions are just like regular functions with no name. They can be used wherever function objects are required.
d=lambda x:x**2 print(d(3)) #output: 9
The above function will return the square of 3 or whatever number you will give.
#exampe2: li=[1,2,3,4,5,6,7,8] nli=list(filter((lambda x:x%2==0),li)) print(nli) #Here we are getting the list of even number using the lambda function
#Using the map in lambda function li=[1,2,3,4,5,6,7,8] nli=list(map((lambda x:x%2==0),li)) print(nli) #it will return the result in true and false #[False, True, False, True, False, True, False, True]
Nested Function in python
def calc(x): def show(y): k=x*y return k return show ob=calc(4) print(ob(5)) output 20
Python Function as an argument
def inc(x): return x+1 def dec(x): return x-1 def operate(func,x): result=func(x) return result print(operate(inc,10)) print(operate(dec,10))
In the above programs, we used the return keyword very often. Return means, the function will return the data and you can store it in a variable.
How to make the function Global in Python
- Go to lib folder, lib folder you will find where python is installed. to get the path simply type python.exe in windows search .and open the file location.
- Create the file with the name you want
- Create the function in the file
- Now to use that function you have to import that function
- To import from myfunction import your function name
- Now simply call it with the function name
I am giving you an example:
I am creating the file with name myfunction.py
Now I am writing the function.
def add(a,b); result=a+b print(result)
Now you have to import the function on top of your program write the below code.
use from myfunction import add
Here myfunction is the file name and add the function which I have created. Let’s see how to use it. add(5, 10 )
The output will be 15
That’s it Folks on this topic. Let us know your comments on this article in the comment box below. Kindly like our facebook page, follows us on twitter and subscribe to our YouTube channel for latest updates.