Skip to main content

Python User-defined Functions

User-defined function is a term used to refer to the functions you define yourself to perform specific tasks.

What are user-defined functions?

User-defined functions are functions that you can define and call.

All the other functions that are not built-in and not library functions then are necessarily user-defined.

note

Defining and calling a function occurs normally (as already explained in the chapter on functions).

note

Functions contained in libraries are called library functions.

Advantages

  • User-defined functions help break down a large program into smaller segments that make the program easy to understand, maintain, and debug.
  • If repeated codes occur in a program, you can use a function to include such codes and execute them when necessary by calling the function.
  • Programmers working on large projects can divide the workload by implementing different functions.

Example

For example, define a function sum_numbers that takes two numbers and returns their sum:

def sum_numbers(x, y):
return x + y

num1 = 1
num2 = 2

print(f"The sum is {sum_numbers(num1, num2)}")

Output

The sum is 3
note

It is a good practice to give meaningful names to functions