Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
83 views

Adv Python

1. The document discusses Python file handling, including opening, reading, writing, and closing files. It describes using different file access modes like read, write, and append. 2. Key methods for file handling in Python include open() to open a file, read() and write() for reading from and writing to files, and close() to close an open file. 3. The with statement is recommended for file handling in Python as it automatically closes the file even if an exception occurs inside the with block.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Adv Python

1. The document discusses Python file handling, including opening, reading, writing, and closing files. It describes using different file access modes like read, write, and append. 2. Key methods for file handling in Python include open() to open a file, read() and write() for reading from and writing to files, and close() to close an open file. 3. The with statement is recommended for file handling in Python as it automatically closes the file even if an exception occurs inside the with block.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Python File Handling

Till now, we were taking the input from the console and writing it back to the console to interact with the user.

Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited
amount of data can be displayed on the console since the memory is volatile, it is impossible to recover the programmatically
generated data again and again.

The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk
to store related information. We can access the stored information (non-volatile) after the program termination.

The file-handling implementation is slightly lengthy or complicated in the other programming language, but it is easier and shorter in
Python.

In Python, files are treated in two modes as text or binary. The file may be in the text or binary format, and each line of a file is ended
with the special character.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
o Close the file

Opening a file
Python provides an open() function that accepts two arguments, file name and access mode in which the file is accessed. The function
returns a file object which can be used to perform various operations like reading, writing, etc.

Syntax:

1. file object = open(<file-name>, <access-mode>, <buffering>)     

The files can be accessed using various modes like read, write, or append. The following are the details about the access mode to open
a file.

SN Access Description
mode

1 r It opens the file to read-only mode. The file pointer exists at the beginning. The file
is by default open in this mode if no access mode is passed.

2 rb It opens the file to read-only in binary format. The file pointer exists at the
beginning of the file.

3 r+ It opens the file to read and write both. The file pointer exists at the beginning of
the file.

4 rb+ It opens the file to read and write both in binary format. The file pointer exists at
the beginning of the file.

5 w It opens the file to write only. It overwrites the file if previously exists or creates a
new one if no file exists with the same name. The file pointer exists at the beginning
of the file.

6 wb It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.

7 w+ It opens the file to write and read both. It is different from r+ in the sense that it

1
overwrites the previous file if one exists whereas r+ doesn't overwrite the previously
written file. It creates a new file if no file exists. The file pointer exists at the
beginning of the file.

8 wb+ It opens the file to write and read both in binary format. The file pointer exists at
the beginning of the file.

9 a It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists with the same
name.

10 ab It opens the file in the append mode in binary format. The pointer exists at the end
of the previously written file. It creates a new file in binary format if no file exists
with the same name.

11 a+ It opens a file to append and read both. The file pointer remains at the end of the
file if a file exists. It creates a new file if no file exists with the same name.

12 ab+ It opens a file to append and read both in binary format. The file pointer remains at
the end of the file.

Simple example to open a file named "file.txt" (stored in the same directory) in read mode and printing its content on the console.

Example

#opens the file file.txt in read mode    
fileptr = open("file.txt","r")    
    
if fileptr:    
    print("file is opened successfully")    

In the above code, we have passed filename as a first argument and opened file in read mode as we mentioned r as the second argument.
The fileptr holds the file object and if the file is opened successfully, it will execute the print statement

The close() method


Once all the operations are done on the file, we must close it through our Python script using the  close() method. Any unwritten
information gets destroyed once the close() method is called on a file object.

We can perform any operation on the file externally using the file system which is the currently opened in Python; hence it is good
practice to close the file once all the operations are done.

The syntax to use the close() method is given below.

Syntax

1. fileobject.close()   

Consider the following example.

# opens the file file.txt in read mode    
fileptr = open("file.txt","r")    
    
if fileptr:    
    print("file is opened successfully")    
    
#closes the opened file    
fileptr.close()  

2
After closing the file, we cannot perform any operation in the file. The file needs to be properly closed. If any exception occurs while
performing some operations in the file then the program terminates without closing the file.

We should use the following method to overcome such type of problem.

try:  
   fileptr = open("file.txt")  
   # perform file operations  
finally:  
   fileptr.close()  

The with statement


The with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files. It is used in the
scenario where a pair of statements is to be executed with a block of code in between.

The syntax to open a file using with the statement is given below.

1. with open(<file name>, <access mode>) as <file-pointer>:    
2.     #statement suite     

The advantage of using with statement is that it provides the guarantee to close the file regardless of how the nested block exits.

It is always suggestible to use the with statement in the case of files because, if the break, return, or exception occurs in the nested
block of code then it automatically closes the file, we don't need to write the close() function. It doesn't let the file to corrupt.

Consider the following example.

Example

with open("file.txt",'r') as f:    
    content = f.read();    
    print(content)    

Writing the file


To write some text to a file, we need to open the file using the open method with one of the following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.

a: It will append the existing file. The file pointer is at the end of the file. It creates a new file if no file exists.

Consider the following example.

Example

# open the file.txt in append mode. Create a new file if no such file exists.  
fileptr = open("file2.txt", "w")  
  
# appending the content to the file  
fileptr.write('''''Python is the modern day language. It makes things so simple. 
It is the fastest-growing programing language''')  
  
# closing the opened the file  
fileptr.close()  

Snapshot of the file2.txt

3
We have opened the file in w mode. The file1.txt file doesn't exist, it created a new file and we have written the content in the file using
the write() function.

Example 2

#open the file.txt in write mode.    
fileptr = open("file2.txt","a")  
    
#overwriting the content of the file    
fileptr.write(" Python has an easy syntax and user-friendly interaction.")    
      
#closing the opened file     
fileptr.close()  

Output:

Python is the modern day language. It makes things so simple.


It is the fastest growing programing language Python has an easy syntax and user-friendly interaction

Snapshot of the file2.txt

We can see that the content of the file is modified. We have opened the file in a mode and it appended the content in the
existing file2.txt.

To read a file using the Python script, the Python provides the read() method. The read() method reads a string from the file. It can
read the data in the text as well as a binary format.

The syntax of the read() method is given below.

Syntax:

fileobj.read(<count>)    

Here, the count is the number of bytes to be read from the file starting from the beginning of the file. If the count is not specified, then
it may read the content of the file until the end.

4
Consider the following example.

Example

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r")  
#stores all the data of the file into the variable content    
content = fileptr.read(10)   
# prints the type of the data stored in the file    
print(type(content))      
#prints the content of the file    
print(content)       
#closes the opened file    
fileptr.close()    

Output:

<class 'str'>
Python is

In the above code, we have read the content of file2.txt by using the read() function. We have passed count value as ten which means
it will read the first ten characters from the file.

If we use the following line, then it will print all content of the file.

1. content = fileptr.read()  
2. print(content)   

3. Output:
Python is the modern-day language. It makes things so simple.
It is the fastest-growing programing language Python has easy an syntax and user-friendly interaction.

Read file through for loop


We can read the file using for loop. Consider the following example.

#open the file.txt in read mode. causes an error if no such file exists.    
fileptr = open("file2.txt","r");     
#running a for loop     
for i in fileptr:    
    print(i) # i contains each line of the file     

Output:

Python is the modern day language.

It makes things so simple.

Python has easy syntax and user-friendly interaction.

Read Lines of the file


Python facilitates to read the file line by line by using a function readline() method. The readline() method reads the lines of the file
from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.

Consider the following example which contains a function readline() that reads the first line of our file "file2.txt" containing three lines.
Consider the following example.

Example 1: Reading lines using readline() function

5
#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r");     
#stores all the data of the file into the variable content    
content = fileptr.readline()     
content1 = fileptr.readline()  
#prints the content of the file    
print(content)     
print(content1)  
#closes the opened file    
fileptr.close()    

Output:

Python is the modern day language.

It makes things so simple.

We called the readline() function two times that's why it read two lines from the file.

Python provides also the readlines() method which is used for the reading lines. It returns the list of the lines till the end of file(EOF) is
reached.

Example 2: Reading Lines Using readlines() function

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","r");     
    
#stores all the data of the file into the variable content    
content = fileptr.readlines()     
  
#prints the content of the file    
print(content)     
    
#closes the opened file    
fileptr.close()    

Output:

