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.
- User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug.
- If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.
- Programmars working on large project can divide the workload by making different functions.
# Program to illustrate
# the use of user-defined functions
sum = x + y
num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))
Enter a number: 2.4 Enter another number: 6.5 The sum is 8.9
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,
print() is a built-in function in Python.