You are on page 1of 47

IOE, Dept.

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.

More About a Function


• Any function can be compared to a black box that takes inputs, processes it and then gives the results.
• However, we may also have a function that does not take any inputs at all, or that does not return
anything at all.
• The inputs that the function takes are known as arguments / parameters.
• When a called function returns some results back to the calling function, it is said to return that result.
• The calling function may or may not pass parameters to the called function. If the called function accepts
arguments, the calling function will pass parameters, else not.
• Function declaration is a declaration statement that identifies a function with its name, a list of arguments
that it accepts, and the type of data it returns.
• Function definition consists of a function header that identifies the function, followed by the body of the
function containing the executable code for that function.
IOE, Dept. of
PPS Unit - 3 Pg. 8
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.

Returning Results from a Function


• We can return the result or output from the function using a ‘return’ statement in the body of the function.
• e.g. return c #returns c value out of function
return 100 #returns 100
return lst #returns the list that contains values
return x, y, z #returns 3 values
• When a function does not return any result, we need not write the return statement in the body of the
function.
• e.g. def sum(a, b) : #function definition
“””This fun. finds sum of two numbers”””
c=a+b
return c
IOE, Dept. of
PPS Unit - 3 Pg. 12
Computer Engg.

Returning Results from a Function


x = sum(10, 15) # call the function
print(‘Sum is = ‘, x)
y = sum(1.5, 1.05) # call the function
print(‘Sum is = ‘, y)

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

Returning Results from a Function


IOE, Dept. of
PPS Unit - 3 Pg. 14
Computer Engg.

Returning Results from a Function


IOE, Dept. of
PPS Unit - 3 Pg. 15
Computer Engg.

Variable Scope and Lifetime in Function


• When we declare a variable inside a function, it becomes a local variable.
• A local variable is a variable whose scope is limited only to that function where it is created.
• That means the local variable value is available only in that function only , but not to the outside of the
function.
• This is called as scope of the variable.
• e.g. def myFun( ):
a=1 # this is local variable
a += 1 # increment it by 1
print(a) # displays 2

myFun( )
print(a) # error, 'a' is not available
IOE, Dept. of
PPS Unit - 3 Pg. 16
Computer Engg.

Variable Scope and Lifetime in Function


• When any variable is created inside a function , it also gets a separate space in a memory.
• This variable is only available for processing within that function only, ie. Scope is limited to that function
only.
• As soon as we leaves the function, the variable, we created gets destroyed from the memory.
• This is called as Lifetime of a variable.
• Lifetime of a variable is the time throughout which the variable exists in the memory.
• The lifetime of a variable inside a function is as long as the function executes.
• These variables get destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
IOE, Dept. of
PPS Unit - 3 Pg. 17
Computer Engg.

Variable Scope and Lifetime in Function


• e.g.
a=1 # global variable
def myFun( ):
a=2 # local variable
print(“a = “, a) # displays local variable
myFun( )
print(“a = “, a) # displays global variable
• Output:
a=2
a=1
IOE, Dept. of
PPS Unit - 3 Pg. 18
Computer Engg.

Recursive Functions / Recursion


• A function that calls itself is known as ‘Recursive Function’.
• The process of calling a function inside itself is called as recursion.
• The concept of recursion helps the programmers to solve complex programs in less number of steps.
• It helps to reduce the time complexity of program.
• It helps to reduce the length of program.
• It helps to code reusability.
• A care should be taken that, we should write the correct statement to leave the recursion.
• If we not, the recursion goes on execution and it’s become unstoppable.
IOE, Dept. of
PPS Unit - 3 Pg. 19
Computer Engg.

Recursive Functions / Recursion


IOE, Dept. of
PPS Unit - 3 Pg. 20
Computer Engg.

Lambda / Anonymous Function


• A function without a name is called as ‘Anonymous Function’.
• As we see, each function is defined using a keyword ‘def’.
• But anonymous functions are not defined using ‘def’. Rather they are defined using a keyword ‘lambda’.
• And hence they are also called as lambda functions.
• e.g. a normal function that returns square of a given value is,
def square(x)
return x * x
• The same function can be written as anonymous function as.
lambda x : x * x
• The lambda is a keyword used to represent anonymous function that being created.
• After that, we have written an argument of the function, ie. ‘x’.
• The ( : ) colon represents the beginning of the function.
IOE, Dept. of
PPS Unit - 3 Pg. 21
Computer Engg.

Lambda / Anonymous Function


