User-Defined Python Functions – A complete Guide

In this Python article, we will cover everything we need to know about the function which includes defining a function to use it. Different parts of a function like a docstring, parameters, name return statements, etc with varieties of different examples.

1. How to define & call a Function in Python?

In python, we define a function as a block of code that contains one or more statements to perform a specific task, it has a name and is executed only when it is called in the program or code.

We pass some arguments or data in the function body for a specific purpose or operation to be performed. Once the operation is completed, the function can return the outcome data.

The function contains codes and statements which can be reused and systematically arranged block inside it. The function can be used a single time or many times for relevant actions. Modularity becomes better when we use functions in the program.

It will be true to say that if we want to organize the program in small blocks then function serves as the best tool. Hence, it does not matter how large the program is, till the time we are using a function that can easily manage and arrange things inside the program. This is very important from the professional point of view to keep functions well organized in modules/classes, keep them small and always have a descriptive name for them.

We define a function by using def keyword:

#defining a function
def funct():    

#calling a function
Syntax of Function

1.1. Syntax of function

Let’s discuss the syntax of functions that will help us to understand the different sections of the function.

  1. The initialization for any header of function will have def Keyword.
  2. The name of the function easily recognizes the function as it is unique. However. there are certain rules for assigning a name to a function that is similar to the way we declare identifiers.
  3. It is not compulsory to pass values inside a function via arguments.
  4. At the end of the function header, we put a colon (:) to signify the end.
  5. The (docstring) is used to describe the working of the function or in short documentation.
  6. Inside the function, we may have single or multiple statements and operations but all the statements should follow the same indentation pattern.
  7. At the bottom of the function, we may place the return keyword to return the value from the function’s body.

2. General Built-in functions

In python, there are many functions available anytime and they are regarded as built-in functions. Here is a list of some of the built-in functions.

Built-in Functions
List of various built-in functions

Here, we shall not discuss each of them. To check the working of all the above built-in functions, visit here.

Regarding the names of these built-in functions, we can reuse the name of the inbuilt functions to create new user-defined function and implement them in the way we want. But it is not the same with the keywords, if we try to use the Keywords as the name of a method then python interpreter will give an error.

Let’s take an example to understand it better.

def True():

File "", line 1
    def True():
SyntaxError: invalid syntax
def max():


Clearly visible from the above example that reusing names of built-in functions give results whereas using keywords throw an error.

3. Pass by Reference vs Pass by Value for a function

In python, by default, the parameters passed to a function are passed by reference. Hence, the changes in reference to parameters are directly reflected in the calling function or vice versa i.e. the changes made in the function are reflected outside the function. But it also depends on whether the variable is a mutable variable or not.

A fresh reference is made to the specified object whenever a variable is passed to a function. Parameter passing in Python is the same as reference passing in Java. For example −

# Defined Function
def choice(count):
  print("List before amending: ", count)
  count[0] = 10
  print("List after amending: ", count)

# Driver code
count = [1, 20, 40]
print("List after function was called: ", count)
List before amending:  [1, 20, 40]
List after amending:  [10, 20, 40]
List after function was called:  [10, 20, 40]

In the above example, we have changed the value in count object while maintaining the reference of the passed object.

4. Docstring in Python function

Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.

Some thoughts on DocumentationDocumentation helps the team who is currently working on the project and the future developers to understand it. But there are various opinions about the documentation, such as by following the clean coding principles, by keeping the functions small and with descriptive names we can write the code in a way that it is too easy to understand and there should be no need for the documentation. So documenting the tricky part of the code is very necessary, but documenting everything makes it difficult to keep it updated, highlighting which documentation is important and sometimes promotes developers to add additional code and update the documentation even if it does not belong to that method. But as mentioned there many thoughts that float around on this topic and this is how I prefer to document my code. Tell us in the comment section what do you think about documentation.

In general, triple quotes are used to define the docstring as it can be of multiple lines. The __doc__ attribute allows us to use the string in a function.

As we mentioned about the docstring in function’s characteristic, let’s discuss what it is.

After defining the function’s header, the foremost string that shortly describes the working of function for string documentation is known as the docstring.

def call(value):
  The function prints the value
  which will be passed 

Function prints the value which will be passed 

5. Return statement in Python function

In python, with the help of the return keyword, we can quickly exit the function block and reach the line from where the function was called.

#defining a function
def funct():
  return [expression_list]

#calling a function

We can return any value from the function body which we have used or declared inside the block or computed by some operation. If return statement is absent, then None object will be returned.

def testing_return(num):
  """This function retuns true for an even number
  otherwise false"""

  if num < 0:
  elif num % 2 != 0:
    return False
    return True


6. How to create a user-defined function in python?

When the definition of function is given by the user to perform certain operations and work they are known as user-defined functions.

Pre-defined functions in python are known as built-in functions and the functions present in the library written by others it is known as library functions.

Apart from all the functions from above, the functions written by the user are categorized under user-defined functions. Hence, it is possible that the function which is a user-defined function for us can become a library function for someone who will consume our library.

def multiply(x,y):
  mul = x * y
  return mul

n1 = 3
n2 = 9

print("Multiplication result: ", multiply(n1,n2))
Multiplication result:  27

7. Function Arguments in Python

