0% found this document useful (0 votes)
1 views

Python Programming - Unit 3

This document outlines a course on Python programming focusing on functions and modules, suitable for individuals with moderate computer experience. It covers essential topics such as defining functions, parameters, function documentation, and modules, along with practical examples. The course aims to equip students with the skills to perform core Python problem-solving and develop their own packages using Python 3.

Uploaded by

nehanixon33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python Programming - Unit 3

This document outlines a course on Python programming focusing on functions and modules, suitable for individuals with moderate computer experience. It covers essential topics such as defining functions, parameters, function documentation, and modules, along with practical examples. The course aims to equip students with the skills to perform core Python problem-solving and develop their own packages using Python 3.

Uploaded by

nehanixon33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 206

Unit –III PYTHON FOR

PROGRAMMING AND
Functions and Modules PRODUCT DEVELOPMENT

© Kalasalingam academy of research and education


Course Outline

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 2. Introduction to Functions

Lesson 3.

Lesson 4.

Lesson 5. The dir Function

© 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.

Lesson 5. The dir Function

© 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

o Grouped by a sequence of statements that perform and activity.

o Breaking the program into smaller and manageable chunks.

o May be small or large.

o Helps in modularization of a very large activity.

o Reduces the repetition of code.

o One function is reusable any number of times.

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Concepts of Function

•Function in any language which comprises of a customary of


def sample(n, m):
statements that are related and put together to achieve a job.
print ("The parameter values
•Every fn is grouped by a sequence of statements that perform
can be represented as {n} and {m}")
and activity.
return n+m
•Every function is a small module that can perform an individual
print(sample(2,5))
task.

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.

2. User-defined functions: These are represented by user Built-in Functions

itself. Lambda functions

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

•represented by the user of the program.


•This enables to split a bigger program in to smaller modules.
•Bigger program can be divided for representing different functions.
Syntax:
def fun_nam(parameters): stmt(s)
return values
•Every function in Python is identified by the "def" keyword. Usage of "def" marks the beginning of the function
header. Every function is identified by its unique name in Python.
•Return is the keyword used in Python to return any value back to the calling location. Return is optional in Python.

© 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 The keyword ‘def’ is used for


create/define a function

o Example:

def test():

print(“Hey! This is inside


function")

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Arguments

❑ It is possible to pass arguments as information in a function.


❑ These are represented after specifying the function name.
Example: Refer the function which gets argument .
//creating a function
//create a new function subtract
with 2 arguments

def sample_subtract (value1,


value2) :
//outputs the resultant value
print (“value1 –value2”)
Output
sample_subtract (200,100)

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Parameters- Function Arguments

Arguments in function can be classified as − 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

def test(firstname, lastname):


print(firstname + " " + lastname)

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

//Find the difference


// documentation
diff_out = x1 - x2
//this program finds the sum, difference, average of
/Print the difference
a number
print (‘Subtraction result of x1 and x2 =‘,
// Initially create a new function
diff_out)
def avg_sum (x1 , x2) :
//Find the average of the 2 numbers
// Finding the sum first of a number
avg_out = sum_out / 2
sum_out = x1 + x2
/Print the average
//Print the sum
print (‘Average result of x1 and x2 =‘, avg_out)
print (‘sum of x1 and x2 =‘, sum_out)
# this is the ending line of my program

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example - Function Documentation

# now to access the function call the function


avg_sum (40, 30)
Multiple
avg_sum (50, 20) Function call
avg_sum (100, 20)
avg_sum (50, 50)
Output

sum of x1 and x2 = 70 sum of x1 and x2 = 120


Subtraction result of x1 and x2 = 10 Subtraction result of x1 and x2 = 80
Average result of x1 and x2 = 35 Average result of x1 and x2 = 60
sum of x1 and x2 =70 sum of x1 and x2 = 100
Subtraction result of x1 and x2 = 30 Subtraction result of x1 and x2 = 0
Average result of x1 and x2 = 35 Average result of x1 and x2 = 50

© 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])