['Python is the modern day language.\n', 'It makes things so simple.\n', 'Python has easy syntax and user-friendly
interaction.']

Creating a new file


The new file can be created by using one of the following access modes with the function open().

x: it creates a new file with the specified name. It causes an error a file exists with the same name.

a: It creates a new file with the specified name if no such file exists. It appends the content to the file if the file already exists with the
specified name.

w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.

Consider the following example.

Example 1

#open the file.txt in read mode. causes error if no such file exists.    
fileptr = open("file2.txt","x")   
print(fileptr)    
if fileptr:    

6
    print("File created successfully")  

Output:

<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>


File created successfully

File Pointer positions


Python provides the tell() method which is used to print the byte number at which the file pointer currently exists. Consider the
following example.

# open the file file2.txt in read mode    

fileptr = open("file2.txt","r")    
  
#initially the filepointer is at 0     
print("The filepointer is at byte :",fileptr.tell())    
    
#reading the content of the file    
content = fileptr.read();    
    
#after the read operation file pointer modifies. tell() returns the location of the fileptr.     
    
print("After reading, the filepointer is at:",fileptr.tell())    

Modifying file pointer position


In real-world applications, sometimes we need to change the file pointer location externally since we may need to read or write the
content at various locations.

For this purpose, the Python provides us the seek() method which enables us to modify the file pointer position externally.

The syntax to use the seek() method is given below.

Syntax:

1. <file-ptr>.seek(offset[, from)    

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be moved. If it is set to 0, the beginning of the file is used as the
reference position. If it is set to 1, the current position of the file pointer is used as the reference position. If it is set to 2, the end of the
file pointer is used as the reference position.

Consider the following example.

Example

# open the file file2.txt in read mode    
fileptr = open("file2.txt","r")    
    
#initially the filepointer is at 0     
print("The filepointer is at byte :",fileptr.tell())    
    
#changing the file pointer location to 10.    
fileptr.seek(10);    
    
#tell() returns the location of the fileptr.     
print("After reading, the filepointer is at:",fileptr.tell())    

7
Python OS module
Renaming the file
The Python os module enables interaction with the operating system. The os module provides the functions that are involved in file
processing operations like renaming, deleting, etc. It provides us the rename() method to rename the specified file to a new name. The
syntax to use the rename() method is given below.

The Python os module enables interaction with the operating system. The os module provides the functions that are involved in file
processing operations like renaming, deleting, etc. It provides us the rename() method to rename the specified file to a new name. The
syntax to use the rename() method is given below.

Syntax:

1. rename(current-name, new-name)    

The first argument is the current file name and the second argument is the modified name. We can change the file name bypassing
these two arguments.

Example 1:

import os    
    
#rename file2.txt to file3.txt    
os.rename("file2.txt","file3.txt")  

Removing the file


The os module provides the remove() method which is used to remove the specified file. The syntax to use the remove() method is
given below.

1. remove(file-name)   

Example 1

import os;    
#deleting the file named file3.txt     
os.remove("file3.txt")    

Creating the new directory


The mkdir() method is used to create the directories in the current working directory. The syntax to create the new directory is given
below.

Syntax:

1. mkdir(directory name)  

Example 1

import os    
    
#creating a new directory with the name new    
os.mkdir("new")    

8
The getcwd() method
This method returns the current working directory.

The syntax to use the getcwd() method is given below.

Syntax

1. os.getcwd()  

Example

1. import os  
2. os.getcwd()  

Changing the current working directory

The chdir() method is used to change the current working directory to a specified directory.

The syntax to use the chdir() method is given below.

Syntax

1. chdir("new-directory")    

Example

import os   

# Changing current directory with the new directiory  
os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")  
#It will display the current working directory  
os.getcwd()  

Deleting directory
The rmdir() method is used to delete the specified directory.

The syntax to use the rmdir() method is given below.

Syntax

1. os.rmdir(directory name)  

Example 1

import os  
#removing the new directory     

9
os.rmdir("directory_name")    

It will remove the specified directory.

Writing Python output to the files


In Python, there are the requirements to write the output of a Python script to a file.

The check_call() method of module subprocess is used to execute a Python script and write the output of that script to a file.

The following example contains two python scripts. The script file1.py executes the script file.py and writes its output to the text
file output.txt.

Example

file.py

temperatures=[10,-20,-289,100]    
def c_to_f(c):    
    if c< -273.15:    
        return "That temperature doesn't make sense!"    
    else:    
        f=c*9/5+32    
        return f    
for t in temperatures:    
    print(c_to_f(t))    

file.py

import subprocess    
    
with open("output.txt", "wb") as f:    
    subprocess.check_call(["python", "file.py"], stdout=f)    

The file related methods


The file object provides the following methods to manipulate the files on various operating systems.

S Method Description
N

1 file.close() It closes the opened file. The file once closed, it can't be read or write
anymore.

2 File.fush() It flushes the internal buffer.

3 File.fileno() It returns the file descriptor used by the underlying implementation to


request I/O from the OS.

4 File.isatty() It returns true if the file is connected to a TTY device, otherwise returns
false.

5 File.next() It returns the next line from the file.

6 File.read([size]) It reads the file for the specified size.

7 File.readline([size]) It reads one line from the file and places the file pointer to the
beginning of the new line.

10
8 File.readlines([sizehint] It returns a list containing all the lines of the file. It reads the file until
) the EOF occurs using readline() function.

9 File.seek(offset[,from) It modifies the position of the file pointer to a specified offset with the
specified reference.

10 File.tell() It returns the current position of the file pointer within the file.

11 File.truncate([size]) It truncates the file to the optional specified size.

12 File.write(str) It writes the specified string to a file

13 File.writelines(seq) It writes a sequence of the strings to a file.

How to take input in Python?


Taking input is a way of interact with users, or get data to provide some result. Python provides two built-in

methods to read the data from the keyboard. These methods are given below.

o input(prompt)
o raw_input(prompt)

input()
The input function is used in all latest version of the Python. It takes the input from the user and then evaluates the expression.
The Python

interpreter automatically identifies the whether a user input a string, a number, or a list. Let's understand the following example.

Example -

# Python program showing  
# a use of input()  
  
name = input("Enter your name: ")  
print(name)  

he Python interpreter will not execute further lines until the user enters the input.

Let's understand another example.

Example - 2

# Python program showing  

# a use of input()  
name = input("Enter your name: ")  # String Input  
age = int(input("Enter your age: ")) # Integer Input  
marks = float(input("Enter your marks: ")) # Float Input  
print("The name is:", name)  
print("The age is:", age)  
print("The marks is:", marks)  

Explanation:

By default, the input() function takes input as a string so if we need to enter the integer or float type input then the input() function
must be type casted.

age = int(input("Enter your age: ")) # Integer Input  

1. marks = float(input("Enter your marks: ")) # Float Input  

11
We can see in the above code where we type casted the user input into int and float.

How input() function works?


o The flow of the program has stopped until the user enters the input.
o The text statement which also knows as prompt is optional to write in input() function. This prompt will display the message on the console.
o The input() function automatically converts the user input into string. We need to explicitly convert the input using the type casting.
o raw_input() - The raw_input function is used in Python's older version like Python 2.x. It takes the input from the keyboard and return as a
string. The Python 2.x doesn't use much in the industry. Let's understand the following example.

Example –

# Python program showing  
# a use of raw_input()  
  
name = raw_input("Enter your name : ")  
print name  

How to check Python version?


To check the Python version, open command line (Windows), shell (Mac), or terminal (Linux/Ubuntu) and run  python -version. It will
display the corresponding Python version.

Check Python version in the running script

We can check the Python version in our running script. Consider the following ways to know Python version in all operating systems.

Commands Operating Output


System/Environment

Python --version or Window/Mac/Linux Python 3.8.1


Python -v or
Python -vv

import sys Python Script 3.8.3 (default, May 13 2020, 15:29:51)


sys.version [MSC v.1915 64 bit (AMD64)]
sys.version_info

Import platform Python Script '3.8.1'

12
platform.python_version(
)

Let's have a look at following image.

Python super() Function


As we all know that, Python is an object-oriented programming language. Therefore, Python follows all the concepts of OOPs, and one
of such concepts is inheritance.

While using the inheritance concept, we can refer to a parent class with the use of super() function inside the inherited or child class.
The super() function we use in the child class returns a temporary created object of the superclass, that allow us to access all of its
method present in the child class.

Benefits of super() function:

Following are the benefits of using a super() function in child class:

o We don't need to remember the parent's class name while using the super() function. This is because we don't have to specify
the name of the parent class to access the methods present in it.
o We can use the super() function with the single inheritance and multiple inheritances.
o The super() function in Python implements code reusability and modularity as there is no need for us to rewrite the whole
function again and again.
o The super() function in Python is known as dynamical function, as we all know that Python is a dynamically typed programming
language.

Following are the benefits of using a super() function in child class:

o We don't need to remember the parent's class name while using the super() function. This is because we don't have to specify
the name of the parent class to access the methods present in it.
o We can use the super() function with the single inheritance and multiple inheritances.
o The super() function in Python implements code reusability and modularity as there is no need for us to rewrite the whole
function again and again.
o The super() function in Python is known as dynamical function, as we all know that Python is a dynamically typed programming
language.

13
Constraints of using super() function:
Following are three constraints that we must have to follow to use the super() function in a Python program

o The arguments are given in the super() function and the arguments in the function that we have called should match.
o Every occurrence of the method that we are using should include the super() keyword after we use it.
o We have to specify the class and methods present in it, which are referred to by the super() function.

Now, as we know that, we can use the super() function in both types of inheritances in Python, i.e., single as well as multiple
inheritances. Therefore, we will learn about using the super() function in both types of inheritance separately and with an example.

Using super() function in single inheritance in Python


In this example, we will use animals as the reference for a single inheritance

example.

Cats, horses, cows, dogs, etc., all are part of class animalia. They all share some common characteristics also:

o They all are pet animals.


o They all have four legs and a tail.
o As part of class animalia, they all are mammals as well.

So, we can say that the class cats, class horses, and class dogs are the subclasses of the class animalia. This is an example of single
inheritance because all the subclasses (class cats, class horses, and class dogs) are inherited from a single parent class only, i.e., class
animalia. Now, look at the following program.

Example -

1. # Define parent class animalia  
class Animalia:  
      
    # define construcors for parent animalia class  
    def __init__(self):  
        self.Legs = 4  
        self.adomestic = True  
        self.atail = True  
        self.amammals = True  
  
    # define mammal class as child class  
    def aMammal(self):  
        if self.amammals:   
            print("The given animal is a mammal type .")  
  
    # define domestic class as child class  
    def aDomestic(self):  
        if self.adomestic:  
            print("The given animal is a domestic animal type.")  
# define dog class    
class Dog(Animalia):  
    def __init__(self):  
        super().__init__() # using super() function to access class methods  
  
    def isMammal(self):  
        super().aMammal() # using mammal class  
  
# define cat class  
class Cat(Animalia):  
14
    def __init__(self):  
        super().__init__()  
  
    def isMammal(self):  
        super().aDomestic() # using domestic class  
  
# define horse class  
class Horse(Animalia):  
    def __init__(self):  
        super().__init__()  
  
    def TailandLegs(self): # using tail and legs class  
        if self.atail and self.Legs == 4:  
            print("The given animal has four legs and a tail")  
  
# Taking the driver's code for defined classes  
Tommy = Dog()  
Tommy.aMammal()  
Tom = Cat()  
Tom.aDomestic()  
Burno = Horse()  
Burno.TailandLegs()  

Explanation:

In the above code, we have defined animalia as parent class and inherited domestic, tail & legs, and mammal class from it. After that, we
have defined the cat, horse, and dog class and used super function in it. With the help of super() function in these classes, we have
accessed methods of animalia class in cat, horse & dog class.

Using super() function in multiple inheritances in Python


In this example, we will use a parent class, i.e., mammal class. Then, we will inherit the 'Can Fly' and 'Can Swim' classes from the mammal
class.

These classes will represent if a given mammal can fly or not and can swim or not. We will define an animal class after that, and it will
inherit from both 'Can Fly' and 'Can Swim' class and return us that given animal have the defined characteristics or not.

So, we can see that the animal class we are using here is inherited from multiple base classes, and therefore, it is an example of multiple
inheritances in Python. Now, look at the following program

Example

# Define Mammal class as parent class  
class aMammals():  
      
    def __init__(self, name):  
        print(name, "Is a mammal of animalia class")  
  
# define can fly as child class       
class FlyCapable(aMammals):  
      
    def __init__(self, FlyCapable_name):  
        print(FlyCapable_name, "is not capable of flying")  
          
        # Calling Parent class Constructor  
        super().__init__(FlyCapable_name)  
# define can swim as child class                  
class SwimCapable(aMammals):  
      

15
    def __init__(self, SwimCapable_name):  
          
        print(SwimCapable_name, "is not capable of swimming")  
              
        super().__init__(SwimCapable_name)  
  
# Inherit animalia class from both fly and swim class         
class animalia(FlyCapable, SwimCapable):  
      
    def __init__(self, name):  
          
        super().__init__(name) # using super() function  
  
  
# Taking driver Code for animalia class  
Burno = animalia("Cat")  

Explanation:

In the above code, we defined mammal as a parent class. After that, we inherited can fly & can swim classes from the mammal class. We
used the methods of both can fly & can swim inside the animalia class with the help of super() function. The animalia class is inherited
from both the can swim and can fly class.

Python OOPs Concepts


Like other general-purpose programming languages, Python is also an object-oriented language since its beginning. It allows us to develop applications using an Object-Oriented
approach. In Python, we can easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The object is related to real-word entities such as book, house, pencil, etc. The oops concept focuses
on writing the reusable code. It is a widespread technique to solve the problem by creating objects.

Major principles of object-oriented programming system are given below.

o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation

Class
The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax

class ClassName:     
        <statement-1>     
        .     
        .      
        <statement-N

Object
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.

16
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.

When we define a class, it needs to create an object to allocate the memory. Consider the following example.

Example:

class car:  
    def __init__(self,modelname, year):  
        self.modelname = modelname  
        self.year = year  
    def display(self):  
        print(self.modelname,self.year)  
  
c1 = car("Toyota", 2016)  
c1.display()  

In the above example, we have created the class named car, and it has two attributes modelname and year. We have created a c1 object to access the class attribute. The c1 object
will allocate memory for these values. We will learn more about class and object in the next tutorial.

Method
The method is a function that is associated with an object. In Python, a method is not unique to class instances. Any object type can have methods.

Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the real-world concept of inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.

It provides the re-usability of the code.

Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means shape. By polymorphism, we understand that one task can be performed in different
ways. For example - you have a class animal, and all animals speak. But they speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on the animal. So,
the abstract "animal" concept does not actually "speak", but specific animals (like dogs and cats) have a concrete implementation of the action "speak".

Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.

Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things so that the name captures the core of what a function
or a whole program does.

Object-oriented vs. Procedure-oriented Programming languages


The difference between object-oriented and procedure-oriented programming is given below:

Index Object-oriented Programming Procedural Programming

1. Object-oriented programming is the problem- Procedural programming uses a list of


solving approach and used where computation instructions to do computation step by step.
is done by using objects.

2. It makes the development and maintenance In procedural programming, It is not easy to


easier. maintain the codes when the project
becomes lengthy.

3. It simulates the real world entity. So real-world It doesn't simulate the real world. It works on
problems can be easily solved through oops. step by step instructions divided into small
parts called functions.

4. It provides data hiding. So it is more secure Procedural language doesn't provide any
than procedural languages. You cannot access proper way for data binding, so it is less
private data from anywhere. secure.

5. Example of object-oriented programming Example of procedural languages are: C,


languages is C++, Java, .Net, Python, C#, etc. Fortran, Pascal, VB etc.

Python Class and Objects


We have already discussed in previous tutorial, a class is a virtual entity and can be seen as a blueprint of an object. The class came into existence when it instantiated. Let's
understand it by an example.

17
Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects of this class.

On the other hand, the object is the instance of a class. The process of creating an object can be called instantiation.

In this section of the tutorial, we will discuss creating classes and objects in Python. We will also discuss how a class attribute is accessed by using the object.

Creating classes in Python


In Python, a class can be created by using the keyword class, followed by the class name. The syntax to create a class is given below.

Syntax

1. class ClassName:    
2.     #statement_suite     

In Python, we must notice that each class is associated with a documentation string which can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.

Consider the following example to create a class Employee which contains two fields as Employee id, and name.

The class also contains a function display(), which is used to display the information of the Employee.

1. class Employee:    
2.     id = 10   
3.     name = "Devansh"    
4.     def display (self):    
5.         print(self.id,self.name)    

Here, the self is used as a reference variable, which refers to the current class object. It is always the first argument in the function definition. However, using  self is optional in the
function call.

The self-parameter

The self-parameter refers to the current instance of the class and accesses the class variables. We can use anything instead of self, but it must be the first parameter of any function
which belongs to the class.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

1. <object-name> = <class-name>(<arguments>)    

The following example creates the instance of the class Employee defined in the above example.

Example

class Employee:    
    id = 10   
    name = "John"    
    def display (self):    
        print("ID: %d \nName: %s"%(self.id,self.name))    
# Creating a emp instance of Employee class  
emp = Employee()    
emp.display()   

In the above code, we have created the Employee class which has two attributes named id and name and assigned value to them. We can observe we have passed the self as
parameter in display function. It is used to refer to the same class attribute.

We have created a new instance object named emp. By using it, we can access the attributes of the class.

Delete the Object


We can delete the properties of the object or object itself by using the del keyword. Consider the following example.

class Employee:  
    id = 10  
    name = "John"  
  
    def display(self):  
        print("ID: %d \nName: %s" % (self.id, self.name))  
    # Creating a emp instance of Employee class  
  
emp = Employee()  
  
18
# Deleting the property of object  
del emp.id  
# Deleting the object itself  
del emp  
emp.display()  

It will through the Attribute error because we have deleted the object emp.

Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance members of the class.

In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in Python. It is used to create an object.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources for the object to perform any start-up task.

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This method is called when the class is instantiated. It accepts the  self-keyword as a first argument which
allows accessing the attributes or method of the class.

We can pass any number of arguments at the time of creating the class object, depending upon the  __init__() definition. It is mostly used to initialize the class attributes. Every class
must have a constructor, even if it simply relies on the default constructor.

Consider the following example to initialize the Employee class attributes.

Example

class Employee:  
    def __init__(self, name, id):  
        self.id = id  
        self.name = name  
  
    def display(self):  
        print("ID: %d \nName: %s" % (self.id, self.name))  
  
  
emp1 = Employee("John", 101)  
emp2 = Employee("David", 102)  
  
# accessing display() method to print employee 1 information  
  
emp1.display()  
  
# accessing display() method to print employee 2 information  
emp2.display()  

Counting the number of objects of a class


The constructor is called automatically when we create the object of the class. Consider the following example.

Example
class Student:    
    count = 0    
    def __init__(self):    
        Student.count = Student.count + 1    
s1=Student()    
s2=Student()    
s3=Student()    
print("The number of students:",Student.count)    
Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the value or the constructor that has only self as an argument. Consider the following example.

Example

class Student:  
    # Constructor - non parameterized  
    def __init__(self):  
        print("This is non parametrized constructor")  

19
    def show(self,name):  
        print("Hello",name)  
student = Student()  
student.show("John")      

Python Parameterized Constructor

The parameterized constructor has multiple parameters along with the self. Consider the following example.

Example

class Student:  
    # Constructor - parameterized  
    def __init__(self, name):  
        print("This is parametrized constructor")  
        self.name = name  
    def show(self):  
        print("Hello",self.name)  
student = Student("John")  
student.show()    

Python Default Constructor


When we do not include the constructor in the class or forget to declare it, then that becomes the default constructor. It does not perform any task but initializes the objects.
Consider the following example.

Example
class Student:  
    roll_num = 101  
    name = "Joseph"  
  
    def display(self):  
        print(self.roll_num,self.name)  
  
st = Student()  
st.display()  

More than One Constructor in Single class


Example of two same constructors in the class.

Example

class Student:  
    def __init__(self):  
        print("The First Constructor")  
    def __init__(self):  
        print("The second contructor")  
  
st = Student()  

In the above code, the object st called the second constructor whereas both have the same configuration. The first method is not accessible by the st object. Internally, the object of
the class will always call the last constructor if the class has multiple constructors.

Note: Constructor overloading is not allowed in python

Python built-in class functions


The built-in functions defined in the class are described in the following table.

SN Function Description

1 getattr(obj,name,default) It is used to access the attribute of the object.

2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.

20
4 hasattr(obj, name) It returns true if the object contains some specific attribute.

class Student:  
    def __init__(self, name, id, age):  
        self.name = name  
        self.id = id  
        self.age = age  
  
    # creates the object of the class Student  
s = Student("John", 101, 22)  
  
# prints the attribute name of the object s  
print(getattr(s, 'name'))  
  
# reset the value of attribute age to 23  
setattr(s, "age", 23)  
  
# prints the modified value of age  
print(getattr(s, 'age'))  
  
# prints true if the student contains the attribute with name id  
  
print(hasattr(s, 'id'))  
# deletes the attribute age  
delattr(s, 'age')  
  
# this will give an error since the attribute age has been deleted  
print(s.age)  

Built-in class attributes


Along with the other attributes, a Python class also contains some built-in class attributes which provide information about the class.

The built-in class attributes are given in the below table.

SN Attribute Description

1 __dict__ It provides the dictionary containing the information about the class namespace.

2 __doc__ It contains a string which has the class documentation

3 __name__ It is used to access the class name.

4 __module__ It is used to access the module in which, this class is defined.

5 __bases__ It contains a tuple including all base classes.

class Student:    
    def __init__(self,name,id,age):    
        self.name = name;    
        self.id = id;    
        self.age = age    
    def display_details(self):    
        print("Name:%s, ID:%d, age:%d"%(self.name,self.id))    
s = Student("John",101,22)    
print(s.__doc__)    
print(s.__dict__)    
print(s.__module__)    

Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to the program because we can use an existing class to create a new class
instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will discuss inheritance in detail.

21
In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name. Consider the following syntax to inherit a base class into the
derived class.

Syntax

class derived-class(base class):  

1.     <class-suite>   

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax.

Syntax

1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):  
2.     <class - suite>  

Example 1

class Animal:  

    def speak(self):  
        print("Animal Speaking")  
#child class Dog inherits the base class Animal  
class Dog(Animal):  
    def bark(self):  
        print("dog barking")  
d = Dog()  
d.bark()  
d.speak()  

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is archived when a derived class inherits another derived class. There is no
limit on the number of levels up to which, the multi-level inheritance is archived in python.

The syntax of multi-level inheritance is given below.

Syntax

22
class class1:  
    <class-suite>   
class class2(class1):  
    <class suite>  
class class3(class2):  
    <class suite>  
.  

Example

class Animal:  

    def speak(self):  
        print("Animal Speaking")  
#The child class Dog inherits the base class Animal  
class Dog(Animal):  
    def bark(self):  
        print("dog barking")  
#The child class Dogchild inherits another child class Dog  
class DogChild(Dog):  
    def eat(self):  
        print("Eating bread...")  
d = DogChild()  
d.bark()  
d.speak()  
d.eat()  

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

he syntax to perform multiple inheritance is given below.

Syntax

class Base1:  
<class-suite>  

class Base2:  
<class-suite>  
.  
.  
.  
class BaseN:  
<class-suite>  

class Derived(Base1, Base2, ...... BaseN):  
<class-suite>  

Example

class Calculation1:  
    def Summation(self,a,b):  
        return a+b;  
class Calculation2:  
    def Multiplication(self,a,b):  
23
        return a*b;  
class Derived(Calculation1,Calculation2):  
    def Divide(self,a,b):  
        return a/b;  
d = Derived()  
print(d.Summation(10,20))  
print(d.Multiplication(10,20))  
print(d.Divide(10,20))  

The issubclass(sub,sup) method

The issubclass(sub, sup) method is used to check the relationships between the specified classes. It returns true if the first class is the subclass of the second class, and false
otherwise.

Consider the following example.

Example

class Calculation1:  
    def Summation(self,a,b):  
        return a+b;  
class Calculation2:  
    def Multiplication(self,a,b):  
        return a*b;  
class Derived(Calculation1,Calculation2):  
    def Divide(self,a,b):  
        return a/b;  
d = Derived()  
print(issubclass(Derived,Calculation2))  
print(issubclass(Calculation1,Calculation2))  

The isinstance (obj, class) method


The isinstance() method is used to check the relationship between the objects and classes. It returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e.,
class.

Consider the following example.

Example
1.
class Calculation1:  
    def Summation(self,a,b):  
        return a+b;  
class Calculation2:  
    def Multiplication(self,a,b):  
        return a*b;  
class Derived(Calculation1,Calculation2):  
    def Divide(self,a,b):  
        return a/b;  
d = Derived()  
print(isinstance(d,Derived))  

Method Overriding
We can provide some specific implementation of the parent class method in our child class. When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform method overriding in the scenario where the different definition of a parent class method is
needed in the child class.

Consider the following example to perform method overriding in python.

Example
1.
class Animal:  
    def speak(self):  
        print("speaking")  
class Dog(Animal):  
    def speak(self):  
        print("Barking")  
d = Dog()  
d.speak()  

Real Life Example of method overriding

class Bank:  
24
    def getroi(self):  
        return 10;  
class SBI(Bank):  
    def getroi(self):  
        return 7;  
  
class ICICI(Bank):  
    def getroi(self):  
        return 8;  
b1 = Bank()  
b2 = SBI()  
b3 = ICICI()  
print("Bank Rate of interest:",b1.getroi());  
print("SBI Rate of interest:",b2.getroi());  
print("ICICI Rate of interest:",b3.getroi());  

Data abstraction in python


Abstraction is an important aspect of object-oriented programming. In python, we can also perform data hiding by adding the double underscore (___) as a prefix to the attribute
which is to be hidden. After this, the attribute will not be visible outside of the class through the object.

Consider the following example.

Example

class Employee:  

    __count = 0;  
    def __init__(self):  
        Employee.__count = Employee.__count+1  
    def display(self):  
        print("The number of employees",Employee.__count)  
emp = Employee()  
emp2 = Employee()  
try:  
    print(emp.__count)  
finally:  
    emp.display()  

Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users. The users only interact with the basic implementation of the
function, but inner working is hidden. User is familiar with that "what function does" but they don't know "how it does."

In simple words, we all use the smartphone and very much familiar with its functions such as camera, voice-recorder, call-dialing, etc., but we don't
know how these operations are happening in the background. Let's take another example - When we use the TV remote to increase the volume. We
don't know how pressing a key increases the volume of the TV. We only know to press the "+" button to increase the volume.

That is exactly the abstraction that works in the object-oriented concept.

Why Abstraction is Important?

In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity. It also enhances the application efficiency. Next, we will learn how we can achieve
abstraction using the Python program.

Abstraction classes in Python


In Python, abstraction can be achieved by using abstract classes and interfaces.

A class that consists of one or more abstract method is called the abstract class. Abstract methods do not contain their implementation. Abstract class can be inherited by the
subclass and abstract method gets its definition in the subclass. Abstraction classes are meant to be the blueprint of the other class. An abstract class can be useful when we are
designing large functions. An abstract class is also helpful to provide the standard interface for different implementations of components. Python provides the  abc module to use the
abstraction in the Python program. Let's see the following syntax.

We import the ABC class from the abc module.

Abstract Base Classes


An abstract base class is the common application program of the interface for a set of subclasses. It can be used by the third-party, which will provide the implementations such as
with plugins. It is also beneficial when we work with the large code-base hard to remember all the classes.

25
Working of the Abstract Classes
Unlike the other high-level language, Python doesn't provide the abstract class itself. We need to import the abc module, which provides the base for defining Abstract Base classes
(ABC). The ABC works by decorating methods of the base class as abstract. It registers concrete classes as the implementation of the abstract base. We use
the @abstractmethod decorator to define an abstract method or if we don't provide the definition to the method, it automatically becomes the abstract method. Let's understand
the following example.

# Python program demonstrate  
# abstract base class work   
from abc import ABC, abstractmethod   
class Car(ABC):   
    def mileage(self):   
        pass  
  
class Tesla(Car):   
    def mileage(self):   
        print("The mileage is 30kmph")   
class Suzuki(Car):   
    def mileage(self):   
        print("The mileage is 25kmph ")   
class Duster(Car):   
     def mileage(self):   
          print("The mileage is 24kmph ")   
  
class Renault(Car):   
    def mileage(self):   
            print("The mileage is 27kmph ")   
          
# Driver code   
t= Tesla ()   
t.mileage()   
  
r = Renault()   
r.mileage()   
  
s = Suzuki()   
s.mileage()   
d = Duster()   
d.mileage()  

Explanation -

In the above code, we have imported the abc module to create the abstract base class. We created the Car class that inherited the ABC class and defined an abstract method named
mileage(). We have then inherited the base class from the three different subclasses and implemented the abstract method differently. We created the objects to call the abstract
method.

Let's understand another example.

# Python program to define   
# abstract class  
  
from abc import ABC  
  
class Polygon(ABC):   
  
   # abstract method   
   def sides(self):   
      pass  
  
class Triangle(Polygon):   
  
     
   def sides(self):   
      print("Triangle has 3 sides")   
  
class Pentagon(Polygon):   
  
     
   def sides(self):   
      print("Pentagon has 5 sides")   
  
class Hexagon(Polygon):   
  
   def sides(self):   
      print("Hexagon has 6 sides")   
  
class square(Polygon):   

26
  
   def sides(self):   
      print("I have 4 sides")   
  
# Driver code   
t = Triangle()   
t.sides()   
  
s = square()   
s.sides()   
  
p = Pentagon()   
p.sides()   
  
k = Hexagon()   
K.sides()   

Explanation -

In the above code, we have defined the abstract base class named Polygon and we also defined the abstract method. This base class inherited by the various subclasses. We
implemented the abstract method in each subclass. We created the object of the subclasses and invoke the  sides() method. The hidden implementations for the sides() method
inside the each subclass comes into play. The abstract method sides() method, defined in the abstract class, is never invoked.

Points to Remember
Below are the points which we should remember about the abstract base class in Python.

o An Abstract class can contain the both method normal and abstract method.
o An Abstract cannot be instantiated; we cannot create objects for the abstract class.

Abstraction is essential to hide the core functionality from the users. We have covered the all the basic concepts of Abstraction in Python.

Python Modules
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. We may have a runnable code inside the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the specific module.

Example

In this example, we will create a module named as file.py which contains a function func that contains a code to print some message on the console.

Let's create the module named as file.py.

1. #displayMsg prints a message to the name being passed.   
2. def displayMsg(name)  
3.     print("Hi "+name);    

Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.

The from-import statement


Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.

1. from < module-name> import <name 1>, <name 2>..,<name n>   

Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.

calculation.py:

#place the code in the calculation.py   
def summation(a,b):  
    return a+b  
def multiplication(a,b):  
    return a*b;  
def divide(a,b):  
    return a/b;  

Main.py:

27
from calculation import summation    
#it will import only the summation() from calculation.py  
a = int(input("Enter the first number"))  
b = int(input("Enter the second number"))  
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation

The from...import statement is always better to use if we know the attributes to be imported from the module in advance. It doesn't let our code to be heavier. We can also import all
the attributes from a module by using *.

Consider the following syntax.

1. from <module> import *   
Renaming a module
Python provides us the flexibility to import some module with a specific name so that we can use this name to use that module in our python source file.

The syntax to rename a module is given below.

1. import <module-name> as <specific-name>   
Example

#the module calculation of previous example is imported in this example as cal.   

import calculation as cal;  
a = int(input("Enter a?"));  
b = int(input("Enter b?"));  
print("Sum = ",cal.summation(a,b))  

Using dir() function


The dir() function returns a sorted list of names defined in the passed module. This list contains all the sub-modules, variables and functions defined in this module.

Consider the following example.

Example

import json  
  
List = dir(json)  
  
print(List)  

The reload() function


As we have already stated that, a module is loaded once regardless of the number of times it is imported into the python source file. However, if you want to reload the already
imported module to re-execute the top-level code, python provides us the reload() function. The syntax to use the reload() function is given below.

1. reload(<module-name>)  

for example, to reload the module calculation defined in the previous example, we must use the following line of code.

1. reload(calculation)  
Scope of variables
In Python, variables are associated with two types of scopes. All the variables defined in a module contain the global scope unless or until it is defined within a function.

All the variables defined inside a function contain a local scope that is limited to this function itself. We can not access a local variable globally.

If two variables are defined with the same name with the two different scopes, i.e., local and global, then the priority will always be given to the local variable.

Consider the following example.

Example

28
name = "john"  
def print_name(name):  
    print("Hi",name) #prints the name that is local to this function only.  
name = input("Enter the name?")  
print_name(name)  

Python packages
The packages in python facilitate the developer with the application development environment by providing a hierarchical directory structure where a package contains sub-
packages, modules, and sub-modules. The packages are used to categorize the application level code efficiently.

Let's create a package named Employees in your home directory. Consider the following steps.

1. Create a directory with name Employees on path /home.

2. Create a python source file with name ITEmployees.py on the path /home/Employees.

ITEmployees.py

def getITNames():  
    List = ["John", "David", "Nick",    "Martin"]  
    return List;  

3. Similarly, create one more python file with name BPOEmployees.py and create a function getBPONames().

4. Now, the directory Employees which we have created in the first step contains two python modules. To make this directory a package, we need to include one more file here, that
is __init__.py which contains the import statements of the modules defined in this directory.

__init__.py

1. from ITEmployees import getITNames  
2. from BPOEmployees import getBPONames  

Now, the directory Employees has become the package containing two python modules. Here we must notice that we must have to create __init__.py inside a directory to convert
this directory to a package.

6. To use the modules defined inside the package Employees, we must have to import this in our python source file. Let's create a simple python source file at our home directory
(/home) which uses the modules defined in this package.

Test.py

1. import Employees  
2. print(Employees.getNames())  

We can have sub-packages inside the packages. We can nest the packages up to any level depending upon the application requirements.

The following image shows the directory structure of an application Library management system which contains three sub-packages as Admin, Librarian, and Student. The sub-
packages contain the python modules.

29
30
Python Exception
An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the program.

Whenever an exception occurs, the program stops the execution, and thus the further code is not executed. Therefore, an exception is
the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error

Python provides a way to handle the exception so that the code can be executed without any interruption. If we do not handle the
exception, the interpreter doesn't execute all the code that exists after the exception.

Python has many built-in exceptions that enable our program to run without interruption and give the output. These exceptions are
given below:

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.

The problem without handling exceptions


As we have already discussed, the exception is an abnormal condition that halts the execution of the program.

Suppose we have two variables a and b, which take the input from the user and perform the division of these values. What if the user
entered the zero as the denominator? It will interrupt the program execution and through a ZeroDivision exception. Let's see the
following example.

Example

a = int(input("Enter a:"))    
b = int(input("Enter b:"))    
c = a/b  
print("a/b = %d" %c)    
    
#other code:    
print("Hi I am other part of the program")  

The above program is syntactically correct, but it through the error because of unusual input. That kind of programming may not be suitable or
recommended for the projects because these projects are required uninterrupted execution. That's why an exception-handling plays an essential
role in handling these unexpected exceptions. We can handle these exceptions in the following way.

Exception handling in python

The try-expect statement

31
Syntax

try:    
    #block of code     
    
except Exception1:    
    #block of code    
    
except Exception2:    
    #block of code    
    
#other code    

Consider the following example.

Example 1

try:  
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
except:  
    print("Can't divide with zero")  

We can also use the else statement with the try-except statement in which, we can place the code which will be executed in the scenario
if no exception occurs in the try block.

The syntax to use the else statement with the try-except statement is given below.

try:    
    #block of code     
    
except Exception1:    
    #block of code     
    
else:    
    #this code executes if no except block is executed    

32
Example 2

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("a/b = %d"%c)    
# Using Exception with except statement. If we print(Exception) it will return exception class  
except Exception:    
    print("can't divide by zero")    
    print(Exception)  
else:    
    print("Hi I am else block")     

The except statement with no exception


Python provides the flexibility not to specify the name of exception with the exception statement.

Consider the following example.

Example

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b;    
    print("a/b = %d"%c)    
except:    
    print("can't divide by zero")    
else:    
    print("Hi I am else block")   

The except statement using with exception variable


We can use the exception variable with the except statement. It is used by using the as keyword. this object will return the cause of the
exception. Consider the following example:

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("a/b = %d"%c)    

33
    # Using exception object with the except statement  
except Exception as e:    
    print("can't divide by zero")    
    print(e)  
else:    
    print("Hi I am else block")     

Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may contain the statements which throw the different type of
exceptions.
3. We can also specify an else block along with the try-except statement, which will be executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.

Example

try:    
    #this will throw an exception if the file doesn't exist.     
    fileptr = open("file.txt","r")    
except IOError:    
    print("File not found")    
else:    
    print("The file opened successfully")    
    fileptr.close()    

Declaring Multiple Exceptions


The Python allows us to declare the multiple exceptions with the except clause. Declaring multiple exceptions is useful in the cases
where a try block throws multiple exceptions. The syntax is given below.

Syntax

try:    
    #block of code     
    
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)    
    #block of code     
    
else:    
    #block of code    

Example.

try:      
    a=10/0;      
except(ArithmeticError, IOError):      
    print("Arithmetic Exception")      
else:      
    print("Successfully Done")       

The try...finally block


Python provides the optional finally statement, which is used with the try statement. It is executed no matter what exception occurs
and used to release the external resource. The finally block provides a guarantee of the execution.

We can use the finally block with the try block in which we can pace the necessary code, which must be executed before the try
statement throws an exception.

The syntax to use the finally block is given below.

Syntax

34
try:    
    # block of code     
    # this may throw an exception    
finally:    
    # block of code    
    # this will always be executed     

Example

try:    
    fileptr = open("file2.txt","r")      
    try:    
        fileptr.write("Hi I am good")    
    finally:    
        fileptr.close()    
        print("file closed")    
except:    
    print("Error")    

Raising exceptions
An exception can be raised forcefully by using the raise clause in Python. It is useful in in that scenario where we need to raise an
exception to stop the execution of the program.

For example, there is a program that requires 2GB memory for execution, and if the program tries to occupy 2GB of memory, then we
can raise an exception to stop the execution of the program.

The syntax to use the raise statement is given below.

Syntax

1. raise Exception_class,<value>    

Points to remember

1. To raise an exception, the raise statement is used. The exception class name follows it.
35
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of the exception.
4. We can pass the value to an exception to specify the exception type.

Example

try:    
    age = int(input("Enter the age:"))    
    if(age<18):    
        raise ValueError   
    else:    
        print("the age is valid")    
except ValueError:    
    print("The age is not valid")    

Example 2 Raise the exception with message

try:  
     num = int(input("Enter a positive integer: "))  
     if(num <= 0):  
# we can pass the message in the raise statement  
         raise ValueError("That is  a negative number!")  
except ValueError as e:  
     print(e)  

Example 3

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    if b is 0:    
        raise ArithmeticError  
    else:    
        print("a/b = ",a/b)    
except ArithmeticError:    
    print("The value of b can't be 0")  

Custom Exception
The Python allows us to create our exceptions that can be raised from the program and caught using the except clause. However, we
suggest you read this section after visiting the Python object and classes.

Consider the following example.

Example

class ErrorInCode(Exception):      
    def __init__(self, data):      
        self.data = data      
    def __str__(self):      
        return repr(self.data)      
      
try:      
    raise ErrorInCode(2000)      
except ErrorInCode as ae:      
    print("Received error:", ae.data)      

Python Date and time


36
Python provides the datetime module work with real dates and times. In real-world applications, we need to work with the date and time. Python
enables us to schedule our Python script to run at a particular timing.

In Python, the date is not a data type, but we can work with the date objects by importing the module named with datetime, time, and calendar.

In this section of the tutorial, we will discuss how to work with the date and time objects in Python.

The datetime classes are classified in the six main classes.

o date - It is a naive ideal date. It consists of the year, month, and day as attributes.
o time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour, minute, second, microsecond,
and tzinfo as attributes.
o datetime - It is a grouping of date and time, along with the attributes year, month, day, hour, minute, second, microsecond, and
tzinfo.
o timedelta - It represents the difference between two dates, time or datetime instances to microsecond resolution.
o tzinfo - It provides time zone information objects.
o timezone - It is included in the new version of Python. It is the class that implements the tzinfo abstract base class.

Tick
In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of the module time returns the total
number of ticks spent since 12 AM, 1st January 1970. A tick can be seen as the smallest unit to measure the time.

Consider the following example

1. import time;  
#prints the number of ticks spent since 12 AM, 1st January 1970  
print(time.time())  

How to get the current time?


The localtime() functions of the time module are used to get the current time tuple. Consider the following example.

Example

1. import time;    
2.     
3. #returns a time tuple     
4.     
5. print(time.localtime(time.time()))  

Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time tuple.

Index Attribute Values

0 Year 4 digit (for example 2018)

1 Month 1 to 12

2 Day 1 to 31

37
3 Hour 0 to 23

4 Minute 0 to 59

5 Second 0 to 60

6 Day of weak 0 to 6

7 Day of year 1 to 366

8 Daylight savings -1,0,1 0r 1

The datetime Module


The datetime module enables us to create the custom date objects, perform various operations on dates like the comparison, etc.

To work with dates as date objects, we have to import the datetime module into the python source code.

Consider the following example to get the datetime object representation for the current time.

Example

1. import datetime  
2. #returns the current datetime object     
3. print(datetime.datetime.now())    

Creating date objects


We can create the date objects bypassing the desired date in the datetime constructor for which the date objects are to be created.

Consider the following example.

Example

1. import datetime    
2. #returns the datetime object for the specified date    
3. print(datetime.datetime(2020,04,04))    

The calendar module


Python provides a calendar object that contains various methods to work with the calendars.

Consider the following example to print the calendar for the last month of 2018.

Example

1. import calendar;    
2. cal = calendar.month(2020,3)    
3. #printing the calendar of December 2018    
4. print(cal)    

38
Printing the calendar of whole year
The prcal() method of calendar module is used to print the calendar of the entire year. The year of which the calendar is to be printed
must be passed into this method.

Example

1. import calendar    
2. #printing the calendar of the year 2019    
3. s = calendar.prcal(2020)  

Python Database Programming

Environment Setup
To build the real world applications, connecting with the databases is the necessity for the programming languages. However, python
allows us to connect our application to the databases like MySQL, SQLite, MongoDB, and many others.

In this section of the tutorial, we will discuss Python - MySQL connectivity, and we will perform the database operations in python. We
will also cover the Python connectivity with the databases like MongoDB and SQLite later in this tutorial.

Install mysql.connector
To connect the python application with the MySQL database, we must import the mysql.connector module in the program.

The mysql.connector is not a built-in module that comes with the python installation. We need to install it to get it working.

Execute the following command to install it using pip installer.

1. >  python -m pip install mysql-connector  

Or follow the following steps.

1. Click the link:

https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b8660d09f91d8d5411298bcacbd309f96/mysql-
connector-python-8.0.13.tar.gz to download the source code.

2. Extract the archived file.

3. Open the terminal (CMD for windows) and change the present working directory to the source code directory.

$  cd mysql-connector-python-8.0.1

4. Run the file named setup.py with python (python3 in case you have also installed python 2) with the parameter build.

$ python setup.py build  

5. Run the following command to install the mysql-connector.

$ python setup.py install 

This will take a bit of time to install mysql-connector for python. We can verify the installation once the process gets over by importing
mysql-connector on the python shell.

Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application to the database.

39
There are the following steps to connect a python application to our database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection


To create a connection between the MySQL database and the python application, the connect() method of mysql.connector module is
used.

Pass the database details like HostName, username, and the database password in the method call. The method returns the connection
object.

The syntax to use the connect() is given below.

1. Connection-Object= mysql.connector.connect(host = <host-name> , user = <username> , passwd = <password> )  

Consider the following example.

Example
import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  
  
#printing the connection object   
print(myconn)  

Here, we must notice that we can specify the database name in the connect() method if we want to connect to a specific database.

Example
1. import mysql.connector  
2.   
3. #Create the connection object   
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")  
5.   
6. #printing the connection object   
7. print(myconn)   

Creating a cursor object


The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It facilitates us to have multiple separate working
environments through the same connection to the database. We can create the cursor object by calling the 'cursor' function of the
connection object. The cursor object is an important aspect of executing queries to the databases.

The syntax to create the cursor object is given below.

1. <my_cur>  = conn.cursor()  
Example
1. import mysql.connector  
2. #Create the connection object   
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")  
4.   
5. #printing the connection object   
6. print(myconn)   
7.   
8. #creating the cursor object  
9. cur = myconn.cursor()  
10.   

40
11. print(cur)  

Creating new databases


In this section of the tutorial, we will create the new database PythonDB.

Getting the list of existing databases


We can get the list of all the databases by using the following MySQL query.

1. >  show databases;  
Example
1. import mysql.connector  
2.   
3. #Create the connection object   
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  
5.   
6. #creating the cursor object  
7. cur = myconn.cursor()  
8.   
9. try:  
10.     dbs = cur.execute("show databases")  
11. except:  
12.     myconn.rollback()  
13. for x in cur:  
14.     print(x)  
15. myconn.close()  

Creating the new database


The new database can be created by using the following SQL query.

create database <database-name>    

Example
import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  
  
#creating the cursor object  
cur = myconn.cursor()  
  
try:  
    #creating a new database  
    cur.execute("create database PythonDB2")  
  
    #getting the list of all the databases which will now include the new database PythonDB  
    dbs = cur.execute("show databases")  
      
except:  
    myconn.rollback()  
  
for x in cur:  
        print(x)  
          
myconn.close()  

Creating the table


41
In this section of the tutorial, we will create the new table Employee. We have to mention the database name while establishing the
connection object.

We can create the new table by using the CREATE TABLE statement of SQL. In our database PythonDB, the table Employee will have the
four columns, i.e., name, id, salary, and department_id initially.

The following query is used to create the new table Employee.

1. >  create table Employee (name varchar(20) not null, id int primary key, salary float not null, Dept_Id int 
Example

import mysql.connector  

#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
#creating the cursor object  
cur = myconn.cursor()  
  
try:  
    #Creating a table with name Employee having four columns i.e., name, id, salary, and department id  
    dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primary key, salary float not null, Dept_id int not n
ull)")  
except:  
    myconn.rollback()  
  
myconn.close()  

Alter Table
Sometimes, we may forget to create some columns, or we may need to update the table schema. The alter statement used to alter the
table schema if required. Here, we will add the column branch_name to the table Employee. The following SQL query is used for this
purpose.

1. alter table Employee add branch_name varchar(20) not null  

Consider the following example.

Example

import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
#creating the cursor object  
cur = myconn.cursor()  
  
42
try:  
    #adding a column branch name to the table Employee  
    cur.execute("alter table Employee add branch_name varchar(20) not null")  
except:  
    myconn.rollback()  
  
myconn.close()  

Insert Operation
Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can mention the format specifier (%s) in place of values.

We provide the actual values in the form of tuple in the execute() method of the cursor.

Consider the following example.

Example
import mysql.connector  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
#creating the cursor object  
cur = myconn.cursor()  
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"  
  
#The row values are provided in the form of tuple   
val = ("John", 110, 25000.00, 201, "Newyork")  
  
try:  
    #inserting the values into the table  
    cur.execute(sql,val)  
  
    #commit the transaction   
    myconn.commit()  
      
except:  
    myconn.rollback()  
  
print(cur.rowcount,"record inserted!")  
myconn.close()  

Read Operation
The SELECT statement is used to read the values from the databases. We can restrict the output of a select query by using various clause
in SQL like where, limit, etc.

Python provides the fetchall() method returns the data stored inside the table in the form of rows. We can iterate the result to get the
individual rows.

In this section of the tutorial, we will extract the data from the database by using the python script. We will also format the output to
print it on the console.

Example
import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
43
#creating the cursor object  
cur = myconn.cursor()  
  
try:  
    #Reading the Employee data      
    cur.execute("select * from Employee")  
  
    #fetching the rows from the cursor object  
    result = cur.fetchall()  
    #printing the result  
      
    for x in result:  
        print(x);  
except:  
    myconn.rollback()  
  
myconn.close()

Reading specific columns


We can read the specific columns by mentioning their names instead of using star (*).

In the following example, we will read the name, id, and salary from the Employee table and print it on the console.

Example
import mysql.connector  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
#creating the cursor object  
cur = myconn.cursor()  
try:  
    #Reading the Employee data      
    cur.execute("select name, id, salary from Employee")  
  
    #fetching the rows from the cursor object  
    result = cur.fetchall()  
    #printing the result  
    for x in result:  
        print(x);  
except:  
    myconn.rollback()  
myconn.close()  

The fetchone() method


The fetchone() method is used to fetch only one row from the table. The fetchone() method returns the next row of the result-set.

Consider the following example.

Example
import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
#creating the cursor object  
cur = myconn.cursor()  
  
try:  
    #Reading the Employee data      

44
    cur.execute("select name, id, salary from Employee")  
  
    #fetching the first row from the cursor object  
    result = cur.fetchone()  
  
    #printing the result  
    print(result)  
  
except:  
    myconn.rollback()  
      
myconn.close()  

Update Operation
The UPDATE-SET statement is used to update any column inside the table. The following SQL query is used to update a column.

update Employee set name = 'alex' where id = 110  

Consider the following example.

Example
import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
#creating the cursor object  
cur = myconn.cursor()  
  
try:  
    #updating the name of the employee whose id is 110  
    cur.execute("update Employee set name = 'alex' where id = 110")  
    myconn.commit()  
except:  
      
    myconn.rollback()  
  
myconn.close()  

Delete Operation
The DELETE FROM statement is used to delete a specific record from the table. Here, we must impose a condition using WHERE clause
otherwise all the records from the table will be removed.

The following SQL query is used to delete the employee detail whose id is 110 from the table.

 delete from Employee where id = 110  

Example

import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  
  
#creating the cursor object  
cur = myconn.cursor()  
  

45
try:  
    #Deleting the employee details whose id is 110  
    cur.execute("delete from Employee where id = 110")  
    myconn.commit()  
except:  
      
    myconn.rollback()  
  
myconn.close()  

Python NumPy Tutorial

Our Python NumPy Tutorial provides the basic and advanced concepts of the NumPy. Our NumPy tutorial is designed for beginners and
professionals.

NumPy stands for numeric python which is a python package for the computation and processing of the multidimensional and single
dimensional array elements.

What is NumPy

NumPy stands for numeric python which is a python package for the computation and processing of the multidimensional and single
dimensional array elements.

Travis Oliphant created NumPy package in 2005 by injecting the features of the ancestor module Numeric into another module
Numarray.

t is an extension module of Python which is mostly written in C. It provides various functions which are capable of performing the
numeric computations with a high speed.

NumPy provides various powerful data structures, implementing multi-dimensional arrays and matrices. These data structures are used
for the optimal computations regarding arrays and matrices.

46
In this tutorial, we will go through the numeric python library NumPy.

The need of NumPy

With the revolution of data science, data analysis libraries like NumPy, SciPy, Pandas, etc. have seen a lot of growth. With a much easier
syntax than other programming languages, python is the first choice language for the data scientist.

NumPy provides a convenient and efficient way to handle the vast amount of data. NumPy is also very convenient with Matrix
multiplication and data reshaping. NumPy is fast which makes it reasonable to work with a large set of data.

There are the following advantages of using NumPy for data analysis.

1. NumPy performs array-oriented computing.


2. It efficiently implements the multidimensional arrays.
3. It performs scientific computations.
4. It is capable of performing Fourier Transform and reshaping the data stored in multidimensional arrays.
5. NumPy provides the in-built functions for linear algebra and random number generation.

Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the replacement to MATLAB as Python is more complete and
easier programming language than MATLAB.

NumPy Environment Setup


NumPy doesn't come bundled with Python. We have to install it using the python pip installer. Execute the following command.

 pip install numpy   

It is best practice to install NumPy with the full SciPy stack. The binary distribution of the SciPy stack is specific to the operating systems.

Windows
On the Windows operating system, The SciPy stack is provided by the Anaconda which is a free distribution of the Python SciPy
package.

It can be downloaded from the official website: https://www.anaconda.com/. It is also available for Linux and Mac.

Linux
In Linux, the different package managers are used to install the SciPy stack. The package managers are specific to the different
distributions of Linux. Let's look at each one of them.

Ubuntu
Execute the following command on the terminal.

$ sudo apt-get install python-numpy  
  
$ python-scipy python-matplotlibipythonipythonnotebook python-pandas  
  
$ python-sympy python-nose  

Redhat
On Redhat, the following commands are executed to install the Python SciPy package stack.

$ sudo yum install numpyscipy python-matplotlibipython   
  
$ python-pandas sympy python-nose atlas-devel   

NumPy Ndarray

47
Ndarray is the n-dimensional array object defined in the numpy which stores the collection of the similar type of elements. In other
words, we can define a ndarray as the collection of the data type (dtype) objects.

The ndarray object can be accessed by using the 0 based indexing. Each element of the Array object contains the same size in the
memory.

The ndarray object can be created by using the array routine of the numpy module. For this purpose, we need to import the numpy.

1. >>> a = numpy.array

Creating a ndarray object


The ndarray object can be created by using the array routine of the numpy module. For this purpose, we need to import the numpy.

1. >>> a = numpy.array  

We can also pass a collection object into the array routine to create the equivalent n-dimensional array. The syntax is given below.

1. >>> numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)  