Arguments can be termed as values or data which is sent to the function body. In the function header, the parentheses intake the specified argument. We separate multiple arguments with the help of a comma.

In the example of the previous section, the function multiply intake two arguments x and y and these values are the n1 and n2 passed as parameters to the function.

In python, we can call the function with arguments, we can pass certain types of formal arguments:

  • Required arguments
  • Default arguments
  • Keyword arguments
  • Variable-length arguments

Let’s implement an example that will be used for the explanation of the following types-

def multiply(x, y=10):
  mul = x * y
  return mul

n1 = 3
n2 = 9

print("Required Arguments: ", multiply(n1, n2))
print("Default Arguments: ", multiply(n1))
print("Keyword Arguments: ", multiply(x=n1, y=n2))
print("Keyword Arguments with different order: ", multiply(y=n2, x=n1))

def multiply_variable_args(*x):
  mul = 1
  for y in x:
    mul *= y
  return mul

print("Variable length arguments: ", multiply_variable_args(n1, n2))
Required Arguments:  27
Default Arguments:  30
Keyword Arguments:  27
Keyword Arguments with different order:  27
Variable length arguments:  27

7.1. Required Arguments

Here, the argument which is passed to the function must follow a correct positional order. The number of arguments in the function definition and the number of parameters in a function call must be exactly the same.

For example, the method call in the example above multiply(n1, n2).

7.2. Default Arguments

When a function is called and some parameters are not passed to the function, the default value is assumed as the argument.

For example, the method call in the example above multiply(n1). Here the value of the parameter y is assumed 10 as y=10 is declared in the method definition.

7.3. Keyword Arguments

In this type of argument passing, a specific name or keyword helps the function identify the argument with the help of a parameter name. Hence, if the keyword is present in the parameters then no matter how we place the argument or skip any argument, the interpreter will use the provided keyword to check the variable.

For example, method calls multiply(x=n1, y=n2)or multiply(y=n2, x=n1) produces the same result.

7.4. Variable Length Arguments

There can be certain cases when we want to perform operations on multiple arguments but by using a single variable. Here comes in picture the arguments known as variable-length arguments. This is done by simply placing an * asterisk mark before the variable which will have multiple values.

For example, the method call in the example above multiply_variable_args(n1, n2).

Apart from the above four, we can pass lists, dictionaries, set, strings, numbers, or any type of data inside the function as an argument. To gather more details and programs on argument in the function, you may visit our Arguments in function post.

8. Recursion of function

Recursion means the function calls the function itself forming a loop that needs a base value to stop.

If there would be no base condition, the recursion will never stop and it will continue to use the memory and processor’s power.

Read more: A detailed guide to Recursion in Python

However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

def recur(x):
  if(x > 0):
    y = x + recur(x - 1)
    y = 0
  return y

print("Value after recursion completes ", recur(10))
Value after recursion completes 55

Note: Recursion should be used with care as sometimes it can increase the memory consumption and also make easier programs difficult to understand and debug. So we should use the recursion only if it solves our problem in an easier way.

9. What is an Anonymous function or Lambda function

Anonymous functions do not follow the standard declaration by using the def keyword. We use the lambda function to create mini anonymous functions.

  • Lambda function returns only one value and can take multiple arguments. But it cannot have multiple commands.
  • Lambda function requires particular expression and hence direct call for the print method cannot be made in an anonymous function.
  • Lambda functions can only access their local namespace variable and no other variable.

Let’s take an example to see the working of lambda function.

mul = lambda n1, n2: n1 * n2      #function is defined

print ("Multiply 2 * 2 : ", mul( 2, 2 ))
print ("Multiply 4 * 4 : ", mul( 4, 4 ))
Multiply 2 * 2 :  4
Multiply 4 * 4 :  16

To learn more about lambda function and anonymous function, please refer to Introduction to Anonymous function in Python article.

10. Scope and Lifetime of variables in Python function

The part of the program through which variables are recognized is known as the scope and lifetime of the variable. Parameters and variables defined inside a function are not visible to the code outside the function. Hence, they have a local scope and some other variables may have global scope and some may have nonlocal scope.

Variables exist in the memory till its lifetime. For example, a function local variable remains in memory during the execution of the function. Once the function has encountered the return statement, the variables are destroyed and the function forgets the previous call’s value.

Let’s implement an example to implement an example in which we will try to access a function local variable outside and see it will throw an error but the same print statement within the function works like a charm(try it and comment if there are any issues with it).

def name_list():
  names = ['James', 'Jonas', 'Jodua', 'John']    

Traceback (most recent call last):   File "C:/Users/ASUS/Documents/", line 3, in      print(names) NameError: name 'names' is not defined

To get more knowledge on the Scope of variables in Python, you may visit our article on Global, Local and Nonlocal Variables in Python.

11. Conclusion

In this article, we learned everything which a user should know about functions in Python. We covered:

  • How can we define a function in python along with syntax of the function
  • Some general Built-in functions
  • Pass by Reference vs Pass by Value for a function
  • What is the use of Docstring in python function
  • How does the Return statement in the python function work and how to create a user-defined function in python?
  • Different function Arguments in Python along with required, default, Keyword and Variable Length Arguments
  • How does Recursion of function works and what is an anonymous function or lambda function
  • Scope and Lifetime of variables in python function

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x