Robotics & Artificial Intelligence

Describe user-defined functions in Python with the help of an example.

Python Functions

1 Like

Answer

A user-defined function is a function that is defined by the user to perform a specific task. It enables the user to write their own code and reuse it whenever required. User-defined functions help in reducing repetition of code and make programs easier to understand and maintain.

In Python, a user-defined function is created using the def keyword, followed by the function name, parameters enclosed in parentheses, and a colon. The statements that define the task of the function form the function body.

Example:

def add(a, b):
    return a + b
result = add(5, 6)
print(result)

In the above example, the function add() is a user-defined function that takes two parameters and returns their sum using the return statement. This function can be called any number of times with different arguments.

Answered By

2 Likes


Related Questions