9.Functions in Python.docx
9.Functions in Python.docx
Website: https://pythonlife.in/
in
it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
e.
Syntax of Function
def dunction_name(parameters)
lif “ “ “ doc string ”””
on
statement(s)
components.
1.Keyword def that marks the start of the function header.
Py
in
def greet(name):
"""
e.
This function greets to
"""
on
print("Hello, " + name + ". Good morning!")
program, or even the Python prompt. To call a function we simply type the
function name with appropriate parameters.
Py
greet('Paul')
Hello, Paul. Good morning!
Try running the above code in the Python program with the function
definition to see the output.
def greet(name):
""" This function greets to
3
Website: https://pythonlife.in/
the person passed in as
a parameter ""“
print("Hello, " + name + ". Good morning!")
greet('Paul')
Output
Hello, Paul. Good morning!
in
Note: In python, the function definition should always be present before the
function call. Otherwise, we will get an error. For example,
e.
# function call
greet('Paul')
lif
# function definition
def greet(name):
on
"""
This function greets to
th
"""
print("Hello, " + name + ". Good morning!")
# Error: name 'greet' is not defined
4
Website: https://pythonlife.in/
Docstrings
The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.
In the above example, we have a docstring immediately below the function header.
in
We generally use triple quotes so that docstring can extend up to multiple lines.
This string is available to us as the _doc_ attribute of the function.
For example:
e.
Try running the following into the Python shell to see the output.
print(greet.__doc__)
lif
This function greets to
on
the person passed in as
a parameter
The return statement is used to exit a function and go back to the place from
where it was called.
Syntax of return
Py
return [expression_list]
This statement can contain an expression that gets evaluated and the value is
returned. If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return the None
object.
5
Website: https://pythonlife.in/
For example:
print(greet("May"))
Hello, May. Good morning!
None
Here, None is the returned value since greet( ) directly prints the name and
no return statement is used.
in
e.
Example of return
def absolute_value(num):
lif
"""This function returns the absolute
on
value of the entered number"""
if num >= 0:
return num
th
else:
return -num
Py
print(absolute_value(2))
print(absolute_value(-4))
Output
2
4
6
Website: https://pythonlife.in/
in
e.
lif Working of functions in Python
on
Scope and Lifetime of variables
th
The lifetime of a variable is the period throughout which the variable exists in
the memory. The lifetime of variables inside a function is as long as the
function executes.
They are destroyed once we return from the function. Hence, a function does
not remember the value of a variable from its previous calls.
in
print("Value outside function:",x)
Output
e.
Value inside function: 10
Value outside function: 20
lif
Here, we can see that the value of x is 20 initially. Even though the function
on
my_func() changed the value of x to 10, it did not affect the value outside the
function.
This is because the variable x inside the function is different (local to the
function) from the one outside. Although they have the same names, they are
th
Types of Functions
8
Website: https://pythonlife.in/
Basically, we can divide functions into the following two types:
1.Built-in functions - Functions that are built into Python.
2.User-defined functions - Functions defined by the users themselves.
Advance Functions
in
Lambda Function
A lambda function is a small anonymous function.
e.
A lambda function can take any number of arguments, but can only
have one expression.
lif
on
th
Py
9
Website: https://pythonlife.in/
Map Function
map() function returns a map object(which is an iterator) of the
results after applying the given function to each item of a given
iterable (list, tuple etc.)
in
Syntax :
map(fun, iter)
e.
fun : It is a function to which map passes each element of given
iterable.
lif
iter : It is a iterable which is to be mapped.
on
# Python program to demonstrate working
# of map.
th
# Return double of n
Py
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
10
Website: https://pythonlife.in/
result = map(addition, numbers)
print(list(result))
Filter Function
in
The filter() method filters the given sequence with the help
of a function that tests each element in the sequence to be
e.
true or not.
syntax:
lif
filter(function, sequence)
on
function: function that tests if each element of a
sequence true or not.
sequence: sequence which needs to be filtered, it can
th
in
return False
e.
# sequence
lif
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
on
# using filter function
filtered = filter(fun, sequence)
th
for s in filtered:
print(s)
12
Website: https://pythonlife.in/
Generator Function
A generator-function is defined like a normal function, but
whenever it needs to generate a value, it does so with the yield
keyword rather than return. If the body of a def contains yield, the
function automatically becomes a generator function.
in
The difference between the yield and the return statement in
e.
Python is:
Return. A function that returns a value is called once. The return
statement returns a value and exits the function altogether.
lif
Yield. A function that yields values, is called repeatedly. The yield
statement pauses the execution of a function and returns a value.
on
When called again, the function continues execution from the
previous yield. A function that yields values is known as a
generator.
th
def simpleGeneratorFun():
yield 1
yield 2
yield 3
13
Website: https://pythonlife.in/
# Driver code to check above generator function
print(value)
Reduce Function
in
the reduce() function receives two arguments, a function and an
iterable. However, it doesn't return another iterable, instead it returns
a single value.
e.
lif
on
th
Py
14
Website: https://pythonlife.in/
import functools
in
# initializing list
lis = [1, 3, 5, 6, 2]
e.
# using reduce to compute sum of list