How Can We Help?
A function is like a self-organized block of code, subprogram, and a small program that is part of a large one and used to perform a single and related action. It can be called a section of a program that is written once and can be executed whenever required in the program, thus making code reusability. It is a subprogram that works on data and produces some output. It provides better modularity for our application and a high degree of code reusing.
Types of Functions:
Python supports two types of functions.
- Built-In functions
- User-defined functions
Built-In functions:
It is a predefined function in Python and the function imported from the standard python library.
Eg. print(), abs(),input(), math.sqrt(), random.random() etc.
A list of some built-in functions of Python is as below. Examples of these functions are available in our different python topics.
- abs()
- all()
- any()
- bin()
- bool()
- filter()
- chr()
- compile()
- complex()
- dict()
- dir()
- eval()
- exec()
- float()
- format()
- globals()
- help()
- hex()
- input()
User-Defined functions:
The user creates it according to their requirement.
E.g., The user creates the math() function for addition and subtraction operations.
Defining a Function in Python
We can define a function in Python by following the below rules.
- The keyword “def” starts the function definition, specifying the function block’s start.
- “def” is followed by <function name> ,which is user defined name.
- <function name> is followed by parenthesis ().
- Any input parameters or arguments can be placed within the parentheses() of the function. It is optional.
- In the end, a colon is marked.
- The first statement of a function can be optional – the documentation string of the function or docstring. It is optional.
- Before writing a block code of the function, an indentation (space) is required before every statement. It should be the same for all statements inside the function.
- The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as a return None.
- ‘Function Definition ‘provides information about the function name and parameters.
- The function name shows what operation is to be performed.
Syntax:
def <function_name>( parameters ):
"function_docstring"
<body of function>
return [expression]
Where a return statement is used inside a function to exit it and return a value and then assigned to the function variables, it is used to send back the control to the caller with the expression. If we do not return a value explicitly means no expression is given after return; None is returned automatically. We can return more than one value in a return statement like return a,b, or return a+b,a-b.
Example (1):
Function for adding two values.
def add(a,b):
"Add two numbers"
print(a+b)
return
In the above example, we created a function name called “add()” , which is used to add two values as ‘a’ and ‘b’ and returns their sum. An ‘a’ and ‘b’ are parameters. An “Add two numbers” is a doc string. An expression is ‘a+b’. A doc string, return statement and print statement are a block of function.
Arguments and Parameters of a Python Function
In Python, two types of data are passed in the function.
Arguments:
It is always shown in the function call or body.
It can be literals, variables, and expressions.
It can be called actual parameters or actual arguments
Example (2)
def add(a,b):
"Add two numbers"
print(a+b)
return
In the above example, “a+b” of the function body is an argument.
Parameters:
It is always shown in the function definition.
It is the data that is received in the function definition.
It must be variable to hold incoming values.
These can be called formal parameters or formal arguments.
Example (3)
def add(a,b):
"Add two numbers"
print(a+b)
return
In the above example, “a” and “b” of the function definition are parameters.
Calling a Python Function
We can execute a function by calling it from another function or directly from the python shell. We can call them in a print statement also.
Syntax:
<function_name> (parameters) or <function_name> (parameters)
Note: By default, parameters have a positional behavior, and we need to give them in the same order that they were defined, like parameters as (animal, flower) so its value as (cat, rose).
Example (3): call function of adding two values.
def add(a,b):
"Add two numbers"
print(a+b)
return
add(2,3)
Output
5
In the above example, we have directly called add() function with parameters (a=2,b=3) as add(2,3), and this calling function is defined out of the function block and returns 5 as 2+3 against the print statement.
Note: Function call will be executed in the order in which it is called.
Reusable Function
We can reuse a function by calling one function in another or multiple places to reduce the code lines and make our program flexible.
Example (4), create a math function using add and sub-functions.
def add(a,b):
return a+b
def sub(a,b):
return a-b
def math(a,b):
c=add(a,b)
d=sub(a,b)
return c,d
math(5,2)
add(5,2)
sub(5,2)
Output:
(7, 3)
7
3
In the above example, we created two functions, “add()” and “sub()“, and then called them directly in the math function. In the math function, we reuse them and get the result as 7 (=5+2) and 3 (=5-2).
Global and local Variables:
Variables in Python and all programming languages have a scope. It means variables will not be available everywhere in the program if we define them as local variables that belong and are available in a particular block of code or program unit.
When we define a variable inside a function, this variable’s scope is local, meaning that the variable is only accessible inside that function. At the same time, all functions can access global variables throughout the program body.
Python supports two types of variables.
Local Variable
It is defined within a function means inside the function.
Example (5): Take division
def div():
a=5
b=15
print("local variables: ",a,b)
return (b/a)
div()
Output:
local variables: 5 15
3.0
In the above example, local variables ‘a’ and ‘b’ are defined inside the function.
Global Variable
It is defined globally as means out of the function.
Example (6), Take division.
b=15
def div():
a=5
print("local variables: ",a)
print("global variables: ",b)
return (b/a)
div()
Output:
local variables: 5
global variables: 15
3.0
In the above example, local variables ‘a’ are defined inside the function, and global variable ‘b’ is outside the function.
Example (7): Multiply Two Values.
result=0
def mul(a,b):
result=a*b
print("local variable result value: ",result)
return result
mul(2,5)
print("global variable result value: ",result)
Output:
local variable result value: 10
10
global variable result value: 0
In the above example, the “result” variable is at the global scope, and then print its value globally, it returns as “0” and when print its value locally means within a function it returns multiplication of two values as
Function Arguments:
Python supports the following argument types.
1) Positional arguments
2) Keyword arguments
3) Default arguments
4) Variable-length arguments
Positional Arguments
Positional arguments are the arguments passed to a function in the correct positional order, and the number of arguments in the function call should match precisely with the function definition.
Example (8)
def add(x,y):
print(x+y)
add(5,10)
Output:
15
In the above example, when add() function is called, the passing values 5 and 10 are at the same position as parameters x and y in function definitions like “x=5” and “y=10“.
Keyword Arguments
When we use keyword arguments in a function call, the caller specifies the arguments by the parameter name.
This allows us to skip one or more arguments if the parameter is optional in our program. The python interpreter can use the keywords provided to match the values with parameters.
Example (9)
def msg(ID,Name):
print(ID,Name)
msg(ID=21,Name='John')
msg(Name='Smith', ID=25)
Output:
21 John
25 Smith
In the above example, when the msg() function is called the first time, the passing value as ID and Name position are at the same position as the function definition. When the msg() function is called the second time, the passing of two values as Name and ID position is not the same as a function definition, but the result for both is the same. So, we can say that data would be processed as per the parameter name, not as per the value position.
Default arguments
A default argument is an argument with a default value if the function caller does not pass a value for that argument.
Example (10)
def msg(ID,Name, Age=16):
print(ID,Name, Age)
msg(ID=1011, Name='John',Age=15)
msg(ID=1021, Name='Smith')
Output:
1011 John 15
1021 Smith 16
In the above example, when the msg() function is called the first time, the passing three different values, 1011, John, and 15, are assigned to respective parameters, and thus respective values are printed in the output. While the msg() function is called the second time, the passing two values, 1021 and Smith, are assigned to ID and Name, respectively. No value is assigned for the third argument via a function call, so for the third parameter, the default value is 16, and according to it result is printed in the output.
Variable-length arguments
When we don’t know how many parameters we need to pass in the function definition, at that time, we use variable length arguments, which define by an asterisk (*) variable tuple name.
The syntax for a function with non-keyword variable arguments:
def function_name([formal_args,] *var_args_tuple ):
function body
return [expression]
We place the asterisk (*) before the variable name that holds the values of all non-keyword variable arguments. The list variable in the example below will remains empty if we don’t pass any additional arguments when we call the function.
Example (11)
def Info(arg1,*varlist):
print("arg1: ",arg1)
print('vartlist: ',*varlist)
Info('Language','Python','Java','C#')
Output:
arg1: Language
vartuple: Python Java C#
In the above example, arg1=Language and vartuple=(Python, Java, C#) can take more parameters.
The Anonymous Functions (lambda)
Anonymous Function is the function that is not bound to a name. It is created by using the keyword “lambda“. It is used to reduce the code lines.
Lambda takes any number of arguments and returns an evaluated expression. It is created without using the ‘def’ keyword.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function can’t be a direct call to print because lambda requires an expression.
Lambda functions have their local namespace and can’t access variables other than those in their parameter list and those in the global namespace.
Syntax:
lambda [arg1 [,arg2,.....argn]]: expression
Example (12)
find_max_value=lambda x,y:x if x>y else y
print(find_max_value(5,8))
Output:
8
In the above example, we can easily find the most significant number among two numbers using the lambda function.
Recursive Function
Before starting a recursive function, let’s first understand what recursion is. Recursion is a process of repeating items in a self-similar way.
If a program allows calling a function inside the same function, it is called a recursive call. The recursive function has a termination condition, which stops the function from calling itself as infinite time.
Example (13)
Find a factorial of a number 4 (1*2*3*4=24).
def factorial(n):
if n==1:
return 1
else:
return n* factorial(n-1)
print(factorial(4))
Output:
24
In the above example, when calling the factorial function factorial(4), it returns n * factorial(n-1) means 4*factorial(3). This process will continue until n = 1; if n=1 is reached in the program, the program will return the factorial result as 24.
Note: Python stops the recursive function calls after 1000 calls because every time function calls itself and stores some memory. So, recursive functions hold much more memory than traditional function calls. To stop this, Python allows only 1000 recursive calls.
Conclusion
Functions are one of the main aspects of all programming languages like Python. In this article we explained the Python function in details and have given 13 practical examples that showcase what are the different types of function in Python and how to create them; also, we explained what function argument types are and how to use each of them, moreover, we speak about anonymous function (lambda) and the last thing we have given an example about how to use a recursive function in python.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.
But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.