Unit 4
Unit 4
Introduction
Functions, modules and packages are all constructs in Python programming that promote code
modularization. The modularization (modular programming) refers to the process of breaking a
large programming task into separate, smaller, more manageable subtasks or modules.
Function
Is a block of organized, reusable code that is used to perform a single, related action/operation
Python has excellent support for functions.
A function can be defined as the organized block of reusable code which can be called whenever
required. A function is a piece of code that performs a particular task.
A function is a block of code which only runs when it is called. Python gives us many built-in
functions like print() but we can also create our own functions called as user-defined functions.
Module
Python programming allows us to logically organize the python code. A module is a single
source code file, The module in Python have the .py file extension. The name of the module will
be the name of the file.
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our Python code
file saved with the extension (.py) is treated as the module.
Packages
Package allow us to create a hierarchical file directory structure of modules,For example, my
module.modl stands for a module mod1, in the package mymodule.
A Python package is a collection of modules which have a common purpose. In short, modules
are grouped together to forms packages.
In the above example, an int value a is added to float value b, and the result is automatically converted to
a float value sum without having to tell the compiler. This is the implicit data conversion.
In implicit data conversion the lowest priority data type always get converted to the highest priority data
type that is available in the source code.
data type conversion function with their description is given below
Sr.
Function Description Example
No.
Converts x to an integer. base x=int('1100',base=2)=12
1 int(x [,base]) specifies the base if x is a string. x=int( '1234’,base=8)=668
Sr
. Function
Description Example
N s
o.
1 min() Returns smallest value among supplied >>> min(20, 10, 30)
arguments. 10
2 max() Returns largest value among supplied > » max(20, 10, 30)
arguments. 30
3 pow( ) The pow() function returns the value of x to the power >>> pow( 2., 3) 8
of y (xy). If a third parameter is present, it returns x to >>> pow(2,3,2) 0
the power of y, modulus z.
4 round() The round() function returns a floating point number that >>> round (10.2345) 10
isa rounded version of the specified number, with the >>> round(5.76543)
specified number of decimals. The default number of decimals is 6
0, meaning that the function will return the >>>round(5.76543,2)
nearest integer. 5.77
5 abs() Absolute function, also known as Modulus (not to >>> abs( -5) 5
be confused with Modulo), returns the non-negative value >>> abs(5) 5
of the argument value.
Function in python is self contained program that performs some particular tasks.Once, a
function is created by the programmer for a specific task, this function can be called anytime to perform
that task.
Python gives us many built-in functions like print°, len() etc. but we can also create our own functions.
These functions are called user-defined functions.
User defined function are the self-contained block of statements created by users according to their
requirements.
A user-defined function is a block of related code statements that are organized to achieve a single
related action or task, A key objective of the concept of the user-defined function is to encourage
modularity and enable reusability of code.
Function Defination
Function definition is a block where the statements inside the function body are written. Functions allow
us to define a reusable block of code that can be used repeatedly in a program. Syntax;
def function_name(parametes):
"function_docstring"
function_statements
return [expression]
Defining Function:
• Function blocks begin with the keyword def followed by the function name and parentheses ().
• Any input parameters or arguments should be placed within these parentheses. We can also define
parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of the
function or docstring.
• The code block within every function starts with a colon: and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None
• The basic syntax for a Python function definition is explained in Fig. 4.2.
Unit 4: Python Functions modules and Packages
Function Calling
• The def statement only creates a function but does not call it. After the def has run, we can call (run)
the function by adding parentheses after the function's name. Example: For calling a function.
a=4
>>> square(a) # function call
16
>>>
Formal Parameters:
• The parameters used in the header of function definition are called formal parameters of the function.
These parameters are used to receive values from the calling function.
They are used in the function header.
They are used to receive the values that are passed to the function through function call.
They are treated as local variables of a function in which they are used in the function header. Example:
For actual and formal parameters.
Example:
>>>def increment(n):
n=n+1
Unit 4: Python Functions modules and Packages
>>> a=3
> >> increment(3)
>> print(a)
3
• when we pass a to increment(n) the function as local variable n referred to the same object.
• When control comes to n =n+1 as integer is immutable, by definition we are not able to modify the
object's value to 4 in place: we must create a new object with the value 4, We may visualize it like
below:
• All this time, the variable a continues to refer to the object with the value 3, since we did not change
the reference:
• We can still "modify" immutable objects by capturing the return of the function.
Function Arguments
• Many build in functions need arguments to be passed with them. Many build in functions require two
or more arguments. The value of the argument is always assigned to a variable known as parameter.
• There are four types of arguments using which can be called are
1. Required arguments
2. Keyword arguments
3. Default arguments, and
4. Variable-length arguments.
1. Required Arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number
of arguments in the function call should match exactly with the function definition.
Example
For required arguments
>>>def display(str):
“this print a string”
Print(str)
Return
>>>display( “hello”)
hello
2. Keyword Arguments
With keyword arguments in python, we can change the order of passing the arguments without any
consequences.
Let’s take a function to divide two numbers, and return the quotient.
>>> divide(a=1,b=2.0)
Output
0.5
Unit 4: Python Functions modules and Packages
>>> divide(b=2.0,a=1)
Output
0.5
3. Default Argument
Python Program arguments can have default values. We assign a default value to an argument using the
assignment operator in python(=).
When we call a function without a value for an argument, its default value (as mentioned) is used.
>>> def greeting(name=”user”):
print("Hello, {name}")
>>> greeting('Ayushi')
Output
Hello, Ayushi
When we call greeting() without an argument, the name takes on its default value- ‘User’.
>>> greeting()
Output
Hello, User
4.Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function.
These arguments are called variable-length arguments and are not named in the function definition,
unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this –
An asterisk (*) is placed before the variable name that holds the values of
all nonkeyword variable arguments. This tuple remains empty if no
additional arguments are specified during the function call. Following is a
simple example −
Example:
Output is:
70
60
50
90
Return Statement
The return statement is used to exit a function. The return statement is used to return a value from
the function. A return statement with no arguments is the same as return None.
Example1:
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where
you have declared a variable.
The scope of a variable determines the portion of the program where you
can access a particular identifier. There are two basic scopes of variables
in Python −
Global variables
Local variables
Unit 4: Python Functions modules and Packages
BASIS FOR
LOCAL VARIABLE GLOBAL VARIABLE
COMPARISON
Declaration Variables are declared inside a Variables are declared outside any
function. function.
Scope Within a function, inside which Throughout the program.
they are declared.
Value Uninitialized local variable result Uninitialized global variable stores
in storage of the garbage value. zero by default.
Unit 4: Python Functions modules and Packages
Access Accessed only by the statements, Accessed by any statement in the
inside a function in which they entire program.
are declared.
Data sharing Not provided Facilitated
Life Created when the function block Remain in existence for the entire time
is entered and destroyed upon your program is executing.
exit.
Storage Local variables are stored on the Stored on a fixed location decided by a
stack unless specified. compiler.
Parameter Necessarily required Not required for global variables.
passing
Changes in a Any modification implied in a The changes applied in the global
variable value local variable does not affect the variable of a function reflect the
other functions of the program. changes in the whole program.
Recursive function
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself.
This has the benefit of meaning that you can loop through data to reach a result.
Example
Factorial of a number specifies a product of all integers from 1 to that number. It is defined by the
symbol explanation mark (!).
For example: The factorial of 5 is denoted as 5! = 1*2*3*4*5 = 120.
Example
To print the fibonacci series upto n_terms
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
def euro_rup():
euro= float(input("Please enter euro:"))
rupees = euro * 79.30
print("Euro: IT",euro)
print("Rupees: ",rupees)
def menu():
print("1: Doller to Rupees")
print("2: Euro to Rupees")
print("3: Exit")
choice=int(input("Enter your choice:"))
if choice==1:
dol_rup()
if choice==2:
euro_rup()
if choice==3:
print("Good bye!")
menu()
Output:
1: Doller to Rupees
2: Euro to Rupees
3: Exit Enter your choice:
1 Please enter dollars:75
Dollars: 75.0
Rupees: 525e.0
Modules
Modules are primarily the (.py) files which contain Python programming code defining functions, class,
variables, etc. with a suffix .py appended in its file name. A file containing .py python code is called a
module.
If we want to write a longer program, we can use file where we can do editing, correction. This is known
as creating a script. As the program gets longer, we may want to split it into several files for easier
maintenance.
We may also want to use a function that we have written in several programs without copying its
definition into each program.
In Python we can put definitions in a file and use them in a script or in an interactive instance of the
interpreter. Such a file is called a module.
Unit 4: Python Functions modules and Packages
Writing Module
Writing a module means simply creating a file which can contains python definitions and statements,
The file name is the module name with the extension ,py.
To include module in a file, use import statement.
Follow the following steps to create modules:
1. Create a first file as a python program with extension as .py. This is your module file where we
can write a function which perform some task.
2. Create a second file in the same directory called main file where we can import the module to
the top of the file and call the function.
3. Second file needs to be in the same directory so that Python knows where to find the module
since it's not a built-in module.
def add(a, h) :
“This function adds two numbers and return the result"
result =a + b
return result
def sub(a, b)
“This function substract two numbers and return the result"
result =a - b
return result
def mul(a, b):
"This function multiply two numbers and return the result"
result = a * b
return result
def div(a, b):
“This function divide two numbers and return the result"
result - a / b
return result
Importing module
Import the definitions inside a module:
import p1
print("Addition=",pl.add(10,20))
print("Subtraction=”,pl.sub(10,20))
print("Multiplication-" ,p1.mul(10,20))
print("division=" ,p1.div(10,20))
Output:
Addition= 30
Subtraction= -10
Multiplication= 200
division- 0.5
Unit 4: Python Functions modules and Packages
Importing module
Import statement is used to imports a specific module by using its name. Import statement creates a
reference to that module in the current namespace. After using import statement we can refer the things
defined in that module.
We can import the definitions inside a module to another module or the interactive interpreter in Python.
We use the import keyword to do this.
Create second file. Let p2.py in same directory where pl.py is created. Write following code in p2.py.
Import the definitions inside a module;
import p1
print(p1.add(10,20)
print(pl.sub(20,10)
Output:
30
10
Import the definitions using the interactive interpreter:
>>> import p1
>>>p1.add(10,20)
30
>>pl.sub(20,10)
10
>>>
Importing Objects From Module:
Import statement in python is similar to #include header_file in C/C++. Python modules can get access
to code from another module by importing the fileifunction using import. Python provides three
different ways to import modules.
1. From x import a.
Imports the module x, and creates references in the current namespace to all public objects defined by
that module. If we run this statement, we can simply use a plain name to refer to things defined in
module x.
We can access attribute / mehods directly without dot notation.
Example 1: Import inside a module (from x import a).
from p1 import add
print("Addition",add(10,20))
Output:
Addition= 30
3. From x import *:
We can use* (asterisk) operator to import everything from the module.
Example 1: Import inside a module (from x import 1)
from p1 import *
print("Addition=",add(10,20))
print("Subtraction=” ,sub(10,20))
print("Multiplication=" ,mul(10,20))
print("division=" ,div(10,20))
output
Addition= 30
Subtraction= -10
Multiplication= 200
division. 0.5
Aliasing module
Unit 4: Python Functions modules and Packages
It is possible to modify the names of modules and their functions within Python by using the as
keyword.
We can make alias because we have already used the same name for something else in the program
or we may want to shorten a longer name.
Example: Create a module to define two functions. One to print Fibonacci series and other for finding
whether the given number is palindrome or not.
Step 1; Create a new file pl.py and write the following code in it and save it.
def add (a,b):
"This function adds two numbers and return the result"
result = a + b
return result
def sub(a, b):
"This function subtract two numbers and return the result" result = a - b
return result
Step 2: Create new file p2.py to include the module. Add the following code and save it
import p1 as m
print("Addition=",m.add(10„20))
print("Subtraction=",m.sub(10,20))
print("Multiolication=",m.mul(10„20))
print("division=" ,m.div(10,20))
The numbers module defines an abstract hierarchy of numeric types. The math and cmath modules
contain various mathematical functions for floating-point and complex numbers, The decimal. module
supports exact representations of decimal numbers, using arbitrary precision arithmetic
2. Decimal Module:
Decimal numbers are just the floating-point numbers with fixed decimal points. We can create decimals
from integers, strings, floats, or tuples.
A Decimal instance can represent any number exactly, round up or down, and apply a limit to the
number of significant digits,
Example :For decimal module,
>>> from decimal import Decimal
>>> Decimal(121)
Decimal('121')
>>> Decimal(0.05)
Docimal('0.05000000000000000277555756156289135105907917022705078125')
>>> Decimal(10.15)
Decimal('15')
>>> Decimal(‘0.012’)+Decimal('0.2')
Decimal(‘0.212’)
>>> Decimal(72)/Decimal(7)
Decimal(110.28571428571428571428571429')
>>> Decimal(2).sqrt()
Decimal(' 1.414213562373095048801688724')
3. Fractions Module:
A fraction is a number which represents a whole number being divided into multiple parts. P3rthon
fractions module allows us to manage fractions in our Python programs.
Example: For fractions module.
>>> import fractions
>>> for num, decimal in [(3, 2), (2, 5), (30, 4)]:
fract = fractions.Fraction(num, decimal)
print(fract)
3/2
2/5
15/2
Unit 4: Python Functions modules and Packages
It is also possible to convert a decimal into a Fractional number. Let's look at a code snippet
>>> import fractions
>>> for deci in[‘0.6’,’2.5’,’2.3’,’4e-1’]
fract = fractions.Fraction(deci)
print(fract)
Output:
3/5
5/2
23/10
215
4.Random Module:
Sometimes, we want the computer to pick a random number in a given range, pick a random
element from a list etc.
The random module provides functions to perform these types of operations. This function is not
accessible directly, so we need to import random module and then we need to call this function using
random static object.
Example: For random module.
>>> import random
>>>print(random,random()) # It generate a random number in the range (0.0, 1.0)
0.27958069234907935
>>>print( randorn.randint(10,20)) # It generate a random integer between x andy inclusive 13
5. Statistics Module:
Statistics module provides access to different statistics functions. Example includes mean (average
value), median (middle value), mode most often value), standard deviation (spread of values).
1. itertools Module:
Python programming itertools module provide us various ways to manipulate the sequence while we are
traversing it.Python itertools chain() function just accepts multiple iterable and return a single sequence
as if all iteams belongs to that sequence.
Example: for itertools with chain()
>>> from itertools import
> >>for value in chain([1,3, 2,51, 3.3], ['C++', 'Python', 'Java']):
print(value)
Output
1,3
2.51
3.3
C++
Python
Java
• Python itertools cycle() function iterate through a sequence upto infinite. This works just like a circular
Linked List.
Example: For intools module with cycles°.
>>> from itertools import *
>>> for item in cycle([1C++1,1Python',']ava']):
index=index+1
if index==10:
break
print(item)
output:
C++
Python
Java
C++
Python
Java
C++
Python
Java
>>>
2. functools Module:
Python functools module provides us various tools which allows and encourages us to write reusable
code.Python functools partial() functions are used to replicate existing functions with some arguments
already passed in. It also crests new version of the function in a well-documented manner.
Suppose we have a function called multiplier which just multiplies two numbers. Its definition looks
like:
Unit 4: Python Functions modules and Packages
def multiplier(x,y):
return x * y
Now, if we want to make some dedicated functions to double or triple a number then we will have to
define new functions as:
def multiplier(x, y):
return x * y
def doubleIt(x):
return multiplier(x, 2)
def tripleIt(x):
return multiplier(x, 3)
But what happens when we need 1000 such functions? Here, we can use partial functions:
Output
Double of 5 is 10
Triple of 5 is 15
Operator Module:
The operator module supplies functions that are equivalent to Python's operators. These functions are
handy in cases where callables must be stored, passed as arguments, or returned as function results.
Functions supplied by the operator module are listed in following table:
Sr.
Function Signature/Syntax Behaves Like
No.
1 abs abs(a) abs(a)
2 add add(a,b) a+b
3 and_ and_(a,b) a&b
4 div div(a,b) a/b
5 eq eq(a,b) a==b
6 gt gt(a,b) a>b
invert,
7 invert(a),inv(a) ~a
inv
8 le le(a,b) a<=b
9 lshift lshift(a,b) a<<b
10 It lt(a,b) A<b
11 mod mod(a,b) A%b
Unit 4: Python Functions modules and Packages
12 mul mul(a,b) a*b
13 ne ne(a,b) a! =b
14 neg neg(a) -a
15 not_ not (a) not a
16 or or_(a,b) alb
17 pos pos(a) +a
18 repeat repeat(a,b) a*b
19 rshift rshift(a,b) a>b
20 xor_ xor(a,b) A^b
1. Local Namespace: This namespace covers the local names inside a function. Python creates this
namespace for every function called in a program. It remains active until the function returns.
Unit 4: Python Functions modules and Packages
Global Namespace: This namespace covers the names from various imported modules used in a
project. Python creates this namespace for every module included in the program. It will last until the
program ends.
Built-in Namespace: This namespace covers the built-in functions and built-in exception names.
Python creates it as the interpreter starts and keeps it until we exit.
Namespaces help us uniquely identify all the names inside a program. According to Python's
documentation "a scope is a textual region of a Python program, where a namespace is directly
accessible." Directly accessible means that when we are looking for an unqualified reference to a name
Python tries to find it in the namespace.
Scopes are determined statically, but actually, during runtime, they are used dynamically. This means
that by inspecting the source code, we can tell what the scope of an object is, but this does not prevent
the software from altering that during runtime.
At any given moment, there are at least following three nested scopes:
When a reference is made inside a function, the name is searched in the local namespace, then in the
global namespace and finally in the built-in namespace.
If there is a function inside another function, a new scope is nested inside the local scope. Python has
two scopes.
Local Scope Variable: All those variables which are assigned inside a function known as local scope
Variable
Global Scope Variable: All those variables which are outside the function termed as global variable.
P1.py
Def m1():
print("first module")
p2.py
def m2():
print("second modulo")
Here mypkg a folder /directory which consist of pl.py and p2.py. We can refer these
two modules with dot notation (mypkg.pl, mypkg.p2) and import them with the one of the following
syntaxes:
Example:
Standards packages
NumPy and SciPy are the standards packages used by Python programming.
NumPy enriches the programming language Python with powerful data structures, implementing multi-
dimensional arrays and matrices.
SciPy (Scientific Python) is often mentioned in the same breath with NumPy. SciPy needs Numpy, as it
is based on the data structures of Numpy and furthermore its basic creation and manipulation functions.
It extends the capabilities of NumPy with further useful functions for minimization, regression, Fourier-
transformation and many others,
Both NumPy and SciPy are not part of a basic Python installation. They have to be installed after the
Python installation. NumPy has to be installed before installing SciPy.
Math
Some of the most popular mathematical functions are defined in the math module. These include
trigonometric functions, representation functions, logarithmic functions and angle conversion
functions.Two mathematical constants are also defined in math module.Pie (x) is a well-known
mathematical constant, which is defined as the ratio of the circumference to the diameter of a circle and
its value is
3.141592653589793.
Another well-known mathematical constant defined in the math module is e_ It is called either’s
number and it is a base of the natural logarithm. Its value is 2318281828459045.
>>> import math
>> math. e
2.718281828459e45
NumPy
NumPy is the fundamental package for scientific computing with Python.
NumPy stands for "Numerical Python". It provides a high-performance multidimensional array object,
and tools for working with these arrays.
An array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive
integers and represented by a single variable.
NumPy's array class is called ndarray. It is also known by the alias array.
In NumPy arrays, the individual data items are called elements.
Unit 4: Python Functions modules and Packages
All elements of an array should be of the same type. Arrays can be made up of any number of
dimensions.
In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total
number of elements in that direction.
The size of an array is the total number of elements contained in an array in the entire dimension.
The size of NumPy arrays are fixed; once created it cannot be changed again.
Numpy arrays are great alternatives to Python Lists.
Some of the key advantages of Numpy arrays are that they are fast, easy to work with, and give users the
opportunity to perform calculations across entire arrays.
Fig. 4.6 shows the axes (or dimensions) and lengths of two example arrays;
a) is a one-dimensional array and
(b) is a two-dimensional array.
A one dimensional array has one axis indicated by Axis-O, That axis has five elements in it, so we say it
has length of five.
A two dimensional array is made up of rows and columns. All rows are indicated by Axis-0 and all
columns are indicated by axis-1. If Axis-O in two dimensional array has three elements, so its length it
three and Axis-1 has six elements, so its length is six,
Execute Following command to install numpy in window, Linux and MAC OS:
Example:
For NumPy with array object.
>>> import numpy as np
>>a=np.array([1,2,3]) # one dimensional array
>>> print(a)
[1 2 3]
>>>arr=np.array([1,2,3],[4,5,6]]) # two dimensional array print(arr)
([1 2 3]
[4 5 6] ]
>>> type(arr)
Unary Operators: Many unary operations are provided as a method of ndarray class. This includes
sum, min, max, etc. These functions can also be applied row-wise or column-wise by setting an axis
parameter.
Binary Operators: These operations apply on array elementwise and a new array is created. You can
use all basic arithmetic operators like +, - etc, In case of +=,==, = operators, the existing array is
modified.
Unit 4: Python Functions modules and Packages
Example: For basic array operators.
>>>arr1=np.array([1,2,3,4,5])
>> arr2,=np.array([2,3,4,5,6])
>>> print(arrl)
[1 2 3 4 5]
Example
>>>arr=np.array([(1,2,3],[4,5,6]])
>>>a=arr.reshape(3,2)
>>> a
Array ( [ [1, 2],
[3, 4],
[5, 67])
slicing of Array:
Slicing is basically extracting particular set of elements from an array. Consider an array ([(1,2,3,4),
(5,6,7,8)1).
Here, the array (1,2,3,4) is at index 0 and (3,4,5,6) is at index 1 of the python numpy array, We need a
particular element (say 3) out of a given array.
Let us consider the below example:
import numpy as np
>>> a=np.array([(1,2,3,4),(5,6,7,8)])
>>> print(4,2])
3
Let us consider the below example:
>>> import numpy as rip
>>> a=np.array([(1,2,3,4),(5,6,7,8)])
>>> print(a[0,2])
3
Now we need the 2nd element from the zero and first index of the array.
The code will be as follows:
import numpy as rip
a=rip.array([(1,2, 3,4), (5, 6,7,8)] )
print(a[9:2])
Unit 4: Python Functions modules and Packages
[3 7]
Here, colon represents all the rows, including zero.
Scipy package
StiPy is organized into sub packages covering different scientific computing domains. These are
summarized in the following table:
4) Matplotlib
Matplotlib.pyplot is a plotting library used for 2D graphics in python programming language. It can
be used in python scripts, shell, web application servers and other graphical user interface toolkits.
There are various plots which can be created using python matplotlib like bar graph, histogram, scatter
plot, area plot, pie plot.
Output:
Bar Graph:
Unit 4: Python Functions modules and Packages
A bar graph uses bars to compare data among different categories, It is well suited when you want to
measure the changes over a period of time_ It can be represented horizontally or vertically
Pandas
Pandas is an open-source Python Library providing high-performance data manipulation and analysis
tool using its powerful data structures.
It is built on the Numpy package and its key data structure is called the DataFrame, DataFrames allow
you to store and manipulate tabular data in rows of observations and Colums of variables.
installing Pandas
The series is a one dimensional array which is Labeled and it is capable of holding array of any type
like Integer, Float,String and Python Objects.
for example, the following series is a collection of integers10, 22, 30. 41...The syntax is as follows!
pandas.Series(data, index, dtype, copy)
It takes four arguments:
1.data: It is the array that needs to be passed as to convert it into a series, This can he Python lists.
numpy Array or a Python Dictionary or Constants.
2.Index This holds the index values for each element passed in data. If it is not specified, default is
numpy.arange(length_of_data).
Output:
0 2
1 4
2 6
3 8
4 10
5 20
dtypa: int32
a 10
Unit 4: Python Functions modules and Packages
b 2i
c 30
d 40
e 50
Dtype:int64
>>>
step 1: Create folder PlyPkg on "local drive. Create modules Message.py and Mathematics.py with
following code:
Message.py
def SayHello(name);
print("hello”, name)
return
Mathematics.py
def sum(x,y):
return x+y
def average(x,y);
return (x+y)/2
def power(x,y):
return x**y
An empty _ _nit_ .py file makes all functions from above modules available when this package is
imported. Note that _ _init_ _.py is essential for the folder to be recognized by Python as a package. We
can optionally define functions from individual modules to be made available.
Step 3: Create p1.py file in MyPkg folder and write following code:
output
hello rudra
power(3,2):9
The specified functions can now be imported in the interpreter session or another executable script.
Create test.py in the MyPkg folder and write following code:
test.py
from MyPkg import power, average, SayHello
SayHello()
x.power(3,2)
print("power(3,2) “’x)
Note that functions power and SayHello() are imported from the package and not from their respective
modules, as done earlier. The output of above script is:
Hello world