English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python Custom Functions

In this tutorial, you will discover the advantages of using user-defined functions and best practices.

What are user-defined functions in Python?

We define the functions we define to perform certain specific tasks as user-defined functions. We have discussedin Pythondefined and calledFunctionin the way.

Functions that come 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.

Advantages of user-defined functions

  1. User-defined functions help to break down large programs into smaller segments, making the program easier to understand, maintain, and debug.

  2. If there is repeated code in the program, functions can be used to include this code and execute it when needed by calling the function.

  3. Programmers working on large projects can divide the workload by executing different functions.

Example of user-defined function

# Project description
# User-defined function usage
def add_numbers(x, y):
   sum = x + y
   return sum
num1 = 5
num2 = 6
print("Total ", add_numbers(num1, num2))

Output result

Enter 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 can easily cause ambiguity and misuse, so it is recommended to make the naming of custom functions as consistent as possible with the function's internal functionality.

It is a good practice to name a function based on the task it performs.

In the above example, print() is a built-in function in Python. Built-in functions.