test(“Sofia", “Tom", “Jerry")

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Keyword Arguments

o These are assigned as key = value.


o Since the value is specified directly,
the argument sequence does not
matter.

Example
def test(kid3, kid2, kid1):
print("The youngest child is " + kid3)

my_function(kid1 = “Rose", kid2


= “John", kid3 = “Jake")

© 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"])

test(firstname = “Gopi", lastname = “Sundar")

© 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

def testme(State = “Delhi"):


print("I reside in " + State)

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

def sample_test (usr_name) :

print(“ Come with me for lunch Ms.


“ +usr_name)

sample_test (“Laila”)

Output
Output

Come with me for lunch Ms. Laila

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Calling a function

def say_hai (* tag_n):


def say_hai (tag_n1, tag_n2, tag_n3): print (‘say hai ', tag_n [0], ', ', tag_n [1], ', ',
print (‘say hai ', tag_n1, ' ! ', tag_n2 , ‘!’ , and ', tag_n3) tag_n [3]))

# 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

Output: say_hai (‘Ronan', ‘Kathy', ‘Enrique')

say hai, Ronan ! ‘Kathy ! Enrique

© 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

Enter the value to find adam number or not : 112 Output


The given input is an Adam value
Enter the value to find adam number or not : 301 15
The given input is an Adam value 25
Enter the value to find adam number or not : 10 45
The given input is an Not an Adam value

© 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

test_in = 20 have global scope.


•The variables that are used inside the local scope are alive only
print (‘Hai, I am within the function’,
during the execution of the scope.
+test_in)
output
test_in = 52

test_sample () Hai, I am within the function 20

print(‘The value of test_in is ‘, +test_in) The value of test_in is 52

© 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 In the driver code, the value of x is set to 20 in this example.

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,

according to the Python interpreter rule of scope.

o The value of x inside the function, which is initialised to 10, has a local scope

o This can be then utilised within the function.

© 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

o Global denotes a variable which is created outside a function and it is available/used by


all the functions
global

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

We represent the rules for keyword ‘global ‘ as follows:

1. Variable which is created within a function is default represented as ‘local’.

2. Variable which is created out of a function is default represented as ‘global’.

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

out of function. 200


def test():
100
A = 200
o It treats these variables as 2 independent variables print(A)

among which the first is global scope and other is test()

local scope: print(A)

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

global global local


test()

© 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

o Non-local variables are utilised in nested functions Example:


with an undefined local scope.
def out():
o This indicates it can't be in both the local and global
scopes. A = "local_scope"

o To generate nonlocal variables, we employ nonlocal def in():


keywords. nonlocal A
A = "nonlocal_Scope"
print("in:", A)

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 The lambda keyword can be used to define short anonymous functions.

o Lambda could receive as many arguments as they like, but they only return single value in the forum of an
expr.

o They can't have numerous expressions or commands in them.

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

z = lambda x1, x2: x1 + x2;


Num = [10, 20, 30, 40, 50]

print "Value of sum : ", z( 20, 30 ) Num = filter(lambda A: A%2 == 0, Num)

print "Value of sum : ", z( 30, 20 ) for i in Num:

print(i, end = ‘ ')

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

❑Every function is grouped by a sequence of statements that perform and activity.

❑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.

Lesson 5. The dir function

© 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

Second Lesson Outline


We will be learning about collections, arguments in
Python Functions

© 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.

•These objects can be forwarded just like normal variables.

•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

def test_fn(input) : List object as parameter


for i in input :
print (i) •In the above example the list created in the

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)

Get the 1st value 2


a = int (input (“Get the 1st value”))
Get the 2nd value 2
b = int (input (“Get the 2nd value”))
Get the 3rd value 2
c = int (input (“Get the 3rd value”))
Get the 4th value 2
d = int (input (“Get the 4th value”))
Get the 5th value 2
e = int (input (“Get the 5th value”))
Get the 6th value 2
f = int (input (“Get the 6th value”))
The total value result is 12
test_sample(a, b, c, d, e, f)
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Passing arguments to functions

•Functions can take in a different no of parameters. The no of parameters a function can


accept is not restricted.

•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():

//printing a message from the function outside

print ('This is my college') output

def test_fn2() :
Output:
//printing a message from the function inside
print ('I would like being home') This is my college

//This is the call to function I would like being home


test_fn2()

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

def hello (fir_name, ls_name) :


def complete_name():
return fir_name +" "+ ls_name
print("Hello, " + complete_name() + "..........")

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 user is asked to provide a value for the calculation.

•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 A function in Python can make a call to other functions.

o It's possible that the function will call the aforementioned.

o These are the functions which can be represented by different types of representations.

o The recursive function recurse is demonstrated in the following graphic.

Disadvantages of Recursion

1. The rationale of recursion can be difficult to follow at times.

2. These calls are inefficient because they consume a huge amount of storage and time.

3. Debugging recursive functions is difficult.

© 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

print("\nRecursion Example Results")


recur(6)

© 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

•This breaks/divides the code in to several small sections

•Recursion makes it easier to generate sequences than nested iteration.

•The code seems to be more simpler.

© 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.

❑Nested function contains one function inside another 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.

Lesson 5. The dir function

© 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

Third Lesson Outline


We will be learning about Map, Filter and Lambda
function in Python

© 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 A function must be given as a parameter along with the iterable object.

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

o map() After relating the supplied function to


each item of a given iterable, the map()
function returns a map object (which is an
iterator) of the results (list, tuple etc.)
o Syntax :
map(func, itera)
Parameters :
func : represents a function.
itert : represent an iterable.

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Map Function Example

def test_sample (x) :


return len (x)

abc = map (test_sample, (“Beatle” , “Bear”, “Dog”, Crocodile”)

//the statement to change the map in to element so that to enhance


readability
output
print (list (abc))

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

num = (4, 5, 6, 7) [8, 10, 12, 14


output = map(add, num)
print(list(output))

© 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

num = (4, 5, 6, 7) output

output = map(squ, num)


print(output) {16, 25, 36, 49}

# converting map object to set


num = set(output)
print(squ)

© 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

x1 = [10, 15, 16] x1 = [25, 45, 50]


x2 = [2, 3, 4] x2 = [5, 5, 8]

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

def test_sample (ab, bc) :


return ab + bc

Output = map (test_sample, (‘Jackie’ , ‘kate’, ‘jeff’) , (‘chan’ , ‘vincelet’, ‘Larson’)

print (list (Output))

output

[‘ Jackiechan’ , ‘katevincelet’, ‘jeffLarson’ ]

© 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]

output = map(lambda a: a + a, num)

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

n1 = [11, 12, 13]


Output :
output
n2 = [2, 3, 2]

[13, 15, 15]


output = map(lambda a, b: a + b, n1, n2)
print(list(output))

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: List of strings

sample = [‘fat', ‘mat', cut', ‘bat']


output

output = list(map(list, sample))


print(output) Output :

[[‘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’]]

output = list(map(list, sample))


print(output)

© 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.

3. This procedure is performed until the container has no more

components. The final result is returned to the console and printed.

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example: reduce()
import functools
output
Output:

The total elements are : 17


a = [ 1 , 2, 6, 5, 3]
Maximum element is : 6

print ("The total elements are : ",last="")


print (functools.reduce(lambda ab,cd : ab+cd,a))

print (“Maximum element is : ",last="")


print (functools.reduce(lambda ab,cd : ab if ab > cd else cd, a))
@google images

© 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.

•A function must be given as a parameter along with the

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]

def sample_test (result) :


output
if result < 18 :

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.

•The lambda keyword is used to identify the functions.

•For evaluation, the function accepts argument(s) and expression.

•Syntax :-

lambda arg: expr

© 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))

//Generates 2nd output


80
N = lambda J, K : J * K

print (N (100 , 5)) 500

//Generates 3rd output 20


O = lambda w, x, y, z : w+x+y+z

print (O (5, 10, 2, 3))

© 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

o These functions are not representable by a specific name.

o This is ‘def’ keyword is used to define a function in Python.

o Likewise, the ‘lambda’ keyword is utilized to assert an anonymous function.

o It represents the input argument and the expresion

Syntax: lambda arg: expr

© 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.

o Lambda functions can be used whenever function objects are necessary.

o Syntactically, lambda functions are limited to a single expression.

o Apart from other forms of expressions in functions, it has a variety of applications in


certain domains of programming.

© 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()

def cube(z): Output: output


return z*z*z 27
27

lam_cube = lambda z: z*z*z

print(cube(3))

# use lambda function


print(lam_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:

//outputs the odd number from the several list of numbers


output
listn = [3, 1, 22, 92, 56, 60, 73, 20, 33, 51]
Output:
final = list(filter(lambda y: (y%2 != 0) , listn))
[3, 1, 73, 33, 51]
print(final)

© 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

adult = list(filter(lambda age_per: age_per>18,


age_per))

//the user above this age is considered as adult

print(adult)

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
lambda() and map()

o This has to take up a 2 different parameters, that is a


o Example:
function arg and a variable
# map() with lambda()
o This will be called as the function lamda with the list, # Doubling a list.
and it returns a fresh list with all of the lambda altered li = [3, 8, 2, 9, 22, 44, 2, 33, 4]
items which are then generated as output.
get_li = list(map(lambda y: y*2, get_li))
print(get_li)

6, 16, 4, 18, 44, 88, 4, 66, 8

© 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 Map function in Python is used to perform function activity on every item in an


object.

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.

Lesson 5. The dir function

© 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

Fourth Lesson Outline


We will be learning about modules and standard
modules in Python

© 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 module can be thought of as a code library.

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

Simply store the code you want in a file with the


extension.py to build a module:

Example

//this is a python module ‘test’

def say_hai (per_name):


return per_name

To be much more interactive, a module is


imported to another using ‘import’ statement

>>> import test

>>> test. say_hai (Jack)

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Module Usage

o Using the import line, we can now use the


output
module we just created:

Example

Import the test module and run the greet


function:

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

Save this code in file test.py

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

Select a .py file.

Examine the project: the converted module package is


generated, and the init .py file has all of the code from
the.py file.

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example
output

We need to import a module named ‘test’, and get


the name1 dictionary:
import test
x = test.name1["age"]
print(x)

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Re-naming a Module

While a python module gets imported, an


alias can be created for better representation.
Example
Create an alias for test called ex:

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 A module is a Python file which contains various descriptions and declarations.

o The module name is attached to the file name followed by ‘.py’

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 Aside from definitions, modules can also include executable statements.

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

$ python def fi_ev(i):


total = 0
4613732 a, b = 0, 1
while a < i:
if a % 2 == 0:
To import everything from a module: sum1 = sum1 + a
a, b = a, a + b
>>> from fib import * 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
Mini module quiz

I have two modules, foo.py and bar.py.

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is __main__"
if __name__ == "__main__": bar.print_hello()
print "bar's __name__ is __main__"

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is
if __name__ == "__main__": __main__"
print "bar's __name__ is bar.print_hello()
__main__"
$ python bar.py

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Mini module quiz

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is
if __name__ == "__main__": __main__"
print "bar's __name__ is bar.print_hello()
__main__"

$ 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

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is __main__"
if __name__ == "__main__": bar.print_hello()
print "bar's __name__ is __main__"

$ 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

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is
if __name__ == "__main__": __main__"
print "bar's __name__ is bar.print_hello()
__main__"

$ 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

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is
if __name__ == "__main__": __main__"
print "bar's __name__ is bar.print_hello()
__main__"

$ 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

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is __main__"
if __name__ == "__main__": bar.print_hello()
print "bar's __name__ is __main__"

$ 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

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is __main__"
if __name__ == "__main__": bar.print_hello()
print "bar's __name__ is __main__"

$ 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

''' Module bar.py ''' ''' Module foo.py'''


import bar
print "Hi from bar's top level!"
print "Hi from foo's top level!"
def print_hello():
print "Hello from bar!" if __name__ == "__main__":
print "foo's __name__ is __main__"
if __name__ == "__main__": bar.print_hello()
print "bar's __name__ is __main__"

$ 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 Modules that are already installed.

o The sys.path variable's list of directories.

o These locations are used to set the sys.path variable:

o The directories listed in the sys.path variable.


o The location of the current directory.

o PYTHONPATH is a Python path

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.

''' Module adder.py '''

def test(data, data_list = []):


data_list.append(data) # Add item to end of list
print data_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.

''' Module adder.py ''' $ python


>>> from adder import *
>>> add_item(3, [])
def test(data, data_list = []): [3]
data_list.append(data) # Add >>> add_item(4)
item to end of list [4]
print data_list >>> add_item(5)
[4, 5]

© 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.

''' Module adder.py ''' $ python


>>> from adder import *
def test(data, data_list = []): >>> add_item(3, [])
data_list.append(data) # Add [3]
item to end of list >>> add_item(4)
print data_list [4]
>>> add_item(5)
[4, 5]
• The default arguments are evaluated just once, when
the function is declared, not each time it is called.
• This means that any modifications you make to a
mutable default argument will be reflected in
subsequent calls to the function.

© 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.

''' Module adder.py ''' $ python


>>> from adder import *
def add_item(item, item_list = []): >>> add_item(3, [])
item_list.append(item) [3]
print item_list >>> add_item(4)
[4]
>>> add_item(5)
The default arguments in Python are evaluated just once,
[4, 5]
when the function is declared, not each time it is called.
Arguments are evaluated at this point!
This means that any modifications you make to an mtable
default argument will be reflected in subsequent calls to
the function.

© 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.

''' Module adder.py ''' $ python


>>> from adder import *
def add_item(item, item_list = None): >>> add_item(3, [])
if item_list == None: [3]
item_list = [] >>> add_item(4)
item_list.append(item) [4]
print item_list >>> add_item(5)
[5]

© 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

o As a part of the sys module, the sys.path variable is available.


o Here's an example of searching a path when an echo is done to represent the own sys.path variable.
>>> import sys
>>> sys.path

This outputs the path of the system

>>> import sys

>>> for print_path in sys.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)

o In the sample above, the sys.version


function is used, which produces a
string containing the Python
Interpreter version along with some
additional information.
o This has printed the version
information along with the time and
date

© 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 To transmit output to the screen console, use the stdout command.

o A print statement, an expression statement, or even a prompt direct for input might
produce a variety of results..

o Streams are set to text mode by default.

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example:

import sys import sys

sys.stdout.write(‘My name')

sys.stdout.write(‘Dear Python! Working on') sys.stdout.write(‘is John')

sys.stdout.write('\n')

sys.stdout.write(‘I reside in India')


Output:
Output:
Dear Python! Working on
My name is John

I reside in India

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
stderr

stderr: Exception occurrence in python is printed to sys.stderr.


Example:
import sys
def print_output_stderr(*x):

# Here x is the array with has the data


# arguments are passed and collected
print(*x, file = sys.stderr)
print_output_stderr("Hello World")

© 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.

The sys.getrecursionlimit() method is used to


sys.getrecursionlimit() method
determine the interpreter's current recursion limit.

Debuggers and coverage tools are all implemented


using it.
This is thread-specific, and you must use
sys.settrace()
threading.settrace to register the trace ().
This can be used to trace the path of the program and
print the path.

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
More Functions in Python sys

The sys.setswitchinterval() method is used to


sys.setswitchinterval() method set the thread switch interval of the
interpreter.
It gives the greatest value that a Py ssize t
sys.maxsize()
variable can hold.

The highest value that may be represented by


sys.maxint
an integer is maxint/INT MAX.

The sys.getdefaultencoding() method is used


sys.getdefaultencoding() method
to retrieve string encoding.

© 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.

It searches the list of directories defined by sys.path if none are found.

It prints the system path as needed by the user

© 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

# The values are removed from the path


print(sys.path)
sys.path = []

# Now starts importing pandas after done with


remove value
import pandas

© 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 = {

Example “per_name": “Jack",


There is only one function and one dictionary in the module
“per_age": 40,
‘demo’:
“per_country": “India"
def greet(name): }
print(“Hai, " + per_name)

© 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

❑Describes on the different python modules.

❑Introduces various standard modules like sys, time etc.

❑ Details on a file containing a set of functions you want to include in your application.

❑There are several built-in modules in Python.

© 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.

Lesson 5. The dir function

© 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

Fifth Lesson Outline

We will be learning about dir function

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
dir() function in Python

• dir() is a powerful intrinsic function Example


class user:
• That returns a list of any object's attributes and
usr_name = “Julie"
methods usr_age = 46
usr_country = “Canada"
Syntax :

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

The dir() function:


Example
print (‘\n Tuple as an argument”)
List all the defined names belonging to the Z = (10, 2)
platform module: print (dir(Z))

print (‘\n list as an argument”)


import platform Z = [10, 20]
test = dir(platform) print (dir(Z))

print(test)

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Using the dir() Function

Parameters :

object [optional] : receives the name of the object class user:


def __dir__(self):
Returns : return [‘usr_age', ‘usr_name',
‘usr_salary']
dir() aims to return a correct list of the object's
attributes when called. doctor = user()
print(dir(doctor))
Furthermore, the dir() function works differently
with different types of objects. Output
It seeks to produce the most relevant information
[‘usr_name’,’usr_age’, ‘usr_salary’]
rather than the whole set.
© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
dir()

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.

4. Return a list of usable attributes for the object using an argument.

© 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

test = [100, 1222, 1333]


<<< class color:
print(dir(test)) def __dir__(self):
return [red', blue', white']
print('\nGive the value of the nil dir()')
print(dir()) <<< s = color()

//this will take a list of values as argument and <<< dir(s)


finally print the dir of values
[red', blue', white']

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
What is math module ?

o This is a standard module in python which helps in implementing mathematical operations


o All function included in this module has to be included using the math.
o This belongs to a class of C library functions. For example,
o # consider square_root
import math
math.sqrt(8)
o The main disadvantage is that complex types of data is not supported using this.
o Another complex alternative to this module is the cmath 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.

Note: The argument is send as a input to math.acos() and it must be in_between -1 to 1.

math.acos(-1) will output the given value of pi.

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

Definition and Usage

o This method actually gives the arc sine of the inputted numbers math.asin() .

o The argument is passed in math.asin() will always take up between -1 to 1.

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

List of Functions in Python Math Module


Function Description
Generates the low integer greater than or
ceil(a)
equal to a.
copysign(a, b) Generates a with the sign of b

fabs(z) generates the absolute value z

factorial(a) gives the factorial of a


Returns the biggest integer less than or
floor(a)
equal to a

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module

fmod(a, b) produces the remainder when a is divided by b

frexp(a) gives the mantissa and exponent of a

fsum(iter) Returns an FP of sum of values in the iterable

isfinite(z) Gives True if z generates an infinity or NaN

isinf(a) Provides True, if a gives a positive or negative value

isnan(a) provides True if a gives a NaN

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module

ldexp(a, x) Returns a * (2**x)

modf(a) Returns the fraction and integ parts of a

trunc(a) Returns the trunk int value of a

exp(a) Returns a**z

expm1(a) Returns a**z - 1

log(a[, x]) Returns the log of a to the base x

log1p(a) Returns the log of 1+a

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module

log2(a) Returns the base2 logarithm of a

log10(a) Returns the base10 logarithm of a

pow(a, b) Returns a power b

sqrt(a) Returns root of a

acos(a) Returns cosine of a

asin(a) Returns sine of a

atan(a) Returns tangent of a

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module

atan2(a, b) Returns atan(a / b)

cos(a) Returns cosine of a

hypot(a, b) Returns sqrt(a*a + b*b)

sin(a) Returns sine of a

tan(a) Returns tangent of a

degrees(a) Converts angle a from radian to degree

radians(a) Converts angle a from degree to radians

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Functions in Python Math Module

acosh(a) Returns cos of a

asinh(a) Returns sine of a

atanh(a) Returns tan inverse of a

cosh(a) Returns hyper cos of a

sinh(a) Returns hyper sine of a

tanh(a) Returns hyper tan of a

erf(a) Returns error function at a

erfc(a) Returns complementary error function at a

gamma(a) Returns Gamma function at a

© 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

Identify the error and correct the errors


a) Def test_sum (I= 20, J))
return I + J
print (“The addition output =“ test_sum (28, -2)

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

a) Def test_sum (I= 20, J))


return I + J
print (“The addition output =“
test_sum (28, -2)

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

Print the output of the following


code segment
Output:
Test_no = 50
Test_tot = 0 py_compile.PyCompileError
: File "./prog.py", line 3 for z
for z in range (20, test_no, 5)
in range (20, test_no, 5) ^
@Google images SyntaxError: invalid syntax
Test_tot+= z
if z % 2 = = 0:
print z*2
else:
print z* 3

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Finding the Output

Print the output of the following code


segment

def test_pow (num1, num2)

remain = num1 * num2


return remain output

def test_sqr (sample)


sample = testpow (sample, 2)
return sample
9
Test_in = 3
Output = test_sqr (Test_in) @Google images
print (Output)

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Finding the Output

Find the output of the following code segment

//import a mathematical module in to


your program 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

Print the output of the following code


segment

def test_prg (num1, num2 = 5)

print ( num1 * num2


@Google images
OUTPUTpy_compile.PyCompileError: File
test_prg (‘ computer’)
"./prog.py", line 1 def
test_prg (‘ lap’, 5) test_prg (num1,num2) ^
SyntaxError: invalid
syntax

© 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.time - enables to represent time not independent of a particular date.

o datetime.datetime - enables use of objects that have together date and time.

o datetime.timedelta = represent differences between dates

o datetime.timezone objects provides time adjustments based on UTC.

© 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)

Second since beginning = 1623930513.3659508

© 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

print(“Will be printed now


time.sleep(3.5)
print(“will be printed after 3.5 seconds.")

© 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.

o It's in essence the contrary of localtime ().

import time
test = (2021, 13, 21, 4, 45, 3, 3, 352, 1)

loc_tim = time.mktime(t)

print("Local time is represented as:", loc_tim)

© 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)

tim_str = "20 May, 2021"


output = time.strptime(tim_str, "%d %B, %Y")

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 Sleep is one of the most common roles among them ().

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)

# printing the finish time


print(“Program has ended in: ", end ="")
print(time.ctime())

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Example 2: Local_Time Print

import time o Within the infinite while loop in the


preceding programme, current local
while True: time is found.
loc_ti = time.localtime() o The programme then waits one
output = time.strftime("%I:%M:%S %p", loc_ti) second.
print(output) o The current local time is calculated
time.sleep(2) and printed once again. This
procedure continues.

© 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

Nonlocal variable and nested function

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 A nested function is one that is well-defined inside alternative function.

o The variables of the enclosing scope can be accessed by nested functions.

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")

Output: Hello welcome

© Kalasalingam academy of research and education FUNCTIONS AND MODULES - UNIT 3 BY DR.N.C.BRINTHA
Defining a Closure Function

What if, instead of using the printer() function in the output


previous example, the last line of the print message() # Output: Hello welcome
method returned it? try = out_msg("Hello welcome")
def out_msg(in): try()

# This is the outer 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 A nested function is required.

o The value defined in the surrounding function must be referenced by the nesting function.

o The nested function must be returned by the enclosing 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 It may also be able to offer an object-oriented solution to the issue.

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

You might also like