'Coding has over 700 languages', '67% of programming jobs aren’t in the technology industry', 'Coding is behind almost everything that is powered by electricity'
Last Updated: Dec 31, 2023

Functions in Python

1 upvote
Basics of python
Free guided path
7 chapters
99+ problems
Earn badges and level up


A function is defined as a reusable block of code used to accomplish a single, related action. The idea is to bring together some repeatedly done tasks and create a function so that instead of writing the same code for different inputs over and over, we can use function calls to reuse the code included in it.
Functions improve the modularity of your application and allow for greater code reuse. 
Functions in Python can be both built-in or user-defined. 

Recommended topics, Divmod in Python, and Convert String to List Python

Creating a Function

Here are some basic principles for defining a function in Python:

  1. Function blocks start with the def keyword followed by the function name and parentheses ().
  2. You can place any arguments or input parameters should be placed within these parentheses. It can be blank also.
  3. The code within a function starts with a colon(:) and is always indented.
  4. The first statement of a function is optional - the function's documentation string or Docstring. A Docstring is a piece of information about what the function does. Docstring is optional, but it is good practice to provide docstring.
  5. The function body contains the code of the task the function is supposed to perform.
  6. The return [expression] statement terminates a function. A return statement without any arguments is the same as a return None.


We will talk about arguments and Docstring later in detail. So keep reading.


def functionName( parameters ):
    return [expression]

Example: Creating a Python Function

# A Python function.
def PythonFun():
  print("Welcome to Coding Ninjas")

Also see, Python Filter Function

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job

Calling a Function

After creating a function, we can call it by using its name followed by parenthesis containing its parameters. A function in Python can be called from another function, application, or directly from a Python prompt.

Example: Calling a Python Function

# A Python function.
def PythonFun(name):
    print("Welcome to Coding Ninjas", name)

# Calling the above function.


Welcome to Coding Ninjas Gazal


You can also read about the Multilevel Inheritance in Python.

Arguments of a Function

An argument is a value passed inside the parenthesis of the function. Any number of arguments separated by a comma can be passed to a function.

Python provides a variety of arguments that can be passed during a function call. 

  1. Required arguments
  2. Default arguments
  3. Keyword arguments
  4. Variable-length arguments

Let's go over each one in detail.

Required Arguments

Required arguments are passed to a function in the correct positional order. In this case, the number of arguments in the function call should match the number of arguments in the function specification; otherwise, it will give a syntax error.
The example of required arguments is as follows:

# Python program to show default arguments.
def PythonFun(name):
    print("Name: ", name)

# Function call


Name: Gazal

Recommended Topic, Floor Division in Python

Default Arguments

A default argument is a parameter that takes on a default value if no value is specified in the function call. You can predefine some default values in the function so that the default value can be used whenever the value of that parameter is not provided.

The following example shows how to use Default parameters.

# Python program to show default arguments.
def PythonFun(name = "Gazal"):
    print("Name: ", name)

# Function call


Name: Gazal

Note: Any number of parameters in a function can have a default value. However, once we have a default argument, all of the arguments to their right must also have default values.

Keyword Arguments

Here the caller can specify the argument name with values so that they do not need to remember the order of parameters.

The following example shows how to use Keyword parameters.

# Python program to show keyword arguments.
def Person(firstName, lastName):
    print(firstName, lastName)

# Function Call
Person(firstName='Gazal', lastName = 'Arora' )
# Changing the order of parameters.
Person(lastName = 'Arora', firstName='Gazal')


Gazal Arora
Gazal Arora

Variable-length Arguments

Python provides this unique variable-length Arguments functionality to pass a variable number of arguments using special symbols.

This is useful when you need to process a function for more arguments than you specified while defining the function. 

There are two types of special symbols:

  • **kwargs (Keyword Arguments)
  • *args (Non-Keyword Arguments)

Example of *args

# Python function to show the use of *args 
def PythonFun(*argv):
    for words in argv:

# Function Call
PythonFun('Welcome', 'to', 'Coding Ninjas')


Coding Ninjas


Example of **kwargs

# Python function to show the use of **kwargs
def PythonFun(**kwargs):
    for key, val in kwargs.items():
        print("%s = %s" % (key, val))
# Function Call
PythonFun(FirstName = 'Gazal', LastName = 'Arora')


FirstName = Gazal
LastName = Arora


The first string following the function is the Document string or Docstring. This is used to explain the function's functionality. Docstring in functions is optional; however, it is recommended.

Syntax to print the docstring of a function is:


The return statement

The function return statement is used to return/terminate from a function, go back to the function's caller, and return the specified data to the caller.

The return statement can be a variable, an expression, or a constant that is returned at the end of function execution. If nothing is sent in a return statement, a None object is returned.

# function to define docstring and return statement.
def length(string):
    # docstring.
    """This function returns the length of the string passed"""
    # returning a number.
    return len(string)

Python Function Pass by Reference vs pass by value 

It's interesting to note that every variable name is a reference in Python. It means that if you modify what a parameter refers to within a function, the change is also reflected in the calling function. For example,

# function to show that parameters are passed by reference.
def pythonFun(myList):
    myList[0] = 2
myList = [1, 2, 3]


[1, 2, 3]
[2, 2, 3]

Here in the output, we can observe that the value of myList[0] was changed inside the pythonFun, but it is also changed in the main function. This proves passing by reference.

Anonymous Functions

An anonymous function in Python does not have a name. As previously stated, the def keyword is used to define normal functions, but the lambda keyword is used to define anonymous functions. For example,

# function to show anonymous functions
def square(x): return x*x
# anonymous function
square_2 = lambda x : x*x





You can practice by yourself with the help of online python compiler.

You can also know about Python Square Root here.

Check out Escape Sequence in Python


  1. What are functions in Python?
    A function is a code that only executes when called. If a return statement is given, Python functions return a value. After defining a function, it can be called from anywhere.
  2. How many types of functions are there in Python?
    There are mainly two kinds of functions. User-defined functions and Built-in functions. User-defined functions are those that the user defines to fulfill a specified purpose. Built-in functions are those that are predefined in Python.

Key takeaways

In this article, we learned about Functions and Arguments in Python. We learned that a function is a block of code used to accomplish a single, related action. It can be used again and again by calling the same function.
We learned about how to create a function in Python. We learned about Arguments of a Function and types of arguments.

Check out this article - Quicksort Python

Recommended Readings:


You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Next article
any in Python
Guided path
Basics of python
7 chapters
127+ Problems
Earn badges and level up
Live masterclass