The parameters are described in the following table.

S Paramete Description
N r

1 object It represents the collection object. It can be a list, tuple, dictionary, set, etc.

2 dtype We can change the data type of the array elements by changing this option to
the specified type. The default is none.

3 copy It is optional. By default, it is true which means the object is copied.

4 order There can be 3 possible values assigned to this option. It can be C (column
order), R (row order), or A (any)

5 subok The returned array will be base class array by default. We can change this to
make the subclasses passes through by setting this option to true.

6 ndmin It represents the minimum dimensions of the resultant array.

To create an array using the list, use the following syntax.

 a = numpy.array([1, 2, 3])  

To create a multi-dimensional array object, use the following syntax.

>>> a = numpy.array([[1, 2, 3], [4, 5, 6]])  

To change the data type of the array elements, mention the name of the data type along with the collection.

48
1. >>> a = numpy.array([1, 3, 5, 7], complex)  

Finding the dimensions of the Array


The ndim function can be used to find the dimensions of the array.

>>> import numpy as np  
>>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])  
  
>>> print(arr.ndim)  

Finding the size of each array element


The itemsize function is used to get the size of each array item. It returns the number of bytes taken by each array element.

Consider the following example.

Example

#finding the size of each item in the array  
import numpy as np  
a = np.array([[1,2,3]])  
print("Each item contains",a.itemsize,"bytes")  

