English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will discover the advantages of using user-defined functions and best practices.
We define functions that perform certain specific tasks as user-defined functions. We have discussedin Pythondefined and calledFunctionway.
Functions included with Python are called built-in functions. If we use functions written by others in the form of a library, they can be called library functions.
All other functions we write ourselves belong to user-defined functions. Therefore, our user-defined functions may be library functions of others.
User-defined functions help to break down large programs into smaller segments, making the program easier to understand, maintain, and debug.
If there is repeated code in the program, functions can be used to contain this code and execute it when needed by calling the function.
Programmers working on large projects can divide the workload by executing different functions.
# Project description # Usage of user-defined functions def add_numbers(x, y): sum = x + y return sum num1 = 5 num2 = 6 print("Total ", add_numbers(num1, num2))
Output result
Enter a number: 2.4 Enter another number: 6.5 Total 8.9
Here, we define the function my_addition() to add two numbers and return the result.
This is our user-defined function. We can multiply two numbers inside the function (this is entirely up to us). However, this internal operation does not match the function command. This may easily cause ambiguity and misuse, so it is recommended to name custom functions as consistent as possible with their internal functions.
It is a good practice to name a function based on the task it performs.
In the above example, print() is Built-in functions.