Class 12th - LT - Junior Software Developer
Class 12th - LT - Junior Software Developer
Developer
(Job Role)
MEMBERS
1. Akshay Sharam, Govt. Hss Girls Narsinghgarh, Rajgarh, AISECT.
2. Aakrati Verma, Govt. Subhash Excellence, Bhopal, AISECT.
3. Amit Sondhiya, Govt. HSS Garh, Rewa, ICA.
4. Prakash Deshmukh, Govt. Hss Dharnakala, Seoni, Satyam.
5. Shashank Dhuper, Govt. HSS Girls PT. Ravishankar Sagar, Satyam.
Job Role – Junior Software Development for Class-XII. There are 05 Vocational Trainers from
SAMGRA SIKSHA ABHIYAN (Secondary Education) Bhopal M.P. attached to PSSCIVE Bhopal for
05 days between 5 June 2023 to 9 June 2023.
GUIDELINE MEMBER
Prerna Kumari, Assistant Professor (Contractual), Department of Engineering and Technology,
PSSCIVE, NCERT, Bhopal.
Page 3 of 200
CONTENTS
Page 4 of 200
Unit1. Relational Database Management System
Chapter 1. RDBMS Concepts
Kushal was playing with his father’s mobile phone. Accidentally all the contacts on the phone were
deleted by him. To recover these contacts his father consulted a technician. The technician recovered
all the contacts available using the Google contacts as these contacts are linked with the Google
account. Thus, it is possible to save and manage the contacts in a smartphone. This is possible with
the use of database applications available with Google. The data can be saved and managed through
database application.
In this session, you will understand the concept of the database and how data is organised in the
database. Data models and the various concepts associated with database application such as
constraints, primary key, foreign key is also discussed. There are various database management
software available in the market. We will discuss MySQL which is a popular Relational Database
Management System (RDBMS).
1.1 INTRODUCTION TO DATABASE SYSTEMS
The word data is taken from "Datum", which means raw facts. Datum is a single piece of factual
information of interest to us. Data, the plural of datum, is a collection of information. Data is the
name given to basic raw facts and entities such as names, numbers and quantity. Its data can be
defined as a collection of facts and records. Data, representing facts, figures, and ideas, are commonly
used in everyday life. it needs to be managed to use it effectively.
Data items are organised or processed to produce the information. It can be used for processing some
useful information from it. The examples of data are weights, prices, costs, numbers of items sold,
employee names, product names, addresses, tax codes, registration fees, obtained marks, reservation
details, images, sounds, multimedia and animated data. Data can exist in the form of text, graphics,
sound, video that represents every kind of information. The data items can be stored manually in a
diary. But it is difficult to retrieve and process the data items when there are a large number of data
items. Through the relational database systems, users can access a view of data called relations.
With Relational Database Management Systems (RDBMS), programmers can perform database
operations without knowing data storage details.
It is observed that the schools are maintaining the student data and that is stored in the register.
After several years of leaving the school, the student can get the duplicate of the school leaving
certificate. For issuing such certificates the office staff check the student data from the registers
which is maintained year-wise and class-wise. By checking the student record, the office staff can
easily give the certificate to the student. This is how the schools are maintaining the student data in
the register.
The office staff also manually maintain student details who are presently learning. Their Admission
number, Name, Date of Birth, Address, Contact Number are stored in the school register.
There are two major types of databases – Relational and Non-relational. Relational databases are the
most commonly used databases today. The following are several types of databases in use: -
Flat file databases – Stores data in permanent files that mostly are in text form;
Hierarchical databases – Arranges data in a tree-like structure;
Network database – Arranges data in network-like structure;
Relational databases – Contains a set of tables in which data are related;
Object databases – Represents information in the form of objects as used in object-oriented
programming.
1.2 FILE SYSTEM
Now you must have noticed that maintaining such types of records manually does not allow you to
correct, modify or delete the data in the register. Also, searching the details of the student is difficult.
Page 5 of 200
To overcome the hassles faced in manual record keeping, this data can be stored in a computer. The
student details are stored in the computer in the form of a separate file.
In computers, any contents are stored in the form of a file, which is opened and viewed in the
respective software. In a computer, a file is a container to store data or information. These files are
stored on the storage device of the computer, such as a hard disk drive or pen drive.
The student data can be stored in the document file or spreadsheet file. These files stored on the
computer can be accessed quickly. To process or manipulate this data, it is required to write the
program in computer programming languages. Various operations can be performed through
computer programming. It includes searching, sorting, computing the percentage of marks, number
of days attendance and retrieving the data.
1.2.1 Limitations of a File System
There are certain limitations to maintain and manipulate such types of data when there are several
hundreds or thousands of students. It also becomes difficult to maintain the number of files as it
increases the volume when data grows. There are certain limitations of the file system to maintain
such type of data. The limitations of file system are:
Difficulty in Access – Files themselves do not provide any mechanism to retrieve data. Data
maintained in a file system is accessed through application programs. While writing such programs,
the developer may not anticipate all the possible ways in which data may be accessed. So, sometimes
it is difficult to access data in the required format and one has to write an application program to
access data.
Data Redundancy – Redundancy means the same data is duplicated in different files. For example,
if we are maintaining student’s data for various purposes then data such as student names are
maintained in different files. The common data in all such files are required to be maintained a
number of times. This may cause data redundancy which is difficult to avoid in a file system.
Redundancy leads to excess storage use and may cause data inconsistency also.
Data Inconsistency – Data inconsistency occurs when the same data maintained in different places
do not match. If the student wants to change the spelling of their name, it needs to be changed in
the number of files where it appears. Likewise, if a student leaves school, the details need to be
deleted from these files. As the files are being maintained by different people, the changes may not
happen in one of the files. In that case, the student name will be different (inconsistent) in both the
files.
Data Isolation – Although these files are maintained for the students of the same class, there is no
link or mapping between these files. The school will have to write separate programs to access these
files. This is because data mapping is not supported in the file system. In a more complex system
where data files are generated by different people at different times, files being created in isolation
may be of different formats. In such cases, it is difficult to write new application programs to retrieve
data from different files.
Data Dependence – Data is stored through specific format or structure in a file. If the structure or
format itself is changed, all the existing application programs accessing that file also need to be
changed. Otherwise, the programs may not work correctly. This is data dependency. Hence, updating
the structure of a data file requires modification in all the application programs accessing that file.
Controlled Data Sharing – There can be different categories of users like teachers, office staff and
parents. Ideally, not every user should be able to access all the data. It means different types of users
should be given different types of access, such as read only. It is very difficult to enforce this kind of
access control in a file system while accessing files through application programs.
1.3 DATABASE MANAGEMENT SYSTEM
Limitations faced in file systems can be overcome by storing the data in a database where data are
logically related. The Database Management Systems (DBMSs) are used as an interface to manage
databases.
Page 6 of 200
A database is an organised collection of data, generally stored and accessed electronically from a
computer system. It supports the storage and manipulation of data. In other words, databases are
used by an organisation as a method of storing, managing and retrieving information. It is possible
to store and organise related data in a database so that it can be managed in an efficient and easy
way.
A DBMS is a collection of software components designed to create and maintain databases and
control all access to them. It used to create a database, store, manage, update/modify and retrieve
data from that database by users or application programs. It is used to provide an effective method
of performing database operations, troubleshooting database issues, and restricting data access.
Relational Database Management System (RDBMS), which is still popular today, is an advanced
version of a DBMS system. Dr. E. F. Codd defined the criteria to determine whether a DBMS is a
relational database management system or not. These criteria are known as Codd’s twelve rules. (E.
F. Codd, 1985).
Some examples of open source and commercial DBMS include MySQL, Oracle, PostgreSQL, SQL
Server, Microsoft Access, MongoDB etc. as presented in Table 1.1.
Table 1.1 Popular DBMS
DBMS Primary Database Model Licence
Oracle RDBMS Commercial (restricted free
version is available)
MySQL RDBMS Open Source
Microsoft SQL Server RDBMS Commercial (restricted free
version is available)
PostgreSQL RDBMS Open Source
MangoDB Document store Open Source
Some database management systems include a graphical user interface for users to create and
manage databases. Other database systems use a command line interface that requires users to
use programming commands to create and manage databases.
A database management system hides certain details about how data are actually stored and
maintained. Thus, it provides users with an abstract view of the data. A database system has a set
of programs through which users or other programs can access, modify and retrieve the stored data.
The DBMS serves as an interface between the database and end users or application programs.
Retrieving data from a database through a special type of commands is called Querying the database.
In addition, users can modify the structure of the database itself through a DBMS.
Databases are widely used in various fields. Some applications are given in Table 1.2.
Page 7 of 200
Table 1.2 Use of Database in Real-life Applications
Crop Loan Kisan credit card data, farmer’s personal data, land area
and cultivation data, loan history, repayment data etc.
Page 8 of 200
● Cost of Hardware and Software of a DBMS is quite high, which increases the budget of your
organisation.
● Most database management systems are often complex systems, so the training for users to use
the DBMS is required.
● The use of the same program at a time by many users sometimes lead to the loss of some data.
● DBMS can't perform sophisticated calculations.
● Data-sets begin to grow large as it provides a more predictable query response time.
● It required a processor with a high speed of data processing.
● The database can fail because of power failure or the whole system stops.
● The cost of DBMS is dependent on the environment, function, or recurrent annual maintenance
cost.
1.3.5 Comparison of Database Management System (DBMS) with File System
The comparative points of DBMS with File System are given in Table 1.3.
Table 1.3: Comparison of DBMS with File System
File System DBMS
A file system is a software that manages and DBMS or Database Management System is a
organises the files in a storage medium. It software application. It is used for accessing,
controls how data is stored and retrieved. creating, and managing databases.
The file system provides the details of data DBMS gives an abstract view of data that hides
representation and storage of data. the details.
Storing and retrieving of data can't be done DBMS is efficient to use as there are a wide
efficiently in a file system. variety of methods to store and retrieve data.
It does not offer data recovery processes. There is a backup recovery for data in DBMS.
The file system doesn't have a crash recovery DBMS provides a crash recovery mechanism
mechanism.
Protecting a file system is very difficult. DBMS offers a good protection mechanism.
In a file management system, the redundancy of The redundancy of data is low in the DBMS
data is greater. system.
Data inconsistency is higher in the file system. Data inconsistency is low in a database
management system.
The file system offers lesser security. Database Management System offers high
security.
File System allows you to store the data as Database Management System stores data as
isolated data files and entities. well as defined constraints and interrelation.
It does not provide support for complicated Easy to implement complicated transactions.
transactions.
The centralization process is hard in the File Centralization is easy to achieve in the DBMS
Management System. system.
It doesn't offer backup and recovery of data if it DBMS systems provide backup and recovery of
is lost. data even if it is lost.
There is no efficient query processing in the file You can easily query data in a database using
Page 9 of 200
system. the SQL language.
This system doesn't offer concurrency. DBMS system provides a concurrency facility.
1.4 Key Concepts in DBMS
It is important to understand the following concepts to efficiently manage data using a DBMS.
(A) Database schema
A database schema is a set of schemas for a database's relations. It consists of tables with all
attributes with their data types and constraints if any. It also represents the relationships among the
tables. It is used to visualise the logical architecture of a database and how the data are organised in
a database. The schema of a relation may not change, but the relation, which is a variable, changes
over time.
Page 10 of 200
called an Insertion operation on the database. In case a student leaves the school, then student as
well as parent data need to be removed from StudentRecord, ParentRecord and AttendanceRecord
tables, respectively. This is called Deletion operation on the database. Suppose Rivaan’s Parent has
changed his mobile number, his Par_Phone should be updated in the ParentRecord file. This is called
an Update operation on the database.
(G) Database Engine
Database engine is the underlying component or set of programs used by a DBMS to create a
database and handle various queries for data retrieval and manipulation.
1.5 RELATIONAL DATA MODEL
A data model describes the structure of the database and represents data. It defines and represents
relationships among relations. In database design, first the conceptual data model is designed for
non-technical users. Then, based on the conceptual data models, the logical data models are designed
by the technical users. It represents how to store and retrieve data logically. Finally, the logical design
models are converted into physical data models that show all table structures. Relational data models
are the most commonly used data model. So, in this topic we will focus on relational data models.
1.5.1 Key terms in Relational Data Model
In relational data models, tables are called relations that store data for different entities. Each relation
in a relational model represents a specific type of entity. An entity is an object and we store data
about the object. In other words, a relation is a two-dimensional table used to store data.
Let us consider the relational database SCHOOLRECORD along with the three relations (tables)
StudentRecord, AttendanceRecord and ParentRecord, as shown in Figure 1.3.
Page 11 of 200
AttendanceRecord Att_Date : date on which attendance is taken
(Att_Date, Stu_RollNo : roll number of the student
Att_Status : Either P (for present) or A (for absent)
Stu_RollNo,
Note: Combination of Att_Date and Stu_RollNo will be
Att_Status)
unique in each record of the table
ParentRecord Par_ID : unique id of the parent
(Par_ID, Par_Name : Name of the parent
Par_Phone : Contact number of the parent
Par_Name,
Par_Address : Address of the parent
Par_Phone, Par_Email : Email id of the parent
Par_Address,
Par_Email)
Each tuple (row) in a relation (table) corresponds to data of a real-world entity as in StudentRecord,
ParentRecord, and AttendanceRecord. In the ParentRecord relation (Table 1.4), each row
represents the facts about the parent and each column name in the ParentRecord table is used to
interpret the meaning of data stored under that column. A database that is modelled on relational
data model concept is called Relational Database. Figure 1.5 shows relation ParentRecord with some
populated data.
Let us now understand the commonly used terminologies in relational data models using Figure 1.4.
Fig 1.4 Relation ParentRecord with its attributes (Columns) and tuples (Rows)
Attribute – Characteristic or parameters for which data are to be stored in a relation. Simply stated,
the columns of a relation are the attributes which are also referred to as fields. For example, Par_ID,
Par_Name, Par_Phone and Par_Address are attributes of relation ParentRecord.
Tuple – Each row of data in a relation (table) is called a tuple. In a table with ‘n’ columns, a tuple is
a relationship between the ‘n’ related values.
Page 12 of 200
Domain – It is a set of values from which an attribute can take a value in each row. Usually, a data
type is used to specify a domain for an attribute. For example, in StudentRecord relation, the
attribute Stu_RollNo takes integer values and hence, its domain is a set of integer values. Similarly,
the set of character strings constitutes the domain of the attribute Stu_Fname.
Degree – The number of attributes in a relation is called the ‘Degree’ of the relation. For example,
relation ParentRecord with four attributes is a relation of degree five.
Cardinality – The number of tuples in a relation is called the Cardinality of the relation. For example,
the cardinality of relation ParentRecord is 10 as there are 10 tuples in the table.
1.5.2 Three Important Properties of a Relation
In relational data model, following three properties are observed with respect to a relation which
makes a relation different from a data file or a simple table.
Property 1: Imposes following rules on an attribute of the relation:
a) Each attribute in a relation has a unique name.
b) Sequence of attributes in a relation is immaterial.
Property 2: Governs following rules on a tuple of a relation:
• Each tuple in a relation is distinct. For example, data values in no two tuples of relation
AttendanceRecord can be identical for all the attributes. Thus, each tuple of a relation must be
uniquely identified by its contents.
• Sequence of tuples in a relation is immaterial. The tuples are not considered to be ordered, even
though they appear to be in tabular form.
Property 3: Imposes following rules on the state of a relation:
• All data values in an attribute must be from the same domain (same data type).
• Each data value associated with an attribute must be atomic (cannot be further divisible into
meaningful subparts). For example, Par_Phone of relation ParentRecord has ten digits numbers
which are indivisible.
• No attribute can have many data values in one tuple. For example, any Parent cannot specify
multiple contact numbers under the Par_Phone attribute.
• A special value “NULL” is used to represent values that are unknown or non-applicable to certain
attributes. For example, if a parent does not share his or her contact number with the school
authorities, then Par_Phone is set to NULL (data unknown).
1.6 KEYS IN A RELATIONAL DATABASE
The tuples within a relation must be distinct. It means no two tuples in a table should have the same
value for all attributes. That is, there should be at least one attribute in which data are distinct
(unique) and not NULL. That way, we can uniquely distinguish each tuple of a relation. So, relational
data models impose some restrictions or constraints on the values of the attributes and how the
contents of one relation can be referred through another relation. These restrictions are specified at
the time of defining the database through different types of keys as given below:
1.6.1 Candidate Key
A relation can have one or more attributes that take distinct values. Any of these attributes can be
used to uniquely identify the tuples in the relation. Such attributes are called ‘candidate keys’ as
each of them are candidates for the primary key.
As shown in Figure 1.5, the relation ParentRecord has five attributes out of which Par_ID and
Par_Phone always take unique values. No two parents will have the same phone number or same
Par_ID. Hence, these two attributes are the candidate keys as they both are candidates for primary
key.
Page 13 of 200
1.6.2 Primary Key
Out of one or more candidate keys, the attribute chosen by the database designer to uniquely identify
the tuples in a relation is called the primary key of that relation. The remaining attributes in the list
of candidate keys are called the ‘alternate keys.
In the relation ParentRecord, suppose Par_ID is chosen as primary key, then Par_Phone will be
called the alternate key.
1.6.3 Composite Primary Key
If no single attribute in a relation is able to uniquely distinguish the tuples, then more than one
attribute is taken together as the primary key. Such a primary key consisting of more than one
attribute is called ‘Composite Primary key’. In relation to AttendanceRecord, Roll Number cannot
be used as primary key as roll number of same students will appear in another row for a different
date. Similarly, in relation to AttendanceRecord, ‘Att_Date’ cannot be used as the primary key
because the same date is repeated for each roll number.
However, combination of these two attributes Stu_RollNo and Att_Date together would always have
unique value in the AttendanceRecord table as on any working day, a student would be marked
attendance only once. Hence {Stu_RollNo, Att_Date} will combine to make the AttendanceRecord
relation composite primary key.
1.6.4 Foreign Key
A foreign key is used to represent the relationship between two relations. A foreign key is an attribute
whose value is derived from the primary key of another relation. This means that any attribute of a
relation (referencing), which is used to refer contents from another (referenced) relation, becomes
foreign key if it refers to the primary key of the referenced relation. The referencing relation is called
‘Foreign Relation’. In some cases, foreign keys can take NULL value if it is not the part of the primary
key of the foreign table.
The relation in which the referenced primary key is defined is called ‘primary relation’ or ‘master
relation’. In Figure 1.5, two foreign keys in STUDENTATTENDANCE database are shown using a
schema diagram where the foreign key is displayed as a directed arc (arrow) originating from it and
ending at the corresponding attribute of the primary key of the referenced table. The underlined
attributes make the primary key of that table.
Fig. 1.5 StudentAttendance Database with the Primary and Foreign keys
Page 14 of 200
Chapter 2. Structured Query Language (SQL)
Once the result date was declared, Shyam was eager to see the result on the website. He opened the
website to enter his Roll number to see the result. After entering the Roll number, he pressed the OK
button. Immediately the score card of Shyam got displayed on the screen and passed with first
division marks. He was very happy and also surprised, how a computer searches the Roll number so
fast among approximately 5 lacs students records. Later on, Shyam understood that it was possible
because of the database query language which is also known as Structured Query Language (SQL).
SQL is used to search, store, modify records in database management systems. In this chapter, you
will understand how to create database objects, insert data in the database and various types of
commands used to retrieve the required data from the database.
Page 15 of 200
● SQL is not case insensitive. For example, the column names ‘salary’ and ‘SALARY’ are the same
for SQL.
● SQL statements terminate with a semicolon (;). In multi-line SQL statements, the “;” is not required
after the first line. Just press the ‘Enter key’ to continue on the next line. The prompt mysql> then
changes to “->”, indicating that statement is continued to the next line. Only at the end of the SQL
statement, put “;” and press Enter.
2.2 Data Types and Constraints in MySQL
We know that a database consists of one or more relations and each relation (table) is made up of
attributes (column). Each attribute has a data type. It is also possible to specify constraints for each
attribute of a relation.
2.2.1 Data type of Attribute
Data type of an attribute indicates the type of data value that an attribute can have. It also decides
the operations that can be performed on the data of that attribute. For example, arithmetic operations
can be performed on numeric data but not on character data. Commonly used data types in MySQL
are numeric types, date and time types, and string types as shown in Table 2.1.
Table 2.1 Commonly used data types in MySQL
Data Type Description
CHAR (n) Specifies character type data of length ‘n’ where ‘n’ could be any value from 0 to
255. ‘CHAR’ is of fixed length, which means, declaring CHAR (10) implies to reserve
spaces for 10 characters. If data does not have 10 characters (for example, ‘city’
has four characters), MySQL fills the remaining 6 characters with spaces padded
on the right.
VARCHAR (n) Specifies character type data of length ‘n’ where n could be any value from 0 to
65535. But unlike CHAR, VARCHAR is a variable-length data type. That is,
declaring VARCHAR (30) means a maximum of 30 characters can be stored but
the actual allocated bytes will depend on the length of the entered string. So ‘city’
in VARCHAR (30) will occupy the space needed to store 4 characters only.
INT ‘INT’ specifies an integer value. Each INT value occupies 4 bytes of storage. The
range of values allowed in integer type are -2147483648 to 2147483647. For values
larger than that, we have to use BIGINT, which occupies 8 bytes.
FLOAT Holds numbers with decimal points. Each FLOAT value occupies 4 bytes.
DATE The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is the 4 digits year,
MM is the 2 digits month and DD are the 2 digits date. The supported range is
'1000-01-01' to '9999-12-31'.
2.2.2 Constraints
Constraints are the certain types of restrictions on the data values that an attribute can have. Table
2.2 lists some of the commonly used constraints in SQL. They are used to ensure correctness of data.
However, it is not mandatory to define constraints for each attribute of a table.
Table 2.2 Commonly used SQL Constraints
Constraint Description
Ensures that a column cannot have NULL values where NULL means missing/
NOT NULL
unknown/not applicable value.
Page 16 of 200
DEFAULT A default value specified for the column if no value is provided.
PRIMARY KEY The column which can uniquely identify each row or record in a table.
FOREIGN The column which refers to the value of an attribute defined as the primary key in
KEY another table.
2.2.3 Types of Structured Query Language (SQL)
SQL is a standardised language used for making communication with relational databases and
performing various operations on it. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used to
perform tasks such as insert, update and delete data in any database. On the basis of different types
of operation, SQL commands are divided into five categories:
1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Query Language (DQL)
4. Transaction Control Language (TCL)
5. Data Control Language (DCL)
Page 17 of 200
Syntax:
CREATE DATABASE databasename;
Example 2.1: The following command is used to create a database with the name “SchoolRecord”.
mysql> CREATE DATABASE SchoolRecord;
After successful execution of the command a message “Query OK” is displayed on the sql prompt. It
is also possible to see the newly created database by using the “show” command. The show command
displays the newly created database along with some default databases of MySQL as shown in Figure
2.4.
Note: In any RDBMS, it is possible to manage multiple databases on a single computer. USE
command is used to select the specific database. After selecting the database, it is possible to create
tables or querying data from this database.
To select the database SchoolRecord, issue the “USE” command followed by the database name.
Note: In LINUX OS environment, names for database and tables are case-sensitive whereas in
WINDOWS OS, there is no such differentiation. However, as a good practice, it is suggested to write
database or table names in the same letter cases that were used at the time of their creation.
2.3.2 CREATE Table
After creating database SchoolRecord, it is required to define relations (create tables) in this
database. In each relation specify attribute (column name) for each attribute with their required data
types. The syntax for the CREATE TABLE statement is as follows.
Syntax:
CREATE TABLE tablename (
Col_name1 datatype constraint,
Col_name2 datatype constraint,
:
Page 18 of 200
Col_nameN datatype constraint);
Let us understand how to choose attribute names and their respected data types. First identify data
types of the attributes in table “StudentRecord” along with their constraint, if any. Let us assume
that there is a total of 100 students in a class and values of Roll number are in a sequence from 1 to
100. Since the data values of attribute “Stu_RollNo” is stored in digits, the data type integer (INT) is
appropriate for this attribute. In the same way, the total number of characters in student First name
and Last name can be up to 20 characters. Since the number of characters can vary for different
students, the data type VARCHAR is used for these columns. The data type VARCHAR is used for
student addresses up to 50 characters in length. The specific data type DATE is used for specifying
any type of date. So, DATE data type is used for attribute “Date of Birth”. For student's parent ID,
Aadhaar number is used which is a 12-digit number. Since the Aadhaar number is of fixed length
and it is not required to perform any mathematical operation, the character data type with fixed
length of 12-character, CHAR (12) is used for this attribute.
Table 2.3 Data types and constraints for the attributes of relation StudentRecord
Attribute Data expected to be stored Data type Constraint
Stu_FName Variable length string of maximum 20 characters Varchar (20) Not Null
Stu_LName Variable length string of maximum 20 characters Varchar (20) Not Null
Stu_Address Variable length string of maximum 50 characters Varchar (50) Not Null
Par_ID Fixed length string of 12 digits Aadhaar number Char (12) Primary Key
Par_Name Variable length string of maximum 20 characters Varchar (20) Not Null
Par_Address Variable length string of size 30 characters Varchar (30) Not Null
Primary Key*
Stu_RollNo Numeric value consisting of maximum 3 digits Int
Foreign Key
Att_Status ‘P’ for present and ‘A’ for absent Char(1) Not Null
Table 2.3, 2.4 and 2.5 show the chosen data type and constraint for each attribute of the relations
StudentRecord, ParentRecord and AttendanceRecord respectively.
Example 2.2: The following command is used to create table StudentRecord. To create the table in
the SchoolRecord database, first open the database with USE SchoolRecord command. Then create
the table under the StudentRecord database by using the CREATE TABLE command.
Page 19 of 200
Note: “,” is used to separate two attributes and each statement terminates with a semicolon (;). The
arrow (->) is an interactive continuation prompt. If we enter an unfinished statement, the SQL shell
will wait for us to enter the rest of the statement.
Example 2.3: The following command is used to Create table ParentRecord.
Page 20 of 200
The SHOW TABLES statement is used to display all the tables in the database. We have created three
tables in the database SchoolRecord.
Example 2.6: The following SQL command is used to display the tables created in the database
SchoolRecord. It shows all the three tables created so far.
“ParentRecord”
A composite primary key is made up of two attributes. The primary key to the “AttendanceRecord”
relation will be the composite primary key of two attributes. “AttendanceDate” and “Stu_RollNo”.
Example 2.8: The following SQL command is used to add the composite primary key to the relation
“AttendanceRecord”.
Page 21 of 200
Syntax:
ALTER TABLE table_name ADD FOREIGN KEY (attribute name)
REFERENCES referenced_table_name (attribute name);
Let us now add foreign key to the table StudentRecord.
In table “StudentRecord”, the attribute Par_ID (the referencing attribute) is a foreign key and it
refers to attribute Par_ID (the referenced attribute) of table “ParentRecord”. Hence, “StudentRecord”
is the referencing table and “ParentRecord” is the referenced table.
Example 2.9: The following SQL command is used to add the foreign key. The ALTER statement
changes the table StudentRecord.
Page 22 of 200
The newly added attribute “income” with data type INT in the table “ParentRecord” can be viewed
using the DESC command as follows.
Page 23 of 200
Syntax:
ALTER TABLE table_name MODIFY attribute
DATATYPE DEFAULT default_value;
To set the default value of “Stu_DOB” of “StudentRecord” to 15th May 2000, write the following
statement.
Note: It is required to specify the data type of the attribute along with DEFAULT while using MODIFY.
(h) Remove an attribute
It is possible to remove attributes from a table using ALTER.
Syntax:
ALTER TABLE table_name DROP attribute;
Example 2.14: The following command is used to remove the attribute income from the table
“ParentRecord”.
Note: The primary key is dropped from the StudentRecord table, but each table should have a
primary key to maintain uniqueness. Hence, to use ADD command to specify primary key for the
StudentRecord table as shown in earlier examples
2.3.5 DROP TABLE Command
Sometimes it may require removing a table in a database or the database itself. DROP statement is
used to remove a database or a table permanently from the system. Since this command will delete
the table or database permanently, you have to be cautious while using this statement as it cannot
be undone. Let us assume that you have created a table with the name “ParantRecord” instead of
“ParentRecord”. DROP command can be used to delete the table created with the wrong name.
Page 24 of 200
Syntax:
DROP TABLE table_name;
It is also possible to drop the entire database.
Syntax:
DROP DATABASE database_name;
Example 2.16: The following command is used to delete the table name “ParantRecord” from the
current database.
Cautions:
1. Using the Drop statement to remove a database will ultimately remove all the tables within
it.
2. DROP statements will remove the tables or databases created by you. Hence you may apply
the DROP statement at the end of the chapter.
Page 25 of 200
2.3.7 CREATE TABLE from Existing Table
If you want to create a new table from an existing table with partial or additional fields, then you can
use the CREATE table command with the SELECT statement. The new table is created with the result
of the SELECT statement with results provided by it.
Syntax:
mysql> Create table NewTableName AS
(Select Field 1, Field 2, Field 3, …Field N from Old_Table_Name)
Example 2.18: The following command is used to Create table “NewStudentRecord” from the existing
table “StudentRecord”.
It will create a new table named “NewStudentRecord” with only 5 attributes and all the records which
were inserted in this table earlier.
Page 26 of 200
It is possible to create a new table with all attributes and all records available in the existing table.
Example 2.19: The following command is used to create a new table “StudentRecord1” with all
attributes and all records available in the existing table “StudentRecord”.
Page 27 of 200
2.3.9 CREATE VIEW command
Like table, view is another database object. It is a special kind of virtual table. It does not hold its
own data. A view can have rows and columns just like in a table. It is possible to create a view using
the CREATE VIEW command, by selecting fields from one or more tables present in the database. A
View can either have all the rows of a table (s) or specific rows based on certain criteria. The syntax
to create a view is as under.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2 .... columnN
FROM table_name WHERE condition;
Example 2.22: The following is the command to create a view from a single table.
Now the view named EMP_VIEW will be created with only those employee records who have a salary
more than 10000. You can use this view similar to the Employee table to see all records using the
SELECT command. To see all records from EMP_VEW, use the SELECT command as under.
Practical Activity 2.1 – Create the table “Employee” and “Department” in MySQL with the
following attributes specification:
Employee Table
Attribute Data expected to be stored Data type Constraint
ename Variable length string of max 30 characters Varchar (30) Not Null
job Variable length string of max 15 characters Varchar (15) Not Null
Page 28 of 200
comm Numeric value consisting of 4 digits Int Not Null
dname Variant length string of max 20 characters Varchar (20) Not Null
loc Variant length string of max 25 characters Varchar (25) Not Null
Caution: While populating records in a table with foreign key, ensure that records in referenced
tables are already populated.
Let us insert some records in the SchoolRecord database. First insert the records in the
ParentRecord table first as it does not have any foreign key. A set of sample records for the
ParentRecord table is shown in Table 2.6.
Table 2.6 Records to be inserted into the ParentRecord Table
Par_ID Par_Nam Par_Phone Par_Address Par_Email
e
452695874564 Manu P 9834567890 203, Khandari, Agra, [email protected]
Singh UP
252154687451 Ashok K 9845678910 144 Gr Kailash, New [email protected]
Sharma Delhi
362115264625 Ashutos 9856789120 JP Greens, Noida, UP [email protected]
h Gaur
602125125261 Sachin 9812389120 Kanda, Bagheshwar, [email protected]
Agrawal UK
225423344657 Chandra 9891201238 Fortune Somya, [email protected]
Roy Bhopal, MP
268953264578 Dinesh Lajpat Nagar, [email protected]
Dixit Mathura, UP
Page 29 of 200
485466192343 Rizwan 9255614563 Deep Nagar, Sahrsa, [email protected]
Alam Bihar
521556651761 Ashish 8544556978 T Nagar, Hyderabad, [email protected]
Gupta Telangana m
686113652987 Gurmeet 9635214789 Shahid Nagar, [email protected]
Singh Amritsar, PB
954891122475 Michal 8554658958 Guindy, Chennai, TN [email protected]
DeSousa
Example 2.23: The following command is used to insert the record in the “ParentRecord” table.
We can use the SQL statement “SELECT * from table_ name;” to view the inserted record after any
statement to see the current changes in table.
It is also possible to provide values only for some of the attributes in a table by just specifying the
attribute name alongside each data value as per the following syntax.
Syntax:
INSERT INTO tablename (column1, column2, ...)
VALUES (value1, value2, ...);
Suppose to insert the sixth record in the “ParentRecord” table (Table 2.6) keeping the value of
“Par_Phone” to NULL. Then it is required to insert the values for the other four fields. In this case,
specify the names of attributes in which the values are to be inserted. The values must be given in
the same order in which attributes are written in the INSERT command.
Example 2.24: The following command is used to insert the record in the “ParentRecord” table by
specifying the field name and corresponding values.
Now observe that all the four values have been inserted in the table ParentRecord except “Par_Phone”
which is being set to NULL at the time of creating a table.
Page 30 of 200
Note: Text and date values must be enclosed in ‘ ’ (single quotes).
Practical Activity 2.2 – Insert the records in the ParentRecord table using INSERT command and
check the records inserted in ParentRecord as below.
Practical Activity 2.3 – Insert the records in StudentRecord table (Table 2.7).
Table 2.7 Records to be inserted into the StudentRecord table
Stu_
Stu_FName Stu_LName Stu_DOB Stu_Address Par_ID
RollNo
1 Rajvardhan Singh 5/15/2003 203, Khandari, Agra UP 452695874564
2 Trilok Sharma 8/15/2004 144 Gr Kailash, New Delhi 252154687451
3 Aditi Gaur 4/6/2005 JP Greens, Noida, UP 362115264625
4 Anshika Agrawal 5/17/2003 Kanda, Bagheshwar, UK 602125125261
5 Nandini Roy 12/29/2003 Fortune Somya, Bhopal, MP 225423344657
6 Pawani Dixit 11/12/2004 Lajpat Nagar, Mathura, UP 268953264578
7 Hiba Rizwan 12/3/2006 Deep Nagar, Sahrsa, Bihar 485466192343
8 Riddhi Gupta 1/11/2005 T Nagar, Hyderabad, Telangana 521556651761
9 Manpreet Singh 9/8/2005 Shahid Nagar, Amritsar, Punjab 686113652987
10 John DeSousa 8/17/2005 Guindy, Chennai, TN 954891122475
Example 2.25: The following command is used to insert the first record in table “StudentRecord”.
Page 31 of 200
When column names are not mentioned in the INSERT command, then it is necessary to mention
the values for all the columns. So, if there is no “ParentID” for Trilok, then mention the NULL value
for the “Par_ID”.
Example 2.26: The following command inserts the second record with “Par_ID” value as NULL.
mysql>INSERT INTO StudentRecord VALUES (2,'Trilok','Sharma','8/15/2004', '144 Gr
Kailash','New Delhi' NULL);
Note/Tip: Please be careful while entering the date in the INSERT command. Use the ‘YYYY-MM-DD’
format to write dates.
Insert the records in the Department table using INSERT command and display it after inserting
all record using SELECT statement.
Page 32 of 200
2.4.2 UPDATION of Records using UPDATE and DELETE Command
UPDATE and DELETE are also part of SQL Data Manipulation Language (DML). UPDATE command
is used to make changes in existing data value(s) of one or more columns of existing records in a
table. For example, we may require some changes in address, phone number or spelling of name.
Syntax:
UPDATE table_name
SET attribute1 = value1, attribute2 = value2, …
WHERE condition;
In the ParentRecord table, Phone number is not available for Parent Name Dinesh Dixit. So, it is
required to update Phone number of Dinesh Dixit, update the table ParentRecord and use the
command.
Example 2.27: The following command is used to update the Phone number of Dinesh Dixit in the
ParentRecord table
.
The updated data can be verified using the statement.
SELECT * FROM ParentRecord.
It is also possible to update values for more than one column using the UPDATE statement.
Suppose, the ParentRecord with Par_ID 485466192343 has requested to change Address to 'WZ - 68,
Azad Avenue, Boriwali, Mumbai’ and Phone number to '9988776644'.
Example 2.28: The following SQL statement will update this record.
mysql> UPDATE ParentRecord SET Par_Address = 'WZ - 68, Azad Avenue, Boriwali, Mumbai’,
Par_Phone = 9988776644 WHERE Par_ID = 485466192343;
The changes affected can be verified by using the SELECT statement as below.
Page 33 of 200
2.4.3 DELETION of Records using DELETE
DELETE statement is used to delete or remove one or more records from a table.
Syntax:
DELETE FROM table_name WHERE condition;
Suppose the student with roll number 2 has left the school.
Example 2.29: The following SQL statement is used to delete that record from the STUDENT table.
The changes affected can be verified by using the SELECT statement as below.
Caution: The WHERE clause should be used in the UPDATE and DELETE statement, otherwise it
will apply on all the records.
Page 34 of 200
2.5.1 SELECT Statement
In SQL, the SELECT statement is used to retrieve data from tables in a database and output is
displayed as per the specified parameter on successful execution of the statement.
Syntax:
SELECT attribute1, attribute2,... attribute N
FROM table_name
WHERE condition;
Here, attribute1, attribute2, ... attributeN are the names of columns of the table table_name from
which data is to be retrieved. The FROM clause is always written with the SELECT clause as it
specifies the name of the table from which data has to be retrieved. The WHERE clause is optional
and is used to retrieve data to meet any specified condition(s).
To select all the columns and rows available in a table, use the following select statement.
SELECT * FROM table_name;
Here * is used to retrieve all columns/attributes available in the table.
Let us use a SELECT statement to retrieve names of the students whose names start with the
alphabet “D”.
Example 2.30: The following SQL query statement is used to retrieve the name and date of birth of a
student whose roll number is 1.
In the above query, observe that the Student Roll Number and Date of birth of the student whose roll
number is 1 is retrieved using WHERE clause.
2.5.2 Querying using database OFFICE
Let us consider an EMP table of employee databases with the following fields. The “empno” is a
primary key and “deptno” as foreign key. Table 2.8 shows the data entered in the Emp table.
Table 2.8 Records available in EMP table
empno ename job mgr hiredate sal comm deptno
Page 35 of 200
7489 Kushaal President NULL 11/14/1995 13000 NULL 10
Observe that the above query retrieves the empno of all the employees from the Emp table as only
one column is specified to retrieve.
Let us see another query that selects two columns such as emp no and corresponding employee name.
Modify the same query by specifying two fields of table as “empno” and “ename”. and observe the
desired output as below.
Example 2.32: The following SQL query statement will retrieve the data of employee number and
name in two columns.
Page 36 of 200
(b) Renaming of columns – There are specific naming conventions of the fields in the table. It is
possible to rename any column while displaying the output by using the alias 'AS'.
Example 2.33: The following SQL query statement selects Employee name as “Name” in the output
for all the employees.
Example 2.34: The following SQL query statement will calculate and to display the annual salary of
employees. Annual salary is calculated as “sal*12”.
Page 37 of 200
Now it doesn’t look nice to display the caption as “sal*12” in the table. It is possible to display it with
new caption as “Annual Salary” for “sal*12”. The revised query and its output are given below.
Observe that “ename” is shown with the caption as “Name” and “sal*12” is shown with the caption
as “Annual Income”.
Note – Annual Income is just the caption to display. It will not add as a new column in the database
table. It is just for displaying the output of the query. If an aliased column name has space as in the
case of Annual Income, it should be enclosed in quotes as ‘Annual Income’.
(c) Distinct Clause – The SELECT clause retrieves all the data through query as output. There may
be a chance of duplicate values such as two persons with the same name working in the department.
The DISTINCT clause has provision to retrieve the unique records by omitting the duplicate records.
The DISTINCT clause is used for this purpose.
Example 2.35: The following SQL query statement shows the different departments available in the
“emp” table.
Page 38 of 200
Let us understand how to retrieve different types of jobs available using the DISTINCT clause in the
following example.
Example 2.36: The following SQL query statement will use a DISTINCT clause to retrieve different
types of jobs available in the “emp” table.
Observe that there are five different job titles although more records exist.
(d) WHERE Clause – It retrieves data that meet some specified conditions. In our OFFICE database,
more than one employee can have the same salary.
Example 2.37: The following SQL query statement will give distinct salaries of the employees working
in the department number 10.
Observe in the output that all the records of employees working in dept no. 10 and having the distinct
salary are retrieved.
In the above example, = operator is used in the WHERE clause. Other relational operators like (<, <=,
>, >=, !=) can also be used to specify conditions as per your requirement. The logical operators AND,
OR, and NOT are used to combine multiple conditions.
Let us see how to compare columns/fields value/s to specific required records or columns.
Page 39 of 200
Example 2.38: The following SQL query statement will display all the details of those employees of 30
departments who earn more than 5000.
Note: Observe the output, two different conditions are being tested separately. First condition tested
for Salary is greater than 5000 and second condition for department number is 10. AND operator
used to join both conditions.
Let us make a comparison of salaries like who is getting more than 8000 and less than 11000.
Example 2.39: The following SQL query statement will select the name and department number of all
those employees who are earning salary between 8000 and 11000 inclusive of both values.
The query in example 2.39 defines a range of salary between 8000 and 11000 that can also be
achieved using a comparison operator BETWEEN, in the query as below. The output of this query
will be the same as above.
Page 40 of 200
Note: The BETWEEN operator defines the range of values in which the column value must fall into,
to make the condition true.
Example 2.40: The following SQL query statement will select details of all the employees who work in
any of the department number 10, 20, or 40.
Page 41 of 200
Note: Here NOT operator is used in combination with IN to retrieve all records except with deptno 10
and 20.
(F) ORDER BY Clause – It is used to display data in an ordered form with respect to a specified
column. By default, ORDER BY displays records in ascending order of the specified column values.
The DESC keyword is used to display the records in descending order.
Let us arrange the records in ascending or descending order using the ORDER BY clause with DESC
clause example 2.42.
Example 2.42: The following SQL query statement selects details of all the employees in ascending
order of their salaries.
Observe that the records are displayed in ascending order of salary of each employee. To arrange
records in descending order, use DESC clause with ORDER BY as in example 2.43.
Example 2.43: The following SQL query statement selects details of all the employees in descending
order of their salaries.
Page 42 of 200
Note: DESC clause used after the column name on which the records to be displayed in descending
order.
(G) Handling NULL Values – SQL supports a special value called NULL to represent a missing or
unknown value. For example, the “Par_Phone” column in the table “ParentRecord” can have missing
values for certain records. Hence, NULL is used to represent such unknown values. It is important
to note that NULL is different from value 0 (zero). Also, any arithmetic operation performed with NULL
value gives NULL. For example, 5 + NULL = NULL because NULL is unknown hence the result is also
unknown. In order to check for NULL value in a column, use IS NULL operator in particular
statements. Example 2.44 illustrates the use of NULL clauses.
Example 2.44: The following SQL query statement selects details of all employees who have not been
given a bonus. This implies that the bonus column will be blank.
Observe the output and see column mgr and comm where NULL is present.
Page 43 of 200
It is also possible to join a NULL statement with any other condition. Example 3.11 shows how to
use it in a statement.
Example 2.45: The following SQL query statement selects emp number, employee names and job of
all those employees who have been given a comm (i.e., comm is not null) and works in the department
30.
(H) Having clause – It is used in a SELECT statement to make a group with certain conditions as a
result of query.
Syntax:
SELECT expression1, expression2, ... expression_n,
aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING condition;
Example 2.45 shows how to use Group by and Having clauses jointly. The HAVING clause must
follow the GROUP BY clause in any SELECT query and must also be preceded by ORDER BY clause
if used.
Example 2.45: The following SQL query statement selects jobs, number of employees in that job, their
total salary and department number wise list where minimum 3 employees of the same type of job
are working.
Page 44 of 200
(I) Substring pattern matching – Many times it may require that the query should not retrieve that
exact text or value, rather it should retrieve the matching of a few characters or values. For example,
to find names starting with “M” or to find pin codes starting with “11”, is called substring pattern
matching. Such patterns cannot match using = operator. SQL provides a LIKE operator that can be
used with the WHERE clause to search for specific patterns in a column.
The LIKE operator makes use of the following two wild card characters - (%) and (-). The percent (%)
is used to represent zero, one, or multiple characters. The underscore (_) is used to represent exactly
a single character.
There are several situations when we search data records for some pattern matching. A very common
situation when you search for any contacts in your smartphone, you just start typing the first few
characters of the name, then immediately a list appears with these characters and you tap on the
required name to call. Example 3.46 to 3.51 demonstrates such situations to search some patterns
in text values of records using LIKE clauses.
Example 2.46: The following SQL query statement selects details of all those employees whose name
starts with 'K'.
Example 2.47: The following SQL query statement selects details of all those employees whose name
ends with 'a', and receives a salary more than 8500.
Example 2.48: The following SQL query statement selects details of all those employees whose name
consists of exactly five letters and starts with any letter but has ‘mita’ after that.
You can also match a particular character or string in between the text simply by using wildcard
characters as shown in example 2.49.
Page 45 of 200
Example 2.49: The following SQL query statement selects all columns of all employees containing
'ma' as a substring in name.
Example 2.50: The following SQL query statement selects all columns of employees containing 'a' as
the second character in their names.
Example 2.51: The following SQL query statement selects records of all the employees except Alam.
Page 46 of 200
GRANT statement – The GRANT statement is used to give access privileges to a specific user to work
with any selected database only.
Syntax:
GRANT SELECT, UPDATE ON Test_Table TO NewUser1, NewUser2;
Example:
GRANT SELECT, UPDATE, DELETE ON carshowroom TO 'WebUser';
Here the user 'WebUser' will be able to use only three SELECT, UPDATE and DELETE SQL statements
when working on carshowroom database.
REVOKE statement – The REVOKE statement is used to withdraw privileges from a specific user so
that specific user could not use a specific statement on a selected database. In other words, it is
useful to take back the given permission/s from the user.
Syntax:
REVOKE Privilege_Name ON Object_Name FROM User_Name.
Example:
REVOKE DELETE ON carshowroom FROM WebUser;
2.7 SQL FOR TRANSACTION CONTROL LANGUAGE (TCL)
Transaction control language (TCL) is the part of SQL commands that allows to permanently change
the databases or undo the database transactions. It is similar to saving the database or undoing the
current changes. The COMMIT, ROLLBACK and SAVEPOINT statements come under this category.
COMMIT – Commit command is used to save all the transactions to the database. After completing
any operation or SQL statement, you can simply write COMMIT as the next statement to permanently
save data in the database.
Syntax:
Commit;
Example:
DELETE FROM ClassStudents WHERE RollNo =25;
Commit;
Here, after the DELETE statement, the COMMIT statement is used. It means the student record
whose RollNo is 25 is permanently deleted. Now after the COMMIT statement, it is not possible to
rollback the record of that student.
ROLLBACK – ROLLBACK command allows to undo transactions that have not already been saved to
the database. This statement is useful to restore the database to the state where the last commit
statement was used. Rollback statement is also used with SAVEPOINT to jump to specific Savepoint
in the database transactions.
Syntax:
ROLLBACK;
SAVEPOINT – This command helps to set a Savepoint within a transaction. Basically, the
SAVEPOINT statement is used to save a transaction temporarily so that the user can rollback to that
point as and when required.
Syntax: SAVEPOINT Savepoint_Name;
Page 47 of 200
CHAPTER 3. FUNCTIONS IN SQL
Page 48 of 200
YearManufacturer Variable length string of maximum 4 Varchar (4) Not Null
characters
FuelType Variable length string of max 10 characters Varchar (10) Not Null
Customer – Stores Customer id, name, address, phone number and email for each customer.
Table 3.2: Attribute specification of “Customer” table
Attribute Data expected to be stored Data type Constraint
CustName Variable length string of max 30 characters Varchar (30) Not Null
CustAdd Variable length string of max 50 characters Varchar (50) Not Null
Email Variable length string of max 50 characters Varchar (20) Not Null
Sale – Stores the invoice number, car id, customer id, sale date, mode of payment, sales person’s
employee id and selling price of the car sold,
Table 3.3: Attribute specification of “Sale” table
Attribute Data expected to be stored Data type Constraint
PaymentMode Variant length string of max 20 characters Varchar (20) Not Null
Page 49 of 200
To proceed further, create database CARSHOWROOM and create all four tables as per the above
specification.
Insert the records in tables Inventory, Customer, Sale and Employee using INSERT command. The
records of these four relations can be viewed using the SELECT command.
Execute the following query to view the records of the “inventory” table. After successful execution of
the query, the records entered in the “inventory” table will be displayed.
Execute the following query to view the records of the “customer” table. After successful execution of
the query, the records entered in the “customer” table will be displayed.
Execute the following query to view the records of the “sale” table. After successful execution of the
query, the records entered in the “sale” table will be displayed.
Page 50 of 200
Execute the following query to view the records of the “employee” table. After successful execution of
the query, the records entered in the “employee” table will be displayed.
Page 51 of 200
2. ROUND (N, D) – Rounds off number N to D number of decimal places. If D=0, then it rounds off
the number to the nearest integer.
Step 2. Add a new column “FinalPrice” to the table “inventory”. Update the table “inventory” with
“FinalPrice” as the sum of Price and 12 percent of the GST. Apply the ROUND function to round
off the GST to one decimal place. Execute the following query to do this.
Page 52 of 200
Display the values of “FinalPrice” for all the records by using the SELECT command.
Step 3. Calculate and display the amount to be paid each month in multiples of 1000 which is
calculated after dividing the FinalPrice of the car into 10 instalments. After dividing the amount
into EMIs, find out the remaining amount to be paid immediately, by performing modular division.
Use the SELECT command to display the result. Execute the following query to do this.
Step 4. Execute the following query to display the “InvoiceNo” and “Commission” value rounded off
to zero decimal places.
Step 5. Execute the following query to display the details of “sale” table where payment mode is
credit card.
Page 53 of 200
Step 6. Execute the query to add a new column “Commission” with total length of 7 with 2 decimal
places to the “sale” table.
Step 7. Execute the query to calculate commission for sales agents as 12% of “SalePrice”.
Step 8. Execute the following query to insert the values to the newly added column “Commission”
and then display all records of the “sale” table where Commission > 73000.
Step 9. Execute the following query to display InvoiceNo, EmpID, SalePrice and Commission such
that commission value is rounded off to 0.
Page 54 of 200
1. UCASE (string) OR UPPER (string) – converts string into uppercase.
3. MID (string, pos, n) OR SUBSTRING (string, pos, n) OR SUBSTR (string, pos, n) – Returns a
substring of size n starting from the specified position (pos) of the string. If n is not specified, it
returns the substring from the position pos till end of the string.
Page 55 of 200
5. LEFT (string, N) – Returns N number of characters from the left side of the string.
6. RIGHT (string, N) – Returns N number of characters from the right side of the string.
7. INSTR (string, substring) – Returns the position of the first occurrence of the substring in the given
string. Returns 0, if the substring is not present in the string.
8. LTRIM (string) – Returns the given string after removing leading white space characters.
9. RTRIM (string) – Returns the given string after removing trailing white space characters.
Page 56 of 200
10. TRIM (string) – Returns the given string after removing both leading and trailing white space
characters.
Step 2. Execute the following query to display the length of email and part of the email from the
email id before the character ‘@’.
The function INSTR will return the position of “@” in the email address. So, to print email id without
“@” position -1 is used.
Let us assume that four-digit area code is reflected in the mobile number starting from position
number 3. For example, 1851 is the area code of mobile number 9818511338.
Step 3. Execute the following query to display the area code of the customer living in Rohini.
Page 57 of 200
Step 4. Execute the following query to display emails after removing the domain name extension
“.com” from emails of the customers.
Step 5. Execute the following query to display details of all the customers having yahoo emails
only.
Now let us use the table “inventory” from CARSHOWROOM database, write SQL queries for the
following:
Step 6. Execute the following query to convert the “CarMake” to uppercase if its value starts with
the letter ‘B’.
Step 7. If the length of the car model is greater than 4 then Execute the following query to fetch
the substring starting from position 3 till the end from attribute Model.
Page 58 of 200
3.2.3 Date and Time Functions
There are various functions that are used to perform operations on date and time data. Some of the
operations include displaying the current date, extracting each element of a date (day, month and
year), displaying day of the week and so on. Some of the date and time functions with examples are
given below.
1. NOW() – It returns the current system date and time.
2. DATE() – It returns the date part from the given date/time expression.
Page 59 of 200
7. DAYNAME(date) – It returns the name of the day from the date.
Step 1. Execute the following query to display the date in the format "Wednesday, 26, November,
1979", if the date of joining is not Sunday.
Page 60 of 200
Step 2. Execute the following query to list the Employee Name, date of birth and Salary for all
employees whose salary is more than 25000, in “emp” table.
Step 3. Execute the following query to list the invoice number, customer id and date of sale. Those
payments are done using bank finance in the “Sale” table.
Step 4. Execute the following query to list all the employees without a peon whose salary is more
than 30000 in the “emp” table.
Step 5. Execute the following query to list all the records without LXI and VXI models in the table
“inventory”.
Page 61 of 200
3.3 Aggregate Functions
In aggregate functions the column must be of numeric type. Some of the aggregate functions are
given below.
1. MAX (column) – Returns the largest value from the specified column.
2. MIN (column) – Returns the smallest value from the specified column.
3. AVG (column) – Returns the average of the values in the specified column.
4. SUM (column) – Returns the sum of the values for the specified column.
5. COUNT (*) – Returns the number of records in a table. COUNT (*) is used with the WHERE clause
to display the number of records that match a particular criterion in the table.
Page 62 of 200
Practical Activity 3.4 – Demonstrate to use aggregate functions in SQL
Let us explore how we can use various aggregate functions in SQL statements to fulfil various
requirements of real-world situations.
Step 1. Execute the following SQL query to display the total number of records from table
“inventory” having a model as VXI.
Step 2. Execute the following SQL query to display the total number of different types of Models
available from table “inventory”.
Step 3. Execute the following SQL query to display the average price of all the cars with Model LXI
from table “inventory”.
Practical Activity 3.5 – Demonstrate to use GROUP BY and HAVING clause in SQL
Consider the “sale” table from the CARSHOWROOM database. Display the number of records in
the “sale” table using the following SQL statement.
Page 63 of 200
In these records, it is observed that the columns, CarID, CustID, SaleDate, PaymentMode, EmpID,
SalePrice can have rows with the same values in it. So, GROUP BY clauses can be used in these
columns to find the number of records of a particular type (column), or to calculate the sum of the
price of each car type.
Step 1. Execute the following SQL query to display the number of Cars purchased by each
Customer from the SALE table.
Step 2. Execute the following SQL query to display the Customer Id and number of cars purchased
if the customer purchased more than 1 car from SALE table.
Step 3. Execute the following SQL query to display the number of people in each category of
payment mode from the table SALE.
Step 4. Execute the following SQL query to display the PaymentMode and number of payments
made using that mode more than once.
Page 64 of 200
3.4 OPERATIONS ON RELATIONS
It is possible to perform certain operations on relations like Union, Intersection and Set Difference to
merge the tuples of two tables. These three operations are binary operations as they work upon two
tables. Note here that these operations can only be applied if both the relations have the same number
of attributes and corresponding attributes in both tables have the same domain.
3.4.1 Union (∪)
This operation is used to combine the selected rows of two tables at a time. If some rows are the same
in both the tables, then the result of the Union operation will show those rows only once. Figure 3.3
shows the union of two sets.
1 Astha 7A
2 Pawani 6A
3 Mohit 7B
4 Vibhanshu 7A
Execute the following query to view the records of the “dance” table. After successful execution of the
query, the records entered in the “dance” table will be displayed.
Page 65 of 200
Sno Name Class
1 Mahak 8A
2 Pawani 6A
3 Lavanya 7A
4 Vibhanshu 7A
5 Abhay 8A
Execute the following query to view the records of “music” table. After successful execution of the
query, the records entered in the “music” table will be displayed.
Step 1. Execute the following SQL query to find the list of students participating in either of events
by using UNION operation on relations DANCE and MUSIC. After execution it will display the union
of DANCE and MUSIC relations.
3.4.2 Intersect (∩) Intersect operation is used to get the common tuples from two tables and is
represented by symbol ∩. Figure 3.9 shows intersection of two sets.
Page 66 of 200
Suppose, we have to display the list of students who are participating in both the events (DANCE and
MUSIC), then intersection operation is to be applied on these two tables. The output of INTERSECT
operation is shown in Table 3.11
Table 3.11 DANCE ∩ MUSIC
Sno Name Class
2 Pawani 6A
4 Vibhanshu 7A
3.4.3 Minus (-)
This operation is used to get tuples/rows which are in the first table but not in the second table and
the operation is represented by the symbol - (minus). Figure 3.10 shows difference operation between
two sets.
1 Mahak 8A
3 Lavanya 7A
5 Abhay 8A
3.4.4 Cartesian Product (×)
Cartesian product operation combines tuples from two relations. It results in all pairs of rows from
the two input relations, regardless of whether or not they have the same values on common
attributes. It is denoted as ‘×’.
The degree of the resulting relation is calculated as the sum of the degrees of both the relations under
consideration. The cardinality of the resulting relation is calculated as the product of the cardinality
of relations on which the Cartesian product is applied. Let us use the relations DANCE and MUSIC
to show the output of Cartesian products. Note that both relations are of degree 3. The cardinality of
DANCE and MUSIC is 4 and 5 respectively.
Applying Cartesian product on these two relations will result in a relation of degree 6 and cardinality
20, as shown in the output of the following query.
Page 67 of 200
3.5 USING TWO RELATIONS IN A QUERY
Till now we have written queries in SQL using a single relation only. Now let us see how to write
queries using two relations.
3.5.1 JOIN on two tables
JOIN operation combines tuples from two tables on specified conditions. This is unlike Cartesian
products which make all possible combinations of tuples. While using the JOIN clause of SQL, specify
conditions on the related attributes of two tables within the FROM clause. Usually, such an attribute
is the primary key in one table and foreign key in another table.
Let us create two tables UNIFORM (UCode, UName, UColor) and COST (UCode, Size, Price) in the
SchoolUniform database. “UCode” is the primary key in table UNIFORM. “UCode” and “Size” are the
composite keys in table COST. Therefore, UCode is a common attribute between the two tables which
can be used to fetch the common data from both tables. Define UCode as foreign key in the “Cost”
table while creating this table. Enter the records in these tables as shown in Table 3.13 and 3.14.
Table 3.13 Uniform table
UCode Uname UColor
1 Shirt White
2 Pant Grey
3 Tie Blue
Table 3.14 Cost table
UCode Size Price
1 L 580
1 M 500
2 L 890
1 M 810
Page 68 of 200
Let us consider two tables created, UNIFORM and COST to demonstrate the joining of two tables.
The joining of two tables can be done in three different ways – using WHERE clause, JOIN clause
and NATURAL JOIN clause
Step 1. Execute the following query to join the two tables using WHERE clause.
As the attribute “UCode” appears in both “uniform” and “cost” tables. Hence alias is used to remove
ambiguity by specifying qualifier U with attribute UCode in SELECT and FROM clauses to indicate
its scope.
Step 2. Execute the following query to join the two tables using JOIN clause.
The output of the query is the same as that of step 1. In this query the JOIN clause is used explicitly
along with the condition in FROM clause. Hence no condition is required in the WHERE clause.
The output of queries in step 1 and 2 has a repetitive column UCode having exactly the same
values. This redundant column provides no additional information. SQL provides the extension of
JOIN operation called NATURAL JOIN, which works similar to JOIN clause in SQL to remove the
redundant attribute. This operator can be used to join the contents of two tables if there is one
common attribute in both the tables.
Step 3. Execute the following query to join the two tables using the NATURAL JOIN clause.
It is clear from the output that the result of this query is the same as above in step 1 and 2, except
that the attribute UCode appears only once.
It is important to note the following points while applying JOIN operations on two or more relations.
● If two tables are to be joined on equal condition on the common attribute, then one may
use JOIN with ON clause or NATURAL JOIN in FROM clause. If three tables are to be joined
on equal condition, then two JOIN or NATURAL JOIN are required.
● In general, N-1 joins are needed to combine N tables on equality conditions.
● Any relational operators can be used with JOIN clauses to combine tuples of two tables.
Page 69 of 200
Unit 2. Advanced Python Programming
Chapter 4. File Handling in Python
4.1 Introduction to File: So far, we have written Python programmes that accept input, manipulate
it, and display the output. However, the output used is only available during programme execution,
and input must be made via the keyboard. This is due to the fact that variables in a programme have
a lifetime that lasts until the programme is executed. What if we wish to save the input data as well
as the created output indefinitely so that we can utilise them later? Organisations typically wish to
permanently retain information on employees, inventories, sales, and so on in order to prevent
recurrent processes of entering the same data. As a result, data is permanently preserved on
secondary storage devices for reusability. We save Python script-mode programmes with the a.py
extension. Each programme is saved as a file on the secondary device. Similarly, the data entered
and the output can be saved indefinitely in a file. So, what exactly is a file? A file is an identified area
on a secondary storage medium where data is permanently saved for subsequent access.
4.2 Types of file: Every file on a computer is stored as a collection of 0s and 1s, or in binary form.
As a result, each file is essentially just a series of bytes put one after the other. Data files are classified
into two types: text files and binary files. A text file is made up of human-readable characters that
can be opened with any text editor. Binary files, on the other hand, are made up of non-human-
readable characters and symbols that must be accessed using specialised programmes.
4.4.1 Text File: A text file can be understood as a sequence of letters consisting of alphabets,
numerals, and other special symbols. Files with extensions like .txt, .py, .csv, etc. are some examples
of text files. When we open a text file using a text editor (e.g., Notepad), we see numerous lines of
text. However, the file contents are not saved in this way internally. Rather, they are recorded as a
sequence of bytes consisting of 0s and 1s. In ASCII, UNICODE, or any other encoding method, the
value of each character in the text file is saved as bytes. So, while opening a text file, the text editor
translates each ASCII value and shows us the equivalent character that is readable by a human
being. For example, The ASCII value 65 (binary equivalent 1000001) will be displayed by a text editor
as the letter ‘A’ since the number 65 in the ASCII character set represents "A."
A text file's lines are separated by a special character known as the End of Line (EOL). In Python, for
example, the default EOL character is the newline (n). Other characters, however, can be used to
signal EOL. When a text editor or programmer interpreter encounters the ASCII equivalent of the
EOL character, the remaining file contents are shown, beginning with a new line. Whitespace is
typically used to separate values in a text file, but commas (,) and tabs (t) are also commonly used to
separate values in a text file.
4.4.2 Binary File: Binary files are also stored in bytes (0s and 1s); however, unlike text files, these
bytes do not represent ASCII character values. They instead reflect the real content, such as images,
audio, video, compressed copies of other files, executable files, and so forth. These files are not
readable by humans. Attempting to open a binary file using a text editor will result in some junk
values. To read or write the contents of a binary file, we require specialised software. A binary file is
a sequence of bytes that is stored on a computer. Even a single bit change in the file can corrupt it
and render it unreadable by the supporting application. Furthermore, because the stored information
is not human-readable, it is difficult to erase any errors that may exist in the binary file. Python
programmes can read and write both text and binary files.
4.3 File Handling: -In real-world applications, computer programmes deal with data from many
sources, such as databases, CSV files, HTML, XML, JSON, and so on. In general, we access files to
either write to them or read data from them. However, file operations include creating and opening
files, writing data to files, traversing files, reading data from files, and so on. The io module in Python
offers many functions for dealing with files.
4.3.1 Opening a file: In Python, we use the open () method to open a file. open () has the following
syntax: open file_object (access_mode, file_name)
Page 70 of 200
This function returns a file handle, which is saved in the variable file_object. We may use this variable
to read and write data to and from files by executing the functions specified in Python's IO module.
If the file does not already exist, the above command creates a new empty file with the name we
choose.
The file_object has properties that provide us with basic information about the file, such as:
● <file.closed> returns true if the file is closed and false otherwise.
● <file.mode> returns the access mode in which the file was opened.
● <file.name> returns the name of the file.
The file_name parameter should be the name of the file to be opened. If the file is not in the current
working directory, we must supply its full path as well as its name.
The access_mode parameter is an optional argument that represents the mode in which the
programme must access the file. It is also known as processing mode. In this context, mode refers to
the operation for which the file must be opened, such as reading, writing, +>both reading and writing,
or adding to the end of an existing file. Read mode is the default. We can also specify whether the file
will be handled in binary () or text () mode. Files are opened in text mode by default, which allows
strings to be read and written. Non-textual data files are opened in binary mode, which implies that
read and write operations are conducted in terms of bytes. Table 4.1 outlines the various file access
modes available that can be used in conjunction with the open() method. In the table, the file offset
position refers to the location of the file object when the file is opened in a specific mode.
Page 71 of 200
Python ensures that any unsaved or unwritten data is flushed off (written) to the file before closing
it. As a result, whenever our job is completed, we should always close the file. In addition, if the file
object is reassigned to another file, the prior file is closed automatically.
4.4 Reading from a Text File
We can write a programme that reads the contents of a file. Before we begin reading a file, we must
ensure that it is opened in "r", "r+", "w+", or "a+" mode. There are three methods for reading the
contents of a file.
4.4.1 The read() method
This technique is used to read a specific number of bytes of data from a file. The syntax of the read()
method is:
file_object.read(n)
Consider the following set of statements to understand the usage of the read() method:
>>>myobject=open("myfile.txt,"'r')
>>>myobject.read(10)
'Hello ever'
>>> myobject.close()
If no argument or a negative integer is supplied in read(), the full file content is read. For example,
>>> myobject=open("myfile.txt,"'r')
>>>print(myobject.read())
Hello everyone
Writing multiline strings
This is the third line.
>>> myobject.close()
4.5 Writing to a Text File
To write to a file, first open it in write or append mode. When we open an existing file in write mode,
the old data is wiped, and the file object is moved to the beginning of the file. In contrast, because
the file object is at the end of the file, new data will be added at the end of the old data in append
mode. After we've opened the file, we can use the following methods to write data to it:
● write(): used to write a single string
● writelines(): for writing a string sequence
4.5.1 The write() method
write() method takes a string as an argument and writes it to the text file. It returns the number of
characters being written on a single execution of the write() method. Also, we need to add a newline
character (\n) at the end of every sentence to mark the end of line.
Consider the following piece of code:
>>> myobject=open("myfile.txt",'w')
>>> myobject.write("Hey I have started
#using files in Python\n")
41
>>> myobject.close()
On execution, write() returns the number of characters written on to the file. Hence, 41, which is the
length of the string passed as an argument, is displayed.
Note: ‘\n’ is treated as a single character
If numeric data are to be written to a text file, the data needs to be converted into string before writing
to the file. For example
Page 72 of 200
>>>myobject=open("myfile.txt",'w')
>>> marks=58
#number 58 is converted to a string using
#str()
>>> myobject.write(str(marks))
2
>>>myobject.close()
The write() actually writes data onto a buffer. When the close() method is executed, the contents from
this buffer are moved to the file located on the permanent storage.
Program 2-1 Writing and reading to a text file
fobject=open("testfile.txt","w") # creating a data file
sentence=input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing a file
print("Now reading the contents of the file: ")
fobject=open("testfile.txt","r")
#looping over the file object to read the file
for str in fobject:
print(str)
fobject.close()
In Program 4.1, the file named testfile.txt is opened in write mode and the file handle named fobject
is returned. The string is accepted from the user and written in the file using write(). Then the file is
closed and again opened in read mode. Data is read from the file and displayed till the end of file is
reached.
Output of Program 2-1:
>>>
RESTART: Path_to_file\Program2-1.py
Enter the contents to be written in the file:
roll_numbers = [1, 2, 3, 4, 5, 6] Now reading the contents of the
file: roll_numbers = [1, 2, 3, 4, 5, 6]
>>>
4.6 Reading File
File object includes the following methods to read data from the file.
● read(chars): reads the specified number of characters starting from the current position.
● readline(): reads the characters starting from the current reading position up to a newline
character.
● readlines(): reads all lines until the end of file and returns a list object.
The following C:\myfile.txt file will be used in all the examples of reading and writing files.
This is the first line.
This is the second line.
This is the third line.
Page 73 of 200
The following example performs the read operation using the read(chars) method.
f = open('C:\myfile.txt') # opening a file
lines = f.read() # reading a file
print(lines) #'This is the first line. \nThis is the
second line.\nThis is the third line.'
f.close() # closing file object
Above, f = open('C:\myfile.txt') opens the myfile.txt in the default read mode from the current
directory and returns a file object. f.read() function reads all the content until EOF as a string. If you
specify the char size argument in the read(chars) method, then it will read that many chars only.
f.close() will flush and close the stream.
4.6.1 Reading a Line
The following example demonstrates reading a line from the file.
f = open('C:\myfile.txt') # opening a file
line1 = f.readline() # reading a line
print(line1) #'This is the first line. \n'
Page 74 of 200
The following code stores a list of numbers in a binary file. The list is first converted in a byte array
before writing. The built-in function byte array() returns a byte representation of the object.
f=open("binfile.bin","wb")
num= [5, 10, 15, 20, 25]
arr=bytearray(num)
f.write(arr)
f.close()
4.8 Access Mode of Files
The file access mode is a string that indicates how a file should be opened. When you use the open
function in Python to open a file, you can specify the mode in which the file should be opened. In
Python, there are numerous file access modes available:
● "r" (read mode): Open the file for reading. If the file does not exist, a FileNotFoundError is raised.
with open('file.txt', 'r') as f: # open the file in read-only mode.
content = f.read()
print(content)
● "w" (write mode): Open the file for writing. If the file exists, its contents are truncated. If the file
does not exist in the file path, a new file is created.
With open("file.txt", "w") as f: # Open the file in write mode
f.write("Hello, world!") # Write "Hello, world!" to the file
● "a" (append mode): Open the file for writing, but instead of truncating its contents, new data is
added to the end of the file. If the file does not exist in the file path, a new file is created.
with open('file.txt', 'a') as f: # Open the file in append mode
f.write('This is a new line.') # Append to already existing content
● "x" (exclusive creation mode): Open the file for writing, but only if the file does not already exist.
If the file exists, a File Exists Error is raised.
● "b" (binary mode): Open the file in binary mode. When used in combination with other modes,
the "b" mode changes the way data is read from or written to the file. For example, "rb" opens the
file in binary read mode, and "wb" opens the file in binary write mode.
with open("file.bin", "rb") as f: # Read binary data from a file
data = f.read()
print(data)
//Output:# b'\x01\x02\x03\x04'
● 't': Text mode: Used in combination with other modes to indicate that the file
should be opened in text mode (default).
● "+" (read and write mode): Open the file for reading and writing. The file's
pointer is positioned at the starting of the file.
● 'r+' Read and write mode: Opens the file for reading and writing and the pointer is placed at the
beginning of the file. If the file does not exist, an error is raised.
with open('file.txt', 'r+') as f: # open the file in read and write mode
content = f.read()
print(content)
f.seek(0) # Seek to the beginning of the file
Page 75 of 200
f.write('This is a new line.') # Write to the file
● 'a+' Read and append mode: Opens the file for reading and writing and the pointer is placed at
the end of the file. If the file does not exist in the file path it is created.
with open('file.txt', 'a+') as f: # Open the file in read and append mode
content = f.read()
print(content)
f.seek(0, 2) # Seek to the end of the file
f.write('This is a new line.') # Append to the file
4.9 Setting Offsets in a File
The functions we've learned so far are used to access data sequentially from a file. However, if we
want to retrieve data at random, Python provides the seek() and tell() functions.
4.9.1 The tell() method
This function returns a number indicating the file object's current location in the file. The supplied
position is the byte location from the start of the file to the current position of the file object. The
syntax for tell() is:
file_object.tell()
4.9.2 The seek() method
This method is used to position the file object at a particular position in a file. The syntax of seek()
is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object. That is, with reference to which
position, the offset has to be counted. It can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file.
For example, the statement fileObject.seek(5,0) will position the file object at 5th byte position from
the beginning of the file. The code in Program 2-2 below demonstrates the usage of seek() and tell().
Program 2-2 Application of seek() and tell()
Print ("Learning to move the file object")
fileobject=open("testfile.txt","r+")
str=fileobject.read()
print (str)
print ("Initially, the position of the file object is: ",fileobject. tell())
fileobject.seek(0)
print ("Now the file object is at the beginning of the file: ",fileobject.tell()) fileobject.seek(10)
print ("We are moving to 10th byte position from the beginning of file")
print ("The position of the file object is at", fileobject.tell())
str=fileobject.read()
print (str)
Page 76 of 200
Output of Program 2-2:
>>>
RESTART: Path_to_file\Program2-4.py
Learning to move the file object
roll_numbers = [1, 2, 3, 4, 5, 6]
Initially, the position of the file object is: 33
Now the file object is at the beginning of the file: 0
We are moving to 10th byte position from the beginning of file
The position of the file object is at 10 numbers = [1, 2, 3, 4, 5, 6]
>>>
4.10 Creating and Traversing a Text File
Let us now do some fundamental operations on a text file after we have learned various techniques
for opening and closing a file, reading and writing data in a text file, locating the position of the file
object, and moving the file object to a specified location. Assume we'll be working with practise.txt to
carry out these tasks.
4.10.1 Creating a file and writing data
We use the open() method to create a text file, passing in the filename and mode. If a file with the
same name already exists, the open() function will behave differently depending on the mode (write
or add). If it is in write mode (w), all existing file contents will be lost, and an empty file with the same
name will be created. If, on the other hand, the file is created in append mode (a), the new data will
be written after the existing data. If the file does not exist, a new empty file will be created in both
circumstances. In Programme 2-3, a file called practise.txt is opened in write mode (w), and three
sentences are saved in it. as shown in the output screen that follows it.
Program 2-3 To create a text file and write data in it
# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
data= input("Enter data to save in the text file: ")
fileobject.write(data)
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n': break
fileobject.close()
Output of Program 2-3:
>>>
RESTART: Path_to_file\Program2-3.py
Enter data to save in the text file: I am interested to learn about Computer Science
Do you wish to enter more data?(y/n): y
Enter data to save in the text file: Python is easy to learn
Do you wish to enter more data?(y/n): n
>>>
4.10.2 Traversing a file and displaying data
Page 77 of 200
We will return to the previous example, where we created the file practise.txt, to read and show data
saved in a text file. The file will be opened in read mode, with reading beginning at the beginning.
Program 2-4 To display data from a text file
fileobject=open("practice.txt","r")
str = fileobject.readline()
while str:
print(str)
str=fileobject.readline()
fileobject.close()
Output of Program 2-4:
>>>
I am interested to learn about Computer SciencePython is easy to learn
4.11 The Pickle Module
We already know that Python treats everything as an object. As a result, all data types, including
lists, tuples, dictionaries, and so on, are considered as objects. During the execution of a programme,
we may need to save the current state of variables so that we can return them to their original value
later. Assume you're playing a video game and want to quit after a while. As a result, the programme
should be able to save the current state of the game as a Python object, containing the current level
or stage, your score, and so on. Similarly, you might want to save a Python dictionary as an object
to be able to recover it later. Python includes a Pickle module that allows you to preserve any object
structure as well as data. Pickle is a Python package for serialising and de-serialising any Python
object structure. Pickling is a method of preserving food by immersing it in a solution that extends
its shelf life. In other words, it is a means of storing food for later use.
The pickle module handles binary files. Data is not written but dumped here, and data is not read
but loaded. To load and dump data, the Pickle Module must be imported. To work with binary files
for pickling and unpickling, the pickle module provides two methods: dump() and load().
4.11.1 The dump() method
This method is used to convert (pickling) Python objects for writing data in a binary file. The file in
which data are to be dumped, needs to be opened in binary write mode (wb).
Syntax of dump() is as follows:
dump(data_object, file_object)
where data_object is the object that has to be dumped to the file with the file handle named file_object.
For example, Program 2-6 writes the record of a student (roll_no, name, gender and marks) in the
binary file named mybinary.dat using the dump(). We need to close the file after pickling.
Program 2-5 Pickling data in Python
Import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()
4.11.2 The load() method
This method is used to load (unpickling) data from a binary file. The file to be loaded is opened in
binary read (rb) mode. Syntax of load() is as follows:
Store_object = load(file_object)
Page 78 of 200
Here, the pickled Python object is loaded from the file having a file handle named file_object and is
stored in a new file handle called store_object. The program 2-7 demonstrates how to read data from
the file mybinary.dat using the load().
Program 2-6 Unpickling data in Python
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb") objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Output of Program 2-6:
>>>
RESTART: Path_to_file\Program2-7.py
The data that were stored in file are: [1, 'Geetika', 'F', 26]
>>>
4.11.3 File handling using pickle module
In the same way that we read and write data in a text file, we will add and display data in a binary
file. Programme 2-8 accepts an employee record from the user and appends it to the binary file TV.
The records are then read from the binary file and presented on the screen using the same object.
The user is free to enter as many records as they want. Before beginning the reading process, the
programme also displays the size of binary files.
Program 2-7 To perform basic operations on a binary file using pickle module
# Program to write and read employee records in a binary file import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1 print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
Page 79 of 200
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError: pass
bfile.close()
Output of Program 2-7:
>>>
RESTART: Path_to_file\Program2-8.py
WORKING WITH BINARY FILES
Enter Records of Employees
RECORD No. 1
Employee number : 11
Employee Name : D N Ravi
Basic Salary : 32600
Allowances : 4400
TOTAL SALARY : 37000
Do you wish to enter more records (y/n)? y
RECORD No. 2
Employee number : 12
Employee Name : Farida Ahmed
Basic Salary : 38250
Allowances : 5300
TOTAL SALARY : 43550
Do you wish to enter more records (y/n)? n
Record entry OVER
Size of binary file (in bytes): 216
Page 80 of 200
Now reading the employee records from the file
Record Number : 1
[11, 'D N Ravi', 32600, 4400, 37000]
Record Number : 2
[12, 'Farida Ahmed', 38250, 5300, 43550]
>>>
As each employee record is stored as a list in the file empfile.dat, hence while reading the file, a list
is displayed showing the record of each employee. Notice that in Program 2-8, we have also used try.
except block to handle the end-of-file exception.
Page 81 of 200
Chapter 5. Exception Handling in Python
5.1 Introduction to Exception Handling
Each and every exception has to be handled by the programmer to avoid the program from crashing
abruptly. This is done by writing additional code in a program to give proper messages or instructions
to the user on encountering an exception. This process is known as exception handling.
Here is simple syntax of try....except...else blocks :
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
5.1.1 Syntax Error: Syntax errors are detected when we have not followed the rules of the particular
programming language while writing a program. These errors are also known as parsing errors. On
encountering a syntax error, the interpreter does not execute the program unless we rectify the errors,
save and rerun the program. When a syntax error is encountered while working in shell mode, Python
displays the name of the error and a small description about the error as shown in figure 5.1
Page 82 of 200
Fig 5.2: An error in the script
5.1.2: Exceptions: Even if a statement or expression is syntactically correct, there might arise an
error during its execution. For example, trying to open a file that does not exist, division by zero and so
on. Such types of errors might disrupt the normal execution of the program and are called exceptions.
An exception is a Python object that represents an error. When an error occurs during the execution of
a program, an exception is said to have been raised. Such an exception needs to be handled by the
programmer so that the program does not terminate abnormally. Therefore, while designing a program,
a programmer may anticipate such erroneous situations that may arise during its execution and can
address them by including appropriate code to handle that exception.
It is to be noted that Syntax Error shown in Figures is also an exception. But, all other exceptions
are generated when a program is syntactically correct.
5.1.3 Need of Exception Handling: Exception handling is being used not only in Python
programming but in most programming languages like C++, Java, Ruby, etc. It is a useful technique
that helps in capturing runtime errors and handling them so as to avoid the program getting crashed.
Following are some of the important points regarding exceptions and their handling:
• Python categorises exceptions into distinct types so that specific exception handlers (code to
handle that particular exception) can be created for each type.
• Exception handlers separate the main logic of the program from the error detection and
correction code. The segment of code where there is any possibility of error or exception, is placed
inside one block. The code to be executed in case the exception has occurred, is placed inside
another block. These statements for detection and reporting the exception do not affect the main
logic of the program.
• The compiler or interpreter keeps track of the exact position where the error has occurred.
• Exception handling can be done for both user-defined and built-in exceptions.
5.2 User Defined Exception: Python detects all the critical errors that occur during Compile-
time and Runtime. It stops the program's execution if the error occurs and raises an exception. Some
commonly raised Exceptions are ArithmeticError, AttributeError, ImportError, IOError,
FileNotFoundError, etc.
Sometimes we must enforce constraints on the values that specific program variables can take or
save the program from running into an undesired state. In such situations, Python allows
programmers to create User-defined Exceptions.
Page 83 of 200
To create a User-defined Exception, we need to create a class directly or indirectly derived from the
built-in Exception class.
Page 84 of 200
Program 1-2 Using try.except block
print ("Practicing for try block") try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print(quotient)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed") print(“OUTSIDE
try..except block”)
In Program 1-2, the ZeroDivisionError exception is handled. If the user enters any non-zero value as
denominator, the quotient will be displayed along with the message “Division performed
successfully”, as shown in Figure 1.10. The except clause will be skipped in this case. So, the next
statement after the try..except block is executed and the message “OUTSIDE try.. except block” is
displayed.
However, if the user enters the value of the denominator as zero (0), then the execution of the try
block will stop. The control will shift to the except block and the message “Denominator as Zero…. not
allowed” will be displayed, as shown in Figure 1.11. Thereafter, the statement following the try..except
block is executed and the message “OUTSIDE try..except block” is displayed in this case also.
Page 85 of 200
Program1-3 Use of multiple except clauses
print ("Handling multiple exceptions") try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
In the code, two types of exceptions (ZeroDivisionError and ValueError) are handled using two
exception blocks for a single try block. When an exception is raised, a search for the matching except
block is made till it is handled. If no match is found, then the program terminates.
However, if an exception is raised for which no handler is created by the programmer, then such an
exception can be handled by adding an except clause without specifying any exception. This except
clause should be added as the last clause of the try..except block. The Program 1-4 given below along
with the output given in Figure 1.11 explains this.
Program 1-4 Use of except without specifying an exception
print ("Handling exceptions without naming them") try: numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ValueError:
print ("Only INTEGERS should be entered")
except:
print (" OOPS.....SOME EXCEPTION RAISED")
If the above code is executed, and the denominator entered is 0 (zero), the handler for
ZeroDivisionError exception will be searched. Since it is not present, the last except clause (without
any specified exception) will be executed, so the message “OOPS.....SOME EXCEPTION RAISED” will
be displayed.
Page 86 of 200
no error then none of the except blocks will be executed. In this case, the statements inside the else
clause will be executed. Program 1-5 along with its output explains the use of else block with the
try... except block.
Program 1-5 Use of else clause
print ("Handling exception using try...except...else") try: numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ",quotient)
Output:
Page 87 of 200
print ("OVER AND OUT")
In the above program, the message “OVER AND OUT” will be displayed irrespective of whether an
exception is raised or not.
5.8 Recovering and continuing with finally: If an error has been detected in the try block and
the exception has been thrown, the appropriate except block will be executed to handle the error.
But if the exception is not handled by any of the except clauses, then it is re-raised after the execution
of the finally block. For example, Program 1.4 contains only the except block for ZeroDivisionError.
If any other type of error occurs for which there is no handler code (except clause) defined, then also
the final clause will be executed first. Consider the code given in Program 1-7 to understand these
concepts.
Program 1-7 Recovering through finally clause
print (" Practicing for try block")
try: numerator=50
denom=int(input("Enter the denominator")) quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT")
While executing the above code, if we enter a non-numeric data as input, the finally block will be
executed. So, the message “OVER AND OUT” will be displayed. Thereafter the exception for which
the handler is not present will be re-raised. The output of Program 1-7 is shown in the below Figure.
Page 88 of 200
exception raised in the try block. The optional else clause contains codes to be executed if no
exception occurs. The optional finally block contains codes to be executed irrespective of whether an
exception occurs or not.
S. Name of the Explanation
No Builtin Exception
1. SyntaxError It is raised when there is an error in the syntax of the Python code.
4. ValueError It is raised when a built-in method or operation receives an argument
that has the right data type but mismatched or inappropriate values.
5. IOError It is raised when the file specified in a program statement cannot be
opened.
4 KeyboardInterrupt It is raised when the user accidentally hits the Delete or Esc key while
executing a program due to which the normal flow of the program is
interrupted.
5 ImportError It is raised when the requested module definition is not found.
6 EOFError It is raised when the end of file condition is reached without reading any
data by input ().
7 ZeroDivisionError It is raised when the denominator in a division operation is zero.
8 IndexError It is raised when the index or subscript in a sequence is out of range.
9 NameError It is raised when a local or global variable name is not defined.
10 IndentationError It is raised due to incorrect indentation in the program code.
11 TypeError It is raised when an operator is supplied with a value of incorrect data
type.
12 OverFlowError It is raised when the result of a calculation exceeds the maximum limit
for numeric data type.
Built-in Exception Classes - Commonly occurring exceptions are usually defined in the
compiler/interpreter. These are called built-in exceptions.
Python’s standard library is an extensive collection of built-in exceptions that deals with the
commonly occurring errors (exceptions) by providing the standardised solutions for such errors. On
the occurrence of any built-in exception, the appropriate exception handler code is executed which
displays the reason along with the raised exception name. The programmer then has to take
appropriate action to handle it. Some of the commonly occurring built-in exceptions that can be
raised in Python are explained in the following table.
Table 1.1 Built-in exceptions in Python
Figure shows the built-in exceptions viz, ZeroDivisionError, NameEError, and TypeError raised by
the Python interpreter in different situations
Page 89 of 200
Fig. 5.10: Example of built-in exceptions
A programmer can also create custom exceptions to suit one’s requirements. These are called user-
defined exceptions. We will learn how to handle exceptions in the next section.
Page 90 of 200
Chapter 6. Implement data structure
using python
6.1 Stack:
The stack is known as a Last in First Out (LIFO) list because the pieces added at the end are
eliminated first. In a stack, the topmost piece that was inserted last is processed first, while the first
element that was placed is handled last. As shown in the figure, this is a stack of books in which the
first book will be placed at the bottom, and the second book will be placed on top. Inserting the third
book will move it to the top of the list. Inserting an element into the stack is referred to as a "push,
while removing an element from the stack is referred to as a "pop." A pointer keeps track of the stack's
top element.
Page 91 of 200
An opPush function that inserts (pushes) a new element into the stack. This function takes two
parameters: the name of the stack (glassStack) into which the element is to be added and the element
to be inserted. We know that an element is always inserted at the top of the stack. As a result, we'll
use the list's built-in method append() to add an element to the stack, which always adds at the end
of the list. Because Python has no restriction on the size of a list, the implemented stack will never
be full unless there is no more memory available. As a result, we will never encounter the 'overflow'
(no space for new elements) stack situation.
def opPush(glassStack,element):
glassStack.append(element)
A function named size to read the number of elements in the glassStack. We will use the len() function
of list in Python to find the number of elements in the glassStack.
def size(glassStack):
return len(glassStack)
A function named top to read the most recent element (TOP) in the glassStack.
def top(glassStack):
if isEmpty(glassStack):
print('Stack is empty')
return None
else:
x =len(glassStack)
element=glassStack[x-1]
return element
A function named opPop to delete the topmost element from the stack. It takes one parameter - the
name of the stack (glassStack) from which element is to be deleted and returns the value of the
deleted element. The function first checks whether the stack is empty or not. If it is not empty, it
removes the topmost element from it. We shall use the builtin method pop() of Python list that
removes the element from the end of the list
def opPop(glassStack):
if isEmpty(glassStack):
print('underflow')
return None
else:
return(glassStack.pop())
A function named display to show the contents of the stack.
def display(glassStack):
x=len(glassStack)
print("Current elements in the stack are: ")
for i in range(x-1,-1,-1):
print(glassStack[i])
Once we define the above functions we can use the following Python code to implement a stack of
glasses.
glassStack = list() # create empty stack
Page 92 of 200
#add elements to stack
element='glass1'
print("Pushing element ",element)
opPush(glassStack,element)
element='glass2'
print("Pushing element ",element)
opPush(glassStack,element)
#display number of elements in stack
print("Current number of elements in stack is",size(glassStack))
#delete an element from the stack
element=opPop(glassStack)
print("Popped element is",element)
#add new element to stack
element='glass3'
print("Pushing element ",element)
opPush(glassStack,element)
#display the last element added to the
#stack
print("top element is",top(glassStack))
#display all elements in the stack
display(glassStack)
#delete all elements from stack
while True:
item=opPop(glassStack)
if item == None:
print("Stack is empty now")
break
else:
print("Popped element is",item)
The output of the above program will be as follows:
Pushing element glass1
Pushing element glass2
Current number of elements in stack is 2
Popped element is glass2
Pushing element glass3
top element is glass3
Current elements in the stack are:
glass3
glass1
Page 93 of 200
Popped element is glass3
Popped element is glass1
Underflow
Stack is empty now
6.3 PUSH and POP Operations
PUSH adds a new element to the stack's top. It is an implantation procedure. We can add pieces to
a stack until it is completely filled. When no more items can be added to a stack, it is said to be full.
Attempting to add an element to a full stack results in an 'overflow' exception. The POP operation is
used to remove the stack's topmost element, that is, the element at the top of the stack. It's a removal
operation. We can delete elements from a stack until it is empty, which means it has no elements.
Attempting to delete an element from an empty stack raises the 'underflow' exception.
In LIFO order, elements are inserted and deleted from a stack. The same concept is used when adding
and removing glasses from a pile. Assume that each glass is numbered and build a stack of glasses.
Figure 6.2 depicts visual representations of PUSH and POP operations on a stack of glasses.
Page 94 of 200
return "stack is empty"
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
6.4 Implementation of queue using Python
There are many ways in which queues can be implemented in a computer program, one way is using
the list data type of Python. For creating a queue structure in the program, following functions need
to be defined:
Let’s create a queue named myQueue. We can create it by assigning an empty list.
myQueue = list()
A function (enqueue) to insert a new element at the end of the queue. The function has two
parameters - name of the queue and element which is to be inserted in the queue.
def enqueue(myQueue, element):
myQueue.append(element)
Note: append() function always adds an element at the end of the list, hence Rear of queue.
We don’t need to implement Is Full, as Python being a dynamic language, does not ask for the creation
of lists having fixed size. Hence, we will never encounter a situation when the queue is full.
A function (isEmpty) to check, if the queue has an element or not? This can be done by checking the
length of the queue. The function has a parameter -- name of the queue and returns True if the queue
is empty False otherwise.
def isEmpty(myQueue):
if len(myQueue)==0:
return True
else:
return False
A function (dequeue) to delete an element from the front of the queue. It has one parameter - name
of the queue and returns the deleted element. The function first checks if the queue is empty or not,
for successful deletion.
def dequeue(myQueue):
if not (isEmpty(myQueue)):
return myQueue.pop(0)
else :
print(“Queue is empty”)
Note: The pop() function with index[0] will delete the element from the beginning of the list, hence
Front of queue.
Page 95 of 200
A function (size) to get the number of elements in the queue. We can use the len() function of Python’s
list to find the number of elements in the queue. The function has one parameter - name of the queue
and returns the number of elements in the queue.
def size(myQueue):
return len(myQueue)
A function (peek) to simply read, but not to delete, the element at the front end of the queue. For this,
we can read the element at index[0] of the queue. The function has one parameter - name of the
queue and returns the value of element at Front if the queue is not empty, None otherwise.
def peek(myQueue):
if isEmpty(myQueue):
print('Queue is empty')
return None
else:
return myQueue[0]
Let us consider the example of a queue that people form while waiting at a bank cash counter.
Usually, following are the events that occur in queue:
• Two friends come together and go to the cash counter, i.e. they form a queue - enqueue operation
is performed two times.
• As soon as the person at the front is serviced, he will be removed from the queue - thus dequeue
operation is performed. Cashier calls Next to serve the next person who is now at the front of the
queue.
• Cashier wants to know the length of the queue - size of the queue is checked.
• Meanwhile, a few more people walk in the bank, and three of them join the queue at the cash
counter, i.e. enqueue happens 3 times.
• Another person gets served and leaves the counter, i.e. dequeue is performed. Cashier calls Next
to serve another person.
• The Next three people get served one after another, i.e. dequeue is performed thrice.
• Cashier calls Next and realises that there are no more people to be served - underflow situation
happens
Now, let us write the code for the above scenario of the bank
Program 3-1 :
myQueue = list()
# each person to be assigned a code as P1, P2, P3,...
element = input("enter person’s code to enter in queue :”)
enqueue(myQueue,element)
element = input("enter person’s code for insertion in queue :")
enqueue(myQueue,element)
print("person removed from queue is:", dequeue(myQueue))
print(“Number of people in the queue is :”,size(myQueue))
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
Page 96 of 200
enqueue(myQueue,element)
print("Now we are going to remove remaining people from the queue")
while not isEmpty(myQueue):
print("person removed from queue is ",
dequeue(myQueue))
Output of Program 3-1:
enter person’s code to enter in queue :P1
enter person’s code to enter in queue :P2
person removed from the queue is :p1
number of people in the queue is :1
enter person’s code to enter in queue :P3
enter person’s code to enter in queue :P4
enter person’s code to enter in queue :P5
Now we are going to remove remaining people from the queue
person removed from the queue is :p2
person removed from the queue is :p3
person removed from the queue is :p4
person removed from the queue is :p5
Queue is empty
6.5 Operations on Queue Using Python
1. ENQUEUE (Insert)
2. DEQUEUE (Delete)
1. ENQUEUE: It is used to insert a new element to the queue at the rear end. We can insert elements
in the queue till there is space in the queue for adding more elements. Inserting elements beyond
capacity of the queue will result in an exception - known as Overflow.
⮚ Let’s create a queue named myQueue. We can create it by assigning an empty list.
myQueue = list()
⮚ A function (enqueue) to insert a new element at the end of the queue. The function has two
parameters - name of the queue and element which is to be inserted in the queue.
def enqueue(myQueue, element):
myQueue.append(element)
Note: append() function always adds an element at the end of the list, hence Rear of queue.
2. DEQUEUE: It is used to remove one element at a time from the front of the queue. We can delete
elements from a queue until it is empty, trying to delete an element from an empty queue will result
in an exception - known as Underflow.
⮚ Let’s create a queue named myQueue. We can create it by assigning an empty list.
myQueue = list()
A function (dequeue) to delete an element from the front of the queue. It has one parameter - name
of the queue and returns the deleted element. The function first checks if the queue is empty or not,
for successful deletion.
def dequeue(myQueue):
Page 97 of 200
if not (isEmpty(myQueue)):
return myQueue.pop(0)
else :
print(“Queue is empty”)
Note: The pop() function with index[0] will delete the element from the beginning of the list, hence
Front of queue.
To perform enqueue and dequeue efficiently on a queue, following operations are also required:
• IS EMPTY : used to check whether the queue has any element or not, so as to avoid Underflow
exceptions while performing dequeue operation.
def isEmpty(myQueue):
if len(myQueue)==0:
return True
else:
return False
• PEEK : used to view elements at the front of the queue, without removing it from the queue.
def peek(myQueue):
if isEmpty(myQueue):
print('Queue is empty')
else:
return myQueue[0]
• IS FULL : used to check whether any more elements can be added to the queue or not, to avoid
Overflow exceptions while performing enqueue operation.
Program3-2:
myQueue = list()
# each person to be assigned a code as P1, P2, P3,...
element = input("enter person’s code to enter in queue :”)
enqueue(myQueue,element)
element = input("enter person’s code for insertion in queue :")
enqueue(myQueue,element)
print("person removed from queue is:", dequeue(myQueue))
print(“Number of people in the queue is :”,size(myQueue))
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
print("Now we are going to remove remaining people from the queue")
while not isEmpty(myQueue):
print("person removed from queue is ",
Page 98 of 200
dequeue(myQueue))
Output 3-2
enter person’s code to enter in queue :P1
enter person’s code to enter in queue :P2
person removed from the queue is :p1
number of people in the queue is :1
enter person’s code to enter in queue :P3
enter person’s code to enter in queue :P4
enter person’s code to enter in queue :P5
Now we are going to remove remaining people from the queue
person removed from the queue is :p2
person removed from the queue is :p3
person removed from the queue is :p4
person removed from the queue is :p5
Queue is empty
6.5.1 Double ended Queue
A deque (pronounced "deck") is an arrangement in which element(s) can be added or removed from
any end, i.e., head/front or tail/rear. This data structure has no restrictions on the side from which
elements can be added or removed; hence, it can be used to build a stack or queue in a programme.
It is also known as a double-ended queue since it allows for insertion and deletion of operations from
either end.
Fig: 6.3 Basic deque structure displaying head and tail to implement stack or queue
6.6 Sequential / Linear Search
The most basic and simplest search method is linear search. It is a method of exhaustive searching
in which each member of a given list is compared to the object to be searched (commonly referred to
as the 'key'). As a result, each element in the list is compared to the key one by one. This method is
repeated until an element matching the key is located and the search is declared successful. If no
element matches the key after traversing the complete list, we declare the search to be unsuccessful,
indicating that the key is not present in the list. This item-by-item comparison is performed in the
order in which the elements appear in the list, commencing with the first element and progressing to
the last. As a result, it is also known as sequential search or serial search. This strategy is excellent
for collecting materials that are small and unsorted. Given a list n umL is I of n elements and key
value K, Algorithm uses a linear search algorithm to find the position of the key K in numL is I.
Algorithm fi. J: Linear Search
LinearSearch(numList, key, n)
Step 1: SET index = 0
Step 2: WHILE index < n, REPEAT
Page 99 of 200
Step 3: IF num1ist[index]= key THEN
PRINT “Element found at position”, index+ 1 STOP
ELSE
index = index+ 1
Step 4: PRINT “Search unsuccessful”
Example: Assume that the numList has seven elements [8, -4, 7, 17, 0, 2, 19]
so, n = 7. We need to search for the key, say 17 in numList. Table 6.1 shows the
elements in the given list along with their index values.
Table 6.1: Elements in numList alongwith their index value
The step-by-step process of linear search using Linear Search Algorithm is given in Table 6.2
Table 6.4 Linear search for key 17 in numList given in Table 6.3
From Table 6.4 Therefore, it is obvious that the algorithm only needed to perform one comparison to
display 'Element found at location 1'. As a result, if the search key is the first item in the list, the
linear search algorithm will always have to conduct only one comparison. This is the very minimum
Note that the algorithm had to make only 1 iteration to display ‘Element found at position 8’. This is
because the key being searched is the middle element in the list. Thus, binary search requires only
1 iteration when the key to be searched is the middle value in the list. This is the minimum amount
of work binary search would have to do to confirm that a key is present in the list.
Now, let us search for key 2 in the list. numList = [2,3,5,7,10,11,12,17,19,23,29,3 1,37,41,43]
In the first iteration, we have the mid value as 17. As 2 is smaller than the mid value (17), we have
to search for the first half of the list in the second iteration. We now consider only 7 elements. As 2
is smaller than the new mid value (7), we have to search for the first half of the remaining list in the
third iteration. We now consider only 3 elements. Observe that the number of elements in the numList
is halved each time. It reduces from 15 elements in iteration 1 to 7 elements in iteration 2, and to 3
elements in iteration 3. In the 3rd iteration, the algorithm finds that key 2 is smaller than the new
As we can see, the binary search algorithm had to make 4 iterations to narrow down the list to a
single element and decide that the search key is the first element of the list. This is clearly the
maximum work required to find a key in the given list.
Program3-6. Binary Search
def binarySearch (list, key):
first = 0
last = len (list) - 1
while (first <= last):
mid (first + last) //2
if list [mid] == key:
return mid
elif key> list(mid]:
first mid + 1
elif key < list [mid]:
last = mid -1
return -1
listl=[] #Create an empty list
print ("Create a list by entering elements in ascending order")
print ("press enter after each element, press -999 to stop")
num = int(input ())
while num!=-999:
list1.append(num)
num = int (input())
Let us consider a list of numbers (34, 16, 2, 93, 80, 77, 51). We can use the hash function remainder
method explained earlier to create a hash table as shown in table below
Table6.9: hash function element % 10 applied on the elements of list
After computing the hash values, each element is inserted at its designated position in the hash table
shown in Table below
Now, to search for a key, we can calculate its index using the hashing function and compare the
element at that index with the key to declare whether the element is present in the list or not. This
search operation involves just one comparison and hence the same amount of time is always required
to search a key irrespective of the size of the list.
Program: Use of hashing to find a key in the given list L
#Function to check if a key is present or not def hashFind(key,hashTable)
Def hashfind (key, hashtable):
If (hashtable [key % 10] == key): #key is present
return ( ( key % 10)+ 10) #return the position
else:
return None #key is not present
#end of function
#create hashtable with 10 empty positions
Hashtable = [None, None, None, None, None, None, None, None, None, None
]
Print (“We have created a hashtable of 10 positions :”)
Print (hashTable)
Handling Big
Project
Effectiveness Reliable
Purpose of
Software
Engineering
decrease
Productivity
time
Requireme
nt Analysis
Feasibility
Maintenance
Study
SDLC
(Software
Development
Deployment Life Cycle) Design
Testing Coding
It's completely feasible that a product will pass verification yet fail validation. This can occur when, for
example, a product is created according to specifications yet the specifications do not satisfy the user's
demands. It is important to:
• Trust but Verify
• Verify but also Validate
8.3 Test Cases
A test case is a document that contains a set of test data, preconditions, expected results, and post
conditions created for a specific test scenario in order to verify compliance with a specific requirement.
Following the application of a set of input values, the programmer has a final result and exits the
system at some point, also known as the execution post condition.
Acceptance Testing
Requirements
System Testing
System
Integration
System
Testing
Design
Unit
Unit design
Testing
Development
Fig 8.8 Types of testing
(i) Acceptance testing: Acceptance testing is often done by the customer to ensure that the delivered
product meets the requirements and works as the customer expected. It falls under the category of
black-box testing
(ii) Regression testing: Regression testing is the testing after modification of a system, component, or
a group of related units to ensure that the modification is working correctly and is not damaging or
imposing other modules to produce unexpected results. It falls under the category of black-box testing.
(iii) Beta testing: Beta testing is the testing which is done by end users, a team outside development,
or publicly releasing full pre-version of the product which is known as beta version. The aim of beta
testing is to cover unexpected errors. It falls under the category of black-box testing.
(iv) Unit testing: Unit testing is the testing of an individual unit or group of related units. It falls under
the category of white-box testing. It is often done by the programmer to test that the unit he/she has
implemented is producing expected output against given input. Statements, functions, methods,
interfaces i.e. units of the code are individually tested for proper execution. It can be automated or can
be done manually. Usually small data is used for unit testing.
(v) Integration testing: Integration testing is testing in which a group of components are combined to
produce output. Also, the interaction between software and hardware is tested in integration testing if
software and hardware components have any relation. It may fall under both white-box testing and
black-box testing. Different approaches used in integration testing are: top down and bottom up
integration testing, sandwich testing (combination of both).
(vi) Stress testing: Stress testing is the testing to evaluate how a system behaves under unfavourable
conditions. Testing is conducted beyond the limits of the specifications. It falls under the category of
black-box testing.
(vii) Performance testing: Performance testing is the testing to assess the speed and effectiveness of
the system and to make sure it is generating results within a specified time as in performance
requirements. It falls under the category of black-box testing.
(viii) Functional testing: Functional testing is the testing to ensure that the specified functionality
required in the system requirements works. It falls under the category of black-box testing.
(ix) System testing: System testing is the testing to ensure that by putting the software in different
environments (e.g., Operating Systems) it still works. System testing is done with full system
implementation and environment. It falls under the category of black-box testing. It is performed after
This is a document
This mentions relating to the
This describes how detail aspects of requirement gathering
Functional test team,
far testing should phase in the SDLC. This
Requirements responsibility
take place before matrix is updated as
releasing the matrix and new needs are
product. rights/responsibili received. These
ty of test matrices assist testers
manager and test in determining the
engineer. source of the demand.
They can be followed
in both directions.
Test Case
Test description Test Case report Test logs
document
This document
contains list of
tests required to This document is a
be conducted. It detailed This document This document
includes Unit test description of all contains test case contains test logs
plan, Integration test cases and report as a result for every test case
test plan, System procedures to of the test. report
test plan and execute them.
Acceptance test
plan.
Library
Generate Fee Management
Report System
LOGIN
MENU
Data Base
Mother
dob Name Addres
s Student Name
Mobile
numbe
r
Name Student Fee Report
Information
Branch
Email
Father ID Receipt
Name No.
Gende
r Date
Admission
No.
Author
Code
Address Enter Roll Number
No.
Library Mangement
Book
Borrowed
Surname
Date Days in
Due Loan
Student Marksheet
First
Email
Name Gender id
Member
type No.
School Name
Reference
Name
No.
Father
Name
Search Page.
Contact
Adding New
Management Delete Contact
Contacts
System
Updating
Contacts
Data
Base
Based on the complexity weightings, one can assign a value to each function point based on the
complexity of the specific functionality in the Contact Management System project. The total functional
points can then be calculated by multiplying the assigned values with the complexity weights and
summing them up for each function type.
For example, if you determine that adding a contact has average complexity, the functional points for
External Inputs (EI) would be 4. Similarly, if displaying contact details is of low complexity, the
functional points for External Outputs (EO) would be 4. After assigning values to each function point,
you can calculate the total functional points by summing up the function points for each function type.
10.4.2 Risk Table
Risk ID Risk Description Probability Impact Severity Mitigation Strategy
R1 Lack of User High High High Conduct thorough user training
Adoption and provide ongoing support.
Ensure the system is intuitive and
user-friendly.
R2 Data Loss or Medium High High Implement robust data backup and
Security Breach security measures, such as
encryption and access controls.
Regularly perform security audits.
R3 Integration Medium Medium Medium Conduct thorough compatibility
Challenges with testing and ensure proper
APIs documentation and support for API
integration. Have fullback options
in case of integration issues.
R4 Inadequate Medium Medium Medium Optimise code and database
System queries for efficient performance.
Performance Perform load testing to identify and
address performance bottlenecks.
R5 Requirement High Medium High Maintain effective communication
Changes or Scope with stakeholders, document
Creep requirements clearly, and manage
scope changes through change
control processes.
R6 Inadequate Medium Medium Medium Implement a comprehensive testing
Testing and plan, including unit testing,
Quality Assurance integration testing, and user
acceptance testing. Follow best
practices for code review and
quality assurance.
First Name
Contact
Addres
s
Gender
Age
First Name
Contact
Updating Contacts
Last Name
Address
Gender
Age