Finding the shape and size of the array


To get the shape and size of the array, the size and shape function associated with the numpy array is used.

Consider the following example.

Example

import numpy as np  
a = np.array([[1,2,3,4,5,6,7]])  
print("Array Size:",a.size)  
print("Shape:",a.shape)  

Reshaping the array objects


By the shape of the array, we mean the number of rows and columns of a multi-dimensional array. However, the numpy module
provides us the way to reshape the array by changing the number of rows and columns of the multi-dimensional array.

The reshape() function associated with the ndarray object is used to reshape the array. It accepts the two parameters indicating the row
and columns of the new shape of the array.

Let's reshape the array given in the following image.

49
Example

import numpy as np  
a = np.array([[1,2],[3,4],[5,6]])  
print("printing the original array..")  
print(a)  
a=a.reshape(2,3)  
print("printing the reshaped array..")  
print(a)  

Slicing in the Array


Slicing in the NumPy array is the way to extract a range of elements from an array. Slicing in the array is performed in the same way as it
is performed in the python list.

Consider the following example to print a particular element of the array.

Example

import numpy as np  
a = np.array([[1,2],[3,4],[5,6]])  
print(a[0,1])  
print(a[2,0])  

NumPy Broadcasting
In Mathematical operations, we may need to consider the arrays of different shapes. NumPy can perform such operations where the
array of different shapes are involved.

