Functions are the piece of code that can be reused within an application at several places. The best benefit of using functions is their reusability. While defining a function, we have to define it only once and we will get different values and different outputs for different places. Functions reduce the size of a program.
Different types of function parameters are,
- With no parameters,
- With one parameter,
- With two parameters and so on... We can use n number of parameters.
Now, we will see how to write functions in Python.
Note
For different Python IDEs, we have different ways to execute, however, the result remains same. For those who are using Visual Studio IDE for Python, the process will be something as follows.
- def display(): #function with no arguments
- print("This is an function with no arguments")
- return
- display()
- def callfun():
- print("This is calling a function into another function")
- display() #calling display() function into call() function
- return
- callfun()
- def message(name): #function with one argument
- print("Hello, "+name)
- return
- message("Kartik")
- message("Sai Vinayak")
- def message(greeting,name): #function with two arguments
- return greeting+", "+name
- msg=message("Hello","Shiv") #message values assigning to msg variable
- show=message("Hi","Rahul") #another message values assigning to show variable
- print(msg)
- print(show)
- def add(a,b): #defining a function that calculates the sum of two numbers
- c=int(a)+int(b) #converting two values into integer type
- print(c)
- return
- add(5,2)
The code will be like this.
Then, the output of the program after execution will be like this.
This is how we can use functions in Python.