Ver. No.: 1.1 Copyright © 2021, ABES Engineering College
Quality Content for Outcome based Learning
4.Functions and Module
Copyright © 2021, ABES Engineering College
General Guideline
© (2021) ABES Engineering College.
This document contains valuable confidential and proprietary information of ABESEC. Such confidential and
proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and
commercialized. Such information is furnished herein for training purposes only. Except with the express prior
written permission of ABESEC, this document and the information contained herein may not be published,
disclosed, or used for any other purpose.
2
Copyright © 2021, ABES Engineering College
3
To describe the importance of functions in Python
Objective of Functions and Modules
To explain the function definition in Python
To develop python programs with functions
To use the void functions and return statements
To explain the difference between different function argument types and use them
To select built-in functions in Python to write programs in Python.
Copyright © 2021, ABES Engineering College
4
Topics Covered
Day 1
4.1 Introduction to
Functions
• 4.1.1 Arguments and
parameters
• 4.1.2 Return
statement
Day 2
4.1 Introduction to
Functions
• 4.1.3 Types of
Function arguments
• 4.1.4 Scope and
Lifetime of variables
Day 3
4.2 Anonymous and
Higher Order Function
• 4.2.1 Anonymous
Function
Day 4
4.2 Anonymous and
Higher Order Function
• 4.2.2 First Class
Function and Higher
Order Function
Copyright © 2021, ABES Engineering College
5
Topics Covered
Day 5
4.3 Modules
• 4.3.1 Creation of
module
• 4.3.2 Importing
module
• 4.3.3 Standard Built-In
Module
Day 6
4.4 Iterative Built-in
Functions
Copyright © 2021, ABES Engineering College
6
4.1 Introduction to functions
4.1.1 Argument and parameters
4.1.2 Return statement
4.1.3 Types of function arguments
4.1.4 Scope and lifetime of variables.
Session Plan - Day 1
Copyright © 2021, ABES Engineering College
7
Introduction
A large program is divided into small blocks of code called functions, to:
 Increase the reusability of code.
 Ease of programming.
Function is a group of all statement(activities) that perform a specific
task.
Copyright © 2021, ABES Engineering College
8
Syntax
The syntax of function definition is:
Copyright © 2021, ABES Engineering College
 Avoid duplication of the similar type of codes
 Increases Program readability and Improved Concept Clarity
 Divide the bigger problem into smaller chunks
 Reusability of code
9
Benefits of Using Functions:
Copyright © 2021, ABES Engineering College
In real world scenario, we need to group all the activities related to a specific
task, like:
1. A task of maintaining student’s basic details involves a group of different activities like:
Collecting their name, branch, batch, age, aadhar number, etc.
2. Similarly, the task of maintaining marks of students involves a group of different activities
like: Collecting marks of English, Physics, Chemistry, Mathematics, etc.
10
Example
Copyright © 2021, ABES Engineering College
 We can create three functions like:
 basic_details ()
 marks()
 work()
11
Contd..
Copyright © 2021, ABES Engineering College
Contd..
12
Function 1: basic_details ()
Copyright © 2021, ABES Engineering College
Contd..
13
Function 2: marks ()
Copyright © 2021, ABES Engineering College
Contd..
14
Function 3: work ()
Copyright © 2021, ABES Engineering College
A function is called using function name through calling environment.
The syntax of function call is:
15
Function Call
Copyright © 2021, ABES Engineering College
16
Flow chart
Copyright © 2021, ABES Engineering College
17
Argumentsand parameters
 Arguments are used to pass the information to the functions.
 They are mentioned after function name inside the parentheses in function
calling statement.
 Any number of arguments can be added by separating them by commas.
Note: The number of parameters in function definition must be same as the number
of arguments in function calling statement.
Copyright © 2021, ABES Engineering College
Write a python program to determine the greater number among two numbers
using function greater(a), by passing one number as argument in function
calling.
18
Example 1
Copyright © 2021, ABES Engineering College
19
Example 2
Write a python program to determine the greater number among two numbers by
passing both the number as argument in function calling.
Copyright © 2021, ABES Engineering College
 Return statement indicate the end of function execution.
 It is also used to return the values or results to the function calling
statement.
20
Return statement
Copyright © 2021, ABES Engineering College
Write a python program to demonstrate the return statement of function for the
addition of two numbers.
21
Example 1
Copyright © 2021, ABES Engineering College
1. Which keyword is used for function?
a) Fun
b) Define
c) Def
d) Function
22
Review Questions
Copyright © 2021, ABES Engineering College
2. What will be the output of the following Python code?
a) 432
b) 24000
c) 430
d) No output
23
Copyright © 2021, ABES Engineering College
24
4.1 Introduction to functions
 4.1.3 Types of Function arguments
 4.1.4 Scope and Lifetime of variables
Session Plan - Day 2
Copyright © 2021, ABES Engineering College
There are five types of arguments in Python function:
25
Types of Function arguments
Copyright © 2021, ABES Engineering College
Default arguments are values that are provided in the function definition.
Syntax:
26
Defaultarguments :
Note: Function can have any number of default arguments. If the values are provided
to the default arguments during the function calling, it overrides the default value.
Copyright © 2021, ABES Engineering College
Write a python program to greet a person with person name and message
provided in function calling statement. If message not provided in function call,
then print a default message “Hi !!”.
27
Example1
Copyright © 2021, ABES Engineering College
Default arguments are keyword arguments whose values are assigned at the
time of function definition.
Syntax:
28
Keywordarguments :
Copyright © 2021, ABES Engineering College
Write a program to demonstrate keyword arguments.
29
Example1
Copyright © 2021, ABES Engineering College
Positional arguments are arguments that need to be included in the proper
position or order while calling the function.
Syntax:
30
Positionalarguments :
Copyright © 2021, ABES Engineering College
Write a program to demonstrate positional arguments.
31
Example1
Copyright © 2021, ABES Engineering College
 When we are not sure in the advance that how many arguments our function
would require.
 This kind of situation is handled through function calls with an arbitrary
number of arguments.
32
ArbitraryArguments
Note: We define the arbitrary arguments while defining a function using the
asterisk (*).
Copyright © 2021, ABES Engineering College
There are two types of arbitrary arguments as illustrated in the given figure
below.
33
Types of ArbitraryArguments
Copyright © 2021, ABES Engineering College
The special syntax *args in function definitions is used to pass the
variable number of arguments to a function.
34
*args
Note: Generally, * args is used by convention but you can take any variable
for example *abc will work in same way as * args.
Copyright © 2021, ABES Engineering College
Write a program to demonstrate *args arbitrary arguments.
35
Example 1
Copyright © 2021, ABES Engineering College
The **kwargs function in python is used to pass an arbitrary number of keyword
arguments called kwargs.
Note: ** (Double star allows us to pass variable number of keyword
arguments). This turns the identifier-keyword pairs into a dictionary within the
function body.
36
**kwargs
Copyright © 2021, ABES Engineering College
Write a program to demonstrate **kwargs arbitrary arguments.
37
**kwargs
Copyright © 2021, ABES Engineering College
Write a program using this function to generate perfect numbers from 1 to 1000. [An
integer number is said to be “perfect number” if its factors, including 1(but not the
number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
38
**kwargs
Copyright © 2021, ABES Engineering College
 Let’s consider a situation that you book a train ticket in sleeper coach and
you got berth in S1 coach and 48 seat number.
 Now your ticket is valid for mentioned train and coach only this is called
scope of your ticket.
 Your ticket would expire after mentioned journey date and that is called
lifetime.
39
ScopeandLifetimeofvariables
Copyright © 2021, ABES Engineering College
 Scope: The scope of a variable determines its accessibility and availability
in different portions of a program. Their availability depends on where they
are defined.
 Lifetime: The lifetime of a variable is the time during which the variable
stays in memory.
40
ScopeandLifetimeofvariables
Copyright © 2021, ABES Engineering College
Three kinds of variables in Python:
 Global Variable
 Local Variables
 Non local variables
41
Types of variables
Copyright © 2021, ABES Engineering College
42
Demonstration of Local and Global
Copyright © 2021, ABES Engineering College
Variables that are declared outside of a function are known as global variables.
Example: Write a program to create global variable in python.
43
Global Variables
Copyright © 2021, ABES Engineering College
 These are variables which are defined inside a function.
 Their scope is only to that function.
 They cannot be accessed from the outside of the function.
Example: Write a program to create local variable in python.
44
Local Variables
Copyright © 2021, ABES Engineering College
45
Example: Local and global variable in one program.
Copyright © 2021, ABES Engineering College
46
Example: To modify the variable outside of the current
scope.
Copyright © 2021, ABES Engineering College
 Nonlocal variables are used in nested functions.
 When a variable is either in local or global scope, it is called a nonlocal
variable.
47
Non - Local Variables
Note: Nonlocal keyword will prevent the variable from trying to bind locally
first, and force it to go a level 'higher up'.
Copyright © 2021, ABES Engineering College
 Nonlocal variables are used in nested functions.
 When a variable is either in local or global scope, it is called a nonlocal
variable.
48
Non - Local Variables
Note: Nonlocal keyword will prevent the variable from trying to bind
locally first, and force it to go a level 'higher up'.
Copyright © 2021, ABES Engineering College
49
Example 1
A program to create local variables for nested functions.
Copyright © 2021, ABES Engineering College
50
Example 2
A program to use nonlocal keyword for nested functions.
Copyright © 2021, ABES Engineering College
What will be the output of the following Python code?
a) 9
b) 3
c) 27
d) 30
51
Review Questions
Copyright © 2021, ABES Engineering College
What will be the output of the following Python code?
a) 9
27
b) 27
9
c) None of the above
d) Both of the above
52
Copyright © 2021, ABES Engineering College
53
4.2 Anonymous and Higher Order Function
4.2.1 Anonymous Function
4.2.1 Lambda Function
Session Plan - Day 3
Copyright © 2021, ABES Engineering College
54
Anonymous Function
 Sometimes we only have single expression to evaluate, so rather than
creating regular function we create anonymous Function.
 These functions do not have return statement, because by default evaluated
single expression is returned.
 This is one liner code and have following properties –
 Function without name
 One expression statement but any number of arguments.
Copyright © 2021, ABES Engineering College
55
Syntax
Copyright © 2021, ABES Engineering College
56
Scenario 1
Suppose we want to increment the value of variable by five, without writing
lengthy code we can use lambda function.
Copyright © 2021, ABES Engineering College
57
Example 1
A program to add three values, using multiple arguments in lambda function.
Copyright © 2021, ABES Engineering College
58
Example 2
A program using lambda function to calculate the simple interest.
Copyright © 2021, ABES Engineering College
1. Python supports the creation of anonymous functions at runtime,
using a construct called __________
a) lambda
b) pi
c) anonymous
d) none of the mentioned
59
Review Questions
Copyright © 2021, ABES Engineering College
2. What will be the output of the following Python code?
a) 48
b) 14
c) 64
d) None of the mentioned
60
Copyright © 2021, ABES Engineering College
61
4.2 Anonymous and Higher Order Function
 4.2.2 First Class Function and
 4.2.2 Higher Order Function
Session Plan - Day 4
Copyright © 2021, ABES Engineering College
62
First Class Function and Higher Order Function
 In first class function, function which can be passed as an argument.
 Functions which take first class function as an argument are called Higher
order function.
Syntax:
Copyright © 2021, ABES Engineering College
63
Properties of First-Class Function:
 Function can be passed as an argument into another function.
 Function can be assigned to a variable.
 Function can be returned from other function.
Copyright © 2021, ABES Engineering College
64
Properties of High Order Function:
 Function can take other function as an argument.
 Function can return other function.
Copyright © 2021, ABES Engineering College
 def loud(name):
 return name.upper()
 def soft(name):
 return name.lower()
 def speak(fun):
 print("hello word")
 return fun("xyz")
 print(speak(soft))
Speak is high order function and loud and soft is first
class function
65
Copyright © 2021, ABES Engineering College
 def apply_operation(func, x, y):
 return func(x, y)

def multiply(a, b):
 return a * b

print(apply_operation(multiply, 3, 4))
66
Copyright © 2021, ABES Engineering College
 Built-in higher order functions are capable of taking other function as
argument.
 These higher order functions are applied over a sequence of data.

67
Built-in Higher order function in Python
Copyright © 2021, ABES Engineering College
First higher order function we would discuss is map function.
Syntax:
68
Map ()
Copyright © 2021, ABES Engineering College
 nums = [1, 2, 3]
 squares = list(map(lambda x: x ** 2, nums))
 print(squares) # Output: [1, 4, 9]
 Map is high order function
 And lambda is first class function
69
Copyright © 2021, ABES Engineering College
One important thing to note that map function always returns map object.
Syntax:
70
Contd..
Copyright © 2021, ABES Engineering College
To access values, we need to type cast map object as some sequence
datatype like lists, tuple, etc.
71
Contd..
Copyright © 2021, ABES Engineering College
A program to convert a string of upper-case words into lower case.
72
Contd..
Copyright © 2021, ABES Engineering College
Filter function is the high order function which takes a filtering criterion, need
to apply on any sequence.
For example, in a bucket of balls of different colors, we have to find only
black color balls, then filter function would work.
Syntax:
73
Filter()
Copyright © 2021, ABES Engineering College
 balls = ["red", "blue", "black", "green", "black", "yellow"]
 black_balls = list(filter(lambda color: color == "black", balls))
 print(black_balls)
74
Copyright © 2021, ABES Engineering College
A list of integers find out even numbers.
75
Contd..
Copyright © 2021, ABES Engineering College
Reduce is used in such scenarios where the values in the iterable would be
calculated to a final value.
For example, take a collection of values (3,4,5) and we need to apply sum to
it. Then we would get 12.
Syntax:
76
Reduce()
Copyright © 2021, ABES Engineering College
 from functools import reduce
 numbers = [1, 2, 3, 4, 5]
 # Use reduce to sum the list
 total = reduce(lambda x, y: x + y, numbers)
 print(total)
77
Copyright © 2021, ABES Engineering College
A program to sum numbers of a list using reduce function.
78
Example 1
Copyright © 2021, ABES Engineering College
 Create a function that takes another function and applies it to a name.
 From a list of fruits, filter out those that start with the letter "a".
 Double each numbers in the list using map
 Calculate the product of all elements in the list using reduce()
 A company wants to increase the salaries of employees by 10%. You are
given a list of current salaries.
 salaries = [40000, 50000, 60000, 70000]
79
Copyright © 2021, ABES Engineering College
Practice Hackerrank Question
 https://www.hackerrank.com/challenges/the-minion-game/problem?
isFullScreen=true
80
Copyright © 2021, ABES Engineering College
What will be the output of the following Python code?
a) 2
b) 4
c) error
d) none of the mentioned
81
Review Questions
Copyright © 2021, ABES Engineering College
What will be the output of the following Python code?
a) 2
b) 1
c) error
d) none of the mentioned
82
Copyright © 2021, ABES Engineering College
83
4.3 Modules
• 4.3.1 Creation of module
• 4.3.2 Importing module
• 4.3.3 Standard Built-In Module
Session Plan - Day 5
Copyright © 2021, ABES Engineering College
84
Introduction
As length of program grows in size and to maintain the reusability of some code we start writing
function. Now if you want to use same function/functions in another program instead of writing
their definition then module comes into picture.
Python provides us to create our own module or provides use to use rich source of given
module to increase the reusability.
Python module can be imported into any program
In python module is simply a python file containing python code, it may contain
statements, functions, methods and classes.
Copyright © 2021, ABES Engineering College
85
Creation of module
A file containing Python code, for example: calc.py, is called a module, and its name would be
calc. A module is created simply putting all functions/statements in one python file
Copyright © 2021, ABES Engineering College
86
Contd..
A file containing Python code, for example: calc.py, is called a module, and its name would be
calc. A module is created simply putting all functions/statements in one python file
Code illustrates that how
to create a module name
‘calc’, which contains the
user defined functions of
addition, subtraction,
multiplication and division
and area.
Copyright © 2021, ABES Engineering College
87
Importing module
To use the module in any application or program we need to import that module using import
keyword.
We can import module in multiple
ways –
• import module-name
• import ... as ...
• from ... import ...
Copyright © 2021, ABES Engineering College
88
Contd..
When we use “import module-name” syntax, it will import all functions/statements from that
module and function will call using module-name and dot operator.
Copyright © 2021, ABES Engineering College
89
Contd..
import ... as ...
We use import ... as ... to give a module name a short alias name while importing it.
Copyright © 2021, ABES Engineering College
90
Contd..
import ... as ...
Example: We import module calc using alias name ‘m’. It will import all functions / statements from
that module and function will call using alias name and dot operator.
Copyright © 2021, ABES Engineering College
91
Contd..
from ... import ...
The from…. Import … statement allows us to import specific functions/variables from a module
instead of importing everything.
Copyright © 2021, ABES Engineering College
92
Contd..
from ... import ...
Multiple function can also be imported using comma (,) operator.
from calc import addition, subtraction
We can also use ‘*’ , for importing all function/statements.
from calc import *
Copyright © 2021, ABES Engineering College
93
Standard Built-In Module
Python has large number of built in functions similarly python contains some of the pre-defined
modules such as:
math random datetime sys os
Copyright © 2021, ABES Engineering College
94
Contd..
The math Module
Python has set of built-in math functions and also has an extensive math module that allows us to
perform mathematical tasks on data. These include trigonometric functions, representation
functions, logarithmic functions, sine functions, cosine functions, exponential, pi etc.
math.sqrt()
This function will calculate the square root of number.
Copyright © 2021, ABES Engineering College
95
Contd..
math.ceil()
Rounds a number up to the nearest
integer.
math.exp()
Return 'E' raised to the power of
different numbers
Copyright © 2021, ABES Engineering College
96
Contd..
math. factorial()
Return the factorial of a number
math.gcd()
Return the greatest common divisor
of two integers.
math.pow()
Returns the value of x to the power of y.
Copyright © 2021, ABES Engineering College
97
Contd..
math.fsum()
Returns the sum of all items in an
iterable.
math.sin()
Return the cosine of x (measured in
radians).
Refrence : https://docs.python.org/3/library/math.html
Copyright © 2021, ABES Engineering College
98
Contd..
The random Module
This module implements pseudo-random number generators for various distributions. We can
generate random numbers in Python by using random module.
random.seed()
The random number generator needs a number to start with (a seed value).
Use the seed() method to customize the start number of the random number generator.
Copyright © 2021, ABES Engineering College
99
Contd..
random.random()
Return random number between 0.0 and 1.0
random.randint(a,b)
Return random integer between a and b,
including both end points.
random.choice()
Choose a random element from a non- empty
sequence like string, list, tuple etc.
random.shuffle()
The shuffle() method takes a sequence and
reorganize the order of the items.
import random
fruits = ['apple', 'banana', 'cherry',
'mango', 'grape']
random_fruit = random.choice(fruits)
print("Randomly selected fruit:",
Copyright © 2021, ABES Engineering College
100
Contd..
The datetime Module
In python there is no date and time data type so python date time module is used for displaying
dates and times, modifying dates and time in different format.
This module supplies classes to work with date and time. These classes provide a number
of functions and built in methods to deal with dates, times and time intervals.
Note:
Classes and Objects we are going to discuss in Object Oriented Programming in Python.
Copyright © 2021, ABES Engineering College
101
Contd..
The datetime Module
Commonly used classes and associated methods in the datetime m
Copyright © 2021, ABES Engineering College
102
Contd..
The date class
A date object of date class represents a date in year, month and day.
Copyright © 2021, ABES Engineering College
103
Contd..
All method and attributes of date object will be called using ‘d’ object and dot operator.
Copyright © 2021, ABES Engineering College
104
Contd..
The time class
Time object represents local time, independent of any day.
Copyright © 2021, ABES Engineering College
105
Contd..
Create a time object and display hour, minute, second and microsecond in time object.
Copyright © 2021, ABES Engineering College
106
Contd..
The datetime class
Information on both date and time is contained in this class.
Copyright © 2021, ABES Engineering College
107
Contd..
Create a time object and display hour, minute, second and microsecond in time object.
Create a datetime
object and display
year, month, hour,
minute in time
object.
Write a program
to fetch the
current datetime
of system and
print it
Copyright © 2021, ABES Engineering College
108
Contd..
The sys Module
The sys module provides system specific parameters and functions. It gives us information
about constants, functions, and methods of the interpreter.
Following are some important use of sys module:
• Exiting current flow of execution in Python
• Command-line Arguments
• Getting version information of Interpreter
• Set or get recursion depth
For more function visit - https://docs.python.org/3/library/sys.html)
Copyright © 2021, ABES Engineering College
109
Contd..
sys.version
Gives version information of Interpreter.
Copyright © 2021, ABES Engineering College
110
Contd..
sys.argv
It returns a list of command line arguments passed to a Python script.
Copyright © 2021, ABES Engineering College
111
Contd..
sys.argv
Write a python script which print sum of given two value through command line
Copyright © 2021, ABES Engineering College
112
Contd..
sys.argv
Write a python script which print sum of given two value through command line
Copyright © 2021, ABES Engineering College
113
Contd..
sys.getrecursionlimit() and sys.setrecursionlimit()
sys.getrecursionlimit()
method is used to find
the current recursion
limit of the interpreter.
sys.setrecursionlimit()
method is used to set
the recursion limit of the
interpreter
Copyright © 2021, ABES Engineering College
114
Review Questions
 What is the output of the code shown below if the system date is
18th August, 2016?
tday=datetime.date.today()
print(tday.month())
A. August
B. Aug
C. 08
D. 8
Copyright © 2021, ABES Engineering College
115
Review Questions
What is returned by math.ceil(3.4)?
a) 3
b) 4
c) 4.0
d) 3.0
What is returned by math.ceil(3.4)?
a) 3
b) 4
c) 4.0
d) 3.0
Copyright © 2021, ABES Engineering College
116
Review Questions
 What will be the output of the following Python code?
import time
print(time.strftime("%d-%m-%Y"))
a) Print today’s date in string format dd-mm-yy
b) Print today’s date in string format dd-mm-yyyy
c) Error
d) None
 State whether true or false.
t1 = time.time()
t2 = time.time()
t1 == t2
a)True
b)False
Copyright © 2021, ABES Engineering College
117
4.3 Modules
 4.4 Iterative Built-in Functions
Enumerate
Zip
Sorted
Zip
Session Plan - Day 6
Copyright © 2021, ABES Engineering College
118
Enumerate: This is built-in function provided by Python. This function
assigns count values to the iterable
Iterative Built-in Functions
What is iterable?
Iterable in python is a collection of
items, sequences like lists, tuple or
any object which have multiple
values on which a repeat operation
can be performed, like
name = [‘amit’, ‘ankur’, ‘aditya’, ‘anshul’,
‘anmol’],
here the name has five items in it.
Copyright © 2021, ABES Engineering College
119
When using the iterators, we need to keep track of the number of items in the
iterator. This is achieved by built in method called enumerate.
This enumerated object can directly be used for loops or converted into a list of
tuples using list () method.
Note: by default enumerate starts from 0 but we can change this start value as per our
convenience.
Contd..
Copyright © 2021, ABES Engineering College
120
Contd..
Example : Demonstrating the enumerate usage in printing days of week.
Copyright © 2021, ABES Engineering College
121
Contd..
Enumerate with for loop
Example
Syntax
Copyright © 2021, ABES Engineering College
122
Contd..
Zip
The function returns a zip object, which is an iterator of tuples where the first item in each
passed iterator is paired together, and then the second item in each passed iterator are paired
together etc.
Example
Syntax
Copyright © 2021, ABES Engineering College
123
Contd..
Sorted
.
Python contains a special built in method for sorting the data in a collection. It preserves the
order of previous sequence or collection
Syntax
Copyright © 2021, ABES Engineering College
124
Contd..
Sorted Example
Copyright © 2021, ABES Engineering College
125
Contd..
Reversed
Reversed () function returns the iterator in a reverse order. Iterator can be any sequence such
as list, tuple etc.
Example
Syntax
Copyright © 2021, ABES Engineering College
126
Review Questions
 Which of the following functions can help us to find the version of python that
we are currently working on?
a) sys.version
b) sys.version()
c) sys.version(0)
d) sys.version(1)
 Suppose there is a list such that: l=[2,3,4]. If we want to print this list in
reverse order, which of the following methods should be used?
a) reverse(l)
b) list(reverse[(l)])
c) reversed(l)
d) list(reversed(l))
Copyright © 2021, ABES Engineering College
127
Review Questions
 Which of the following functions is not defined under the sys module?
a) sys.platform
b) sys.path
c) sys.readline
d) sys.argv
 To obtain a list of all the functions defined under sys module, which of the
following functions can be used?
a) print(sys)
b) print(dir.sys)
c) print(dir[sys])
d) print(dir(sys))
Copyright © 2021, ABES Engineering College
128
 In this unit you learnt the importance of using functions and how to use
functions.
 Further you learnt how to define functions, to write functions with
different argument types.
 Further you learnt describe the difference between the in- built functions and user
defined functions,
 Further you to write user defined functions, to use Functions in- built functions,
import math module in to a Python program and to use lambda functions.
Summary
Copyright © 2021, ABES Engineering College
129
1. https://docs.python.org/3/tutorial/controlflow.html
2. Think Python: An Introduction to Software Design, Book by Allen B. Downey
3. Head First Python, 2nd Edition, by Paul Barry
4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna Jablonski,
Fletcher Heisler
5. https://www.fullstackpython.com/turbogears.html
6. https://www.cubicweb.org
7. https://pypi.org/project/Pylons/
8. https://www.upgrad.com/blog/python-applications-in-real-world/
9. https://www.codementor.io/@edwardbailey/coding-vs-programming-what-s-the-difference-yr0aeug9o
References
Copyright © 2021, ABES Engineering College
130
Thank You

