In Python, a function is a named block of code that performs a specific task. Use functions whenever you need to perform the same task several times without writing the same code again. A function can take arguments and return a value.
Functions follow the DRY principle, which stands for Don’t Repeat Yourself. If you need to do the same task many times, you can define that task once in a function and call the function whenever you need it.
Functions improve efficiency and reduce errors because the code is reused. Once you create a function, you can call it anywhere and any number of times. The main benefits of functions are reusability and modularity.
Table of contents
- Types of Functions
- Creating a Function
- Calling a function
- Docstrings
- Return Value From a Function
- The pass Statement
- How does Function work in Python?
- Scope and Lifetime of Variables
- Python Function Arguments
- Recursive Function
- Python Anonymous/Lambda Function
- Functions are first-class objects
- Type hints in functions
- Summary
Types of Functions
Python supports two types of functions:
- Built-in function
- User-defined function
Built-in function
Functions that come with Python itself are called built-in functions or predefined functions. Some of them are:range(), id(), type(), input(), len(), print(), etc.
Example: Python range() function generates the immutable sequence of numbers starting from the given start integer to the stop integer.
User-defined function
Functions that you write yourself for your own needs are called user-defined functions.
Creating a Function
Use the following steps to define a function in Python.
- Use the
defkeyword followed by the function name and parentheses. - Inside the parentheses, list the parameters the function needs, if any (optional), and end the line with a colon (
:). - Write the function body as an indented block of code. This block is the action you want the function to perform.
In Python, you don’t use curly braces for the function body. Instead, the body must be indented under the def line. Wrong indentation causes an IndentationError.
Syntax of creating a function
def function_name(parameter1, parameter2):
# function body
# write some action
return valueCode language: Python (python)
Here,
function_name: Function name is the name of the function. We can give any name to function.parameter: Parameter is the value passed to the function. We can pass any number of parameters. Function body uses the parameter’s value to perform an actionfunction_body: The function body is a block of code that performs some task. This block of code is nothing but the action you wanted to accomplish.- return value: Return value is the output of the function.
Note: While defining a function, we use two keywords, def (mandatory) and return (optional).

