User-defined Functions

Course- Python >

Functions that we define ourselves to do certain specific task are referred as user-defined functions. The way in which we define and call functions in Python are already discussed. Functions that readily come with Python are called built-in functions. If we use functions written by others in the form of library, it can be termed as library functions. All the other functions that we write on our own fall under user-defined functions. So, our user-defined function could be a library function to someone else.

Advantages of user-defined functions

  1. User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug.
  2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.
  3. Programmars working on large project can divide the workload by making different functions.

Example of a user-defined function


# Program to illustrate
# the use of user-defined functions

def my_addition(x,y):
   """This function adds two
   numbers and return the result"""
   sum = x + y
   return sum

num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
print("The sum is", my_addition(num1,num2))

Output


Enter a number: 2.4
Enter another number: 6.5
The sum is 8.9

Explanation

 

Here, we have defined the function my_addition() which adds two numbers and returns the result. This is our user-defined function. We could have multiplied the two numbers inside our function (it's all up to us). But this operation would not be consistent with the name of the function. It would create ambiguity. It is always a good idea to name functions according to the task they perform.

In the above example, input(), print() and float() are built-in functions of the Python programming language.