Functions
Functions
Functions
Python Functions
Functions in python:
Why we use Functions:
•Sometimes when we write a program, we use the same code again and again and what we do is we write the same
code multiple times which increases the line of codes as well as the code complexity also. To overcome this
problem, we use functions.
Defining a Function
•A function is a reusable block of programming statements designed to perform a certain task. To define a function,
Python provides the def keyword. The following is the syntax of defining a function.
Syntax:
def function_name(parameters):
"""docstring"""
statement1
statement2
...
...
return [expr]
• The keyword def is followed by a suitable identifier as the name of the function and
parentheses. One or more parameters may be optionally mentioned inside parentheses. The :
symbol after parentheses starts an indented block.
• The first statement in the function body can be a string, which is called the docstring. It
explains the functionality of the function/class. The docstring is not mandatory.
• The function body contains one or more statements that perform some actions. It can also use
pass keyword.
• Optionally, the last statement in the function block is the return statement. It sends an
execution control back to calling the environment. If an expression is added in front of return,
its value is also returned to the calling code.
Example: User-defined Function
def greet():
"""This function displays 'Hello World!'"""
print('Hello World!')
greet()
• Above, we have defined the greet() function. The first statement is a docstring that mentions
what this function does. The second like is a print method that displays the specified string to
the console. Note that it does not have the return statement.
• To call a defined function, just use its name as a statement anywhere in the code. For example,
the above function can be called using parenthesis, greet().
• Example: Calling User-defined Function
greet()
• By default, all the functions return None if the return statement does not exist.
def greet():
"""This function displays 'Hello World!'"""
print('Hello World!')
val = greet()
print(val)
Benefits of using Functions
•Write once use multiple: Sometimes in the program, we write some code and then later we
need that code again to perform the same task. What we do is we write the same code again.
This is not the best practice to go through. We use the concept of functions in python. We define
the function once and call it multiple times when required.
•Easy Readability: Using the concept of functions, we do not write the same code again and
again. Hence our program became structured and readable. Hence it improves the readability of
our program/code.
•Reduce Execution Time: Using functions our lines of code is reduced and hence it results in the
fast execution of our program.
Types of Functions in Python:
•There are two types of Function in Python Programming:
•Types of Functions in Python: There are two types of functions available in python. These are:
1.Built-in Functions or Pre-defined
2.User-defined Functions
1). Built-in Functions:
•Built-in functions are the functions that are already written or defined in python. We only need
to remember the names of built-in functions and the parameters used in the functions. As these
functions are already defined so we do not need to define these functions. Below are some built-
in functions of Python.
Built-in Functions used in Python
Function name Description
1)len() It returns the length of an object/value.
2)list() It returns a list.
3)max() It is used to return maximum value from a sequence (list,sets) etc.
4)min() It is used to return minimum value from a sequence (list,sets) etc.
5)open() It is used to open a file.
6)print() It is used to print statement.
7)str()It is used to return string object/value.
8)sum() It is used to sum the values inside sequence.
9)type() It is used to return the type of object.
10)tuple() It is used to return a tuple.
#In built functions
x = [1,2,3,4,5]
print(len(x)) #it return length of list
print(type(x)) #it return object type
Output: 5 <class 'list'>
2). User-Defined Functions:
The functions defined by a programmer to reduce the complexity of big problems and to use
that function according to their need. This type of functions is called user-defined functions.
Example of user-defined functions:
x=3
y=4
def add():
print(x+y)
add()
Output:7
Call a function:
To call a function we simply type the function name with appropriate parameters
Example:
def f1():
print("Hello World")
f1()
Output : Hello World
The return statement
•The return statement is used to exit a function and go back to the place from where it was
called.
•The return statement is used at the end of the function and returns the result of the function.
•A return statement with no arguments is the same as return None.
Syntax: return value
Example:
def f1(a,b):
c=a+b
return c
sum=f1(10,20)
print(sum)
Output:
30
Parameters and arguments:
•A parameter is the variable listed inside the parentheses in the function definition.
•An argument is the value that are sent to the function when it is called.
•Parameters are the names used when defining a function, and into which arguments will be
mapped.
•Arguments are the things which are supplied to any function call, while the function code refers
to the arguments by their parameter names.
a, b are parameters a, b are arguments
Types of arguments:
1.Default arguments
2.Keyword arguments
3.Required arguments
4.Variable number of arguments
1.Default Arguments
Default arguments are values that are provided while defining functions.
The assignment operator = is used to assign a default value to the argument.
Default arguments become optional during the function calls.
If we provide a value to the default arguments during function calls, it overrides the default
value.
The function can have any number of default arguments
Default arguments should follow non-default arguments.
Example:
•The default value is given to argument band c
def add(a,b=5,c=10):
return (a+b+c)
•This function can be called in 3 ways
1.Giving only the mandatory argument
print(add(3))
#Output:18
•2. Giving one of the optional arguments.
3 is assigned to a, 4 is assigned to b.
print(add(3,4))
#Output:17
•3. Giving all the arguments
print(add(2,3,4))
#Output:9
2.Keyword Arguments
•Functions can also be called using keyword arguments of the form kwarg=value.
•During a function call, values passed through arguments need not be in the order of parameters in
the function definition. This can be achieved by keyword arguments. But all the keyword arguments should
match the parameters in the function definition.
•Example:
def add(a,b=5,c=10):
return (a+b+c)
•Calling the function add by giving keyword arguments
1.All parameters are given as keyword arguments, so no need to maintain the same order.
print(add(b=10,c=15,a=20))
#Output:45
2. During a function call, only giving mandatory argument as a keyword argument. Optional default arguments are
skipped.
print(add(a=10))
#Output:25
3.Positional Arguments
•During a function call, values passed through arguments should be in the order of parameters in the
function definition. This is called positional arguments.
•Keyword arguments should follow positional arguments only.
•Example:
def add(a,b,c):
return (a+b+c)
•The above function can be called in two ways:
•During the function call, all arguments are given as positional arguments. Values passed through arguments are
passed to parameters by their position. 10 is assigned to a, 20 is assigned to b and 30 is assigned to c.
print (add(10,20,30))
#Output:60
•2. Giving a mix of positional and keyword arguments, keyword arguments should always follow positional arguments
print (add(10,c=30,b=20))
#Output:60
Variable-length arguments
•Variable-length arguments are also known as arbitrary arguments. If we don’t know the number of arguments
needed for the function in advance, we can use arbitrary arguments
Two types of arbitrary arguments
4.arbitrary positional arguments
5.arbitrary keyword arguments
4. arbitrary positional arguments:
•For arbitrary positional argument, an asterisk (*) is placed before a parameter in function definition which
can hold non-keyword variable-length arguments. These arguments will be wrapped up in a tuple. Before the
variable number of arguments, zero or more normal arguments may occur.
def add(*b):
result=0
for i in b:
result=result+i
return result
print (add(1,2,3,4,5))
#Output:15
•print (add(10,20))
#Output:30
5.arbitrary keyword arguments:
•For arbitrary positional argument, a double asterisk (**) is placed before a parameter in a function which
can hold keyword variable-length arguments.
Example:
def fn(**a):
for i in a.items():
print (i)
fn(numbers=5,colors="blue",fruits="apple")
Output:
('numbers', 5)
('colors', 'blue')
Categories of functions (or)Types of user defined functions in Python:
1.Function with no argument and no return value.
2.Function with no argument and with a Return value.
3.Function with argument and No Return value.
4.Function with argument and return value.
1.Function with no argument and no return value
• Defining, declaring, or calling the function, We won’t pass any arguments to the function.
•This type of function won’t return any value when we call the function.
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Output: 30
2.Function with no argument and with a Return value
•Not pass any arguments to the function while defining, declaring, or calling the function.
• When we call the function, this type of function returns some value.
Example:
def add():
a=10
b=20
c=a+b
return c
print(add())
Output: 30
3.Function with argument and No Return value
• It allows to pass the arguments to the function while calling the function.
•But not return any value when we call the function.
Example:
def add(a,b):
c=a+b
print(c)
add(10,20)
Output: 30
4.Function with argument and return value
•It is used to pass the arguments to the function while calling the function.
• It returns some value when we call the function.
Example:
def add(a,b):
c=a+b
return c
print(add(10,20))
Output:
30
Scope of Variables
•All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
•The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python −
1.Global variables
2.Local variables
•Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
•This means that local variables can be accessed only inside the function in which
they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope.
• The variable defined outside of a function is called “Global” and the variable defined inside a
function is called “Local” variable.
• Scope of the Global variable is everywhere inside the program. We can access the global
variable even inside the function also. But the scope of the local variable is limited. It is only
accessible inside the function only where it has been defined or declared.
• We cannot use a local variable outside of the function. If we do so, then the compiler will
generate an error as a variable is not defined.
Local Variable Global Variable
Local variable is declared inside a function. Global variable is declared outside the
function.
It is lost when the function terminates. It is lost when the program ends.
The scope is limited. The scope remains throughout the program.
It is stored on the stack It is stored on a fixed location decided by
the compiler
#Local and Global variable
x = 23 #This is the Global Variable
def fnc_name():
y = 24 #This is Local Variable
print(y)
fnc_name()
print(y)
Output:
24
Error: variable not defined
• if a variable that is already present in global scope is declared in a local scope of a function as
well, the compiler gives priority in the local scope. Further, change of its value inside function
doesn't affect it in the global space.
Example:
x=10
def myfunction():
x=10
x=x*2
print ('x inside function: ', x)
myfunction()
print ('x in global scope: ',x)
Output
x inside function: 20
x in global scope: 10
• Python also has a global keyword. It allows a globally declared variable to be used and
modified inside a function, ensuring that the modifications are reflected globally as well.
Example:
x=10
def myfunction():
global x
x=x*2
print ('global variable x inside function: ',x)
return
myfunction()
print ('global variable x in global scope: ',x)
Output
global variable x inside function: 20
global variable x in global scope: 20
Python Lambda Expresssions
•Lambda Functions and Anonymous Functions in Python
•The def keyword is used to define a function in Python, as we have seen.
•The lambda keyword is used to define anonymous functions in Python. Usually, such a function
is meant for one-time use.
Syntax:lambda [arguments] : expression
•The lambda function can have zero or more arguments after the : symbol. When this function is
called, the expression after : is executed.
square = lambda x : x * x
n = square(5)
print(n)
•Above, the lambda function starts with the lambda keyword followed by parameter x. An
expression x * x after : returns the value of x * x to the caller.
•The whole lambda function lambda x : x * x is assigned to a variable square in order to call it like
a named function.
• The variable name becomes the function name so that We can call it as a regular function, as
shown below.
• The expression does not need to always return a value. The following lambda function does
not return anything.
Example:
greet = lambda name: print('Hello ', name)
greet('Steve')
Note:
The lambda function can have only one expression. Obviously, it cannot substitute a function
whose body may have conditionals, loops, etc.
• The following lambda function contains three parameters:
Example:
sum = lambda x, y, z : x + y + z
n = sum(5, 10, 15)
print(n)
• A lambda function can take any number of parameters by prefixing * before a
parameter, as shown below:
sum = lambda *x: x[0]+x[1]+x[2]+x[3]
n = sum(5, 10, 15, 20)
print(n)
Parameterless Lambda Function
The following is an example of the parameterless lambda function.
Example: Parameterless Lambda Function
greet = lambda : print('Hello World!')
greet()
Anonymous Function
We can declare a lambda function and call it as an anonymous function, without assigning it to a
variable.
Example:
(lambda x: print(x*x))(5)
Above, lambda x: x*x defines an anonymous function and call it once by passing arguments in
the parenthesis (lambda x: x*x)(5).
Recursion
•Recursion is the process of defining something in terms of itself.
Python Recursive Function
•In Python, we know that a function can call other functions. It is even possible for the function
to call itself. These types of construct are termed as recursive functions.
•The following image shows the working of a recursive function called recurse.
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Advantages of Recursion
•Recursive functions make the code look clean and elegant.
•A complex task can be broken down into simpler sub-problems using recursion.
•Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
•Sometimes the logic behind recursion is hard to follow through.
•Recursive calls are expensive (inefficient) as they take up a lot of memory and
time.
•Recursive functions are hard to debug.
Python range()
The range() function returns a sequence of numbers between the give range.
Example
# create a sequence of numbers from 0 to 3
numbers = range(4)
# iterating through the sequence of numbers
for i in numbers:
print(i)
Output:
0
1
2
3
Note: range() returns an immutable sequence of numbers that can be easily converted to lists,
tuples, sets etc.
Syntax of range()
The range() function can take a maximum of three arguments:
range(start, stop, step)
The start and step parameters in range() are optional.
Now, let's see how range() works with different number of arguments.
1)range() with Stop Argument
•If we pass a single argument to range(), it means we are passing the stop argument.
•In this case, range() returns a sequence of numbers starting from 0 up to the number (but not
including the number).
# numbers from 0 to 3 (4 is not included)
numbers = range(4)
print(list(numbers)) # [0, 1, 2, 3]
# if 0 or negative number is passed, we get an empty sequence
numbers = range(-4)
print(list(numbers)) # []
2)range() with Start and Stop Arguments
•If we pass two arguments to range(), it means we are passing start and stop arguments.
•In this case, range() returns a sequence of numbers starting from start (inclusive) up to stop
(exclusive).
# numbers from 2 to 4 (5 is not included)
numbers = range(2, 5)
print(list(numbers)) # [2, 3, 4]
# numbers from -2 to 3 (4 is not included)
numbers = range(-2, 4)
print(list(numbers)) # [-2, -1, 0, 1, 2, 3]
# returns an empty sequence of numbers
numbers = range(4, 2)
print(list(numbers)) # []
3)range() with Start, Stop and Step Arguments
•If we pass all three arguments,
•The first argument is start, the second argument is stop, the third argument is step
•The step argument specifies the incrementation between two numbers in the sequence.
# numbers from 2 to 10 with increment 3 between numbers
numbers = range(2, 10, 3)
print(list(numbers)) # [2, 5, 8]
# numbers from 4 to -1 with increment of -1
numbers = range(4, -1, -1)
print(list(numbers)) # [4, 3, 2, 1, 0]
# numbers from 1 to 4 with increment of 1
# range(0, 5, 1) is equivalent to range(5)
numbers = range(0, 5, 1)
print(list(numbers)) # [0, 1, 2, 3, 4]
1)Return multiple values from a function
def calculation(a, b):
return a + b, a - b
display_student(“Venkatesh", 30)
showStudent = display_student
showStudent(“Venkatesh", 30)
3)Write a python program using function to find the largest element in a list.
def largest(L,n) :
max = L[0]
for i in range(1, n) :
if L[i] > max :
max =L[i]
return max
M = [10, 24, 45, 90, 98]
n = len(M)
max= largest(M, n)
print ("Largest in the given List is", max)
Output:
Largest in the given List is 98
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))