You are on page 1of 37

CO1 - Material

1.Python OOPs Concepts

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-world 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.

• Class
• Object
• Method
• Inheritance
• Polymorphism
• Data Abstraction
• 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.
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.

1
Example:

class student:
def __init__(self,studname, regno):
self.studentname = studname
self.regno = regno
def display(self):
print(self.studname,self.regno)

s1 = student("Ram", 1908)
s1.display()

Output:

Ram 1908

In the above example, we have created the class named student, and it has two attributes
studname and regno. We have created a s1 object to access the class attribute. The 11 object will
allocate memory for these values.

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.

2
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.

Python Class and Objects

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.

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

class ClassName:
#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.
3
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.

Example

class Employee:
id = 10
name = "John"
def display (self):
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.

<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()
4
emp.display()

Output:

ID: 10
Name: John

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.

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()
# 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.
5
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()

Output:
ID: 101
Name: John
ID: 102
Name: David

6
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)

Output:

The number of students: 3

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")
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
7
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()

Output:

This is parameterized constructor

Hello John

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()

Output:

101 Joseph

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another
class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

8
Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

Create a class named Person, with firstname and lastname properties, and
a printname method:

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Smith")
x.printname()

Output:

John Smith

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:

Example

Create a class named Student, which will inherit the properties and methods from
the Person class:

class Student(Person):
pass

9
Note: Use the pass keyword when you do not want to add any other properties or methods to the
class.

Now the Student class has the same properties and methods as the Person class.

Example

Use the Student class to create an object, and then execute the printname method:

x = Student("Srinvasa", "Rao")
x.printname()

Output:-

Srinivasa Rao

Add the __init__() Function

We have created a child class that inherits the properties and methods from its parent.

We want to add the __init__() function to the child class (instead of the pass keyword).

Note: The __init__() function is called automatically every time the class is being used to create
a new object.

Example

Add the __init__() function to the Student class:

class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the


parent's __init__() function.

10
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

x = Student("Srinivasa", "Rao")
x.printname()

Output:
Srinivasa Rao

Now we have successfully added the __init__() function, and kept the inheritance of the parent
class, and we are ready to add functionality in the __init__() function.

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)

x = Student("John", "Smith")
11
x.printname()

Output :

John Smith

By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.

2. Collections
Python Lists
mylist = ["apple", "banana", "cherry"]
List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example

Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the
items will not change.

12
Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has
been created.

Allow Duplicates

Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types

List items can be of any data type:

Example

String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

13
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))

The list() Constructor

It is also possible to use the list() constructor when creating a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets


print(thislist)

Python Collections (Arrays)

There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate members.


• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered and unindexed. No duplicate members.
• Dictionary is a collection which is unordered and changeable. No duplicate members.

When choosing a collection type, it is useful to understand the properties of that type. Choosing
the right type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security

Access Items

List items are indexed and you can access them by referring to the index number:

Example

Print the second item of the list:


thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Note: The first item has index 0.
14
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:

Example

This example returns the items from the beginning to, but NOT included, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from "cherry" and to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:

15
Example

This example returns the items from "orange" (-4) to, but NOT included. "mango" (-1):

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1])

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

Python - Loop Lists


Loop Through a List
You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Learn more about for loops in our Python For Loops Chapter.

Loop Through the Index Numbers


You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.

Example

Print all items by referring to their index number:

16
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])

The iterable created in the example above is [0, 1, 2].

List Methods

Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the


specified value

extend() Add the elements of a list (or any iterable), to


the end of the current list

index() Returns the index of the first element with the


specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

17
remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python Tuples
Tuple

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example

Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.

18
Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
has been created.

Allow Duplicates

Since tuple are indexed, tuples can have items with the same value:

Example

Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length

To determine how many items a tuple has, use the len() function:

Example

Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python
will not recognize it as a tuple.

Example

One item tuple, remember the commma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
19
Tuple Items - Data Types

Tuple items can be of any data type:

Example

String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple can contain different data types:

Example

A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")

type()

From Python's perspective, tuples are defined as objects with the data type 'tuple':

<class 'tuple'>

Example

What is the data type of a tuple?

mytuple = ("apple", "banana", "cherry")


print(type(mytuple))

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

Example

Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)

20
Tuple Methods

Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value


occurs in a tuple

index() Searches the tuple for a specified value and


returns the position of where it was found

