Python Functions
In python, function is a block of code, and it will contain a series of statements to execute whenever it is called in the program.
In python, functions are useful to reduce code duplication and improve code reusability. For example, if you want to execute the same block of statements in multiple places, you can create one function with the required statements and use it wherever required in your application.
Function Syntax:
To define a function in python, you need to use the?def?keyword followed by the function name and parentheses?( ). Following is the syntax of defining the function in python.
def?function_name(parameters):
? ??"""docstring"""
? ? statement(s)
? ? ...
? ? ...
? ??return?[expr]
If you observe the above function syntax, we used different components to define the function.
? The?def?keyword is used to indicate the start of the function.
? function_name?is the name to uniquely identify the function.
? parameters?are optional and these are useful?to send values to the function.
? The colon (:) symbol is used to indicate the start of the code block.
? docstring?is optional, and it is useful to provide information about the function.
? statement(s)?inside the function body to perform the required tasks, and the statements must follow the same indentation.
? The?return?statement is useful to return a value from the function, and it’s optional.?
To create a block of statements inside of the function body, you need to follow the same indentation for all the statements. To know more about
specifying the indentation in python, refer to?Python basic syntaxes.
Function Example:
Following is the example of creating and calling a function to execute the block of statements in python.
def?userdetails():
? ??''' Function to get user details'''
? ? name =?"Suresh Raina"
? ? location =?"Hyderabad"
? ??print("Name: {}"(name))
? ??print("Location: {}"(location))
userdetails()
If you observe the above example, we created the?userdetails()?function without specifying any parameters.
When you execute the above python program, you will get the result as shown below.
Name: Suresh Raina
Location: Hyderabad
Return Statement in Function:
You can use the?return?statement in function to return the values. Following is the example of creating a function to return a value in python.
def?multiply(a, b):
? ??return?a * b
c = multiply(10,?5)
print("10 * 5 = "(c))
The above example will return the result as shown below.
10 * 5 = 50
Function with Parameters:
In python, you can create the functions to receive one or more parameter/argument values based on functional requirements.
Following is the example of creating the function with required parameters/arguments in python.
def?userdetails(name, location):
? ??''' Function to get user details'''
? ??print("Name: ".(name))
? ??print("Location:"(location))
userdetails("Virat Kohli",?"Bangaluru")
If you observe the above example, we created the?userdetails?function with two parameters (name,?location) to receive the values as function arguments.
When you execute the above python program, you will get the result as shown below.
Name: Virat Kohli
Location : Bangaluru
Note: The terms both?parameters?and?arguments?will refer to the same thing. These are useful to pass the information to the functions.
Python Lambda Functions:
In python, lambda functions are the?functions?without a name, and we can also call it anonymous functions.
The lambda functions are useful for sending functions as arguments to other functions and performing operations with an anonymous function name.
The lambda functions are not a substitute for normal functions because the lambda functions will operate on a single expression and do not contain
any other statements to execute as normal functions.
Lambda Function Syntax:
As discussed in the?python functions?article, we will use the?def?keyword to define the function but to define the lambda function; you need to use
the?lambda?keyword followed by the arguments and expression.
Following is the syntax of defining the lambda function in python.
lambda?argument(s): expression
The lambda function will accept any number of arguments, but it will allow having only one expression. When the lambda function is called, the expression will return the value.
Lambda Function Example:
Following is the example of creating and calling the lambda function in python.
multiply =?lambda?x: x *?10
print(multiply(9))
If you observe the above example, we used the?lambda?keyword to create the lambda function, and we are calling the lambda function by sending an argument value.
When you execute the above python program, you will get the result as shown below.
90
If required, you can also send multiple arguments to the lambda function. Following is the example of sending multiple arguments to the lambda
function.
sum?=?lambda?a, b, c: a + b + c
print(sum(10,?20,?40))
If you observe the above example, we are sending multiple arguments to the lambda function to execute the defined expression (a + b + c).
When you execute the above python program, you will get the result as shown below.
70
Function with Lambda Function:
In python, you can use lambda functions inside of other functions based on your requirements.
Following is the example of using lambda or anonymous function inside of another function in python.
def?calculate(b):
? ??return?lambda?a: a * b
x = calculate(5)
print(x(10))
If you observe the above example, we created a lambda function inside another function (calculate) to return the value. We are calling the lambda function by sending the required arguments.?
When you execute the above python program, you will get the result as shown below.
50
In lambda functions, it’s not mandatory to return the value. Following is the example of creating the lambda function without returning any value.
x =?lambda?str:?print(str)
x("welcome to elysium")
If you observe the above example, we are not returning any value from the lambda function expression. Instead, we are just printing the text.
When you execute the above python program, you will get the result as shown below.
welcome to python
This is how you can use lambda or anonymous functions in python to create functions without a name based on your requirements.?
Recursive Function Example:
Following is the example of defining the recursive function in python.
def?calculate(a, b):
? ??if?a >?0?and a <=?10:
? ? ? ? x = a * b
? ? ? ??print("{} * {} = {}".format(a, b, x))
? ? ? ? calculate(a +?1, b)
calculate(1,?5)
If you observe the above example, we created the?calculate?function and we are calling the same?calculate?function inside of the function body.
When you execute the above python example, you will get the result as shown below.
1 * 5 = 5
2 * 5 = 10
领英推荐
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
As discussed, if you create a recursive function without any condition to stop the recursion you will get a recursion exception.
def?calculate(a, b):
? ? x = a * b
? ? calculate(a, b)
? ??print("Result:{}".format(x))
calculate(10,5)
When you execute the above python example, you will get an exception like as shown below.
Traceback (most recent call last):
?File "", line 5, in
?File "", line 3, in calculate
?File "", line 3, in calculate
?File "", line 3, in calculate
?[Previous line repeated 1022 more times]
RecursionError: maximum recursion depth exceeded
This is how you can implement the function recursion in python to call the same function based on your requirements.?
Python Global Keyword:
In python, if you want to create a?local variable?inside the function and you want to access the same variable outside of the function as a?global variable, then you need to define the variable with the?global?keyword.
Generally, if you create a variable inside of the function, that variable scope is limited to within that function but by using the?global?keyword, you can create?global variables?inside of the function.
Following is the example of creating the global variable inside of the function using the?global?keyword in python.
def?captain():
??global?player
? player =?"King Kohli"
Captain()
print("Welcome to RCB, "+ player)
If you observe the above example, we created a global variable (msg) inside of the?greeting()?function using a?global?keyword, and we are accessing the same variable outside of the function.
When you execute the above python example, you will get the result as shown below.
Welcome to RCb, King Kohli
Change Global Variable Inside of Function:
In some scenarios, we are not allowed to change the value of global variables inside of the function.
Following is the example of changing the global variable value inside of the function in python.
x =?10
def?calculate():
? ? x = x +?2
? ??print("Inside x val (x))
calculate()
print("Outside x val (x))
When you execute the above python program, you will get the exception as shown below.
Traceback (most recent call last):
? File "variables.py", line 5, in calculate()
? File "variables.py", line 3, in calculate x = x + 2
UnboundLocalError: local variable 'x' referenced before assignment
In this case, the?global?keyword is useful to make changes to the global variables inside of the function.
Following is the example of changing the value of the global variable inside of a function using the?global?keyword in python.
x =?10
def?calculate():
? ??global?x
? ? x = x +?2
? ??print("Inside x val: {}".format(x))
calculate()
print("Outside x val: {}".format(x))
If you observe the above example, we are modifying the value of the global variable (msg) inside of the function by using the python?global?keyword.
When we execute the above program, we will get the result as shown below.
Inside x val: 12
Outside x val: 12
If you observe the above result, the global variable (msg) value has been updated with the changes we made in the?calculate?function.?
Python Range() Function:
In python, range () function is useful to generate the sequence of numbers starting from 0 based on the specified values. For example, if you specify
the range(5) it will generate the numbers starting 0 to 4.
Range() Function Syntax
The following is the syntax of defining the range() function in python.
range(start, stop, step)?
If you observe the above range() function syntax, we used three parameters to define the range function, and all those parameters should be integers.
? start?- It's optional and useful to specify the starting position. In case if this value is not specified, by default, it will consider?0.
? stop?- It's required and useful to specify the ending position to stop generating the numbers.
? step?- It's optional and useful to specify the incrementation. By default, it's?1.
Range() Function Example:
The following is the example of using the range() function in python to generate the sequence of numbers.
#starting from 0 to 3
print("----0 to 3----")
a =?range(4)?
for?x?in?a:
? ??print(x)
#starting from 2 to 5
print("----2 to 5----")
b =?range(2,6)
for?y?in?b:
? ??print(y)
#starting from 5 to 14, but increment 3 instead of 1
print("----5 to 14, Increment 3----")
c =?range(5,?15,?3)
for?z?in?c:
? ??print(z)
If you observe the above example, we used different arguments in the range() function to generate the sequence of numbers based on our requirements.?
When you execute the above python example, you will get the result as shown below.
----0 to 3----
0
1
2
3
----2 to 5----
2
3
4
5
----5 to 14, Increment 3----
5
8
11
14
This is how you can use the range() function in your program to generate the sequence numbers based on your requirements.