In this tutorial you will learn user defined functions in Python with the help of examples.
In the last tutorial of Python functions, we discussed that there are two types of functions in Python: Built-in functions and user defined functions. Built-in functions are those that are already defined in Python libraries and we can call them directly. User defined functions are those that we define ourselves in our program and then call them wherever we want. In this article, we are going to discuss about user defined functions.
What are User defined Functions in Python
A function that you define yourself in a program is known as user defined function. You can give any name to a user defined function, however you cannot use the Python keywords as function name.
In python, we define the user-defined function using def
keyword, followed by the function name.
Function name is followed by the parameters in parenthesis, followed by the colon
For example:
def function_name(parameter_1, parameter_2, ...) : statements ....
Calling a user-defined function
You can call a user defined function by using function name followed by the arguments in the parenthesis.
For example:
function_name(argument_1, argument_2)
Example of a user-defined function
In the following example we have defined a user-defined function sum
. This function can accept two arguments as we have defined this function with two parameters. Inside the print() function we are calling the function sum
and passing the numbers x & y as arguments.
In the sum() function we have a return statement that returns the sum of two parameters, that are passed to the function as arguments.
As you can see, we have used a print() function in the following example without even defining that function, this is because print() is a built-in function, which is already available to use and we can just call it.
# Program to demonstrate the # use of user defined functions def sum(a,b): total = a + b return total x = 10 y = 20 print("The sum of",x,"and",y,"is:",sum(x, y))
Output:
Leave a Reply