Set

Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is both unordered and unindexed.

Sets are written with curly brackets.

Example

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

21
Set items can appear in a different order every time you use them, and cannot be referred to by
index or key.

Unchangeable

Sets are unchangeable, meaning that we cannot change the items after the set has been created.

Once a set is created, you cannot change its items, but you can add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Example

Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

Get the Length of a Set

To determine how many items a set has, use the len() method.

Example

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Set Items - Data Types

Set items can be of any data type:

Example

String, int and boolean data types:

22
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

Example

A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}

type()

From Python's perspective, sets are defined as objects with the data type 'set':

<class 'set'>

Example

What is the data type of a set?

myset = {"apple", "banana", "cherry"}


print(type(myset))

The set() Constructor

It is also possible to use the set() constructor to make a set.

Example

Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets


print(thisset)

Python Dictionaries
Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is unordered, changeable and does not allow duplicates.
23
Dictionaries are written with curly brackets, and have keys and values:

Example

Create and print a dictionary:

thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items

Dictionary items are unordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example

Print the "brand" value of the dictionary:

thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Unordered

When we say that dictionaries are unordered, it means that the items does not have a defined
order, you cannot refer to an item by using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
24
Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example

Duplicate values will overwrite existing values:

thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Dictionary Length

To determine how many items a dictionary has, use the len() function:

Example

Print the number of items in the dictionary:

print(len(thisdict))

Dictionary Items - Data Types

The values in dictionary items can be of any data type:

Example

String, int, boolean, and list data types:

thisdict ={
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]

25
Python Exception handling

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.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.

These exceptions can be handled using the try statement:

Example

The try block will generate an exception, because x is not defined:


26
#The try block will generate an error, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Output:
An exception occurred

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example

This statement will raise an error, because x is not defined:

#This will raise an exception, because x is not defined:


print(x)

Output:
Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in <module>
print(x)
NameError: name 'x' is not defined

Roles of Exceptional Handling in Python

• Error handling: The exceptions get raised whenever Python detects an error in a
program at runtime. As a programmer, if you don't want the default behavior, then code
a 'try' statement to catch and recover the program from an exception. Python will jump
to the 'try' handler when the program detects an error; the execution will be resumed.
• Event Notification: Exceptions are also used to signal suitable conditions & then passing
result flags around a program and text them explicitly.

27
• Terminate Execution: There may arise some problems or errors in programs that it
needs a termination. So try/finally is used that guarantees that closing-time operation
will be performed. The 'with' statement offers an alternative for objects that support it.
• Exotic flow of Control: Programmers can also use exceptions as a basis for
implementing unusual control flow. Since there is no 'go to' statement in Python so that
exceptions can help in this respect.
Example

>>> (x,y) = (696,0)


>>> try:# simple use of try-except block for handling errors
... z = x/y
... except ZeroDivisionError:
... print ("This is a DIVIDED BY ZERO error")
...
This is a DIVIDED BY ZERO error
>>>

The ‘try-Except’ Clause with No Exception

The structure of such type of 'except' clause having no exception is shown with an example.
try:

# all operations are done within this block.


......
except:
# this block will get executed if any exception encounters.
......
else:
# this block will get executed if no exception is found.

......

All the exceptions get caught where there is try/except the statement of this type. Good
programmers use this technique of exception to make the program fully executable.

‘except’ Clause with Multiple Exceptions

try:
# all operations are done within this block.
......
except ( Exception1 [, Exception2[,….Exception N ] ] ] ) :
28
# this block will get executed if any exception encounters from the above lists of exceptions.
......
else:
# this block will get executed if no exception is found.
......

The ‘try-Finally’ Clause


try:
# all operations are done within this block.
......
# if any exception encounters, this block may get skipped.
finally:
......
# this block will definitely be executed.

Pytest
Pytest is a testing framework based on python. It is mainly used to write API test cases. This
tutorial helps you understand −

• Installation of pytest.
• Various concepts and features of pytest

Pytest is a python based testing framework, which is used to write and execute test codes. In the
present days of REST services, pytest is mainly used for API testing even though we can use
pytest to write simple to complex tests, i.e., we can write codes to test API, database, UI, etc.
Advantages of Pytest
The advantages of Pytest are as follows −
• Pytest can run multiple tests in parallel, which reduces the execution time of the test
suite.
• Pytest has its own way to detect the test file and test functions automatically, if not
mentioned explicitly.
• Pytest allows us to skip a subset of the tests during execution.
• Pytest allows us to run a subset of the entire test suite.
• Pytest is free and open source.
• Because of its simple syntax, pytest is very easy to start with.

