Adv Python
Adv Python
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.
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
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.
Syntax
1. fileobject.close()
# 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.
try:
fileptr = open("file.txt")
# perform file operations
finally:
fileptr.close()
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.
Example
with open("file.txt",'r') as f:
content = f.read();
print(content)
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.
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()
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:
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.
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.
#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:
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.
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:
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.
#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.']
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.
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:
# 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())
For this purpose, the Python provides us the seek() method which enables us to modify the file pointer position externally.
Syntax:
1. <file-ptr>.seek(offset[, from)
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.
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")
1. remove(file-name)
Example 1
import os;
#deleting the file named file3.txt
os.remove("file3.txt")
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.
Syntax
1. os.getcwd()
Example
1. import os
2. os.getcwd()
The chdir() method is used to change the current working directory to a specified directory.
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.
Syntax
1. os.rmdir(directory name)
Example 1
import os
#removing the new directory
9
os.rmdir("directory_name")
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)
S Method Description
N
1 file.close() It closes the opened file. The file once closed, it can't be read or write
anymore.
4 File.isatty() It returns true if the file is connected to a TTY device, otherwise returns
false.
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.
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.
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.
Example –
# Python program showing
# a use of raw_input()
name = raw_input("Enter your name : ")
print name
We can check the Python version in our running script. Consider the following ways to know Python version in all operating systems.
12
platform.python_version(
)
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.
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.
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.
example.
Cats, horses, cows, dogs, etc., all are part of class animalia. They all share some common characteristics also:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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()
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")
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()
Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,self.name)
st = Student()
st.display()
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.
SN Function Description
2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object.
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)
SN Attribute Description
1 __dict__ It provides the dictionary containing the information about the class namespace.
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()
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()
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 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.
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))
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.
Example
1.
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
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());
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.
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.
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.
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.
# 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.
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.
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 *.
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.
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))
Example
import json
List = dir(json)
print(List)
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.
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.
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.
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.
31
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
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")
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")
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()
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")
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.
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.
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")
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.
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)
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.
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.
1. import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print(time.time())
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.
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
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())
Example
1. import datetime
2. #returns the datetime object for the specified date
3. print(datetime.datetime(2020,04,04))
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)
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.
1. > python -m pip install mysql-connector
https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b8660d09f91d8d5411298bcacbd309f96/mysql-
connector-python-8.0.13.tar.gz to download the source code.
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
$ 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.
Pass the database details like HostName, username, and the database password in the method call. The method returns the connection
object.
1. Connection-Object= mysql.connector.connect(host = <host-name> , user = <username> , passwd = <password> )
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)
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)
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()
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()
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.
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
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.
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()
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()
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
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()
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.
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.
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.
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
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)
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.
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.
a = numpy.array([1, 2, 3])
>>> 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)
>>> import numpy as np
>>> arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
>>> print(arr.ndim)
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")
Example
import numpy as np
a = np.array([[1,2,3,4,5,6,7]])
print("Array Size:",a.size)
print("Shape:",a.shape)
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.
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)
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.
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.
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=' ')
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.
52
1. numpy.around(num, decimals)
S Paramete Description
N r
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.
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))
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.floor(arr))
Example
1. import numpy as np
2. arr = np.array([12.202, 90.23120, 123.020, 23.202])
3. print(np.ceil(arr))
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