Functions Using Python

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,
  1. With no parameters, 
  2. With one parameter, 
  3. 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.
  1. def display(): #function with no arguments  
  2. print("This is an function with no arguments")  
  3. return  
  4. display()  
  5. def callfun():  
  6. print("This is calling a function into another function")  
  7. display() #calling display() function into call() function  
  8. return  
  9. callfun()  
  10. def message(name): #function with one argument  
  11. print("Hello, "+name)  
  12. return  
  13. message("Kartik")  
  14. message("Sai Vinayak")  
  15. def message(greeting,name): #function with two arguments  
  16. return greeting+", "+name  
  17. msg=message("Hello","Shiv") #message values assigning to msg variable  
  18. show=message("Hi","Rahul") #another message values assigning to show variable  
  19. print(msg)  
  20. print(show)  
  21. def add(a,b): #defining a function that calculates the sum of two numbers  
  22. c=int(a)+int(b) #converting two values into integer type  
  23. print(c)  
  24. return  
  25. 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.
Ebook Download
View all
Learn
View all