29
Install pytest

1. Run the following command in your command line:


C:\Users\admin>pip install -U pytest
2. Check that you installed the correct version:
C:\Users\admin>python --version
Python 3.9.0
Example

Square.py

import math
def test_sqrt():
num = 25
assert math.sqrt(num) == 5
def testsquare():
num = 7
assert 7*7 == 40
def tesequality():
assert 10 == 11

output

E:\auto>pytest square.py
================================================================== test
session starts
===================================================================
platform win32 -- Python 3.9.0, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: E:\auto
collected 2 items
square.py .F
[100%]
=====================================================================
=== FAILURES
=====================================================================
===
_______________________________________________________________________
testsquare
_______________________________________________________________________
def testsquare():
num = 7
> assert 7*7 == 40
E assert (7 * 7) == 40
30
square.py:9: AssertionError
================================================================ short
test summary info
=================================================================
FAILED square.py::testsquare - assert (7 * 7) == 40
============================================================== 1 failed,
1 passed in 0.10s
===============================================================

MongoDB
MongoDB is a document-oriented, open-source database program that is platform-independent.
MongoDB, like some other NoSQL databases , stores its data in documents using a JSON
structure. This is what allows the data to be so flexible and not require a schema.

Some of the more important features are:

• You have support for many of the standard query types, like matching (==), comparison
(<, >), or even regex
• You can store virtually any kind of data - be it structured, partially structured, or even
polymorphic
• To scale up and handle more queries, just add more machines
• It is highly flexible and agile, allowing you to quickly develop your applications
• Being a document-based database means you can store all the information regarding your
model in a single document
• You can change the schema of your database on the fly
• Many relational database functionalities are also available in MongoDB (e.g. indexing)

As for the operations side of things, there are quite a few tools and features for MongoDB that
you just can’t find with any other database system:

• Whether you need a standalone server or complete clusters of independent servers,


MongoDB is as scalable as you need it to be
• MongoDB also provides load balancing support by automatically moving data across the
various shards
• It has automatic failover support - in case your primary server goes down, a new primary
will be up and running automatically
• The MongoDB Management Service or MMS is a very nice web tool that provides you
with the ability to track your machines
• Thanks to the memory mapped files, you’ll save quite a bit of RAM, unlike relational
databases

31
If you take advantage of the indexing features, much of this data will be kept in memory for
quick retrieval. And even without indexing on specific document keys, Mongo caches quite a bit
of data using the least recently used method.

While at first Mongo may seem like it’s the solution to many of our database problems, it isn’t
without its drawbacks. One common drawback you’ll hear about Mongo is its lack of support for
ACID transactions. Mongo does support ACID transactions in a limited sense, but not in all
cases. At the single-document level, ACID transactions are supported (which is where most
transactions take place anyway). However, transactions dealing with multiple documents are not
supported due to Mongo’s distributed nature.

Mongo also lacks support for native joins, which must be done manually (and therefore much
more slowly). Documents are meant to be all-encompassing, which means, in general, they
shouldn’t need to reference other documents. In the real world this doesn’t always work as much
of the data we work with is relational by nature. Therefore many will argue that Mongo should
be used as a complementary database to a SQL DB, but as you use MongoDB you’ll find that is
not necessarily true.

Create Python File

from pymongo import MongoClient # import mongo client to connect


import pprint
# Creating instance of mongoclient
client = MongoClient()
# Creating database
db = client.klu
student = {"regno": "1099",
"name": "RAM",
"dept": "CSE",
}
# Creating document
students = db.students
# Inserting data
students.insert_one(student)
# Fetching data
pprint.pprint(students.find_one())

Output:
E:\auto>python pymongoconnect.py
{'_id': ObjectId('5fd0945d020d5ae6da5ac9a9'),
'dept': 'CSE',
'name': 'RAM',
'regno': '1099'}

32
Check Databases

The following command is used to show available databases.

> show dbs


admin 0.000GB
config 0.000GB
klu 0.000GB
local 0.000GB

Check Collection

The following command is used to show available collection into the database

> show collections

Python – MySQL

MySQL is an Open-Source database and one of the best type of RDBMS (Relational Database
Management System).

