Modular Programming
Modular Programming
Modular Programming
– MODULAR PROGRAMMING
FUNCTIONS
DEFINATION - DEF
IMPLEMENTATION
ARGUMENTS
DOCSTRING
RETURN
FUNCTIONS AS OBJECTS
ANONYMOUS FUNCTIONS – LAMBDA
MAP / FILTER / REDUCE
MODULES
__NAME__
PACKAGES
__INIT__
__ALL__
Functions |||
A function is a self-contained block of reusable code that performs a coherent task of some
kind. When you define a function, you specify the name and the sequence of statements. Later,
you can “call” the function by its name. Functions could be categorized as – the User-defined
functions build-in functions.
global functions,
local functions,
lambda functions, and
methods.
Global objects (including functions) are accessible to any code in the same module
(i.e., the same .py file) in which the object is created. Global objects can also be accessed from
other modules.
Local functions (also called nested functions) are functions that are defined inside other
functions. These functions are visible only to the function where they are defined; they are
especially useful for creating small helper functions that have no use elsewhere.
Lambda functions are expressions, so they can be created at their point of use; however, they
are much more limited than normal functions.
Methods are functions that are associated with a particular data type and can be used only in
conjunction with the data type — object-oriented programming.
Python provides many built-in functions, and the standard library and third party libraries add
hundreds more (thousands if we count all the methods), so in many cases the function we want
has already been written. For this reason, it is always worth checking Python’s online
documentation to see what is already available.
def functionName(parameters):
suite
The parameters are optional, and if there are more than 1 they are written as a sequence of
comma-separated identifiers.
For example, here is a function that calculates the area of a triangle using Heron’s formula:
Inside the function, each parameter, a, b, and c, is initialized with the corresponding value that
was passed as an argument. When the function is called, we must supply all of the arguments,
for example,
heron(3, 4, 5).
If we give too few or too many arguments, a TypeError exception will be raised. When we do a
call like this we are said to be using positional arguments, because each argument passed is set
as the value of the parameter in the corresponding position.
DOCSTRING OF FUNCTION
The first string after the function header is called the docstring and is short for
documentation string. It is used to explain in brief, what a function does. Although optional,
documentation is a good programming practice.
In the below example, we have a docstring immediately below the function header. We have
used a double quotes because it is just one line of strings but generally use triple quotes so that
docstring can extend up to multiple lines. This string is available to us as __doc__ attribute of
the function.
If we type the following line in the command shell we can see the output:
>>> print(displayEmployees.__doc__)
‘This function displays the employee details’
>>> letter_count('M Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32
bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information.')
10
>>> letter_count('e')
0
>>> letter_count('M Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32
bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information.', 'e')
9
>>> letter_count('M Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32
bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information.', ' ')
22
>>>
>>>
>>> def multiplyFunction(num1, num2):
“This function multiply the parameters and return the result”
result = num1 * num2
return result
>>> #let's write the program to take data from keyboard and call the function
>>> value1 = int(input("Enter a value :"))
>>> value2 = int(input("Enter a value :"))
>>> #call the function to display the result
>>> res = multiplyFunction(value1, value2)
>>> print("The result is %d" %res)
While the argument list consists of a comma separated list of arguments and the expression is
an arithmetic expression using these arguments. In the below example we will use a lambda
function to return the product.
Lamda example.....
Enter a number in val1 :90
Enter a number in val2 :9
810
The above two programs are same but in the latter case we have use a list function -
results = list(map(square, numbers)). So if we need to compile with Python 3.x.x we need to
use a list to output the list. If we compile without list() we will get the output shown below:
In the above example, we have created a user-defined function square and using a map
function. That is one way of doing. In the below program we will use a lamda function with
the map() function.
>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
The reduce function is in the functools in Python 3.x.x, so we have imported it in the example.
10
At each step, reduce passes the current addition, along with the next item from the list, to the
passed-in lambda function. By default, the first item in the sequence initialized the starting
value.
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING
Modules |||
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code. Modules present a whole group of
functions, methods, or data that should relate to a common theme. To make a module usable,
two things need to be available. First, the module itself has to be installed on the system. The
simplest way to begin using a module is with the import keyword:
import sys
This will import the module named sys that contains services Python offers that mostly involve
system - specific items.
A module can contain any Python code we like. All the programs we have written so far have
been contained in a single .py file, and so they are modules as well as programs. The key
difference is that programs are designed to be run, whereas modules are designed to be
imported and used by programs.
Not all modules have associated .py files—for example, the sys module is built into Python,
and some modules are written in other languages (most commonly, C). However, much of
Python’s library is written in Python, so, for example, if we write import collections we can
create named tuples by calling collections.namedtuple(), and the functionality we are
accessing is in the collections.py module file. It makes no difference to our programs what
language a module is written in, since all modules are imported and used in the same way.
import importable
import importable1, importable2, ..., importableN
import importable as preferred_name
from importable import *
syntax is used, we can define an __all__ list in the module itself, in which case doing:
For example, to import the function fib from the module fib.py, use the following statement-
This statement does not import the entire module fib into the current namespace; it just
introduces the item fib from the module fib.py into the global symbol table of the importing
module.
if __name__ == "__main__":
f=fib(100)
print(f)
When you run the above code, the following output will be displayed.
The Python interpreter looks in the directories that are part of the module search path. These
directories are listed in the sys.path variable from the sys module.
The path, or list of directories that Python should search through, is stored in the sys module, in
a variable named path. To access this name, you will need to import the sys module. Until you
do that, the sys.path won’t be available to you:
You can see that sys.path is a normal list, and if you want to add directories that will be
checked for your modules, because you want them somewhere that isn’t already in sys.path,
you can alter it by using the usual methods — either the append method to add one directory,
or the extend method to add any number of directories.
If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
If globals() is called from within a function, it will return all the names that can be
accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using
the keys() function.
Packages ||
A package is simply a directory that contains a set of modules and a file called
__init__.py.
For example, here is the necessary line for the Graphics/__init__.py file:
That is all that is required, although we are free to put any other code we like in the
__init__.py file. Now we can write a different kind of import statement:
The from package import * syntax directly imports all the modules named in the __all__ list.
So, after this import, not only is the Xpm module directly accessible, but so are all the others.
As noted earlier, this syntax can also be applied to a module, that is, from module import *, in
which case all the functions, variables, and other objects defined in the module (apart from
those whose names begin with a leading underscore) will be imported.