Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
- Increase Code Readability
- Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:

Syntax of Python Function Declaration
Types of Functions in Python
Below are the different types of functions in Python:
- Built-in library function: These are Standard functions in Python that are available to use.
- User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of functionalities and properties to it as we require. By the following example, we can understand how to write a function in Python. In this way we can create Python function definition by using def keyword.
Python
# A simple Python function
def fun():
print("Welcome to GFG")
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python followed by parenthesis containing parameters of that particular function. Below is the example for calling def function Python.
Python
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Output:
Welcome to GFG
Python Function with Parameters
If you have experience in C/C++ or Java then you must be thinking about the return type of the function and data type of arguments. That is possible in Python as well (specifically for Python 3.5 and above).
Python Function Syntax with Parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later in this article so you can come back to it again if not understood.
Python
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
Note: The following examples are defined using syntax 1, try to convert them in syntax 2 for practice.
Python
# some more functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r = 3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
Output:
False True
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the number passed as an argument to the function is even or odd.
Python
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Output:
even
odd
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the function call. In Python, we have the following function argument types in Python:
- Default argument
- Keyword arguments (named arguments)
- Positional arguments
- Arbitrary arguments (variable-length arguments *args and **kwargs)
Let’s discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument. The following example illustrates Default arguments to write functions in Python.
Python
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Output:
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller does not need to remember the order of parameters.
Python
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice
Positional Arguments
We used the Position argument during the function call so that the first argument (or value) is assigned to name and the second argument (or value) is assigned to age. By changing the position, or if you forget the order of the positions, the values can be used in the wrong places, as shown in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned to the age.
Python
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because
# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
Arbitrary Keyword Arguments
In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of arguments to a function using special symbols. There are two special symbols:
- *args in Python (Non-Keyword Arguments)
- **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
Python
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output:
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments
Python
# Python program to illustrate
# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='Geeks', mid='for', last='Geeks')
Output:
first == Geeks
mid == for
last == Geeks
Docstring
The first string after the function is called the Document string or Docstring in short. This is used to describe the functionality of the function. The use of docstring in functions is optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
Python
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
print(evenOdd.__doc__)
Output:
Function to check if the number is even or odd
Python Function within Functions
A function that is defined inside another function is known as the inner function or nested function. Nested functions can access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.
Python
# Python program to
# demonstrate accessing of
# variables of nested functions
def f1():
s = 'I love GeeksforGeeks'
def f2():
print(s)
f2()
# Driver's code
f1()
Output:
I love GeeksforGeeks
Anonymous Functions in Python
In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.
Python
# Python code to illustrate the cube of a number
# using lambda function
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))
Output:
343
343
Recursive Functions in Python
Recursion in Python refers to when a function calls itself. There are many instances when you have to build a recursive function to solve Mathematical and Recursive Problems.
Using a recursive function should be done with caution, as a recursive function can become like a non-terminating loop. It is better to check your exit statement while creating a recursive function.
Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(4))
Output
24
Here we have created a recursive function to calculate the factorial of the number. You can see the end statement for this function is when n is equal to 0.
Return Statement in Python Function
The function return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller. The syntax for the return statement is:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant which is returned at the end of the function execution. If none of the above is present with the return statement a None object is returned.
Example: Python Function Return Statement
Python
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Output:
4
16
Pass by Reference and Pass by Value
One important thing to note is, in Python every variable name is a reference. When we pass a variable to a function Python, a new reference to the object is created. Parameter passing in Python is the same as reference passing in Java.
Python
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
# Driver Code (Note that lst is modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to something else, the connection between the passed and received parameters is broken. For example, consider the below program as follows:
Python
def myFun(x):
# After below line link of x with previous
# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]
# Driver Code (Note that lst is not modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[10, 11, 12, 13, 14, 15]
Another example demonstrates that the reference link is broken if we assign a new value (inside the function).
Python
def myFun(x):
# After below line link of x with previous
# object gets broken. A new object is assigned
# to x.
x = 20
# Driver Code (Note that x is not modified
# after function call.
x = 10
myFun(x)
print(x)
Output:
10
Exercise: Try to guess the output of the following code.
Python
def swap(x, y):
temp = x
x = y
y = temp
# Driver code
x = 2
y = 3
swap(x, y)
print(x)
print(y)
Output:
2
3
Quick Links
FAQs- Python Functions
What is function in Python?
Python function is a block of code, that runs only when it is called. It is programmed to return the specific task. You can pass values in functions called parameters. It helps in performing repetitive tasks.
What are the 4 types of Functions in Python?
The main types of functions in Python are:
- Built-in function
- User-defined function
- Lambda functions
- Recursive functions
How to Write a Function in Python?
To write a function in Python you can use the def keyword and then write the function name. You can provide the function code after using ‘:’. Basic syntax to define a function is:
def function_name():
#statement
What are the parameters of a function in Python?
Parameters in Python are the variables that take the values passed as arguments when calling the functions. A function can have any number of parameters. You can also set default value to a parameter in Python.
What is Python main function?
The Python main function refers to the entry point of a Python program. It is often defined using the if __name__ == "__main__": construct to ensure that certain code is only executed when the script is run directly, not when it is imported as a module.
Similar Reads
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
10 min read
Python def Keyword
Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In Python def
6 min read
Difference between Method and Function in Python
Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method d
3 min read
First Class functions in Python
First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of
2 min read
Assign Function to a Variable in Python
In this article, we are going to see how to assign a function to a variable in Python. In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Implementation Simply assign a function to the de
3 min read
User-Defined Functions
Python User defined functions
A function is a set of statements that take inputs, do some specific computation, and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. Functi
7 min read
Python User defined functions
A function is a set of statements that take inputs, do some specific computation, and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. Functi
7 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read
Defining a Python function at runtime
In Python,we can define a python function at runtime execute with the help of FunctionType(). First we import types module then perform compile() function and pass parameter exec and after that with the help FunctionType() define the function at runtime. Example 1: Function to print GEEKSFORGEEKS. C
1 min read
Call a function by a String name - Python
In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
3 min read
Explicitly define datatype in a Python function
Unlike other languages Java, C++, etc. Python is a strongly, dynamically-typed language in which we don't have to specify the data type of the function's return value and its arguments. It relates types with values instead of names. The only way to specify data of specific types is by providing expl
3 min read
Built-in and Special Functions
Global and Local Variables
Global keyword in Python
In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python. What is the purpose of global keywords in python? A global keyword is a keyword that allows a user to m
5 min read
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variabl
5 min read
Accessing Python Function Variable Outside the Function
In Python, variables defined within a function have local scope by default. But to Access function variables outside the function usually requires the use of the global keyword, but can we do it without using Global. In this article, we will see how to access a function variable outside the function
4 min read
Return Statements
How to pass optional parameters to a function in Python?
In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function
5 min read
Returning Multiple Values in Python
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python Code # A Python program to return multiple # values from a
4 min read
Python None Keyword
None is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. C/C++ Code def check_return(): pass print(c
2 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store
4 min read
Advanced Function
*args and **kwargs in Python
In Python, *args and **kwargs are used to allow functions to accept an arbitrary number of arguments. These features provide great flexibility when designing functions that need to handle a varying number of inputs. Example: [GFGTABS] Python # *args example def fun(*args): return sum(args) print(fun
4 min read
*args and **kwargs in Python
In Python, *args and **kwargs are used to allow functions to accept an arbitrary number of arguments. These features provide great flexibility when designing functions that need to handle a varying number of inputs. Example: [GFGTABS] Python # *args example def fun(*args): return sum(args) print(fun
4 min read
Recursion in Python
Recursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks. Python Recursive FunctionIn Python, a recursive function is de
6 min read
Python Inner Functions
In Python, functions are treated as first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functio
6 min read
Decorators in Python
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it. But before diving deep into de
7 min read
Python - Get Function Signature
Let’s consider a scenario where you have written a very lengthy code and want to know the function call details. So what you can do is scroll through your code each and every time for different functions to know their details or you can work smartly. You can create a code where you can get the funct
3 min read
Help function in Python
In Python, the help() function is a built-in function that provides information about modules, classes, functions, and modules. In this article, we will learn about help function in Python. help() function in Python SyntaxSyntax: help([object]) Parameters (Optional) : Any object for which we want so
6 min read
Function Relationships
Passing function as an argument in Python
A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are first class objects. In the example below, a function is assigned to a variable. This assignment doesn’t call the function. It takes the function obj
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store
4 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help
5 min read
Map Reduce and Filter Operations in Python
In this article, we will study Map, Reduce, and Filter Operations in Python. These three operations are paradigms of functional programming. They allow one to write simpler, shorter code without needing to bother about intricacies like loops and branching. In this article, we will see Map Reduce and
3 min read