Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating a Function
2.1.
Syntax
3.
Calling a Function
4.
Arguments of a Function
5.
Required Arguments
6.
Default Arguments
7.
Keyword Arguments
8.
Variable-length Arguments
8.1.
Example of *args
8.2.
Example of **kwargs
9.
Docstring
10.
The return statement
11.
Python Function Pass by Reference vs pass by value 
12.
Anonymous Functions
13.
FAQs
14.
Key takeaways
Last Updated: Mar 27, 2024

Functions in Python

Author GAZAL ARORA
1 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

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.

Syntax

def functionName( parameters ):
    "function_docstring"
    function_body
    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
Bootcamp

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.
PythonFun("Gazal")

Output

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
PythonFun('Gazal')

Output

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
PythonFun()

Output

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')

Output

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:
        print(words)

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

Output

Welcome
to
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')

Output

FirstName = Gazal
LastName = Arora

Docstring

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:

print(function_name.__doc__)

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)
 
print(length("Gazal"))

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]
print(myList)
pythonFun(myList)
print(myList)

Output

[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

print(square(2))
print(square_2(2))

Output

4
4

 

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

FAQs

  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
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass