Professional Documents
Culture Documents
PPS Unit - 3
PPS Unit - 3
of
PPS Unit - 3 Pg. 1
Computer Engg.
Function - Introduction
Function:
• A function is similar to a program that consists of a group of statements that are intended to perform a
specific task.
• A function is a block of organized and reusable program code that performs a single, specific and well
defined task.
• The main purpose of function is to perform a specific task or work.
• Hence, when there are several tasks to be performed, the programmer will write several functions.
• Python enables its programmers to break up a program into functions, each of which can be written
more or less independently of the others.
• Therefore, the code of one function is completely insulated from the codes of the other functions.
IOE, Dept. of
PPS Unit - 3 Pg. 2
Computer Engg.
Function - Introduction
• There are several ‘Built-in’ functions in Python to perform a specific task, e.g. print(), input(), power(),
sqrt() etc.
• Similar to these functions, a programmer can also create his own functions which are called as ‘User-
Defined’ functions.
• Every function have an interface to the outside world in terms of how information is transferred to it and
how results are generated by the function are transmitted back from it.
• This interface is basically specified by the function name.
• e.g. we are using functions such as input() to take input from the user, print() to display some information
on the screen, int() to convert the user entered information into int datatype.
IOE, Dept. of
PPS Unit - 3 Pg. 3
Computer Engg.
Functions in Python
Need for Function:
• In normal daily life, human depends on many people to complete his task.
• e.g. When a person wants to arrange a large party, lot of work is required like, decoration, arranging food,
inviting guests etc.
• To get the party successfully done, the best idea is to divide these tasks between several people around
you.
• Python language provides a term called as Function, which is acts like these people.
• The function helps to simplify the complexity of program by splitting a large task into smaller tasks.
• Python provides library functions and also allows user to define their own functions.
IOE, Dept. of
PPS Unit - 3 Pg. 4
Computer Engg.
Functions in Python
Need for Function: cont..
• Dividing the program into separate well defined functions facilitates each function to be written and
tested separately.
• This simplifies the process of program development.
• Understanding, coding and testing multiple separate functions are far easier than doing the same for one
huge program / function.
• If a big program has to be developed without the use of any function, then there will be a large number of
lines in the code and maintaining that program will be a big problem. Also a large size program is a
serious issue in micro-computers where memory space is limited.
• All python libraries contain pre-defined and pre-tested functions which the programmer are free to use
them directly in their programs, without worrying about their code details.
IOE, Dept. of
PPS Unit - 3 Pg. 5
Computer Engg.
Functions in Python
Need for Function: cont…
• This speeds up the program development by allowing the programmer to concentrate only on the code
that has to be written from scratch. (ie. They are not available in the libraries.)
• When a big program is broken into comparatively smaller functions, then different programmers
working on that project can divide the workload by writing different functions.
• Like Python libraries, programmers can also make their own functions and use them from different
points in the main program or any other program that needs its functionalities.
• Code reuse is one of the most prominent reason to use functions.
• Once a function is written, it can be called multiple times within the same program or by a different
program wherever its functionality is required.
IOE, Dept. of
PPS Unit - 3 Pg. 6
Computer Engg.
Function - Advantages
• Functions are important in programming because they are used to process data, make calculations or
perform any task which is required in the software development.
• Once a function is written, it can be reuse as and when required for any number of times, so called as
reusable code. Save the time to perform the same thing again and again.
• Functions provides modularity for programming. A module represents a part of the program. The whole
program gets divide into several modules, this makes programming easy.
• Code maintenance will become easy because of functions. So addition of the new code and deletion of the
unwanted code becomes easy with the help of functions.
• When there is an error in the software, the corresponding function can be modified without disturbing
the other functions in the software.
• The use of functions in a program will reduce the length of the program.
IOE, Dept. of
PPS Unit - 3 Pg. 7
Computer Engg.
Defining a Function
• It is possible to create our own functions, called as user-defined functions.
• We can define a function using keyword def followed by function name.
• After the function name, we should write parentheses ( ) which may contain parameters / arguments.
• Syntax,
def fun_name(arg1, arg2, ……) : # function header
“”” function docstring “””
function statements # function body
• e.g. def sum(a, b) :
“””This function finds Sum of Two numbers”””
c=a+b # indented statements shows
print(c) # function body
IOE, Dept. of
PPS Unit - 3 Pg. 9
Computer Engg.
Defining a Function
• Keyword ‘def’ represents the starting of function definition.
• ‘sum’ is the name of the function.
• Function name followed by compulsory parentheses ( ), as it denotes it is a function and not a variable or
something else.
• sum(a, b) – Here ‘a’ and ‘b’ are called parameters/arguments.
• A parameter is a variable that receives data from outside into a function.
• So this function receives two values from outside and those values are stored in the variables ‘a’ and ‘b’
respectively.
• Colon ‘:’ represents the beginning of the function body.
• The function body contains a group of statements.
• The statement inside the “”” …… “”” triple quotes, are called ‘docstring’, that gives information about the
function. These ‘docstrings’ are optional. But writing it is a good programming practice.
IOE, Dept. of
PPS Unit - 3 Pg. 10
Computer Engg.
Calling a Function
• A function cannot run on its own. It runs only when we call it.
• To get the code from function, we need to call a function using its name.
• While calling the function, we should pass the necessary values to the function in parentheses as,
sum( 10, 15)
• When this statement is executed, the Python interpreter jumps to the function definition and copies the
values 10 and 15 into the parameters ‘a’ and ‘b’ respectively.
• e.g. def sum(a, b) : # function definition
“”” This function finds sum of two numbers “”” # optional
c=a+b
print(“Sum is = “, c)
sum(10, 15) # function calling
sum(1.5, 10.5) # function calling with different values
IOE, Dept. of
PPS Unit - 3 Pg. 11
Computer Engg.
• In the above program, the result is returned by the sum() function through ‘c’ using the statement :
return c
• When we call the function, the result returned by function comes into the variable ‘x’.
• As the function returns a value, we should catch this value in a variable.
• So ultimately, ‘return c’ value get catched into variable ‘x’ and ‘y’ respectively.
IOE, Dept. of
PPS Unit - 3 Pg. 13
Computer Engg.
myFun( )
print(a) # error, 'a' is not available
IOE, Dept. of
PPS Unit - 3 Pg. 16
Computer Engg.
Documentation String
• Also called as “””docstring”””.
• Generally we should write a string as the first statement in the function body.
• This string is called as ‘docstring’, that gives information about the function.
• Docstring is a literal that is written as the first statement in a function, module or class.
• Docstrings are generally written inside triple quotes “”” ……. “”” or ‘’’ ……. ‘’’.
• e.g. “”” This function finds sum of two numbers. “””
• We can write docstring in single line and multiple lines also.
• These docstrings are shown in the form of output to the user.
• When an Application Programming Interface documentation file is created, the function name and
docstring are stored in that file thus providing clear description about the function.
• Writing docstring is a good programming practice.
IOE, Dept. of
PPS Unit - 3 Pg. 25
Computer Engg.
Documentation String
• Writing a docstrings are optional. That means it is not compulsory to write them.
Accessing a docstring:
• The docstring can be accessed using the __doc__ method of the object or using the help function.
IOE, Dept. of
PPS Unit - 3 Pg. 26
Computer Engg.
Documentation String
IOE, Dept. of
PPS Unit - 3 Pg. 27
Computer Engg.
Introduction to Modules
• A module is to be same as code library.
• It is a file containing a set of functions you want to include in your application.
• A module represents a group of functions, variables, classes, methods etc.
• The modules are created by grouping related functions, classes, methods into several modules and later
use these modules in the other programs.
• It means, when a module is developed, it can be reused in any program that needs that module.
• Modules helps to logically organize the Python code.
• In module we can group related code which makes the code easier to understand as well as use.
• A module is a file consisting of Python code.
• A module has ability to define functions, classes and variables.
• A module can also contain executable code.
IOE, Dept. of
PPS Unit - 3 Pg. 30
Computer Engg.
Modules in Python
Creating a Simple Module:
• A module is created just like a Python file.
• Write the code as you want to add in module, and save the file with desired filename.py
• e.g. # A simple module, calc.py
Modules in Python
The import statement:
• We can use any Python source file as a module by executing an import statement in some other Python
source file.
• When interpreter encounters an import statement, it imports the module if the module is present in the
search path.
• A search path is a list of directories that the interpreter searches for importing a module.
• E.g., to import the module calc.py, we need to put the following command at the top of the script :
# importing module calc.py
import calc
print (add(10, 2)) # display output : 12
print (subtract(10, 2)) # display output : 8
print (divide(10, 2)) # display output : 5
IOE, Dept. of
PPS Unit - 3 Pg. 32
Computer Engg.
Modules in Python
The from ……. import statement:
• Python’s from statement is used to import only desired code libraries from a module into the current
program.
• If we does not want to import the whole module into the current namespace, but instead of it only
specific functionalities we want to import, we can does it by from …. import statement.
• Syntax , from modname import name1[, name2[,….name N ]]
• e.g. from fact import factorial
• Above statement can be used to for the purpose of importing the function factorial from the module fact.
• This instruction does not import the whole module fact into the current namespace, rather it only
includes the item factorial from the module fact.
• Importing such a module is actually added to respective symbol table.
IOE, Dept. of
PPS Unit - 3 Pg. 33
Computer Engg.
Variables in Module
• Along with functions, modules can also contain variables of all types.
• e.g. Create a module named - “studmodule.py”
student = { "name" : "Kunal", "age" : 21, "country" : "India"}
• Import the module, and access the student dictionary.
import studmodule
n = studmodule.student[“name”]
a = studmodule.student[“age”]
c = studmodule.student[“country”]
print(n, “ “ , a, “ “, c)
• It will displays output as : Kunal 21 India
IOE, Dept. of
PPS Unit - 3 Pg. 34
Computer Engg.
Re-Naming a Module
• It is possible to create an alias name of existing module when we import a module, by using a keyword
‘as’.
• It helps a programmer by using alias name instead of full name of module especially when a module
name is too long.
• e.g. Import the module, and access the student dictionary.
import studmodule as st
n = st.student[“name”]
a = st.student[“age”]
c = st.student[“country”]
print(n, “ “ , a, “ “, c)
• It will displays output as : Kunal 21 India
IOE, Dept. of
PPS Unit - 3 Pg. 35
Computer Engg.
Introduction to Packages
• We always organize several files in different folders and sub-folders depending upon some specific
criteria, so that it become easy to find and manage them.
• In the same manner, a package in Python adopts the concept of the modular approach to next logical
level.
• As we have seen, a module is able to contain multiple objects, such as, classes, functions etc.
• A package can contain one or more relevant modules.
• Physically a package is nothing but a directory containing one or more module files.
Creating a Package:
• Create a new folder named MyApp in home directory.
• Inside MyApp, create a subfolder with the name ‘mypackage’.
• Create an empty file in mypackage folder as __init__.py
IOE, Dept. of
PPS Unit - 3 Pg. 36
Computer Engg.
Introduction to Packages
• In same way create a following files with the code as….
• greet.py • functions.py
Introduction to Packages
• Our package folder structure is just like this….,
__init__.py
functions.py
IOE, Dept. of
PPS Unit - 3 Pg. 38
Computer Engg.
Introduction to Packages
Importing a Module from a Package:
• To test whether our package has been successfully created or not we have to invoke the Python prompt
from the MyApp folder.
• i.e. $:\MyApp>
• Now import the functions module from the mypackage package and give call to its power() function.
Introduction to Packages
• The package folder contains a special file known as __init__.py, which stores the package’s content.
• There are two main purposes of this file :
1. The python interpreter recognizes a folder as a package when it found __init__.py in it.
2. __init__.py explains particular resources from its modules to be imported.
• Whenever a package is imported, an empty __init__.py file has responsibility to make all functions from
above modules available.
• When a regular package is imported, this __init__.py file is implicitly executed, all the functions within a
module and package gets available for all.
• We create this __init__.py initially empty, but as per requirements we can add a code to it.
• When we import any package Python adds some additional attributes to this.
IOE, Dept. of
PPS Unit - 3 Pg. 40
Computer Engg.
Python - OS Module
• Python allows to perform many Operating System tasks.
• The OS module in Python provides number of functions for the purpose of creating and removing a
directory, accessing its contents, changing and identifying the current directory.
Create Directory:
• To create a new directory, Python provides the mkdir() function in the OS module.
• e.g. import os
os.mkdir(“d:\\testfolder”)
Changing Current Working Directory:
• To change the current working directory to a newly created directory prior of performing any operations
on it, use chdir() function.
• e.g. import os
os.chdir(“d:\\testfolder”)
IOE, Dept. of
PPS Unit - 3 Pg. 42
Computer Engg.
Python - OS Module
Working Directory Change:
• To check whether the current working directory has been changed or not, OS moduke provides getcwd()
function. It displays a list of directories which get changed.
• e.g. import os
os.getcwd()
• Displays output as : ‘d:\\testfolder’
Removing a Directory:
• OS module provides rmdir() function which removes the specified directory.
• e.g. import os
os.rmdir(“d:\\testfolder”)
• We can not remove a directory which is not empty and which is a current working directory.
IOE, Dept. of
PPS Unit - 3 Pg. 43
Computer Engg.
Python - OS Module
List Files and Sub-Directories:
• OS module provides listdir() function to get list of all files and directories in the specified directory.
• e.g. import os
os.listdir(“c:\python”)
• If directory is not specified, then list of files and directories in the current working directory will be
displayed.
• e.g. os.listdir()
IOE, Dept. of
PPS Unit - 3 Pg. 44
Computer Engg.
math.log():
• This function returns the natural logarithm of a given number. It is calculated to the base e.
math.log10():
• This function returns base 10 logarithm of the given number and called as the standard logarithm.
IOE, Dept. of
PPS Unit - 3 Pg. 47
Computer Engg.
math.sqrt():
• This function returns square root of any given number.
math. expm1():
• This function returns e raised to the power of any number minus 1.
• e is the base of natural logarithm.