For example, if we consider the matrix multiplication operation, if the shape of the two matrices is the same then this operation will be
easily performed. However, we may also need to operate if the shape is not similar.

Consider the following example to multiply two arrays.

Example

import numpy as np  
a = np.array([1,2,3,4,5,6,7])  
b = np.array([2,4,6,8,10,12,14])  
c = a*b;  
print(c)  

However, in the above example, if we consider arrays of different shapes, we will get the errors as shown below.

Example

import numpy as np  
a = np.array([1,2,3,4,5,6,7])  
b = np.array([2,4,6,8,10,12,14,19])  
c = a*b;  
print(c)  

50
NumPy Array Iteration
NumPy provides an iterator object, i.e., nditer which can be used to iterate over the given array using python standard Iterator interface.

Consider the following example.

Example

import numpy as np  
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])  
print("Printing array:")  
print(a);  
print("Iterating over the array:")  
for x in np.nditer(a):  
    print(x,end=' ')  

Order of the iteration doesn't follow any special ordering like row-major or column-order. However, it is intended to match the memory
layout of the array.

Example

import numpy as np  
a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]])  
print("Printing the array:")  
print(a)  
print("Printing the transpose of the array:")  
at = a.T  
print(at)  
  
#this will be same as previous   
for x in np.nditer(at):  
    print(print("Iterating over the array:")  
for x in np.nditer(a):  
    print(x,end=' ')  

NumPy Mathematical Functions


Numpy contains a large number of mathematical functions which can be used to perform various mathematical operations. The
mathematical functions include trigonometric functions, arithmetic functions, and functions for handling complex numbers. Let's discuss
the mathematical functions.

Trigonometric functions
Numpy contains the trigonometric functions which are used to calculate the sine, cosine, and tangent of the different angles in radian.

The sin, cos, and tan functions return the trigonometric ratio for the specified angles. Consider the following example.

Example

import numpy as np  
arr = np.array([0, 30, 60, 90, 120, 150, 180])  
print("\nThe sin value of the angles",end = " ")  
print(np.sin(arr * np.pi/180))  
51
print("\nThe cosine value of the angles",end = " ")  
print(np.cos(arr * np.pi/180))  
print("\nThe tangent value of the angles",end = " ")  
print(np.tan(arr * np.pi/180))  

On the other hand, arcsin(), arccos(), and arctan() functions return the trigonometric inverse of the specified angles.

The numpy.degrees() function can be used to verify the result of these trigonometric functions. Consider the following example.

Example

import numpy as np  
arr = np.array([0, 30, 60, 90])  
print("printing the sin values of different angles")  
  
sinval = np.sin(arr*np.pi/180)  
  
print(sinval)  
print("printing the inverse of the sin")  
cosec = np.arcsin(sinval)  
  
print(cosec)  
  
print("printing the values in degrees")  
print(np.degrees(cosec))  
  
print("\nprinting the cos values of different angles")  
cosval = np.cos(arr*np.pi/180)  
  
print(cosval)  
print("printing the inverse of the cos")  
sec = np.arccos(cosval)  
print(sec)  
  
print("\nprinting the values in degrees")  
print(np.degrees(sec))  
  
print("\nprinting the tan values of different angles")  
tanval = np.tan(arr*np.pi/180)  
  
print(tanval)  
print("printing the inverse of the tan")  
cot = np.arctan(tanval)  
print(cot)  
  
print("\nprinting the values in degrees")  
print(np.degrees(cot))  

Rounding Functions
The numpy provides various functions that can be used to truncate the value of a decimal float number rounded to a particular
precision of decimal numbers. Let's discuss the rounding functions.

The numpy.around() function


This function returns a decimal value rounded to a desired position of the decimal. The syntax of the function is given below.

52
1. numpy.around(num, decimals)  

It accepts the following parameters.

S Paramete Description
N r

1 num It is the input number.

2 decimals It is the number of decimals which to which the number is to be rounded. The
default value is 0. If this value is negative, then the decimal will be moved to the
left.

Consider the following example.

Example

import numpy as np  
arr = np.array([12.202, 90.23120, 123.020, 23.202])  
print("printing the original array values:",end = " ")  
print(arr)  
print("Array values rounded off to 2 decimal position",np.around(arr, 2))  
print("Array values rounded off to -1 decimal position",np.around(arr, -1))  

The numpy.floor() function


This function is used to return the floor value of the input data which is the largest integer not greater than the input value. Consider
the following example.

Example

1. import numpy as np  
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])  
3. print(np.floor(arr))  

The numpy.ceil() function


This function is used to return the ceiling value of the array values which is the smallest integer value greater than the array element.
Consider the following example.

Example

1. import numpy as np  
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])  
3. print(np.ceil(arr))  

Numpy statistical functions


Numpy provides various statistical functions which are used to perform some statistical data analysis. In this section of the tutorial, we
will discuss the statistical functions provided by the numpy.

Finding the minimum and maximum elements from the array


The numpy.amin() and numpy.amax() functions are used to find the minimum and maximum of the array elements along the specified
axis respectively.

Consider the following example.

53
Example

import numpy as np  
  
a = np.array([[2,10,20],[80,43,31],[22,43,10]])  
  
print("The original array:\n")  
print(a)  
print("\nThe minimum element among the array:",np.amin(a))  
print("The maximum element among the array:",np.amax(a))  
  
print("\nThe minimum element among the rows of array",np.amin(a,0))  
print("The maximum element among the rows of array",np.amax(a,0))  
  
print("\nThe minimum element among the columns of array",np.amin(a,1))  
print("The maximum element among the columns of array",np.amax(a,1))  

54

You might also like