Python Programming - Unit 3
Python Programming - Unit 3
PROGRAMMING AND
Functions and Modules PRODUCT DEVELOPMENT
CO 1
Course description
This course aims to teach everyone the core of
programming computers using Python. We cover
CO 2
python programming from basics to core. The course
has no pre-requisites and avoids all but the simplest
mathematics. Anyone with moderate computer
experience should be able to master the materials in
CO 3. this course. This course will cover Python data types,
functions, control and looping constructs, regular
expressions, user interface modules and the data
analytic packages. Once a student completes this
CO 4. course, they will be ready to perform core python
problem solving and also develop their own python
packages. This course covers Python 3.
CO 5.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Syllabus
Unit III Functions and Modules - 9 hrs
a) Functions
Introduction, Defining Your Own Functions,
Parameters, Function Documentation, Keyword
and Optional Parameters, Passing Collections to Functions and Modules
a Function, Variable Number of Arguments,
Scope, Functions - "First Class Citizens", Passing Outcomes
Functions to a Function, map, filter, Mapping
Functions in a Dictionary, Lambda, Inner
Functions, Closures
b) Modules
Modules, Standard Modules – sys, math, time,
The dir Function
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Unit 3 Outline
Lesson 1.
Lesson 1.
Lesson 3.
Lesson 4.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Course Progress
Lesson 1.
Lesson 2.
Lesson 3.
Lesson 4.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Topic 1
Concepts of Function
Topic 2
Types of Function
Topic 3
Scope or Lifetime of Variables
Topic 4
Function Documentation
First Lesson Outline
We will be learning about basics of Python
Functions
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Function - Introduction, Defining Your Own Functions
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Concepts of Function
Output:
The parameter values
can be represented as
{n} and {m} 7
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Concepts of Function
o Function Types :
1. Built-in functions: These are the functions represent within
User-defined Functions
itself.
Recursive functions
o Functions may be small or large.
@google images
o Providing functions inside a code helps in
modularization of a very large activity.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions: Built in functions
Example:
Function Description
•This language has a lot of modules
abs() Absolute value of a number is printed
that are pre-coded and voluntarily test = abs(-9.52)
available for use in programs. print(test)
Output: 9.52
•These are called as builtin functions. all() Checks the arguments and returns true if all the arg
are true
•A lot of built-in functions are offered sample = [True, False, True, True]
in Python. n = all(sample)
print(n)
•Some commonly used built in Output:
functions are as follows. false
any() sample = [True, False, True, True]
n = all(sample)
print(n)
Output:
false
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions: User-defined Functions
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
Syntax:
def func_nam(arg): """docstring""" stmt(s)
Example
Function call
# Program is odd/even
def even_odd(x):
if (a % 2 == 0):
even_odd(4)
even_odd(6)
print "even"
else: output
print "odd"
even
odd
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Creating a Function
o Example:
def test():
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Arguments
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Parameters- Function Arguments
1. Required arguments
2. Keyword arguments
3. Variable length arguments
4. Default arguments
@google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Number of Arguments
o The function about to be called should be called by specifying the required arguments
o If you have created a function to accept 2 arguments then make sure you call the function
using that arguments
Example
Function
Definition
Function Call
test(“Raju", “Ram")
Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example - Function Documentation
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example - Function Documentation
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example - Function Documentation
Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example - Function Documentation
Multiple
Function call
Function
Call
Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Required arguments
o The arguments supplied to a function in the correct sequence according to the argument position are known as
required arguments.
o The number of arguments in the function call should exactly match the number of parameters in the function
declaration.
When the default value
Example for multiply is m=1 &
def test_mul (m, n=1) :
b=3 and declare i as 5,
def print( test_str ):
we get the expected
"This prints the passed string in this function" result, 15
return m * n
print test_str
//Print the output by making a call to fn
return; print (‘The multiplication result is =‘, test_mul (3, n=5))
Function
Call
print()
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Arbitrary Arguments
Arbitrary Arguments, *args
Add a ‘*’ before the name of the parameter in the
function declaration to check the number of
arguments supplied to function.
Arbitrary Arguments
Example
Normally, when we are not clear with the number
of arguments then append ‘*’
in parameter name: Function call
def test(*children):
print("The youngest child is " + children[2])
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Keyword Arguments
Example
def test(kid3, kid2, kid1):
print("The youngest child is " + kid3)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Arbitrary Keyword Arguments, **kwargs
Add two asterisks: ** before the parameter name in the
function definition;
this will be helpful when a no. of keyword arguments will be
used in a function.
Example
when the number of keyword arguments is uncertain,
precede the parameter name with a double **:
def test(**child):
print(“the lname is " + child["lastname"])
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Default Parameter Value
o When a function is being called without any argument then, it takes default value:
Example
testme(“Tamilnadu")
testme(“Karnataka") Output
testme ()
testme(“Kerala")
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Calling a function
sample_test (“Laila”)
Output
Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Calling a function
# The function will call the say_hai with multiple parameters # Not clear on the number of parameters the
say_hai (‘Ronan', ‘Kathy', ‘Enrique') function is about to take
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Returning a Value from Function
•The return statement used in Python functions helps to return one or more value.
•The return statement should be the last statement inside a function because as soon as the
return statement is encountered, the flow inside the function starts and the control is
transferred to the location where the function was invoked.
•As stated earlier, return statement exits a function and returns a value to the statement from
where it has been invoked.
Syntax:
return [expr_list]
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Adam Number Program using Function
•In the example program function is used to check the number is adam number or not.
•Function is invoked by passing a number that is read from the user. Does number is
passed as a parameter and the body of the function checks whether the number id adam
or not.
•At the end of the execution of the function body code block, the final sum is returned to
the invocation line of the function. The result is then displayed.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Adam Number Program using Function
def test_rev (input_num): input_num = int (input (“Enter the value to find adam
test_remain = 0 number or not”))
test_sum = 0 Test_i=input_num **2
while (input_num > 0) :
test_remain = input_num * 10 + Test_j= test_rev (input_num)
test_remain
test_sum = test_sum *10 + Test_k=Test_j**2
test_remain
input_num = input_num / / 10 Test_l = test_rev (Test_k)
return (test_sum)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example –Adam Number
def test1(ex):
if (Test_i = = Test_l) : return 5 * ex
print (“The given input is an Adam value”)
else: print(test1(3))
print (“The given input is NOT an Adam value”) print(test1(5))
print(test1(9))
Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example –Adam Number
Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Scope or Lifetime of Variables
•Every variable used in Python has a lifetime. Lifetime is identified as the duration during which the variable
remains active and can be accessed.
•Lifetime of a variable varies depending upon where the variable is used inside a program
• All the variables defined inside program and the parameters that are passed to a function follow the rule of the
scope.
•The parameters that are used inside a function are visible and active only within the function.
•Outside of the function these parameters and other variables that are given within the function only cannot be
accessed.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Scope of Variables
def test_sample () :
•Variable that are defined outside the program in the driver code
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example – Local Scope
o Local scope of a variable is within a function and it is present inside that function.
o A variable created within a function is available inside that function:
def test(): Local
A = 200 scope
print(A)
test()
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Scope of Variables
o Then a call to func() is made, which sets the value of x to 10 once more.
o The variable x specified inside the function and the variable x defined in the driver code are different,
o The value of x inside the function, which is initialised to 10, has a local scope
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Function Inside Function
o The variable ‘x’ is not accessible outside of the function, however it is accessible within the function:
o Example
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
A = 300
def test():
print(A)
test() Output
print(A)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Global Keyword - Rules
3. Keyword ‘global’ can be used for reading and writing a global variable within a
function.
4. Keyword ‘global’ when represented outside a function will not have any effect.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Global in Nested Functions
def test():
The output is :
A = 10
def inside(): Before calling inside : 10
global A Call inside
After calling inside: 10 A in main: 255
A = 255
print("Before calling inside: ", A)
print(“Call inside")
bar()
print("After calling inside: ", A)
test()
print(“A in main: ", A)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
To update the value of a global variable inside a
function, use the global keyword to refer to the
variable:
We are now
abc = 300 accessing
and
def test(): changing
global abc the global
abc= 500 variable ‘f’
test()
print(abc)
@geeksforgeeks
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Naming Variables
Output:
o When we use the identical variable name into and A = 100
Example
The function prints the local value A and after that
outputs the global A:
@google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Global and Local Var
A= "global "
def test():
global A
B = "local"
A = A* 2
print(A)
print(B)
Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Global and Local var
A= 65
• The same name A to represent the local and global variables
def test():
in the previous code.
A= 20
• When we print the same variable, we get a diverse result
print("local scope A:", A)
since it is declared in both local and global with in test() and
outside test().
test() • Local variable A: 20 is printed when we print the variable
print("global scope A:", A) inside test(). This is referred to as the variable's local scope.
Output output
local scope A: 20
Global scope A: 65
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Non_local Variables
Output in()
print("out:", A)
in: nonlocal_scope
out: nonlocal_scope
out()
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
The Anonymous Functions
o These are referred to be anonymous since they are not declared using the normal def keyword.
o Lambda could receive as many arguments as they like, but they only return single value in the forum of an
expr.
o Lambda normally uses an expression, an anonymous function can’t consider a open call to account.
o Lambda functions have their own local namespace, that means they can only access variables in their
argument list and the global namespace.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Syntax
o Lambda functions have only one statement in their syntax, that can be represented as given below:
o lambda [arg1 [,arg2,.....argn]]:expression
Output: Output:
o Value of sum: 50 Value of sum : 50 10 20 30 40 50
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lesson Summary
❑Functions are useful for breaking the program into smaller and manageable chunks.
❑Python has a lot of functions that are pre-coded and readily available for use in programs.
❑Lifetime is identified as the duration during which the variable remains active and can be accessed.
❑Lifetime of a variable varies depending upon where the variable is used inside a program
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Course Progress
Lesson 1.
Lesson 2.
Lesson 3.
Lesson 4.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Topic 1
Passing Collections to a Function
Topic 2
Passing arguments to a Function
Topic 3
Nested Function Call
Topic 4
Recursive Function
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Passing Collections to a Functions
•Collection of objects of any type like list, tuple, set or dictionary can be sent as an argument
to a function.
•When passing normal variables, a single value of the variable is passed from the calling
function to the called function. Whereas when an object like a list or dictionary pass
parameter, all the values inside those objects are passed onto the called function.
•Inside the function code block the values can be used for execution just like in a normal
program execution.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Passing Collections to a Function
input = [“ball” , “cat”, “cricket”, “ball”] driver code is passed as a parameter to the
functions function1().
test_fn(input)
•The parameters are then used inside the code
output block of the function like normal object usage
ball and are executed. List elements passed as
cat arguments and returned.
cricket
ball
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Passing arguments to functions
def test_sample (a,b,c,d,e,f) :
tot = a+b+c+d+e+f output
print (“The total value result is”, tot)
•It is possible to sent any number of input from the function that is calling and to the
called function in order. Care should be taken when passing parameters.
•parameters are sent onto the function in the proper numerical sequence by the way they
are sent from the calling function.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Inner function
def test_fn1():
def test_fn2() :
Output:
//printing a message from the function inside
print ('I would like being home') This is my college
test_fn1()
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Nested function call
•Nested functions, such as nested loops, are supported in Python. A nested function is a
function that is nested inside another function.
•There is an outer function and an inner function, just like in nested loops. The outer
function will not be invoked if the inner function is called. Inner functions must be
explicitly invoked.
•Because the outer and inner functions are in the same scope, any variable declared inside
the outer function is available from the inner function.
•The local scope takes precedence over the outer function's functional scope by default.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example – Nested function call
hello('Jack', 'Darwin')
@google images
Output
Hello.......... Jack Darwin
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Recursive Function
•Recursion is the process of doing something on itself, as the name implies. Recursive functions
are possible in Python.
•Recursive functions are similar to regular functions, but they constantly call themselves.
•The calculation of a factorial of a given number is the best example of a recursive function.
•The function factorial() is continuously executed in this example until the value provided to it
matches the exit condition.
•The recursive function is called, and the multiplication is repeated until the requirement is met.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Recursive Function
o These are the functions which can be represented by different types of representations.
Disadvantages of Recursion
2. These calls are inefficient because they consume a huge amount of storage and time.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Recursive Function output
def fac_no(i):
if i == 0:
return 1 The fact of a number is i = 4
else: The fact of a number is i = 3
return i * fac_no (i-1) The fact of a number is i = 2
def fac_no(i) : The fact of a number is i = 1
print(“The fact of a number is i = " + str(i))
if i == 1: The in between results are shown as 2 * fac_no( 1 )= 2
return 1 The in between results are shown as 3 * fac_no( 1 )= 6
else: The in between results are shown as 4 * fac_no( 1 )= 24
output = n=i * fac_no (i-1)
print(“The in between results are shown as",
i, “
* fac_no (" ,i-1, ")= ",output) print (fac_no(4))
return output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
def recur(n): output
if(n > 0):
output = n + recur(n- 1)
print(output)
else:
output = 0
return output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Merits of Recursive Function
Merits:
•This gives a very good arrangement of code and enhances the readability of code
•Since, it is not need to include code that has been coming repeatedly coming in the program
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lesson Summary
❑Collection of objects of any type like list, tuple, set or dictionary can be sent as an argument to a
function.
❑Recursive functions are also normal function, but they call themselves repeatedly.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Course Progress (use before starting new lesson)
Lesson 1.
Lesson 2.
Lesson 3.
Lesson 4.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Topic 1
Map Function
Topic 2
Filter Function
Topic 3
Lambda Function
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
map(), reduce() and filter()
@google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Map Function
o In Python, the map function is used to conduct function activity on all of the items in an object
o The iterable object can be any object, which can be passed to the map() function as a parameter.
o The code block that needs to be executed on the iterable object is included in the function that is supplied as
a parameter to the map function.
o Syntax:
map(function, iterables)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python map() function
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Map Function Example
5 4 3 9
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Map Function Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example – Doubling Numbers using map()
def add(x):
return x+ x
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Calculate square of number using map()
def squ(x):
return x*x
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Map Function Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example 2: Use lambda function for calculating Square
num = (1, 2, 3, 4)
output = map(lambda A: A*A, num)
print(output)
num= set(output)
print(num)
Output
{16, 1, 4, 9}
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Passing Multiple Iterators to map() Using Lambda
output = map(lambda a1, a2: a1+a2, x1, x2) output = map(lambda a1, a2: a1- a2, x1, x2)
print(list(output)) print(list(output))
Output Output
[12, 18, 20] [20, 40, 42]
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Map Function Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Double all numbers using map and lambda
output
Output :
num = (11, 12, 13, 14)
[22, 24, 26, 28]
print(list(output))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Add two lists using map and lambda
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: List of strings
[[‘f', 'a', 't'], [‘m’, 'a', 't'], ['c', ‘u', 't'], [‘b', 'a', 't']]
sample = [‘computer', ‘laptop']
[[‘c', ‘o', ‘m‘, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’], [‘l’, ‘a‘, ‘p’, ‘t’, ‘o’, ‘p’]]
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
reduce() in Python
The reduce(fun,seq) method applies a certain function on entirely of the list components said in the
arrangement sent along. "functools“module
Working :
1. The first two elements of the sequence are chosen in the first step, and the result is achieved.
2. The result is then saved again after applying the similar func to the earlier obtained result and the no is
found to preceding the 2nd element.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: reduce()
import functools
output
Output:
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Filter Function
•The filter() function returns just the items in the iterable that satisfy a filtering criterion.
•The iterable's elements that don't meet the criterion aren't returned to the result.
•In Python, the filter function, like the map() method, is used to perform any function action on every item in an
object. Any object, such as a list, tuple, or set, can be iterable.
•They can be passed as a parameter to the filter() and map() functions, respectively.
iterable object.
@google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Filter Function
•The function that is passed as a parameter to the filter() function contains the code block
that must be run on the iterable object.
•The filter function creates a result by running the code block inside the function on each
iterable item
•.Syntax:
filter(function, iterables)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
filter()
The filter() method filters a sequence by calling a function that determines whether each component in the
classification is true or false.
syntax:
filter(func, seq)
Parameters:
func: the function for testing an element in sequence is true or not.
seq: the content which has to be filtered
Returns:
Outputs an iterator that was filtered.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
Usr_age = [3, 2, 6, 1, 93, 55, 33, 44, 22, 4]
return 0 93
else:
55
return 1
44
Usr_adult_1 = filter (sample_test , Usr_age)
22
For result in Usr_adult_1 :
print (result)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Filter Function Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Filtering vowels
def test(input): seq = [‘h', ‘s', 'e', ‘i', ‘m', 'se', ‘z', ‘n']
filter_output = filter(test, seq)
vowel = ['a', 'e', 'i', 'o', 'u']
print('The find out values in the output are:')
if (input in vowel):
for x in filter_output:
return 1 print(x)
else: output
Output:
return 0
The find out values in the output are: e e
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lambda Functions
Lambda functions
•In Python, lambda functions are functions that don't have a name.
•Because there is no name for these lambda functions, they are referred to as anonymous functions.
•Syntax :-
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lambda Function Example
//Generates 1st output
M = lambda I : I -20
output
print( M (100))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lambda Function Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python Lambda Functions
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lambda function
o This function accepts any number of inputs but only evaluates and returns one
expression.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example – lambda function adds 10 to the passed argument
output
x = lambda y: y + 5
print(x(10)) output
a = lambda b: b + 20
print(x(20)) 15
40
c = lambda d: d + 55 60
print(x(5))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: lambda function that multiplies arg a with b
x = lambda y, z: y * z
output
print(x(6, 5))
a = lambda b, c: b * c *d
print(a (5, 5, 5))
30
125
i = lambda j, k: j - k 5
print(x(10, 5))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: lambda function that sums the arg a, b and c
output
x = lambda p, q, r: p + q + r
print(x(3, 5, 5))
y = lambda a, b, c: a – b - c
print(y(10, 5, 5))
x = lambda p, q, r: p * q * r
print(x(2, 2, 2))
13
x = lambda p, q, r: p + q - r 0
print(x(30, 5, 5)) 8
30
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: def() and lambda()
print(cube(3))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Using lambda() Function with filter()
In Python, the filter() method accepts two parameters: a function and a list.
This is a good approach to get out all the items of a sequence "arrangement" that the function returns True.
Example:
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
output
age_per = [12, 90, 15, 56, 21, 65, 5] Output:
//this will be used to represent the persons bigger [90, 56, 21, 65]
than 18
print(adult)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
lambda() and map()
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Using lambda() Function with reduce()
output
o In Python, the reduce() method accepts two parameter: a fn and a Output:
list. 526
o A lambda function and an iterable are used to invoke the The result goes as this
function, and a new result is returned. (((((10+18)+40)+28)+30)+500).
o This performs a repeating action on the iterable's pairs.
o Example
from functools import reduce
List_x = [10,18, 40, 28, 30, 500]
total = reduce((lambda a, b: a + b), List_x)
print (total)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lesson Summary
o The filter function in Python returns only the items that satisfy a filtering condition
inside the iterable.
o Lambda functions in Python are functions that are defined without a name.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Course Progress
Lesson 1.
Lesson 2.
Lesson 3.
Lesson 4.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Topic 1
Modules - Introduction
Topic 2
Standard Modules - sys, math, time
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Modules
''' Module fib.py ''' This is taken and stored in a file name with .py
from __future__ import print_function extension
We have just created a module.
def fi_ev(x):
sum = 0
i, j = 0, 1
while i < a:
if i % 2 == 0:
sum = sum + i
i, j = j, i + j
return total
if output == "__main__":
final = raw_input(“Max Fibonacci
number: ") @google images
print(fi_ev(int(final)))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Definition?
o A file that contains a group of functions that can be used to represent in a programme.
@google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Creation - Module
Example
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Module Usage
Example
import test
test.greet("Jonathan")
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Variables in Module
The module can include not only functions, but also variables of any type (array, dictionary, object,
and so on):
Example
name1 = {
"name": “jack",
"age": 32,
"country": “India"
}
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
To convert a Python module to a Python package
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Re-naming a Module
import test as ex
x = ex.name1["age"]
print(x)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Built-in Modules
Python uses with a collection of built-in modules which we can use each time when it is
neededt.
Example
import platform
//this is used to print the system platform information
y = platform.system()
print(y)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Modules
o The output representation of the global variable ‘ex’ within a module is the module's
name.
o The value of the variable ‘ex’ will be "main" if a module is executed directly.
o These are only run the first time the module name appears in an import statement
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Modules
We could run our module directly at the ''' Module fib.py '''
command line. In this case, the module’s from __future__ import print_function
__name__ variable has the value “__main__”.
def fi_ev(i):
total = 0
$ python fib.py a, b = 0, 1
Max Fibonacci number: 4000000 while a < i:
4613732 if a % 2 == 0:
sum1 = sum1 + a
a, b = a, a + b
return sum1
if output == "__main__":
test = raw_input(“Max Fibonacci number: ")
print(fi_ev(int(test)))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Modules
''' Module fib.py '''
from __future__ import print_function
$ python
>>> import fib def fi_ev(i):
>>> fib.even_fib(4000000) total = 0
4613732 a, b = 0, 1
while a < i:
if a % 2 == 0:
sum1 = sum1 + a
a, b = a, a + b
return sum1
if output == "__main__":
test = raw_input(“Max Fibonacci number:
")
print(fi_ev(int(test)))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Modules
The modules can be imported to the ''' Module example.py '''
program easily by calling it. from __future__ import print_function
def fi_ev(i):
$ total = 0
>>> import example a, b = 0, 1
>>> fi.fi_ev(3000000) while a < i:
if a % 2 == 0:
sum1 = sum1 + a
a, b = a, a + b
return sum1
if output == "__main__":
test = raw_input(“Max Fibonacci
number: ")
print(fi_ev(int(test)))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Modules
I can import the definitions of the module ''' Module fib.py '''
directly into the interpreter. from __future__ import print_function
if output == "__main__":
test = raw_input(“Max Fibonacci number:
")
print(fi_ev(int(test)))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
$ python bar.py
What is the output when we execute the bar module directly?
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
$ python bar.py
Hi from bar's top level!
bar's __name__ is __main__
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
$ python foo.py
Now what happens when we execute the foo module directly?
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
$ python foo.py
Hi from bar's top level!
Hi from foo's top level!
foo's __name__ is __main__
Hello from bar!
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
$ python
>>> import foo Now what happens when we import the foo module into the interpreter?
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
$ python
>>> import foo
Hi from bar's top level!
Hi from foo's top level! And if we import the bar module into the interpreter?
>>> import bar
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz
$ python
>>> import foo
Hi from bar's top level!
Hi from foo's top level!
>>> import bar
>>>
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Module search path
o When a module is imported, Python has no idea where it is, so it looks for it in the following places, in the
following order:
o A Python application can change the sys.path variable to point somewhere else at any time.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Surprising behavior
Let’s say I have the following Python module. It defines the add_item function whose
arguments are item and item_list, which defaults to an empty list.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Surprising behavior
Let’s say I have the following Python module. It defines the add_item function whose arguments are item and
item_list, which defaults to an empty list.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Surprising behavior
This bizarre behavior actually gives us some insight into how Python works.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Surprising behavior
This bizarre behavior actually gives us some insight into how Python works.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Surprising behavior
An easy fix is to use a sentinel default value that tells you when to create a new mutable argument.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python sys Module
o Python's sys module has a number of methods and variables that can be used to alter various
aspects.
o It allows you to work with the interpreter since it gives you access to methods and fns that
work closely with it.
@data-flair
techvidvan
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Module search path
>>> print(print_path)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example:
import sys
print(sys.version)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Input and Output
o Variables in the sys modules gives for
good control of input and output.
import sys
o This can serve as an enabler to send input Input_stdin = sys.stdin
and output to different devices.
for line in Input_stdin:
o This is represented by if 'exit' == line.strip():
print(“Exiting or terminating the
stdin program”)
exit(0)
else:
stdout
print(‘The output image is'.format(line))
stderr
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
stdin
o This is used to provide a standard input to the system
o It's a input device used to provide input.
o It uses the input() function internally. It also adds a ‘\n' at the end of each sentence.
Example:
import sys
for line in sys.stdin:
if ‘x' == line.rstrip():
break
print(first : {data}')
print("Exit_program")
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
stdout
stdout:
o In Python, the interpreter's standard output stream corresponds to this built-in file object.
o A print statement, an expression statement, or even a prompt direct for input might
produce a variety of results..
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example:
sys.stdout.write(‘My name')
sys.stdout.write('\n')
I reside in India
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
stderr
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
sys.path
This is an variable which is capable of searching a path for all Python modules.
Example
>>> import sys
>>>sys.path
The sys module has a built-in part called sys.path.
It contains a directory list that the interpreter will look through to get the
appropriate module.
When a module (a python file) is imported into a Python file, the interpreter first
searches its built-in modules for the requested module.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
sys.maxsize
Returns the largest integer a variable can The sys module's maxsize attribute gives the
take. greatest number a python size variable can
hold.
Example: sys.maxsize
The extreme size of lists and strings in Python
>>> import sys is determined by the Python platform's pointer.
output The size value returned by maxsize is
>>>sys.maxsize
determined by the architecture of the platform:
8224472036854775807 May be for a 32 bit number -2 power 32
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
More Functions in Python sys
Function Description
To set the maximum depth sys.setrecursionlimit()
sys.setrecursionlimit()
method.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
More Functions in Python sys
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Working with Modules
sys.path
The sys module's built-in variable sys.path delivers a list of directories where the
interpreter will look for the required module.
When a module is imported into a Python file, the interpreter looks for it among the
interpreter's built-in modules first.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
Example 1: Listing out all the paths Example 2: Truncating the value of sys.path
import sys
import sys
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Import From Module
Using the from keyword, we can choose to import only pieces
from a module. user1 = {
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
The import import() function searches for the from math import *
module in the local scope first.
The function's return value is then mirrored in the
print(pi)
starting code's output.
print(math.pi)
print(factorial(7)
from test import user1
print (user1["age"])
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lesson Summary
❑ Details on a file containing a set of functions you want to include in your application.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Course Progress
Lesson 1.
Lesson 2.
Lesson 3.
Lesson 4.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Topic 1
dir function
Topic 2
math module
Topic 3
Exercises
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
dir() function in Python
dir({object}) print(dir(user))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Using the dir() Function
print(test)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Using the dir() Function
Parameters :
1. The dir() function returns all of the providing object's properties and methods, but not
their values.
2. All properties and methods, including built-in properties that are default for all objects,
will be returned by the function.
3. Without arguments, the method returns a list of names in the current local scope.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
dir()
o Because it tries to produce the most relevant, rather than full, information, the default
dir() method works differently with different sorts of objects:
o The list contains the names of the module's attributes if the item is a module object.
o If the object is a type or class object, the list includes the names of its attributes as well
as the attributes of its bases in a recursive manner.
o The names of attributes, its class's attributes, and its class's basic attributes make up the
rest of the list.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: Python dir() function
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
What is math module ?
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python math Module
There are lots of mathematical modules in python. This is very helpful during program implementation
This module has a lot of mathematical functions
Method Description
math.acos() Returns numbers arc cosine
math.acosh() Returns numbers inverse hyperbolic cosine
math.asin() Returns numbers arc sine
math.asinh() Returns numbers inverse hyperbolic sine
math.atan() Returns numbers arc tangent in radians
math.atan2() Returns numbers arc tangent of y/x
math.atanh() Returns numbers inverse hyperbolic tangent
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
math.acos()
The math.acos() method prints the arc cosine value of the input number.
Syntax
math.acos(z)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python math.asin() Method
o This method actually gives the arc sine of the inputted numbers math.asin() .
o math.asin(1) this will give the pi/2, and math.asin(-1) will give the value of –pi/2.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module
o The following tables gives a list of all the mathematical module in python
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Exercises: Spot the Error
Find error in the following code(if any) and correct code by rewriting code and underline the
correction;‐
i, j = 0
if (i = j)
i+j=z
print (result_num)
@Google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Answer
output
Error
i, j = 0, 0
If ( j = = i) :
Z= i+j
@Google images
Print (Z)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Exercises: Spot the Error
Find error in the following code(if any) and correct code by rewriting code and underline the
correction;‐
a= int(“Enter value of a:”)
for in range [0,10]:
if a=b
print( a + b)
else:
print( a‐b)
@Google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Answer
Error
a= int(input (“Enter value of a:”)
for in range (0,10):
if a= = b
print( a + b)
else:
print( a‐b) @Google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Exercises: Spot the Error
b) def main ()
print(“Many Men”)
c) def test_fc () :
print (10 + 20)
@Google images
test_fc (2)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Answer
output
b) def main ()
print(“Many Men”)
c) def test_fc () :
print (10 + 20)
test_fc (2) @Google images
// No parameter passed
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Finding the Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Finding the Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Finding the Output
import math
3
@Google images
print (math. Floor (2.8)) 2
print (math. Ceil (2.8))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Finding the Output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Useful modules in the Standard Library
o Python includes a number of builtin modules that provide regularly used function
o The Python std Library is a collection of modules that deal with common programming
tasks and is included with the standard version of Python, thus there is no need to install
it separately.
o It has modules for communicating with the operating system, read and write CSV,
generate random number and work with date & times, etc.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Date and time: datetime
o The datetime module represent on the way to generate about dates and times:
o datetime.date - this enable to creation of date and not associated with a time.
o datetime.datetime - enables use of objects that have together date and time.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
prev = datetime.datetime(1989, 2, 13, 11, 20, 55)
import datetime
print(prev)
cur = datetime.datetime.today()
print(prev< cur)
print(cur.year)
diff = cur - prev
print(cur.hour)
print(type(diff))
print(cur.minute) print(diff)
print(cur.weekday())
print(cur.strftime("%a %d %d %d"))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Output
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time Module
o Python represents a time module to get hold of dealing with time based tasks.
o Import the module first in to the program to make use of the same in your program.
Syntax
import time
o There are lot of time modules like time, ctime, sleep, local_time etc.
@Google images
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.time()
The time() function returns the number of seconds that have passed since the beginning of
time.
Example
import time
sec = time.time()
print("Second since beginning =", sec)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.ctime()
o The time.ctime() function receives the sec which is taken from the beginning as parameter
and outputs the string string mentioning local time.
import time
# seconds passed
sec = 185629464.77743904
loc_time = time.ctime(sec)
print("Local time is printed as:", loc_time) Local time is printed as:
Wed Jun 1 11:44:24 2021
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.sleep()
o The sleep() function suspends the current execution of thread's for the specified amount
of time.
import time
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.localtime()
o The localtime() function accepts an input of the amount of seconds since the begin and
returns time in local time.
import time
print = time.localtime(537846869)
Current time
print(“Output:", print)
print("\nyear is:", print.tm_year)
print("hour is:", print.tm_hour)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.gmtime()
o The gmtime() function accepts an response of the amount of secs since period and produces struct time in
Universal Time .
import time
out = time.gmtime(4374674823)
print(“output:", out)
print("\nyear:", result.tm_year)
print("tm_hour:", result.tm_hour)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.asctime()
o The asctime() function inputs struct_time as an parameter and outputs a string for printing
the output of the same.
Example
import time
test = (2021, 13, 21, 4, 45, 3, 3, 352, 1)
output = time.asctime(test)
print(“The result of the program is:", output)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.mktime()
o The struct time argument is supplied to the mktime() function, which returns the number of
seconds since the era in local time.
import time
test = (2021, 13, 21, 4, 45, 3, 3, 352, 1)
loc_tim = time.mktime(t)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.strftime()
o The strftime() function receives the struct_time as the paramenter and output a sequence
of character based on the needed format.
For example,
import time
nam_tup = time.localtime() # to receive struct time
tim_str = time.strftime("%m/%d/%Y, %H:%M:%S", nam_tup)
print(tim_str)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python time.strptime()
The strptime() function receives a sequence of character that represent time and outputs
the struct_time.
time.struct_time(tm_year=2021,
import time tm_mon=5, tm_mday=20, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=3,
tm_yday=140, tm_isdst=-1)
print(output)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python sleep()
o The sleep() function waits the thread execution for a provided number of time and it is
represented in seconds.
o Python offers a time module that contains various useful functions for dealing with time-
related activities.
o This delays the execution of the currently executed thread for the number of seconds
provided by the user.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example 1: Python sleep()
import time
Program has started to execute : Thu
print(“Program has started to execute : ", end ="")
print(time.ctime())
Jun 17 12:39:14 2021
# using sleep() to stop code execution for a while Program has ended in: Thu Jun 17
12:39:23 2021
time.sleep(9)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example 2: Local_Time Print
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Output – Calendar
output
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Modified better version of the above program.
import time
while True:
loc_tim = time.loc_tim()
output = time.strftime("%I:%M:%S %p", loc_time)
print(output, final="", flush=1)
print("\n", final="", flush=1)
time.sleep(2)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Python Closures
o We must first comprehend what a nested function and a nonlocal variable are formerly
so that one can understand what a closure is.
o These functions has to be declared and also they are read only, so it has to be declared
explicit in-order to use it/
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Nested function accessing a non-local variable
def out_msg(in):
# This is the outer function Output:
output
def print():
Hello welcome
# nested function
print(in)
print()
out_msg("Hello welcome")
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Defining a Closure Function
def print():
Closure fn = function (either created or returned by
# nested function other) + context_outer
print(in)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
When to use closures?
o The concept of closure in Python represent the nested function which is reffered as a
value in its enclosed scope.
o The following things that have to be used to ensure closure in Python are represented as
follows.
o The value defined in the surrounding function must be referenced by the nesting function.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
When to use closures?
o Closures can be used to prevent the use of global values and to hide data.
o Closures can give an alternative and more elegant way when there are only a
uncommon methods to implement in a class.
o When the number of characteristics and methods grows, it's preferable to create a
class.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: closure
def print_mul_of(n):
//Multiplier of 4
def test(a): ex4 print_mul_of(4)
return a * i //Multiplier of 5
ex3 print_mul_of(5)
return test
// Output: 25
print(ex5(5))
output
// Output: 6
Here's a basic example where using a print(ex2(3))
closure rather than establishing a class and
creating objects can be preferable. // Output: 36
print(ex5(ex6(6)))
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Lesson Summary
o Describes on listing all the defined names belonging to the platform module.
o Closure function is an introduction and description of a function that remembers values in surrounding
scopes even if they are not in memory.
o Introduces the Python time module, which includes functions for working with times and converting
between different representations.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Thank You!
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA