Python Chapter-10,11,12,13
Python Chapter-10,11,12,13
Python Chapter-10,11,12,13
CHAPTER-10
MODULES and PACKAGES
Create a Module
To create a module just save the code you want in a file with the file extension .py
Example: Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement
Example: Import the module named mymodule, and call the greeting function
import mymodule
mymodule.greeting("Jonathan")
Example:
# Python Module example for addition of two numbers
<------ addition.py------>
def add(a, b):
result = a + b
return result
<------ example.py------>
import addition
addition.add(10,20)
Namespace in Python
In python we deal with variables, functions, libraries and modules etc. There is a chance the
name of the variable you are going to use is already existing as name of another variable or as the
name of another function or another method. In such scenario, we need to learn about how all these
names are managed by a python program. This is the concept of namespace.
Following are the three categories of namespace
1) Local Namespace: All the names of the functions and variables declared by a program are held in
this namespace. This namespace exists as long as the program runs.
2) Global Namespace: This namespace holds all the names of functions and other variables that are
included in the modules being used in the python program. It encompasses all the names that are
part of the Local namespace.
3) Built-in Namespace: This is the highest level of namespace which is available with default names
available as part of the python interpreter that is loaded as the programing environment. It
encompasses Global Namespace which in turn encompasses the local namespace.
Example:
a = 10 # global variable
def function_local( ):
b=20
a=30 # local variable
print(a)
print(b)
def function_inner( ):
b=35
a=25
print(a)
print(b)
function_inner( )
print(a)
Output:
30
20
25
35
10
Packages
Packages are a way of structuring many packages and modules which help in a well-
organized hierarchy of data set, making the directories and modules easy to access.
To tell Python that a particular directory is a package, we create a file named __init__.py inside it an d
then it is considered as a package and we may create other modules and sub-packages within it.
This __init__.py file can be left blank or can be coded with the initialization code for the package.
def addition(a,b):
print(a+b)
Output:
30
CHAPTER-11
NumPy
What is NumPy?
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
NumPy stands for Numerical Python.
Arrays are very frequently used in data science, where speed and resources are very important.
Install numpy
Example:
import numpy
Output
[1, 2, 3, 4, 5]
NumPy as np
NumPy is usually imported under the np alias.
import numpy as np
Ouput:
[1 2 3 4 5]
1.19.2
NOTE:
type( ): This built-in Python function tells us the type of the object passed to it. Like in above code it
shows that arr is numpy.ndarray type.
Indexing
import numpy as np
Ouput:
4
import numpy as np
Ouput:
2nd element on 1st row: 2
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Ouput:
6
Negative Indexing
Use negative indexing to access an array from the end.
import numpy as np
Ouput:
10
Slicing arrays
Slicing in python means taking elements from one given index to another given index.
We pass slice instead of index like this: [start:end]
We can also define the step, like this: [start:end:step]
import numpy as np
Ouput:
2, 3, 4, 5
import numpy as np
Ouput:
[1 2 3 4]
Govt. Polytechnic, Arakere, Srirangapatna Page 7
Python Programming
import numpy as np
Ouput:
[5 6]
import numpy as np
Ouput:
[2, 4]
import numpy as np
Ouput:
[1, 3, 5, 7]
import numpy as np
Ouput:
[3, 8]
import numpy as np
Ouput:
[[2 3 4]
[7 8 9]]
Arithmetic operations
add( ), subtract( ), multiply( ), and divide( )
a = np.array([1,3,5,7])
b = np.array([2,4,6,8])
print(a)
print(b)
print(np.add(a,b))
print(np.subtract(a,b))
print(np.multiply(a,b))
print(np.divide(a,b))
print(np.square(a))
Ouput:
[1 3 5 7]
[2 4 6 8]
[ 3 7 11 15]
[-1 -1 -1 -1]
[ 2 12 30 56]
[0.5 0.75 0.83333333 0.875 ]
[ 1 9 25 49]
import numpy as np
a = np.arange(8)
print('The original array:')
print(a)
b = a.reshape(4,2)
print('The modified array:')
print(b)
Output:
The original array:
[0 1 2 3 4 5 6 7]
The modified array:
[[0 1]
[2 3]
[4 5]
[6 7]]
transpose( ):This function permutes the dimension of the given array. It returns a view wherever
possible.
import numpy as np
a = np.arange(12).reshape(3,4)
Output:
The original array is:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
The transposed array is:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
squeeze( ):This function removes one-dimensional entry from the shape of the given array. Two
parameters are required for this function.
import numpy as np
x = np.arange(9).reshape(1,3,3)
print('Array X:')
print(x)
y = np.squeeze(x)
print('Array Y:')
print(y)
Output:
Array X:
[[[0 1 2]
[3 4 5]
[6 7 8]]]
Array Y:
[[0 1 2]
[3 4 5]
[6 7 8]]
The shapes of X and Y array:
(1, 3, 3) (3, 3)
concatenate( ):
Concatenation refers to joining. This function is used to join two or more arrays of the same shape
along a specified axis.
import numpy as np
a = np.array([[1,2],[3,4]])
print('First array:')
print(a)
b = np.array([[5,6],[7,8]])
print('Second array:')
print(b)
Output:
First array:
[[1 2]
[3 4]]
Second array:
[[5 6]
[7 8]]
append( ):This function adds values at the end of an input array. The append operation is not inplace,
a new array is allocated. Also the dimensions of the input arrays must match otherwise ValueError
will be generated.
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print('First array:')
print(a)
Output:
First array:
[[1 2 3]
[4 5 6]]
Append elements to array:
[1 2 3 4 5 6 7 8 9]
split( ):This function divides the array into subarrays along a specified axis.
import numpy as np
a = np.arange(9)
print('First array:')
print(a)
Output:
First array:
[0 1 2 3 4 5 6 7 8]
Split the array in 3 equal-sized subarrays:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
1. np.amin( )- This function determines the minimum value of the element along a specified axis.
2. np.amax( )- This function determines the maximum value of the element along a specified axis.
3. np.mean( )- It determines the mean value of the data set.
4. np.median( )- It determines the median value of the data set.
5. np.std( )- It determines the standard deviation
6. np.var( ) – It determines the variance.
7. np.ptp( )- It returns a range of values along an axis.
8. np.average( )- It determines the weighted average
9. np.percentile( )- It determines the nth percentile of data along the specified axis.
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
Output:
Our array is:
[[3 7 5]
[8 4 3]
[2 4 9]]
Applying amin() function:
[3 3 2]
Applying amin() function again:
[2 4 3]
Applying amin() function:
2
Applying amax() function:
9
Applying amax() function again:
[8 7 9]
Applying amax() function again:
[7 8 9]
Pandas
Pandas is a Python library.
Pandas is used to analyze data.
What is Pandas?
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was created
by Wes McKinney in 2008.
Installation of Pandas
If you have Python and PIP already installed on a system, then installation of Pandas is very easy.
import pandas
Pandas as pd
Pandas is usually imported under the pd alias.
alias: In Python alias are an alternate name for referring to the same thing.
1.1.3
What is a Series?
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)
Output:
0 1
1 7
2 2
Create Labels
With the index argument, you can name your own labels.
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)
Output:
x 1
y 7
z 2
What is a DataFrame?
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with
rows and columns.
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
print(df)
Output:
calories duration
0 420 50
1 380 40
2 390 45
Locate Row
As you can see from the result above, the DataFrame is like a table with rows and columns.
Pandas use the loc attribute to return one or more specified row(s)
print(df.loc[0])
Output:
calories 420
duration 50
Output:
calories duration
0 420 50
1 380 40
Named Indexes
With the index argument, you can name your own indexes.
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
Output:
calories duration
day1 420 50
day2 380 40
day3 390 45
Column Selection: In Order to select a column in Pandas DataFrame, we can either access the columns
by calling them by their columns name.
Output:
calories
day1 420
day2 380
day3 390
Example Program
import pandas as pd
points_table = {'Team_':['MI', 'CSK', 'Devils', 'MI', 'CSK',
'RCB', 'CSK', 'CSK', 'KKR', 'KKR', 'KKR', 'RCB'],
'Rank_' :[1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],
'Year_' :[2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Point_':[876,789,863,673,741,812,756,788,694,701,804,690]}
df = pd.DataFrame(points_table)
print(df)
Output:
Team_ Rank_ Year_ Point_
0 MI 1 2014 876
1 CSK 2 2015 789
2 Devils 2 2014 863
3 MI 3 2015 673
4 CSK 3 2014 741
5 RCB 4 2015 812
6 CSK 1 2016 756
7 CSK 1 2017 788
8 KKR 2 2016 694
9 KKR 4 2014 701
10 KKR 1 2015 804
11 RCB 2 2017 690
Rename:
CHAPTER-12
FILES
Files are named locations on disk to store related information. They are used to permanently
store data in a non-volatile memory (e.g. hard disk).
When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
1) Open a file
2) Read or write (perform operation)
3) Close the file
Opens a file for writing. Creates a new file if it does not exist or
W
truncates the file if it exists.
Opens a file for exclusive creation. If the file already exists, the
X
operation fails.
Opens a file for appending at the end of the file without truncating
A
it. Creates a new file if it does not exist.
When working with files in text mode, it is highly recommended to specify the encoding type.
f = open("test.txt", mode='r', encoding='utf-8')
This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close( )
This program will create a new file named test.txt in the current directory if it does not exist. If it does
exist, it is overwritten.
We can read the text.txt file we wrote in the above section in the following way:
f = open("test.txt",'r',encoding = 'utf-8')
f.read(4) # read the first 4 data
'This'
Alternatively, we can use the readline( ) method to read individual lines of a file. This method reads a
file till the newline, including the newline character.
f.readline( )
'This is my first file\n'
f.readline( )
'This file\n'
f.readline( )
'contains three lines\n'
f.readline( )
CHAPTER-13
EXCEPTION HANDLING
These errors can be broadly classified into two classes:
1. Syntax errors
2. Logical errors (Exceptions)
Example:
if a < 3
print(a)
Output
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax missing :
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the common
standard exceptions. A list of common exceptions that can be thrown from a standard Python
program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
Exceptions in Python
Python has many built-in exceptions that are raised when your program encounters an error
When these exceptions occur, the Python interpreter stops the current process and passes it to
the calling process until it is handled. If not handled, the program will crash.
Example:
import sys
a=10
b=0
try:
print("a = ",a)
print("b = ",b)
d = a/b
print("d = ",d)
except:
print("Div by Zero error")
Output:
a = 10
b= 0
Div by Zero error
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except:
# handle all other exceptions
pass
except Exception1:
#block of code
else:
#this code executes if no except block is executed
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = ",c)
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:2
a/b = 5.0
Hi I am else block
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
Example:
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Output:
Enter a number: 7
Not an even number!
Enter a number: 6
0.16666…
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
try:
raise(MyError(3*2))
Output:
A New Exception occured: 6
Raising Exceptions
The raise statement allows the programmer to force a specified exception to occur. For example:
raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
The sole argument to raise indicates the exception to be raised. This must be either an
exception instance or an exception class (a class that derives from Exception). If an exception class is
passed, it will be implicitly instantiated by calling its constructor with no arguments:
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
Output:
An exception flew by!
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-bf6ef4926f8c> in <module>
1 try:
----> 2 raise NameError('HiThere')
3 except NameError:
4 print('An exception flew by!')
5 raise
NameError: HiThere