Python Unit 04
Python Unit 04
Introduction:
• Functions, modules and packages are all constructs in
programming that promote code modularization.
• Modularization refers to the process of breaking a large
programming task into a separate, smaller, more
manageable subtasks or modules.
A function is a block of organized, reusable code which
can be called whenever required. A function is a piece of
code that performs a particular task.
A module in programming allows us to logically organize
the python code. A module is a single source code file.
The module in python have the .py extension. The name of
the module will be the name of the file.
A module can be defined as a python program file which
contains a python code including python function, class or
variables.
Python packages allow us to create a hierarchical file
directory structure of modules.
A python package is a collection of modules which have
a common purpose. i.e modules are grouped together to
form package.
1
B P Bhagat Sr. Lect. Computer Engineering
1. Use of Python Built-in Functions:
• Functions are self contained block of statements that act like
a program that perform specific task.
• The python interpreter has a number of functions that are
always available for use called as built-in functions.
e.g. print() functions.
Type Data Conversion Functions-
• To convert between types we simply use the type name as a
function. This type conversion functions to directly convert
one type of data type to another.
Python define Python Implicit Data Type Conversion:
-It takes place either during compilation or during run time
and is handled directly by python.
Example : Converting integer to float
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
• Python always converts smaller data type to larger data
type to avoid the loss of data. 2
Python Explicit Data Type Coversion -
• In Explicit Type Conversion, users convert the data type of
an object to required data type. We use the predefined
functions like int(), float(), str(), etc to perform explicit type
conversion called as typecasting because the user casts
(change) the data type of the objects.
Syntax :(required_datatype)(expression)
Typecasting can be done by assigning the required data type
function to the expression.
1.int(a,base) : This function converts any data type to integer.
‘Base’ specifies the base in which string is if data type is string.
2.float() : This function is used to convert any data type to a
floating point number.
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : Function is used to convert any data type to a list type.
9. dict(): Function is used to convert a tuple of order (key, value)
into a dictionary.
10.str() : Used to convert integer into a string.
11.complex(real, imag) : : This function converts real numbers to
complex(real, imag) number.
3
Example 1:
# Python code to demonstrate Type conversion
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c) #18
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
# Pprint (e) #10010.0
Example 2:
#Python code to demonstrate Type conversion
s = ‘A'
c = ord(s)
print ("After converting character to integer : ",end="")
print (c) #65
# printing integer converting to hexadecimal string
c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c) #0x38
# printing integer converting to octal string
c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c) #0o70 4
Example 3:-Python code to demonstrate Type conversion using
set(), list(), tuple()
s = ‘hello'
c = list(s) print ("After converting str to list : ",end="")
print (c) #['h', 'e', 'l', 'l', 'o‘]
c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c) #('h', 'e', 'l', 'l', 'o')
c = set(s)
print ("After converting string to set : ",end="")
print (c) #{'l', 'e', 'o', 'h'}
Example 4:-Python code to demonstrate Type conversion
complex(), str(),using dict()
a = 1 b = 2 tup = (('a', 1) ,('f', 2), ('g', 3))
c = complex(1,2)
print ("After converting int to complex number : ",end="")
print (c) #(1+2j)
# printing integer converting to string
c = str(a) #1
print ("After converting integer to string : ",end="") print (c)
# printing tuple converting to expression dictionary
c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c) #{'a': 1, 'f': 2, 'g': 3}
5
Formatting Numbers and Strings –
• The built-in format() method returns a formatted representation
of the given value controlled by the format specifier.
Syntax: format(value,format)
e.g. x=12.345
print(format(x,".2f")) #12.35
Parameter values-
< - Left aligns the result within the available space
e.g. x=10.23456
print(format(x,"<10.2f")) # ‘10.23 ‘
> - Right aligns the result within the available space
e.g. x=10.23456
print(format(x,“>10.2f")) #‘ 10.23 ‘
^ - Center aligns the result within the available space
e.g. x=10.23456
print(format(x,“^10.2f")) #‘ 10.23 ‘
+, - - Use a sign to indicate if the result is positive or negative
e.g. x=10.234 y=10.234
print(format(x,"+")) # +10.234
print(format(y,"-")) # -10.234
6
, - Use a comma as a thousand sepeartor
e.g. x=10000000
print(format(x,",")) Output:10,000,000
_ - Use a underscore as a thousand seperator.
e.g. x=10000000
print(format(x,"_")) Output: 10_000_000
b - binary format
e.g. x=10
print(format(x, "b")) Output:1010
c – convert the value to corresponding unicode character.
x=10
print(format(x,"c")) Output: \n
e - Scientific character with a lower case e
e.g. x=10
print(format(x, "e")) Output:1.000000e+01
E – Scientific character with a upper case E.
x=10
print(format(x, “E")) Output:1.000000E+01
f - fix point number format
e.g. x=10
print(format(x,“f")) Output:10.000000
g – General Format.
x=10
print(format(x,“g")) Output:10
o - octal format
e.g.x=10
print(format(x,“o")) Output:12
x – Hex Format, lower case
x=10
print(format(x,“x")) Output: a
X - Hex format, Upper case
e.g.x=10 print(format(x,“X")) Output:A
% – Percentage format
x=100 print(format(x,“%")) Output:10000.000000% 7
Built-in Mathematical Functions -
• In Explicit Type Conversion, users convert the data type of an object to required data
type. Use predefined functions e.g int(), float(), str(), etc to perform explicit type
conversion. It is also called typecasting because the user casts (change) the data type
of the objects.
Syntax :(required_datatype)(expression)
Typecasting can be done by assigning the required data type function to the expression.
Built-In functions (Mathematical):
• These functions doesn’t require any external code file/modules/ Library files.
• These are a part of the python core and are just built within the python compiler hence
there is no need of importing these modules/libraries in our code.
floor()- Returns the greatest integral value smaller than the number.
e.g. import math
print(math.floor(2.3)) o/p 2
cos()- Returns the cosine of value passed as argument. The value passed in this function
should be in radians.
e.g. import math
print(math.cos(3) o/p
0.9899924966004454
cosh()- Returns the hyberbolic cosine of x.
e.g. import math
print(math.cosh(3)) o/p 10.067661995777765
Actual Parameters:
• The parameters used in the function call are called actual
parameters. These are the actual values that are passed to the function.
• The data types of actual parameters must match with the
corresponding data types of formal parameters(variables) in the
function definition.
• They are used in the function call.
• They are actual values that are passed to the function definition
through the function call.
• They can be constant values or variable names(such a local or global)
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 treated as local variables of a function in which they are used
in the function header.
12
Call by object reference:
Python utilizes a system, which is known as “Call by Object Reference”
or “Call by assignment”. In the event that you pass arguments like whole
numbers, strings or tuples to a function, the passing is like call-by-value
because you can not change the value of the immutable objects being passed
to the function. Whereas passing mutable objects can be considered as call by
reference because when their values are changed inside the function, then it
will also be reflected outside the function.
There are four types of arguments using which can be called are required
arguments, keyword arguments, default arguments and variable length
arguments.
Required Arguments:
These 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: Required Arguments
def printme(str):
"This prints a passed string into this function"
print(str)
return
# Call printme function
mylist=[10,20,30]
printme() # required arguments
Output:Traceback (most recent call last):
File "D:\python programs\sample.py", line 8, in <module> printme()
14
TypeError: printme() missing 1 required positional argument: 'str’
Keyword Arguments:
• These are the arguments related to the function calls.
• When we use it in the function call, the caller identifies the
arguments by the parameter name.
• This allows us to skip arguments or place them out of order
because the python interpreter is able to use the keywords provided
to match the values with parameters.
Example 1: Keyword Arguments
def printme(str):
"This prints a passed string into this function"
print(str)
return
printme(str="My string") #Output: My string
17
Scope of Variables:
• All variables in a program may not be available at all areas in that program.
• There are two basic scopes of variables in python
Local variables:
• When we declare a variable inside a function, it becomes a local variable.
• Its scope is limited only to that function where it is created.
Global variables:
• When we declare a above a function it becomes a global variable.
• Such variables are available to all functions which are written after it.
print(b)
3.Modules
• A module are primarily .py files that represents group of
classes, methods and functions.
• We have to group them depending on their relationship into
various modules and later use these modules in other
programs.
• It means, when a module is developed it can be reused in any
program that needs that module.
• We can create our own modules and use whenever we need
them.
• Once a module is created, any programmer in the project
team can use that module.
• Hence modules will make s/w development easy and faster.
Advantages of modules
19
Writing Module
Writing a module means simply creating a file which contains
python definition and statements. The file name is the module
name with the extension .py. To include module in a file, use the
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 performs 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.
Example: Create p1.py file and add the below code in the file
def add(a,b):
result=a+b
return result
def sub(a,b):
result=a-b
return result
def mul(a,b):
result=a*b
return result
def div(a,b):
result=a/b
return result
Create p2.py file in same directory where p1.py is created and add
the below code in the file:
import p1
print("Addition= ", p1.add(10,20))
print("Subtraction= ", p1.sub(20,10))
print("Multiplication= ", p1.mul(10,20))
print("Division= ", p1.div(40,20)) 20
Importing Modules:
Import statement is used to import a specific module by using its
name. Import statement creates a reference to that module in the
current namespace.
e.g. import employee
• In this case we have to access the functions in employee module
using employee.hra(), employee.da() etc. To avoid this we can use
from employee import *
from employee import hra, da
Example://using from x import *
from p1 import *
print("Addition= ",add(10,20))
print("Multiplication= ",mul(10,20))
When importing using the from keyword, do not use the module name
when referring to elements in the module.
Example: using from x import a,b
from p1 import add,sub
print("Addition= ",add(10,20))
print("Subtraction= ",sub(10,20))
Import with renaming (Aliasing Modules):
• 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.
Syntax: import module as another_name
e.g. if a module created with name p1 which has function named ‘add’
import p1 as p
print(‘addition is’, p.add) 21
Python Built-in Modules:
• A module is a collection of python objects such as functions,
classes and so on.
• Python interpreter is bundled with a standard library
consisting of large number of built-in modules.
• Built-in modules are generally written in C and bundled with
python interpreter in precompiled form. A built-in module may
be a python script(.py) containing useful utilities.
• A module may contain one or more functions, classes, constants
or any other python resources.
Random module:
• To pick a random number in a given range or a list a random
module is used.
• To access it so we need to import random module and then we need
to call this function using random static object.
Example: import random
print(random.random())
print(random.randint(10,20))
Output: 0.8709966760966288 16
Statistics module:
• It provides access to different statistics functions such as mean,
median, mode, standard deviation.
Example:import statistics
print(statistics.mean([2,5,6,9])) o/p: 5.5
print(statistics.median([1,2,3,8,9])) o/p : 3
print(statistics.mode([2,5,3,2,8,3,9,4,2,5,6])) o/p 2
print(statistics.stdev([1,1.5,2,2.5,3,3.5,4,5])) 25
1.3693063937629153
• Functional Programming Modules:
Itertools Module:
• It 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 items belongs to that
sequence.
Example:
from itertools import * #works
#from itertools import chain //works
#import itertools //NameError: name 'chain' is not defined
for value in chain([1.3,2.51,3.3],['c++','python','java']):
print(value) Output:1.3
2.51
3.3
c++
python
26
java
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:
functools Module:
• It provide us various tools which allows and encourage us to
write reusable code.
• Python functools partial() functions are used to replace existing
functions with some arguments already passed in. It also creates
new version of the function in a well documented manner.
Example: Suppose we have a function called multiplier which
multiplies two numbers. Its definition looks like:
def multiplier(x,y): return
x*y
Now if we want to make some dedicated functions to double or
triple a number we will have to define new functions as:
from functools import partial
#from functools import *
def multiplier(x,y):
return x*y
double=partial(multiplier,y=2)
triple=partial(multiplier)
print('Double of 5 is {}'.format(double(5)))
print('Triple of 5 is {}'.format(triple(5,5)))
Output:Double of 5 is 10 27
Triple of 5 is 25
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.
Function supplied by operator module are:
29
Python Variable Scoping:
• Scope is the portion of the program from where a namespace
can be accessed directly without any prefix.
• At any given moment there are atleast following three nested
scope.
1. Scope of the current function which has local names.
2. Scope of the module which has global names.
3. Outermost scope which has built-in names.
• 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 variables which are assigned inside a
function.
• Global scope variable-All those variables which are outside the
function termed.
# Example pf Global and Local Scope
global_var=30 # global scope
def scope():
local_var=40 #local scope
print(global_var)
print(local_var)
scope()
print(global_var)
Output:
30
40 30
30
4.4 Python Packages:
greet.py
def SayHello(name):
print("Hello ", name)
functions.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
D:\MyApp>python
>>> from mypackage import functions
>>> functions.power(3,2)
9
>>> from mypackage.functions import sum
>>> sum(10,20)
30
>>> average(10,12)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
NameError: name 'average' is not defined 33
NumPy:
• NumPy is the fundamental package for scientific computing with
python. It stands for “Numeric Python”.
import numpy as np
a=np.array([10,20,30])
print(a) #[10 20 30]
arr=np.array([[1,2,3],[4,5,6]]) #[[1 2 3]
print(arr) [4 5 6]]
print("Shape of array: ",arr.shape) #(2, 3)
print("Size of array: ",arr.size) #6
arr=np.array([[1,2,3],[4,5,6],[7,8,9]]) #[[1 2 3]
print(arr ) [4 5 6]
[7 8 9]]
print(type(arr)) # <class ‘numpy.ndarray’>
print("No. of dimension: ", arr.ndim) #2
print("Shape of array: ", arr.shape) #(3, 3)
print("Size of array: ", arr.size) #9
print("Type of elements in array: ", arr.dtype) #int32/int64 35
print("No. of bytes: ", arr.nbytes) #24
Basic Array Operations:
•In NumPy array allows a wide range of operations which can be performed
on a particular array or a combination of Arrays.
• These operations include some basic mathematical operation as well as
Unary and Binary operations.
import numpy as np
from scipy import linalg
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(linalg.det(a)) # find determinant of array #o/p 0.0
Scatter Plot:
• This graph will only mark the point that is being plotted in the graph.
41
Bar Graph:
• A bar graphuses 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.
e.g.
from matplotlib import pyplot as plt
x=[2,4,8,10]
y=[2,4,3,2]
plt.xlabel('X-axis')
plt.text(0.5,0,'X-axis')
plt.ylabel('Y-axis')
plt.text(0,0.5,'Y-axis')
plt.title('Graph')
plt.text(0.5,1.0,'Graph')
plt.bar(x,y,label="Graph",color='g', width=0.5)
plt.show()
42
Program to display Horizontal bar
import numpy as np
import matplotlib.pyplot as plt
objects = ('Python','C++','Java','Perl','Scala','Lisp')
y_pos = np.arange(len(objects))
performance=(10,8,6,4,2,1)
plt.barh(y_pos,performance,align='center',alpha=0.5)
plt.yticks(y_pos,objects)
plt.xlabel('Usage')
plt.title('Programming language usage')
plt.show()
Output-
43
• NumPy arange() is an inbuilt numpy function that returns
a ndarray object containing evenly spaced values within
the given range. The arange() returns an array with evenly
spaced elements as per the interval. The interval mentioned is half
opened i.e. [Start, Stop)
Example:
import numpy as np
import matplotlib.pyplot as plt # data to plot
n_groups = 4
means_P1 = (90, 55, 40, 65)
means_P2 = (85, 62, 54, 20)
# create plot
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
rects1 = plt.bar(index, means_P1,
bar_width,alpha=opacity,color='b',label='P1')
rects2 = plt.bar(index + bar_width, means_P2,
bar_width,alpha=opacity,color='g',label='P2')
plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by person')
plt.xticks(index + bar_width, ('A', 'B', 'C', 'D'))
plt.legend()
plt.tight_layout()
plt.show() 44
Pandas:
• It is an open source python library providing high performance data
manipulation and analysis tool using its powerful data structures.
• Pandas is python library which is used for data analysis purpose.
• In pandas data can be represented in 3 ways:
1. Series
2. Data frames
3. Panel
Series-
It is one dimensional array like structure defined in pandas.
It can be used to store the data of any type.
e.g.import pandas as pd
data=[1.1,2.1,3.1,4.1,5.1,6.1,7.1,8.1]
df=pd.Series(data)
print('The series is:\n',df)
print('The type is:',type(df))
45
DataFrame-Dataframes are two dimensional structures which
consist of columns and rows.
• It can be used to store the data of any type.
import pandas as pd
dict1={'a':1.1,'b':2.1,'c':3.1,'d':4.1}
dict2={'a':5.1,'b':6.1,'c':7.1,'d':8.1}
data={'Col 1':dict1,'Col 2':dict2}
df=pd.DataFrame(data)
print(df)
Example:-
import pandas as pd
s1=pd.Series([1,3,4,5,6,2,9])
s2=pd.Series([1.1,3.5,4.7,5.8,2.9,9.3,8.9])
s3=pd.Series([‘a’,’b’,’c’,’d’,’e’,’f’,’g’])
data={‘first’:s1,’second’:s2,’third’:s3}
dfseries=pd.DataFrame(data)
print(dfseries)
46
Panel-
• Panel is a three dimensional data structure with homogeneous data.
• It is hard to represent the panel in graphical representation.
• But a panel can be illustrated as a container of DataFrame.
It takes following arguments-
data: The data can be of any form like ndarray, list, dict,
map, DataFrame
item: axis 0, each item corresponds to a dataframe contained
inside.
major_axis: axis 1, it is the index (rows) of each dataframes.
minor_axis: axis 2, it is the column of DataFrames.
dtype: The data type of each column.
copy: It takes a Boolean value to specify whether or not to
copy the data. The default value is false.
Example 1: # creating an empty panel
import pandas as pd
import numpy as
npdata = np.random.rand(2,4,5)
p = pd.Panel(data)
print p
Output:<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4 47
Example 2: #creating an empty panel
import pandas as pd
import numpy as np
data {'Item1':pd.DataFrame(np.random.randn(4, 3)), 'Item2' :
pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print(p)
Output:
Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis) Items
axis: Item1 to Item2
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 2
The Panel class in pandas used to be a three-dimensional data
structure, providing
a container for handling three-dimensional data. However, as of
pandas version 0.25.0,
the Panel class has been deprecated, and its usage is discouraged.
Instead, pandas
recommends using other data structures like
DataFrame or MultiIndex DataFrame for handling multi-
dimensional data.
import pandas as pd
import numpy as np
npdata = np.random.rand(2, 4, 5)
# Reshape the 3D array into a 2D array
reshaped_data = npdata.reshape(npdata.shape[0], -1)
print(reshaped_data)
# Create a DataFrame
df = pd.DataFrame(reshaped_data)
print(df) 48