Install MySQL Connector Library for Python

For Python 2.7 or lower install using pip as:

pip install mysql-connector

For Python 3 or higher version install using pip3 as:

pip3 install mysql-connector

Procedure To Follow In Python To Work With MySQL


1. Connect to the database.
2. Create an object for your database.
3. Execute the SQL query.
4. Fetch records from the result.
5. Informing the Database if you make any changes in the table.

1. Installing MySQL

MySQL is one of the most popular databases.

33
Download and install MySQL from the MySQL's official website. You need to install
the MySQL server to follow this tutorial.

Next, you have to install mysql.connector for Python. We need mysql.connector to


connect Python Script to the MySQL database. Download
the mysql.connector from here and install it on your computer.

Now, check whether you have installed the mysql.connector correctly or not using the
following code.

Import mysql.connector

If the above code runs without any errors, then you have successfully installed mysql.connector,
and it is ready to use.

2. Connecting And Creating


Now, we will connect to the database using username and password of MySQL. If you don't
remember your username or password, create a new user with a password.
To create a new user refer to MySQL official documentation.
Now, connect to the database using your username and password

## Connecting to the database

## importing 'mysql.connector' as mysql for convenient


import mysql.connector as mysql

## connecting to the database using 'connect()' method


## it takes 3 required parameters 'host', 'user', 'passwd'
db = mysql.connect(
host = "localhost",
user = "root",
passwd = "passwd"
)

print(db) # it will print a connection object if everything is fine

34
2.1. Creating Databases
Now, we will create a database with the name klucse.
To create a database in MySQL, we use CREATE DATABASE database_name statement.

import mysql.connector as mysql


db = mysql.connect(
host = "localhost",
user = "root",
passwd = "passwd"
)

## creating an instance of 'cursor' class which is used to execute the 'SQL' statements in 'Python'
cursor = db.cursor()

## creating a databse called 'klucse'


## 'execute()' method is used to compile a 'SQL' statement
## below statement is used to create the 'klucse' database
cursor.execute("CREATE DATABASE klucse")

If the database already exists you will get an error. Make sure that the database does not exist.
See all the databases present in MySQL using the following code.
To see all the databases we use SHOW DATABASES statement.
import mysql.connector as mysql

db = mysql.connect(
host = "localhost",
user = "root",
passwd = "passwd"
)

cursor = db.cursor()

## executing the statement using 'execute()' method


cursor.execute("SHOW DATABASES")

## 'fetchall()' method fetches all the rows from the last executed statement
databases = cursor.fetchall() ## it returns a list of all databases present

## printing the list of databases


print(databases)

## showing one by one database


for database in databases:
print(database)

35
Creating Tables
Creating tables in the database to store the information. Before creating tables, we must select a
database first.
Run the following code, to select klucse database.
Use the CREATE TABLE table_name to create a table in the selected database.

import mysql.connector as mysql

db = mysql.connect(
host = "localhost",
user = "root",
passwd = "dbms",
database = "datacamp"
)

cursor = db.cursor()

## creating a table called 'users' in the 'datacamp' database


cursor.execute("CREATE TABLE users (name VARCHAR(255), user_name
VARCHAR(255))")

You have successfully created the table users in the klucse database. See all the tables present in
the database using the SHOW TABLES statement.

import mysql.connector as mysql


db = mysql.connect(
host = "localhost",
user = "root",
passwd = "passwd",
database = "klucse"
)
cursor = db.cursor()
## getting all the tables which are present in 'klucse' database
cursor.execute("SHOW TABLES")
tables = cursor.fetchall() ## it returns list of tables present in the database
## showing all the tables one by one
for table in tables:
print(table)

36
Inserting Data
Inserting data into table to store it. Use INSERT INTO table_name (column_names)
VALUES (data) statement to insert into the table.
Inserting A Single Row
Let's see how to insert a single row into the table.

import mysql.connector as mysql

db = mysql.connect(
host = "localhost",
user = "root",
passwd = "passwd",
database = "klucse"
)
cursor = db.cursor()
## defining the Query
query = "INSERT INTO users (name) VALUES (%s)"
## storing values in a variable
values = ("K.L.University”)
## executing the query with values
cursor.execute(query, values)
## to make final output we have to run the 'commit()' method of the database object
db.commit()
print(cursor.rowcount, "record inserted")

37

You might also like