Python Functions and Modules Detailed Notes.pptx

  • 1.
    Ver. No.: 1.1Copyright © 2021, ABES Engineering College Quality Content for Outcome based Learning 4.Functions and Module
  • 2.
    Copyright © 2021,ABES Engineering College General Guideline © (2021) ABES Engineering College. This document contains valuable confidential and proprietary information of ABESEC. Such confidential and proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such information is furnished herein for training purposes only. Except with the express prior written permission of ABESEC, this document and the information contained herein may not be published, disclosed, or used for any other purpose. 2
  • 3.
    Copyright © 2021,ABES Engineering College 3 To describe the importance of functions in Python Objective of Functions and Modules To explain the function definition in Python To develop python programs with functions To use the void functions and return statements To explain the difference between different function argument types and use them To select built-in functions in Python to write programs in Python.
  • 4.
    Copyright © 2021,ABES Engineering College 4 Topics Covered Day 1 4.1 Introduction to Functions • 4.1.1 Arguments and parameters • 4.1.2 Return statement Day 2 4.1 Introduction to Functions • 4.1.3 Types of Function arguments • 4.1.4 Scope and Lifetime of variables Day 3 4.2 Anonymous and Higher Order Function • 4.2.1 Anonymous Function Day 4 4.2 Anonymous and Higher Order Function • 4.2.2 First Class Function and Higher Order Function
  • 5.
    Copyright © 2021,ABES Engineering College 5 Topics Covered Day 5 4.3 Modules • 4.3.1 Creation of module • 4.3.2 Importing module • 4.3.3 Standard Built-In Module Day 6 4.4 Iterative Built-in Functions
  • 6.
    Copyright © 2021,ABES Engineering College 6 4.1 Introduction to functions 4.1.1 Argument and parameters 4.1.2 Return statement 4.1.3 Types of function arguments 4.1.4 Scope and lifetime of variables. Session Plan - Day 1
  • 7.
    Copyright © 2021,ABES Engineering College 7 Introduction A large program is divided into small blocks of code called functions, to:  Increase the reusability of code.  Ease of programming. Function is a group of all statement(activities) that perform a specific task.
  • 8.
    Copyright © 2021,ABES Engineering College 8 Syntax The syntax of function definition is:
  • 9.
    Copyright © 2021,ABES Engineering College  Avoid duplication of the similar type of codes  Increases Program readability and Improved Concept Clarity  Divide the bigger problem into smaller chunks  Reusability of code 9 Benefits of Using Functions:
  • 10.
    Copyright © 2021,ABES Engineering College In real world scenario, we need to group all the activities related to a specific task, like: 1. A task of maintaining student’s basic details involves a group of different activities like: Collecting their name, branch, batch, age, aadhar number, etc. 2. Similarly, the task of maintaining marks of students involves a group of different activities like: Collecting marks of English, Physics, Chemistry, Mathematics, etc. 10 Example
  • 11.
    Copyright © 2021,ABES Engineering College  We can create three functions like:  basic_details ()  marks()  work() 11 Contd..
  • 12.
    Copyright © 2021,ABES Engineering College Contd.. 12 Function 1: basic_details ()
  • 13.
    Copyright © 2021,ABES Engineering College Contd.. 13 Function 2: marks ()
  • 14.
    Copyright © 2021,ABES Engineering College Contd.. 14 Function 3: work ()
  • 15.
    Copyright © 2021,ABES Engineering College A function is called using function name through calling environment. The syntax of function call is: 15 Function Call
  • 16.
    Copyright © 2021,ABES Engineering College 16 Flow chart
  • 17.
    Copyright © 2021,ABES Engineering College 17 Argumentsand parameters  Arguments are used to pass the information to the functions.  They are mentioned after function name inside the parentheses in function calling statement.  Any number of arguments can be added by separating them by commas. Note: The number of parameters in function definition must be same as the number of arguments in function calling statement.
  • 18.
    Copyright © 2021,ABES Engineering College Write a python program to determine the greater number among two numbers using function greater(a), by passing one number as argument in function calling. 18 Example 1
  • 19.
    Copyright © 2021,ABES Engineering College 19 Example 2 Write a python program to determine the greater number among two numbers by passing both the number as argument in function calling.
  • 20.
    Copyright © 2021,ABES Engineering College  Return statement indicate the end of function execution.  It is also used to return the values or results to the function calling statement. 20 Return statement
  • 21.
    Copyright © 2021,ABES Engineering College Write a python program to demonstrate the return statement of function for the addition of two numbers. 21 Example 1
  • 22.
    Copyright © 2021,ABES Engineering College 1. Which keyword is used for function? a) Fun b) Define c) Def d) Function 22 Review Questions
  • 23.
    Copyright © 2021,ABES Engineering College 2. What will be the output of the following Python code? a) 432 b) 24000 c) 430 d) No output 23
  • 24.
    Copyright © 2021,ABES Engineering College 24 4.1 Introduction to functions  4.1.3 Types of Function arguments  4.1.4 Scope and Lifetime of variables Session Plan - Day 2
  • 25.
    Copyright © 2021,ABES Engineering College There are five types of arguments in Python function: 25 Types of Function arguments
  • 26.
    Copyright © 2021,ABES Engineering College Default arguments are values that are provided in the function definition. Syntax: 26 Defaultarguments : Note: Function can have any number of default arguments. If the values are provided to the default arguments during the function calling, it overrides the default value.
  • 27.
    Copyright © 2021,ABES Engineering College Write a python program to greet a person with person name and message provided in function calling statement. If message not provided in function call, then print a default message “Hi !!”. 27 Example1
  • 28.
    Copyright © 2021,ABES Engineering College Default arguments are keyword arguments whose values are assigned at the time of function definition. Syntax: 28 Keywordarguments :
  • 29.
    Copyright © 2021,ABES Engineering College Write a program to demonstrate keyword arguments. 29 Example1
  • 30.
    Copyright © 2021,ABES Engineering College Positional arguments are arguments that need to be included in the proper position or order while calling the function. Syntax: 30 Positionalarguments :
  • 31.
    Copyright © 2021,ABES Engineering College Write a program to demonstrate positional arguments. 31 Example1
  • 32.
    Copyright © 2021,ABES Engineering College  When we are not sure in the advance that how many arguments our function would require.  This kind of situation is handled through function calls with an arbitrary number of arguments. 32 ArbitraryArguments Note: We define the arbitrary arguments while defining a function using the asterisk (*).
  • 33.
    Copyright © 2021,ABES Engineering College There are two types of arbitrary arguments as illustrated in the given figure below. 33 Types of ArbitraryArguments
  • 34.
    Copyright © 2021,ABES Engineering College The special syntax *args in function definitions is used to pass the variable number of arguments to a function. 34 *args Note: Generally, * args is used by convention but you can take any variable for example *abc will work in same way as * args.
  • 35.
    Copyright © 2021,ABES Engineering College Write a program to demonstrate *args arbitrary arguments. 35 Example 1
  • 36.
    Copyright © 2021,ABES Engineering College The **kwargs function in python is used to pass an arbitrary number of keyword arguments called kwargs. Note: ** (Double star allows us to pass variable number of keyword arguments). This turns the identifier-keyword pairs into a dictionary within the function body. 36 **kwargs
  • 37.
    Copyright © 2021,ABES Engineering College Write a program to demonstrate **kwargs arbitrary arguments. 37 **kwargs
  • 38.
    Copyright © 2021,ABES Engineering College Write a program using this function to generate perfect numbers from 1 to 1000. [An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3]. 38 **kwargs
  • 39.
    Copyright © 2021,ABES Engineering College  Let’s consider a situation that you book a train ticket in sleeper coach and you got berth in S1 coach and 48 seat number.  Now your ticket is valid for mentioned train and coach only this is called scope of your ticket.  Your ticket would expire after mentioned journey date and that is called lifetime. 39 ScopeandLifetimeofvariables
  • 40.
    Copyright © 2021,ABES Engineering College  Scope: The scope of a variable determines its accessibility and availability in different portions of a program. Their availability depends on where they are defined.  Lifetime: The lifetime of a variable is the time during which the variable stays in memory. 40 ScopeandLifetimeofvariables
  • 41.
    Copyright © 2021,ABES Engineering College Three kinds of variables in Python:  Global Variable  Local Variables  Non local variables 41 Types of variables
  • 42.
    Copyright © 2021,ABES Engineering College 42 Demonstration of Local and Global
  • 43.
    Copyright © 2021,ABES Engineering College Variables that are declared outside of a function are known as global variables. Example: Write a program to create global variable in python. 43 Global Variables
  • 44.
    Copyright © 2021,ABES Engineering College  These are variables which are defined inside a function.  Their scope is only to that function.  They cannot be accessed from the outside of the function. Example: Write a program to create local variable in python. 44 Local Variables
  • 45.
    Copyright © 2021,ABES Engineering College 45 Example: Local and global variable in one program.
  • 46.
    Copyright © 2021,ABES Engineering College 46 Example: To modify the variable outside of the current scope.
  • 47.
    Copyright © 2021,ABES Engineering College  Nonlocal variables are used in nested functions.  When a variable is either in local or global scope, it is called a nonlocal variable. 47 Non - Local Variables Note: Nonlocal keyword will prevent the variable from trying to bind locally first, and force it to go a level 'higher up'.
  • 48.
    Copyright © 2021,ABES Engineering College  Nonlocal variables are used in nested functions.  When a variable is either in local or global scope, it is called a nonlocal variable. 48 Non - Local Variables Note: Nonlocal keyword will prevent the variable from trying to bind locally first, and force it to go a level 'higher up'.
  • 49.
    Copyright © 2021,ABES Engineering College 49 Example 1 A program to create local variables for nested functions.
  • 50.
    Copyright © 2021,ABES Engineering College 50 Example 2 A program to use nonlocal keyword for nested functions.
  • 51.
    Copyright © 2021,ABES Engineering College What will be the output of the following Python code? a) 9 b) 3 c) 27 d) 30 51 Review Questions
  • 52.
    Copyright © 2021,ABES Engineering College What will be the output of the following Python code? a) 9 27 b) 27 9 c) None of the above d) Both of the above 52
  • 53.
    Copyright © 2021,ABES Engineering College 53 4.2 Anonymous and Higher Order Function 4.2.1 Anonymous Function 4.2.1 Lambda Function Session Plan - Day 3
  • 54.
    Copyright © 2021,ABES Engineering College 54 Anonymous Function  Sometimes we only have single expression to evaluate, so rather than creating regular function we create anonymous Function.  These functions do not have return statement, because by default evaluated single expression is returned.  This is one liner code and have following properties –  Function without name  One expression statement but any number of arguments.
  • 55.
    Copyright © 2021,ABES Engineering College 55 Syntax
  • 56.
    Copyright © 2021,ABES Engineering College 56 Scenario 1 Suppose we want to increment the value of variable by five, without writing lengthy code we can use lambda function.
  • 57.
    Copyright © 2021,ABES Engineering College 57 Example 1 A program to add three values, using multiple arguments in lambda function.
  • 58.
    Copyright © 2021,ABES Engineering College 58 Example 2 A program using lambda function to calculate the simple interest.
  • 59.
    Copyright © 2021,ABES Engineering College 1. Python supports the creation of anonymous functions at runtime, using a construct called __________ a) lambda b) pi c) anonymous d) none of the mentioned 59 Review Questions
  • 60.
    Copyright © 2021,ABES Engineering College 2. What will be the output of the following Python code? a) 48 b) 14 c) 64 d) None of the mentioned 60
  • 61.
    Copyright © 2021,ABES Engineering College 61 4.2 Anonymous and Higher Order Function  4.2.2 First Class Function and  4.2.2 Higher Order Function Session Plan - Day 4
  • 62.
    Copyright © 2021,ABES Engineering College 62 First Class Function and Higher Order Function  In first class function, function which can be passed as an argument.  Functions which take first class function as an argument are called Higher order function. Syntax:
  • 63.
    Copyright © 2021,ABES Engineering College 63 Properties of First-Class Function:  Function can be passed as an argument into another function.  Function can be assigned to a variable.  Function can be returned from other function.
  • 64.
    Copyright © 2021,ABES Engineering College 64 Properties of High Order Function:  Function can take other function as an argument.  Function can return other function.
  • 65.
    Copyright © 2021,ABES Engineering College  def loud(name):  return name.upper()  def soft(name):  return name.lower()  def speak(fun):  print("hello word")  return fun("xyz")  print(speak(soft)) Speak is high order function and loud and soft is first class function 65
  • 66.
    Copyright © 2021,ABES Engineering College  def apply_operation(func, x, y):  return func(x, y)  def multiply(a, b):  return a * b  print(apply_operation(multiply, 3, 4)) 66
  • 67.
    Copyright © 2021,ABES Engineering College  Built-in higher order functions are capable of taking other function as argument.  These higher order functions are applied over a sequence of data.  67 Built-in Higher order function in Python
  • 68.
    Copyright © 2021,ABES Engineering College First higher order function we would discuss is map function. Syntax: 68 Map ()
  • 69.
    Copyright © 2021,ABES Engineering College  nums = [1, 2, 3]  squares = list(map(lambda x: x ** 2, nums))  print(squares) # Output: [1, 4, 9]  Map is high order function  And lambda is first class function 69
  • 70.
    Copyright © 2021,ABES Engineering College One important thing to note that map function always returns map object. Syntax: 70 Contd..
  • 71.
    Copyright © 2021,ABES Engineering College To access values, we need to type cast map object as some sequence datatype like lists, tuple, etc. 71 Contd..
  • 72.
    Copyright © 2021,ABES Engineering College A program to convert a string of upper-case words into lower case. 72 Contd..
  • 73.
    Copyright © 2021,ABES Engineering College Filter function is the high order function which takes a filtering criterion, need to apply on any sequence. For example, in a bucket of balls of different colors, we have to find only black color balls, then filter function would work. Syntax: 73 Filter()
  • 74.
    Copyright © 2021,ABES Engineering College  balls = ["red", "blue", "black", "green", "black", "yellow"]  black_balls = list(filter(lambda color: color == "black", balls))  print(black_balls) 74
  • 75.
    Copyright © 2021,ABES Engineering College A list of integers find out even numbers. 75 Contd..
  • 76.
    Copyright © 2021,ABES Engineering College Reduce is used in such scenarios where the values in the iterable would be calculated to a final value. For example, take a collection of values (3,4,5) and we need to apply sum to it. Then we would get 12. Syntax: 76 Reduce()
  • 77.
    Copyright © 2021,ABES Engineering College  from functools import reduce  numbers = [1, 2, 3, 4, 5]  # Use reduce to sum the list  total = reduce(lambda x, y: x + y, numbers)  print(total) 77
  • 78.
    Copyright © 2021,ABES Engineering College A program to sum numbers of a list using reduce function. 78 Example 1
  • 79.
    Copyright © 2021,ABES Engineering College  Create a function that takes another function and applies it to a name.  From a list of fruits, filter out those that start with the letter "a".  Double each numbers in the list using map  Calculate the product of all elements in the list using reduce()  A company wants to increase the salaries of employees by 10%. You are given a list of current salaries.  salaries = [40000, 50000, 60000, 70000] 79
  • 80.
    Copyright © 2021,ABES Engineering College Practice Hackerrank Question  https://www.hackerrank.com/challenges/the-minion-game/problem? isFullScreen=true 80
  • 81.
    Copyright © 2021,ABES Engineering College What will be the output of the following Python code? a) 2 b) 4 c) error d) none of the mentioned 81 Review Questions
  • 82.
    Copyright © 2021,ABES Engineering College What will be the output of the following Python code? a) 2 b) 1 c) error d) none of the mentioned 82
  • 83.
    Copyright © 2021,ABES Engineering College 83 4.3 Modules • 4.3.1 Creation of module • 4.3.2 Importing module • 4.3.3 Standard Built-In Module Session Plan - Day 5
  • 84.
    Copyright © 2021,ABES Engineering College 84 Introduction As length of program grows in size and to maintain the reusability of some code we start writing function. Now if you want to use same function/functions in another program instead of writing their definition then module comes into picture. Python provides us to create our own module or provides use to use rich source of given module to increase the reusability. Python module can be imported into any program In python module is simply a python file containing python code, it may contain statements, functions, methods and classes.
  • 85.
    Copyright © 2021,ABES Engineering College 85 Creation of module A file containing Python code, for example: calc.py, is called a module, and its name would be calc. A module is created simply putting all functions/statements in one python file
  • 86.
    Copyright © 2021,ABES Engineering College 86 Contd.. A file containing Python code, for example: calc.py, is called a module, and its name would be calc. A module is created simply putting all functions/statements in one python file Code illustrates that how to create a module name ‘calc’, which contains the user defined functions of addition, subtraction, multiplication and division and area.
  • 87.
    Copyright © 2021,ABES Engineering College 87 Importing module To use the module in any application or program we need to import that module using import keyword. We can import module in multiple ways – • import module-name • import ... as ... • from ... import ...
  • 88.
    Copyright © 2021,ABES Engineering College 88 Contd.. When we use “import module-name” syntax, it will import all functions/statements from that module and function will call using module-name and dot operator.
  • 89.
    Copyright © 2021,ABES Engineering College 89 Contd.. import ... as ... We use import ... as ... to give a module name a short alias name while importing it.
  • 90.
    Copyright © 2021,ABES Engineering College 90 Contd.. import ... as ... Example: We import module calc using alias name ‘m’. It will import all functions / statements from that module and function will call using alias name and dot operator.
  • 91.
    Copyright © 2021,ABES Engineering College 91 Contd.. from ... import ... The from…. Import … statement allows us to import specific functions/variables from a module instead of importing everything.
  • 92.
    Copyright © 2021,ABES Engineering College 92 Contd.. from ... import ... Multiple function can also be imported using comma (,) operator. from calc import addition, subtraction We can also use ‘*’ , for importing all function/statements. from calc import *
  • 93.
    Copyright © 2021,ABES Engineering College 93 Standard Built-In Module Python has large number of built in functions similarly python contains some of the pre-defined modules such as: math random datetime sys os
  • 94.
    Copyright © 2021,ABES Engineering College 94 Contd.. The math Module Python has set of built-in math functions and also has an extensive math module that allows us to perform mathematical tasks on data. These include trigonometric functions, representation functions, logarithmic functions, sine functions, cosine functions, exponential, pi etc. math.sqrt() This function will calculate the square root of number.
  • 95.
    Copyright © 2021,ABES Engineering College 95 Contd.. math.ceil() Rounds a number up to the nearest integer. math.exp() Return 'E' raised to the power of different numbers
  • 96.
    Copyright © 2021,ABES Engineering College 96 Contd.. math. factorial() Return the factorial of a number math.gcd() Return the greatest common divisor of two integers. math.pow() Returns the value of x to the power of y.
  • 97.
    Copyright © 2021,ABES Engineering College 97 Contd.. math.fsum() Returns the sum of all items in an iterable. math.sin() Return the cosine of x (measured in radians). Refrence : https://docs.python.org/3/library/math.html
  • 98.
    Copyright © 2021,ABES Engineering College 98 Contd.. The random Module This module implements pseudo-random number generators for various distributions. We can generate random numbers in Python by using random module. random.seed() The random number generator needs a number to start with (a seed value). Use the seed() method to customize the start number of the random number generator.
  • 99.
    Copyright © 2021,ABES Engineering College 99 Contd.. random.random() Return random number between 0.0 and 1.0 random.randint(a,b) Return random integer between a and b, including both end points. random.choice() Choose a random element from a non- empty sequence like string, list, tuple etc. random.shuffle() The shuffle() method takes a sequence and reorganize the order of the items. import random fruits = ['apple', 'banana', 'cherry', 'mango', 'grape'] random_fruit = random.choice(fruits) print("Randomly selected fruit:",
  • 100.
    Copyright © 2021,ABES Engineering College 100 Contd.. The datetime Module In python there is no date and time data type so python date time module is used for displaying dates and times, modifying dates and time in different format. This module supplies classes to work with date and time. These classes provide a number of functions and built in methods to deal with dates, times and time intervals. Note: Classes and Objects we are going to discuss in Object Oriented Programming in Python.
  • 101.
    Copyright © 2021,ABES Engineering College 101 Contd.. The datetime Module Commonly used classes and associated methods in the datetime m
  • 102.
    Copyright © 2021,ABES Engineering College 102 Contd.. The date class A date object of date class represents a date in year, month and day.
  • 103.
    Copyright © 2021,ABES Engineering College 103 Contd.. All method and attributes of date object will be called using ‘d’ object and dot operator.
  • 104.
    Copyright © 2021,ABES Engineering College 104 Contd.. The time class Time object represents local time, independent of any day.
  • 105.
    Copyright © 2021,ABES Engineering College 105 Contd.. Create a time object and display hour, minute, second and microsecond in time object.
  • 106.
    Copyright © 2021,ABES Engineering College 106 Contd.. The datetime class Information on both date and time is contained in this class.
  • 107.
    Copyright © 2021,ABES Engineering College 107 Contd.. Create a time object and display hour, minute, second and microsecond in time object. Create a datetime object and display year, month, hour, minute in time object. Write a program to fetch the current datetime of system and print it
  • 108.
    Copyright © 2021,ABES Engineering College 108 Contd.. The sys Module The sys module provides system specific parameters and functions. It gives us information about constants, functions, and methods of the interpreter. Following are some important use of sys module: • Exiting current flow of execution in Python • Command-line Arguments • Getting version information of Interpreter • Set or get recursion depth For more function visit - https://docs.python.org/3/library/sys.html)
  • 109.
    Copyright © 2021,ABES Engineering College 109 Contd.. sys.version Gives version information of Interpreter.
  • 110.
    Copyright © 2021,ABES Engineering College 110 Contd.. sys.argv It returns a list of command line arguments passed to a Python script.
  • 111.
    Copyright © 2021,ABES Engineering College 111 Contd.. sys.argv Write a python script which print sum of given two value through command line
  • 112.
    Copyright © 2021,ABES Engineering College 112 Contd.. sys.argv Write a python script which print sum of given two value through command line
  • 113.
    Copyright © 2021,ABES Engineering College 113 Contd.. sys.getrecursionlimit() and sys.setrecursionlimit() sys.getrecursionlimit() method is used to find the current recursion limit of the interpreter. sys.setrecursionlimit() method is used to set the recursion limit of the interpreter
  • 114.
    Copyright © 2021,ABES Engineering College 114 Review Questions  What is the output of the code shown below if the system date is 18th August, 2016? tday=datetime.date.today() print(tday.month()) A. August B. Aug C. 08 D. 8
  • 115.
    Copyright © 2021,ABES Engineering College 115 Review Questions What is returned by math.ceil(3.4)? a) 3 b) 4 c) 4.0 d) 3.0 What is returned by math.ceil(3.4)? a) 3 b) 4 c) 4.0 d) 3.0
  • 116.
    Copyright © 2021,ABES Engineering College 116 Review Questions  What will be the output of the following Python code? import time print(time.strftime("%d-%m-%Y")) a) Print today’s date in string format dd-mm-yy b) Print today’s date in string format dd-mm-yyyy c) Error d) None  State whether true or false. t1 = time.time() t2 = time.time() t1 == t2 a)True b)False
  • 117.
    Copyright © 2021,ABES Engineering College 117 4.3 Modules  4.4 Iterative Built-in Functions Enumerate Zip Sorted Zip Session Plan - Day 6
  • 118.
    Copyright © 2021,ABES Engineering College 118 Enumerate: This is built-in function provided by Python. This function assigns count values to the iterable Iterative Built-in Functions What is iterable? Iterable in python is a collection of items, sequences like lists, tuple or any object which have multiple values on which a repeat operation can be performed, like name = [‘amit’, ‘ankur’, ‘aditya’, ‘anshul’, ‘anmol’], here the name has five items in it.
  • 119.
    Copyright © 2021,ABES Engineering College 119 When using the iterators, we need to keep track of the number of items in the iterator. This is achieved by built in method called enumerate. This enumerated object can directly be used for loops or converted into a list of tuples using list () method. Note: by default enumerate starts from 0 but we can change this start value as per our convenience. Contd..
  • 120.
    Copyright © 2021,ABES Engineering College 120 Contd.. Example : Demonstrating the enumerate usage in printing days of week.
  • 121.
    Copyright © 2021,ABES Engineering College 121 Contd.. Enumerate with for loop Example Syntax
  • 122.
    Copyright © 2021,ABES Engineering College 122 Contd.. Zip The function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc. Example Syntax
  • 123.
    Copyright © 2021,ABES Engineering College 123 Contd.. Sorted . Python contains a special built in method for sorting the data in a collection. It preserves the order of previous sequence or collection Syntax
  • 124.
    Copyright © 2021,ABES Engineering College 124 Contd.. Sorted Example
  • 125.
    Copyright © 2021,ABES Engineering College 125 Contd.. Reversed Reversed () function returns the iterator in a reverse order. Iterator can be any sequence such as list, tuple etc. Example Syntax
  • 126.
    Copyright © 2021,ABES Engineering College 126 Review Questions  Which of the following functions can help us to find the version of python that we are currently working on? a) sys.version b) sys.version() c) sys.version(0) d) sys.version(1)  Suppose there is a list such that: l=[2,3,4]. If we want to print this list in reverse order, which of the following methods should be used? a) reverse(l) b) list(reverse[(l)]) c) reversed(l) d) list(reversed(l))
  • 127.
    Copyright © 2021,ABES Engineering College 127 Review Questions  Which of the following functions is not defined under the sys module? a) sys.platform b) sys.path c) sys.readline d) sys.argv  To obtain a list of all the functions defined under sys module, which of the following functions can be used? a) print(sys) b) print(dir.sys) c) print(dir[sys]) d) print(dir(sys))
  • 128.
    Copyright © 2021,ABES Engineering College 128  In this unit you learnt the importance of using functions and how to use functions.  Further you learnt how to define functions, to write functions with different argument types.  Further you learnt describe the difference between the in- built functions and user defined functions,  Further you to write user defined functions, to use Functions in- built functions, import math module in to a Python program and to use lambda functions. Summary
  • 129.
    Copyright © 2021,ABES Engineering College 129 1. https://docs.python.org/3/tutorial/controlflow.html 2. Think Python: An Introduction to Software Design, Book by Allen B. Downey 3. Head First Python, 2nd Edition, by Paul Barry 4. Python Basics: A Practical Introduction to Python, by David Amos, Dan Bader, Joanna Jablonski, Fletcher Heisler 5. https://www.fullstackpython.com/turbogears.html 6. https://www.cubicweb.org 7. https://pypi.org/project/Pylons/ 8. https://www.upgrad.com/blog/python-applications-in-real-world/ 9. https://www.codementor.io/@edwardbailey/coding-vs-programming-what-s-the-difference-yr0aeug9o References
  • 130.
    Copyright © 2021,ABES Engineering College 130 Thank You