Modular Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

PROGRAMMING WITH PYTHON 3.6.

– MODULAR PROGRAMMING

 FUNCTIONS
 DEFINATION - DEF
 IMPLEMENTATION
 ARGUMENTS
 DOCSTRING
 RETURN
 FUNCTIONS AS OBJECTS
 ANONYMOUS FUNCTIONS – LAMBDA
 MAP / FILTER / REDUCE
 MODULES
 __NAME__
 PACKAGES
 __INIT__
 __ALL__

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

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.

Four kinds of functions can be created in Python:

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

The general syntax for creating a (global or local) function is:

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.

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

For example, here is a function that calculates the area of a triangle using Heron’s formula:

def heron(a, b, c):


s = (a + b + c) / 2
return math.sqrt(s * (s - a) * (s - b) * (s - c))

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.

So in this case, a is set to 3, b to 4, and c to 5, when the function is called.

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:

>>> #user-defined function to print the Employee details


>>> def displayEmployees(empCode, empName):
‘’’This function displays the employee details’’’
print("Employee Code :%s, Employee name is : " %(empCode, empName))

>>> print(displayEmployees.__doc__)
‘This function displays the employee details’

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

THE RETURN STATEMENT


Function always returns a value. The return statement is used to exit a function and go
back to the place from where it was called. This statement can contain expression which gets
evaluated and the value is returned. If there is no expression in the statement or the return
statement itself is not present inside a function, then the function will return the None object.
Some functions have parameters for which there can be a sensible default. For example, here is
a function that counts the letters in a string, defaulting to ‘abcd’.

>>> def letter_count(text, letters='abcd'):


letters = frozenset(letters)
count = 0
for char in text:
if char in letters:
count += 1
return count

>>> 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)

The output of the above program is as follows:

Enter a value :99


Enter a value :9
The result is 891
Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

THE ANONYMOUS FUNCTIONS


 Python supports the creation of anonymous functions.
 Anonymous functions are not bound to a name at runtime, they are created using a
construct called "lambda".
 The lambda operator or lambda function is a way to create small anonymous functions,
i.e. functions without a name.
 These functions are throwaway functions, i.e. they are just needed where they have been
created.
 Lambda functions are mainly used in combination with the functions filter(), map() and
reduce().

The general syntax of a lambda function is as follows:

LAMBDA ARGUMENT_LIST: EXPRESSION

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.

>>> print("Lamda example.....")


>>> val1 = int(input("Enter a number in val1 :"))
>>> val2 = int(input("Enter a number in val2 :"))
>>> #use a lamda function to multiply val1 and val2
>>> result = lambda x, y : x * y
>>> print(result(val1, val2))

The output of the above program is as follows:

Lamda example.....
Enter a number in val1 :90
Enter a number in val2 :9
810

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

THE MAP, FILTER, AND REDUCE FUNCTION


THE MAP FUNCTION
The map() function applies a function to every member of an iterable (e.g.,a list) and
returns the result. Typically, one would use an anonymous inline function as defined by
lambda, but it is possible to use any function.

>>> #let's first demonstrate a map() with a user-definied function


>>> #define a function which takes an input and return the squares
>>> def square(x):
return x**2
>>> #list of numbers
>>> numbers =[1,2,3,4,5,6,7,8,9,10]
>>> #use map() and pass the square() and the list
>>> results = list(map(square, numbers))
>>> print (results)

The output of the above program is as follows:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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:

<map object at 0x02E75C70>

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.

>>> #list of numbers


>>> numbers =[1,2,3,4,5,6,7,8,9,10]
>>> #use map() and use lamda
>>> results = map(lambda x: x**2, numbers)
>>> print(list(results))

The output of the above program is as follows:

>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

THE FILTER FUNCTION


Filter extracts each element in the sequence for which the function returns True. Filter
takes a function returning True or False and applies it to a sequence, returning a list of only
those members of the sequence for which the function returned True. In the above examples
we have use a map function and lamda function to square a list of numbers. Let’s modify that
program and partially display squared results using a filter function.

>>> numbers =[1,2,3,4,5,6,7,8,9,10]


>>> #use map() with lamda
>>> results =list(map(lambda x: x**2, numbers))
>>> partial_squares = list(filter(lambda x: x > 5 and x < 50, results))
>>> print(results)
>>> print(partial _squares)

The output of the above program is shown below:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


[9, 16, 25, 36, 49]

THE REDUCE FUNCTION


The reduce function continually applies the function to the sequence and returns a single
value. For example if we need to add a sequence of numbers say 1,2,3,4. It would look like the
below diagram:

The reduce function is in the functools in Python 3.x.x, so we have imported it in the example.

>>> from functools import reduce


>>> result = reduce( (lambda x, y: x + y), [1, 2, 3, 4] )
>>> print(result)

The output of the above program is as follows:

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.

Several syntaxes can be used when importing. For example:

import importable
import importable1, importable2, ..., importableN
import importable as preferred_name
from importable import *

If we want to control exactly what is imported when the:

from module import *

syntax is used, we can define an __all__ list in the module itself, in which case doing:

from module import *

will import only those objects named in the __all__ list.


Training imparted by: Michael Devine. #8884009669
PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

For example, to import the function fib from the module fib.py, use the following statement-

>>> # Fibonacci numbers module


>>> def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

>>> from fib import fib


>>> fib(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

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.

Executing Modules as Scripts


Within a module, the module’s name (as a string) is available as the value of the global
variable __name__. The code in the module will be executed, just as if you imported it, but
with the __name__ set to "__main__". Add this code at the end of your module-

# Fibonacci numbers module inside the fib.py file


def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

if __name__ == "__main__":
f=fib(100)
print(f)

When you run the above code, the following output will be displayed.

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

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:

> > > import sys


> > > print(sys.path)
[‘C:/Python31/Chapter 6’, ‘C:\\Python30\\Lib\\idlelib’,
‘C:\\Windows\\system32\\python31.zip’, ‘C:\\Python31\\DLLs’,
‘C:\\Python31\\lib’, ‘C:\\Python31\\lib\\plat-win’,
‘C:\\Python31’, ‘C:\\Python31\\lib\\site-packages’]

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.

The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the global and
local namespaces depending on the location from where they are called.

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

Training imparted by: Michael Devine. #8884009669


PROGRAMMING WITH PYTHON 3.6. – MODULAR PROGRAMMING

Packages ||
A package is simply a directory that contains a set of modules and a file called
__init__.py.

In some situations it is convenient to load in all of a package’s modules using a single


statement. To do this we must edit the package’s __init__.py file to contain a statement which
specifies which modules we want loaded. This statement must assign a list of module names to
the special variable __all__.

For example, here is the necessary line for the Graphics/__init__.py file:

__all__ = ["Bmp", "Jpeg", "Png", "Tiff", "Xpm"]

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:

from Graphics import *


image = Xpm.load("sleepy.xpm")

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.

Training imparted by: Michael Devine. #8884009669

You might also like