Creating a function without any parameters
Let’s start with a simple function that prints a welcome message.
Output
Welcome to PYnative
Creating a function with parameters
Let’s create a function that takes two parameters and displays their values.
In this example, we create a function with two parameters, name and course_name.
Output
Hello John Welcome to PYnative Your course name is Python
Creating a function with parameters and return value
Functions can return a value. The return value is the output of the function. Use the return keyword to return a value from a function.
Calling a function
Once you have defined a function, you can call it by its name. You can also call it from another function, or from another program by importing it.
To call a function, write its name followed by parentheses. If the function accepts parameters, pass the values inside the parentheses.
Example
Calling a function of a module
Python comes with many built-in modules whose functions you can use in your code. For example, the random module has functions for generating random numbers and data.
Let’s see how to use functions defined in any module.
- First, we need to use the import statement to import a specific function from a module.
- Next, we can call that function by its name.
Docstrings
In Python, a documentation string is called a docstring. It is descriptive text (like a comment) that explains what a piece of code does, so other people can understand and use it.
You write a docstring as the very first statement inside a module, class, function, or method.
It is written using triple single quotes (''' ''') or triple double quotes (""" """).
You can read the docstring of any object, such as a list, a dict, or your own function, using its __doc__ attribute, or by passing the object to help().
Single-Line Docstring
A single-line docstring fits on one line. The opening and closing quotes must be the same, and by convention, you should use triple double quotes (""").
Output
Return the square of a number.
When you use the help() function to get information about a function, it shows the docstring.
Output
Help on function square in module __main__:
square(x)
Return the square of a number.
Multi-Line Docstring
A multi-line docstring starts with a short summary line, followed by a blank line and a more detailed description, such as the function’s arguments and return value.
The general format of writing a multi-line Docstring is as follows:
Example
Output
Description of function.
Arguments:
parameter1 (int): Description of parameter1.
Returns:
int: Description of the return value.
Return Value From a Function
In Python, the return statement sends a value back from a function. It returns the value of the expression that follows the return keyword.
Syntax of return statement
def fun():
statement-1
statement-2
statement-3
.
.
return [expression]Code language: Python (python)
The return value is the result of the function.
- The
returnstatement ends the function execution. - For a function, it is not mandatory to return a value.
- If a
returnstatement is used without any expression, then theNoneis returned. - The
returnstatement should be inside of the function block.
Example
Output
Even numbers are: [2, 42, 62, 70]
Return Multiple Values
You can also return multiple values from a function. Write them after the return keyword, separated by commas.
Example:
In this example, we return four values from a function and read them into four variables. Python actually packs the values into a single tuple, and the assignment unpacks it.
The pass Statement
In Python, pass is a keyword that does nothing. A function body can’t be empty, so when you want to define a function now and write its code later, put pass in the body.
When Python reaches a pass statement, nothing happens. It is a placeholder that keeps the code syntactically valid.
Example
How does Function work in Python?
Functions let you write short, clean code that can be reused throughout a program.
Functions help you organize code. A function accepts parameters as input, processes them, and returns a value as output.
When you call a function, Python jumps to the function’s code, runs it with the arguments you passed, and then returns to the line where the function was called, bringing back the return value.
The following diagram shows how the function works.

Scope and Lifetime of Variables
The scope of a variable is the part of the program where it can be accessed. Variables created inside a function have a local scope: they can be used only inside that function.
You can’t access local variables from outside the function, because they are not visible there.
Note: An inner function (a function defined inside another function) can read the variables of the outer function.
Local variables exist only while the function is running. Once the function returns, they are destroyed. So a function doesn’t remember the values of its local variables from a previous call.
The following code shows the scope of a variable inside a function.
Example
In the above example, we print the global variable and the local variable from outside the function. The global variable global_lang is accessible by its name.
But when we try to access the local variable local_lang from outside the function, we get a NameError, because it exists only inside the function.
Local Variable in function
A local variable is declared inside a function and can’t be accessed from outside of it. Its scope is limited to the function where it is declared.
If we try to access the local variable from the outside of the function, we will get the error as NameError.
Example
Output
Value is : 888
print("Value is :", loc_var) # gives error,
NameError: name 'loc_var' is not defined
Global Variable in function
A global variable is a variable declared outside of any function. It is accessible from all functions in the same module.
Example
Output
Value in 1st function : 999 Value in 2nd function : 999
Global Keyword in Function
A function can read a global variable, but it can’t change it by assignment, because assigning creates a new local variable instead. The global keyword tells Python to use the global variable. We use it for two purposes:
- To create a global variable from inside a function.
- To change the value of an existing global variable from inside a function.
Let’s see what happens when we assign to a global variable inside a function without the global keyword.
Output
Value in 1st function : 5 Value in 2nd function : 555 Value in 3rd function : 5
As you can see, function2() treated global_var as a new variable (local variable). To solve such issues or access/modify global variables inside a function, we use the global keyword.
Example:
Output
Value in 1st function : 5 Value in 2nd function : 555 Value in 3rd function : 555
Nonlocal Variable in Function
In Python, nonlocal is a keyword used inside an inner function (a function defined inside another function). It tells Python that a variable refers to the variable of the outer function.
Use nonlocal when an inner function needs to change a variable that belongs to the enclosing function, instead of creating a new local variable.
Example
Output
value of x inside inner function is : 700 value of x inside outer function is : 700
Python Function Arguments
An argument is a value, variable, or object that you pass to a function when you call it. Python supports four types of arguments:
- Positional arguments
- keyword arguments
- Default arguments
- Variable-length arguments
Read the complete guide on Python function arguments.
Positional Arguments
Positional arguments are passed to a function in the correct positional order: the 1st argument goes to the 1st parameter, the 2nd argument to the 2nd parameter, and so on. In the example below, the function subtracts its second argument from its first, so swapping them changes the result.
Example
If you pass more arguments than the function accepts, you get an error.
Output
TypeError: add() takes 2 positional arguments but 3 were given
With positional arguments, both the number and the order of the arguments matter. If you change the order, the result may change. If you pass the wrong number of arguments, you get an error.
Keyword Arguments
A keyword argument is a value passed to a function together with the parameter name and an equals sign, for example, name="John".
Example
Output
Hello John Wilson Hello Kelly Ault
With keyword arguments, the order doesn’t matter, but every required parameter must still receive a value. Otherwise, you get an error.
When you mix positional and keyword arguments, the positional arguments must come first, followed by the keyword arguments. Otherwise, you get a SyntaxError, as the following example shows.
Example
Default Arguments
A default argument takes a default value when you don’t pass it in the function call. You assign the default value in the function definition using the = operator.
For example, a function show_employee(name, salary=9000) accepts an employee’s name and salary. If the salary is missing from the function call, the function automatically uses the default value 9000.
Example
Output
Hello John Hello Guest
When you pass an argument, the function uses that value. When you leave it out, the function uses the default value. Parameters with default values must come after parameters without them.
Warning: don’t use a mutable default value
A default value is created only once, when the function is defined, not every time it is called. If the default is a mutable object such as a list, changes to it are kept between calls. Use None as the default and create a new list inside the function instead.
Variable-length Arguments
Sometimes you don’t know in advance how many arguments a function will receive. Such arguments are called variable-length arguments. Declare one by putting an asterisk (*) before the parameter name.
def fun(*var):
function bodyCode language: Python (python)
You can pass any number of arguments to this function. Inside the function, all of them are collected into a tuple. By convention, this parameter is usually named *args.
Example
Output
Sum is: 0 Sum is: 26 Sum is: 87.5
Variable-length keyword arguments (**kwargs)
To accept any number of keyword arguments, put two asterisks (**) before a parameter name. Inside the function, those arguments are available as a dictionary.
Output
name : Jessa age : 28
Read more: The complete guide on Python function arguments.
Recursive Function
A recursive function is a function that calls itself.
For example, calculating the factorial of a number is a repetitive task: the factorial of 5 is 5 times the factorial of 4, and so on. So a function can call itself with a smaller number each time until it reaches 0.
factorial(5)
5*factorial(4)
5*4*factorial(3)
5*4*3*factorial(2)
5*4*3*2*factorial(1)
5*4*3*2*1 = 120
Example
Output
factorial of a number is: 40320
The advantages of recursive functions are:
- Recursion can make code shorter.
- It can make code easier to read for problems that are naturally recursive.
- It is useful for breaking a complex problem into smaller sub-problems, such as working with trees or nested data.
The disadvantages of recursive functions are:
- Recursive functions usually use more memory and run slower than an equivalent loop, because each call is stored on the call stack.
- Recursive functions can be harder to debug.
- Python limits the recursion depth (1000 calls by default). Going deeper raises a
RecursionError, so every recursive function needs a base case that stops the recursion, likeif no == 0above.
Python Anonymous/Lambda Function
Sometimes you need a small function without a name. A function without a name is called an anonymous function or lambda function.
Anonymous functions are handy for short, one-time operations. A normal function is defined with the def keyword, while an anonymous function is created with the lambda keyword.
Unlike a normal function, a lambda function body is a single expression, not a block of statements. For example, lambda n: n + n returns double its argument.
Syntax of lambda function:
lambda arguments: expressionCode language: Python (python)
A lambda function can take any number of arguments, but it contains only one expression, and it returns the value of that expression. For example, add = lambda x, y: x + y creates a function, and add(2, 3) returns 5.
Let’s print the even numbers from a list, first without a lambda function and then with one. Compare the number of lines and the readability of the code.
Example 1: Program for even numbers without lambda function
Output
Even numbers are: [10, 12, 78, 6]
Example 2: Program for even number with a lambda function
Output
Even numbers are: [10, 12, 78, 6]
You don’t write a return statement in a lambda function. The value of the expression is returned automatically.
Lambda functions are most useful when you need to pass a short function as an argument to another function, for example, to built-in functions such as filter(), map(), sorted(), and functools.reduce().
filter() function in Python
In Python, the filter() function keeps only the items of a sequence for which a given function returns True. Use it to select values based on a condition.
Syntax of filter() function:
filter(function, sequence)Code language: Python (python)
where,
function– a function that returnsTruefor the items to keepsequence– any iterable, such as a list, tuple, or string
Example: lambda function with filter()
Output
Positive numbers are: [5, 12, 6, 9]
map() function in Python
In Python, the map() function applies a function to every item of a sequence and returns the results as a new iterable (an object you can loop over or convert to a list).
Ex: for every element present in the sequence, perform cube operation and generate a new cube list.
Syntax of map() function:
map(function,sequence)Code language: Python (python)
where,
function– the function to apply to each item of the sequencesequence– any iterable, such as a list, tuple, or string
Example: lambda function with map() function
Output
Cube values are: [8, 27, 64, 512, 729]
reduce() function in Python
In Python, the reduce() function combines the items of a sequence into a single value. It applies a two-argument function to the first two items, then to that result and the next item, and so on.
The reduce() function is present in the functools module; hence, we need to import it using the import statement before using it.
Syntax of reduce() function:
reduce(function, sequence)Code language: Python (python)
Example: lambda function with reduce()
Output
Addition of all list elements is : 54
Functions are first-class objects
In Python, a function is an object like any other value. You can assign it to a variable, store it in a list, pass it as an argument to another function, and return it from a function. That’s exactly why filter(), map(), and reduce() can accept a function as their first argument.
Type hints in functions
You can add optional type hints to show what type each parameter should be and what the function returns. Python doesn’t enforce them at runtime, but they make code easier to read, and editors and tools such as mypy use them to catch mistakes.
Summary
- A function is a named, reusable block of code. Define it with
def, and call it by its name followed by parentheses. - Use
returnto send a result back. Without it, a function returnsNone. Return several values separated by commas, and Python packs them into a tuple. - Document functions with docstrings, and read them with
help()or__doc__. - Variables created inside a function are local. Use
globalornonlocalonly when you really need to change an outer variable. - Arguments can be positional, keyword, default,
*args, or**kwargs. Never use a mutable object as a default value. - Recursive functions call themselves and need a base case. Lambda functions are small anonymous functions, often used with
filter(),map(),reduce(), andsorted().
