Unit -3
Functions and Modules
NEED FOR FUNCTIONS
|
a) Dividing the program into separate well defined function facilitates each function to be written and tested separately.
b) Function A calls other functions for dividing the entire code into smaller sections (or functions)
c) Understanding ,coding and testing multiple separate function are for easier doing the same for one huge function.
d) All libraries in Python contain pre-defined and pre-tested functions which the programmers are free to use directly in their programs without warring abouttheir code details.
e) Programmers can also make their own functions and us. then from different points in the main program or any other program that needs It functionalities.
1) Function Definition
a) When a called functions returns some result back the calling function, it is said to return that result.
b) The calling function may or may not pass parameter to the called function. If the called function accepts arguments, the calling function well pass parameters else not.
c) 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.
d) Function definition consist of a function header the identifies the function, followed by the body of the function containing the executables code for that function.
e) There are 2 basic type of functions, built in functions & user defined ones.
f) The built in function come as a part of the Python language. for Eg. di().len() or abs().
g) The user defined functions, on the other hand as function created by user in their programs user.
h) The first statement of a function can be an option all statement the documentation string of the function or do string describe what the function does.
i) The code block within the function is properly indented to form the block code.
j) A function may have a return statement .
k) You can assign a function name to a variable doing this will allow you to call the same function using the name of that variables.
Ex). def diff(x,y) : # function to subtract 2 nos.
a = 20
b = 10
operation = diff # function name assigned to a variable
print (operation(a,b)) # function called using variable name.
O/P : 10
When a function is defined, space is allocated for that function in the memory. A function definition compresses of 2 parts.
Function header - Function body
Syntax : def function_name(var1,var2…)
Documentation string
statement block
return[expression]
Ex)
def func()
For I in range(4);
Print(“Hello World”)
Func()
O/P : Hello World Hello World Hello World Hello World
Function can take parameters which are nothings some values that are passed to it so that the function can manipulate then to produce the declared result parameters are specified within the pair of parentheses in the function definition and are separated by commas.
Ex)
def func(i,j):
To some variable in the calling program.
For Eg : variable_name = function_name(var1,var 2,……)
Ex)
def total(a,b) : # function accepting parameter
result = a + b
print(“Sum of”,a,”and”,b,”-“,result)
a = int(input(“Enter the first number :”))
b= int(input(“Enter the second number :”))
total(a,b) # function call with 2 arguments
O/P :Enter the first number : 10
Enter the second number : 20
Sum of 10 and 20 = 30.
a) In Python, you cannot just access any variable from any past if your program.
b) Some of the variables may not even exist for the entire declaration of the program.
c) Scope of the variable : Part of the program in which a variables: Part of the program in which a variable is accessible is called its scope.
d) Lifetime of the variable : Duration for which the variable exists is called its Lifetime.
A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.
Note: Return statement cannot be used outside the function.
Syntax:
def fun():
statements
.
.
return [expression]
a) Lambda or anonymous functions are so called become the are not declared as other functions using the def keyword Rather they are created using the lambda keyword.
b) Lambda functions are throw-away functions i.e.are just needed where they have been created and be used anywhere a function is required. The lambda feature was added to Python due to the demand LISP programmers.
c) Lambda functions contain only a single line.
Syntax:
Lambda arguments : expression
- The arguments contain a comma separated list of arguments and the expression is an arithmetic expression that user these arguments.
Ex)
sum = Lambda x,y : x +y
print(“sum=”,sum(3,5))
O/P :sum = 8
- Lambda x,y : x +y is same as writing ,
Def sum(x,y):
return x +y
Key Points to remember :
Lambda function have no name
Lambda functions can take any no.of arguments.
Lambda function can return just one value in the form of an expression.
Ex)
def small(a,b)
if(a<b)
return a
else
return b
sum = lambda x,y : x +y
diff = lambda x,y : x – y
print(“Smaller of 2 nos=”,small(sum(-3,-2),diff(-1,2))
O /P : Smaller of 2 nos = -5
Doc strings serve the same purpose as that of comments, as they are designed to explain code.
def functionname(parameter):
“function_docstring”
Function statements
return[expression]
- Docstrings are important as they help tools to automatically generate online or printed documents
Ex)
def func():
“ “ “ The program just prints a message
It will display Hello World !! “ “ “
print(“Hello World!!!”)
print(func._doc_)
O/P : Hello World !!!
The program just prints a message
It will display Hello World!!!
- Triple quotes are used to extend the docstring to multiple lines This docstring specified can be accessed through the _doc_attribute of the function.
-In case of multiple lines in the documentation string the second line should be blank to separate the summary from the rest of the description.
1) Instead of tabs use 4 spaces for indentation.
2) Insert blank lines to separate functions and classes, and statement blocks inside functions
3) Whatever required ,use comments to explain the code
4) Also document string that explains the purpose of the function.
5) Use spaces around operators and after commas.
6) Name of the classes should be written as ClassName
7) Name of the function should be in lower case with underscores to separate words for eg. display _into() and get_data ().
8) Do not use non- ASCII characters in function names or any other identifier.
Modules allows you to reuse one or more function in your programmers, even in the programs in which those function have not been defined.
The program in which you want to use functions or variables defined in the modules will simply import that particular module(or. py file)
The basic way to use a module is to add import module name as the first line of your program and then writing module_name var to access functions and values with the name var in the module.
Eg)
import sys
Print(“\n PYTHONPATH=\n”,sys.path)
- when the import sys statement is executed ,Python looks for the sys .py module in one of the directories listed in its sys.path variable .If the file is found ,then the statements in the module is executed.
Eg)
from math import pi
print(“PI =”,+pi)
O/P : PI = 3.1415926
- To import more than one item from a module use comma separated list.
Eg).
from math import pi , sqrt
- you can also import a module with a different name using the as keyword.
Eg.from math import sqrt as square_root
Print(square_root(81))
O/P : 9.0
Python module is a file that contains some definitions and statement .When a Python file is executed directly, it is considered the main module of a program.
The main module may import any no. of other module which may is turn import other modules.
The main module of a Python program cannot be imported into other modules.
Python supports 3 types of modules – those written by the programmer, those that are installed from external sources, and those that are pre-installed with Python.
Modules that are pre-installed in Python are together known as the standard library.
Some useful modules in the standard libraries are string ,datetime,math,random,os,multiprocessing,subprocess,socket,email,json,doctest,unittest,pab ,arapases sand sys.
Reference Books
- R. G. Dromey, “How to Solve it by Computer”, Pearson Education India; 1st edition, ISBN-10: 8131705625, ISBN-13: 978-8131705629 Maureen Spankle, “Problem Solving and Programming Concepts”, Pearson; 9th edition, ISBN-10: 9780132492645, ISBN-13: 978-0132492645
- Romano Fabrizio, “Learning Python”, Packt Publishing Limited, ISBN: 9781783551712, 1783551712
- Paul Barry, “Head First Python- A Brain Friendly Guide”, SPD O’Reilly, 2nd Edition, ISBN:978-93-5213-482-3
- Martin C. Brown, “Python: The Complete Reference”, McGraw Hill Education, ISBN-10: 9789387572942, ISBN-13: 978-9387572942, ASIN: 9387572943
- Jeeva Jose, P. Sojan Lal, “Introduction to Computing & Problem Solving with Python”, Khanna Computer Book Store; First edition, ISBN-10: 9789382609810, ISBN-13: 978-9382609810