• The expression x * x is the statement within the lambda function.
• Here, we did not use any name for the function.
• Normal lambda function format / syntax is,
lambda argument_list : expression
• Normally, if a function returns some value, we assign that value to a variable.
y = square(5)
• But, lambda functions return a function and hence they should be assigned to a function, as,
f = lambda x : x * x
• Here, ‘f’ is the function name to which the lambda expression is assigned.
• Now, if we call the function f( ) as,
value = f(5)
• Here ‘value’ contains the square value of 5 ie. 25.
IOE, Dept. of
PPS Unit - 3 Pg. 22
Computer Engg.

Lambda / Anonymous Function


• Lambda functions contain only one expression and they return the result implicitly.
• Hence, we should not write any ‘return’ statement in the lambda functions
IOE, Dept. of
PPS Unit - 3 Pg. 23
Computer Engg.

Lambda / Anonymous Function


IOE, Dept. of
PPS Unit - 3 Pg. 24
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.

Good Programming Practice


• As a programmer we want to write the code to fulfill following issues,
1. Write efficient and optimized code.
2. Write code that takes up minimum possible memory.
3. Write code which executes in faster way.
4. Apply simplified coding style which looks clean and clear.
5. Make a habit to properly document your code.
6. Follow standard coding style guidelines as specified by the organization.
7. Write code in simple instructions so that it would be easy to understand for new developers.
8. Follow the consistency of your code with others.
9. Use latest version / release of Python when starting a new project.
10.Analyze the code after writing for issues like, coverage, quality, optimization and performance.
IOE, Dept. of
PPS Unit - 3 Pg. 28
Computer Engg.

Good Programming Practice


11. It is good practice to test your code for any errors/bugs/defects.
12. Give proper training /demo to end user while deploying your software.
13. Provide best service for your customers, ie. Service after sales.
IOE, Dept. of
PPS Unit - 3 Pg. 29
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

def add(x, y):


return (x+y)

def multiply(x, y):


return (x*y)

def subtract(x, y):


return (x-y)

def divide(x, y):


return (x/y)
IOE, Dept. of
PPS Unit - 3 Pg. 31
Computer Engg.

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

def SayHello(name): def sum(a, b):

print(“Hello “ + name) return a + b

return def average(a, b):


return (a + b)/2
def power(a, b):
return a ** b

• So in this way we have created our own package known as mypackage.


IOE, Dept. of
PPS Unit - 3 Pg. 37
Computer Engg.

Introduction to Packages
• Our package folder structure is just like this….,

__init__.py

MyApp mypackage greet.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.

• e.g. from mypackage import functions


functions.power(3, 2) # displays output 9
• e.g. from mypackage.functions import sum
sum(10, 20) # displays output 30
IOE, Dept. of
PPS Unit - 3 Pg. 39
Computer Engg.

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.

Introduction to Standard Library Modules


• Python has provided a number of built-in functions.
• They are loaded automatically as the interpreter starts and are always available.
• e. g. print(), input() etc.
• A huge number of pre-defined functions are available within Python in the form for code library. These
functions are defined in modules.
• As we know, the contents of a module can be made available to any other program.
• Most of the built-in modules are written in C language and integrated with the Python interpreter.
• Each built-in module contains resources for certain system-specific functionalities such as OS
management, disk IO, etc.
• The standard library also contains many Python files that containing useful utilities.
• To get a list of all available modules, use command as,
• e.g. help(‘modules’)
IOE, Dept. of
PPS Unit - 3 Pg. 41
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.

Python - SYS Module


• The sys module provides several functions as well as variables used for the purpose of manipulating
different parts of the Python runtime environment.
sys.argv:
• sys.argv returns a list of command line arguments passed to a Python program.
• Name of the program is present at index 0 in this list, and remaining arguments are stored at the
subsequent indices.
• e.g. import sys
print(“Hello { } Welcome to { }”, format( sys.argv[1], sys.argv[2] ))
• When this program code executes, it displays the runtime arguments which we passed at the time of
compilation.
• e.g. Python abc. py Kunal Nashik
• Output: Hello Kunal Welcome to Nashik
IOE, Dept. of
PPS Unit - 3 Pg. 45
Computer Engg.

Python - SYS Module


sys.exit:
• It is used to securely exit from the program when any exception occurs.
• It will exit to either the Python console or the command prompt.
sys.maxsize:
• Returns the largest integer a variable can take.
sys.path:
• This is an environment variable that is a search path for all Python modules.
• Once you invoke it, it will displays a list of all search paths for all Python related modules.
sys.version:
• This is used to get a string containing the version number of the current Python interpreter.
IOE, Dept. of
PPS Unit - 3 Pg. 46
Computer Engg.

Python – Math Module


• Python Math module provide several mathematical functions, such as trigonometric functions,
representation functions, logarithmic functions etc.
• It also defines mathematical constants, ie. Pie and Euler number etc.

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.

Python – Math Module


math.exp():
• This function returns a floating point number after raising e to the given number.

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.

math.cos(): math.sin(): math.tan():

You might also like