Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are functions in Python?
3.
Creating a Function
3.1.
Syntax
4.
Calling a Function
5.
Arguments of a Function
6.
Required Arguments
7.
Default Arguments
8.
Keyword Arguments
9.
Variable-length Arguments
9.1.
Example of *args
9.2.
Example of **kwargs
10.
Docstring
11.
The return statement
12.
Python Function Pass by Reference vs pass by value 
13.
Anonymous Functions
14.
Frequently Asked Questions
14.1.
How many types of functions are there in Python?
14.2.
What is the formula for function?
14.3.
What are the five functions in Python?
15.
Conclusion
Last Updated: Sep 5, 2024
Easy

Functions in Python

Author GAZAL ARORA
1 upvote

Introduction

Functions in Python are essential building blocks which allows you to organize and reuse code efficiently. They enable you to break down complex tasks into simpler parts, making your code more readable and maintainable. By defining functions, you can execute specific tasks with just a single call thus reducing repetition in your projects.

Functions in Python

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

What are functions in Python?

Functions in Python are reusable blocks of code designed to perform specific tasks. They allow you to encapsulate a sequence of statements into a single unit that can be executed whenever needed. Functions can take inputs, known as arguments, and return outputs after processing. By using functions, you can reduce code duplication, improve readability, and make your programs more modular and easier to maintain. Python's flexibility allows defining both built-in and user-defined functions to suit various programming needs.

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

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.

Frequently Asked Questions

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.

What is the formula for function?

In Python, a function is defined using the syntax def function_name(parameters):, followed by an indented block of code that performs the desired task.

What are the five functions in Python?

Five common Python functions include print(), len(), type(), max(), and min(). These built-in functions help with output, data manipulation, and obtaining information about variables.

Conclusion

In conclusion, Functions in Python are fundamental to writing clean, efficient, and modular code. They enable you to break down complex problems into manageable tasks, promote code reuse, and enhance readability. By mastering the use of functions, you can create more organized and maintainable programs, ultimately becoming a more proficient and effective Python developer.

Check out this article - Quicksort Python

Recommended Readings:

Live masterclass