You are on page 1of 115

ISBN: 978-81-943696-6-0 Publication Year: 2020 Edition: 1st

Pages: 376 MRP: 475.00 Paperback

Click Here to Buy Main Book Online


Computer Science with Python Programming is a textbook designed for the students of Class XII, CBSE. It covers complete course of
Computer Science. The book has been written in easy to understand language and contains ample examples. However, every attempt has been
made to keep the text as precise as possible.
The code has been tested in Python 3.x on a machine with Windows 10.
Each chapter of the book includes a variety of end-chapter exercises in the form of MCQs with answers, review questions, and programming
exercises to help readers test their knowledge. It may be stated here that the topics in the book have been written considering the fact that some
of the readers may opt Computer Science as their career.
Key Features:
• The book has sections dedicated to Computer System and Organization to help the students to understand the basics.
• Offers in-depth treatment of topics such as Pyplot and functions.
• The book introduces Django.
• Provides points to remember and a Glossary with definitions of the key terms at the end of each chapter which will help readers to
quickly recollect the important concepts.
• Questions, given at the end of each chapter and the Appendices would help students during viva and examinations.
Harsh Bhasin has done his B Tech. in Computer Science and M Tech. in Computers and is currently pursuing PhD. He qualified UGC NET in
2012 and received the Visvesvaraya Fellowship from DIETY in 2016. He was awarded the Young Researcher’s Award by ErNet in 2012. Mr.
Bhasin has authored a few papers, including those published in journals like Soft Computing. He has also authored “Programming in C#”
(2014), “Algorithm Analysis and Design” (2015) and “Theory of Computation”. He has been actively involved in research both as an author
and reviewer for ACM, Pearson, Oxford University Press, Springer etc. Mr. Bhasin was the editor in chief of the special issue on
“Applicability of Soft Computing Techniques in NP Problems,” SciEp, USA.
Professionally, Mr. Bhasin is a programmer and has been involved in the development of many Enterprise Resource Planning Systems while
being the proprietor of a firm based in Faridabad, Haryana, India. He has a vast industrial experience. He was an Assistant Professor in
Department of Computer Science, FMIT, Jamia Hamdard. He has also taught as visiting faculty in many colleges including Delhi
Technological University.
His areas of interest include Genetic Algorithms, Theory of Computation, C#, Python, Algorithms, Cellular Automata and Machine
Learning.
His personal interests include Hindi poetry and Hindustani Classical Music. Mr. Bhasin is also a blogger. You can reach him at his
Facebook page DTU Computation or via email at i_harsh_bhasin@yahoo.com.

LONDON • NEW DELHI • NAIROBI


Bangalore • Chennai • Cochin • Guwahati • Hyderabad • Kolkata • Lucknow • Mumbai
NEW AGE
Visit us at www.newagepublishers.com
COMPUTER SCIENCE
WITH

PYTHON
SUPPLEMENT
For the new topics introduced by CBSE in
the latest Syllabus issued in July, 2020

CLASS XII

Committed to Educate the Nation

IN INDIA

NEW AGE INTERNATIONAL (P) LIMITED, PUBLISHERS


LONDON • NEW DELHI • NAIROBI

Visit us at www.newagegolden.com
Dear Students
Use this free Supplement
along with the
Main Book

Click Here to Buy Main Book Online

LONDON • NEW DELHI • NAIROBI


Bangalore • Chennai • Cochin • Guwahati • Hyderabad • Kolkata • Lucknow • Mumbai
NEW AGE
Visit us at www.newagepublishers.com
COMPUTER SCIENCE WITH PYTHON
CLASS XII
New topics introduced in the Latest Syllabus Issued by CBSE for Academic Year 2020-21
Dear Teachers/Students
Please note that the CBSE has introduced new topics in the syllabus for the academic year
2020-21 in Computer Science with Python. We have therefore added these new topics in the
additional matter section of this Supplement.

UNIT 1: COMPUTATIONAL THINKING AND PROGRAMMING–2


File Handling
1.
Text File: Basic operations on a text file: Open (filename – absolute or relative path,
mode), Close a text file, Reading and Manipulation of data from a text file, Appending
data into a text file, standard input / output and error streams, relative and absolute paths.
2.
Binary File: Basic operations on a binary file: Open (filename – absolute or relative
path, mode), Close a binary file, Pickle Module – methods load and dump; Read, Write/
Create, Search, Append and Update operations in a binary file.
3.
CSV File: Import csv module, functions – Open, Close a csv file, Read from a csv file
and Write into a csv file using csv.reader ( ) and csv.writerow( ).
Mutable/immutable properties of data objects

UNIT 2: COMPUTER NETWORKS


Networking III
1. Mobile processors; https; Introduction To Web services: WWW, Extensible Markup
Language (XML); Domain Names; URL; Web Hosting, infrared, radio link, microwave
link and satellite link.
2. WiFi card, RJ45 connector, Modem, Tree, PAN PPP Wireless / Mobile Communication
protocol such as GSM, GPRS and WLL. Remote Login (Telnet) and Internet
3. Evolution of Networking: ARPANET, Internet, Interspace Different ways of sending
data across the network with reference to switching techniques (Circuit and Packet
switching).
4. Data Communication terminologies: Concept of Channel, Bandwidth (Hz, KHz, MHz)
and Data transfer rate (bps, Kbps, Mbps, Gbps, Tbps)
Along with these topics this supplement also contains three other units consisting of chapters
shifted to class XII syllabus.
The following table maps the rest of the topics with the sections of the main course book.

Author

(i)
CLASS XII, CBSE, COMPUTER SCIENCE,
REVISED SYLLABUS (2020-2021)
Unit I
Data-structures: Lists as covered in Class XI, Stacks – Push, Pop Chapter 10
using a list
Using Python libraries: Import Python libraries Chapter 5
Functions: scope, parameter passing, passing strings, lists, tuples, Chapter 3
dictionaries to functions, default parameters, positional parameters,
return values

Unit II
Mobile Telecommunication Technologies 1G, 2G, 3G, 4G and 5G
12.14 XII CS
Electronic mail protocols such as SMTP, POP3 12.7 to 12.10 XII CS
India IT Act, Cyber Law, Cyber Crimes, IPR issues, hacking Chapter 17, CS XII
Hyper Text Markup Language (HTML) 12.5
Hyper Text Transfer Protocol (HTTP) 12.5
Transmission media: Twisted pair cable, coaxial cable, optical 11.4 CS, XII
fiber
Network devices: Ethernet Card, Router, Switch, Gateway 11.7 CS XII
Network Topologies and types: Bus, Star, LAN, WAN, MAN 11.3 to 11.6
Network Protocol: TCP/IP, File Transfer Protocol (FTP), HTTP, 12.4 to 12.9 XII CS
SMTP, POP3

Unit III
Database Concepts: Introduction to database concepts and its 15.1, 15.4
need. Relational data model: Concept of relation
Key, primary key, candidate key, alternate key and foreign key 15.2
Structured Query Language: General Concepts: Advantages 15.5, 15.8, 15.9
of using SQL, Data Definition Language and Data Manipulation
Language
Data Types: number / decimal, character / varchar / varchar2, date 16.3
Interface of Python with an SQL database - Connecting SQL Chapter 16 XII CS
with Python - Creating Database connectivity Applications -
Performing Insert, Update, Delete queries - Display data by using
fetchone(),fetchall(),rowcount

(ii)
CONTENTS
Class XI, CBSE, Computer Science, 5.6 Traversal 26
Revised Syllabus (2020-2021) ii
5.7 Functions 28
Syllabus v 5.8 Conclusion 36
ADDITIONAL MATTER Chapter 6: Strings 40–60
Chapter 1: Mathematical Functions 2–4 6.1 Introduction 40
1.1 Math Module 2 6.2 Loops Revised 41
1.2 Random Module 3 6.3 String Operators 43
1.3 Statistics Module 4 6.4 In-build Functions 45
Chapter 2: Networking-I 5–7 6.5 Illustrations 52
2.1 Bandwidth 5 6.6 Conclusion 56
2.2 Bit Rate 5 UNIT 2: COMPUTER NETWORKS
2.3 Evolution of Networking 6 Chapter 7: Safely Accessing Website and
2.4 Packet Switching V/s Circuit Switching 7 Communication Data: Computer Threats 62–72
7.1 Introduction 62
Chapter 3: Networking-II 8–11
7.2 Virus 62
3.1 Extendible Markup Language 8
7.3 Spyware 63
3.2 Domain Name System 9
7.4 Adware 65
3.3 Uniform Resource Locator (URL) 10
7.5 Cookies 66
3.4 Web Hosting 10
7.6 Trojans 67
3.5 Communication 10
7.7 Spamming 67
Chapter 3A: Networking-III 12–14 7.8 Eavesdropping 68
3A.1 WiFi Cards 12 7.9 Phishing 68
3A.2 RJ-45 Connector 12 7.10 Introduction to Firewalls 69
3A.3 Remote Login and TELNET 13 7.11 Authentication 69
3A.4 Personal Area Network (PAN) 13 7.12 Conclusion 70
3A.5 Point-to-Point Protocol (PPP) 13
Chapter 8: Introduction to Computer
3A.6 Mobile Communication Protocols 13 Networks-II 73–78
Chapter 4: File Handling: CSV Files and 8.1 Website 73
Serialization 15–20 8.2 Web Servers 73
4.1 Introduction 15 8.3 Web Browser 74
4.2 Important Methods 16
UNIT 3: DATABASE MANAGEMENT
4.3 Illustrations 16
4.4 Serialization: Pickle Module 19 Chapter 9: Structured Query Language II 80–100
9.1 Introduction 80
UNIT 1: COMPUTATIONAL THINKING 9.2 Viewing all Tables 80
AND PROGRAMMING–2 9.3 Select Statements 81
Chapter 5: Lists 22–39 9.4 Updating Tables 87
5.1 Introduction 22 9.5 Cartesian Product 87
5.2 Lists 23 9.6 Join 89
5.3 Accessing Elements: Indexing and 9.7 Types of Joins 91
Slicing 23 9.8 Index 91
5.4 Mutability 25 9.9 Drop Index 92
5.5 Operators 26 9.10 Conclusion 92

(iii)
DEDUCTED
COMPUTER SCIENCE - 083

CLASS XII

Topic reduced

Unit I: Computational Thinking and Programming - 2

•• Recursion – simple algorithms with recursion : print a message forever, sum


of first n natural numbers, factorial, Fibonacci numbers, recursion on arrays :
binary search

•• Idea of efficiency : performance measurement in terms of the number of


operations.

•• Data-structures: Lists as covered in Class XI, Stacks – Push, Pop using a list,
Queues – Insert, Delete using a list. (One of the data structure Stack or Queue.
Note : While setting the question paper a students will have an option between
Stack and Queue.)

Unit II: Computer Networks

•• Web Scripting Client side (VB Script, Java Script, PHP) and Server side (ASP,
JSP, PHP), Web 2.0 (for social networking)

•• E-commerce payment transactions using online banking, mobile banking,


payment apps and services.

Unit III: Database Management

CREATE TABLE, DROP TABLE, ALTER TABLE, UPDATE ....SET, INSERT, DELETE

1. Suggested Practical List: Python Programming

•• Recursively find the factorial of a natural number

•• Write a recursive code to find the sum of all elements of a list.

•• Write a recursive code to compute the nth Fibonacci number

(iv)
SYLLABUS
Computer Science (Revised)–[CLASS-XII, Code No. 083, 2020-21]

1. Prerequisites
Computer Science- Class XI

2. Learning Outcomes
•• Apply the concept of functions.
•• Ability to use Python libraries.
•• Apply the concept of file handling.
•• Ability to use basic data structures: Stacks.
•• Explain the basics of computer networks.
•• Ability to use connectivity between Python and SQL.

3. Distribution of Marks:
Unit Unit Name Theory Periods
No. Marks
Theory Practical
I Computational Thinking and Programming–2 40 50 30
II Computer Networks 10 10 ---
III Database Management 20 20 10
Total 70 80 40

UNIT I: COMPUTATIONAL THINKING AND PROGRAMMING - 2


•• Revision of the basics of Python covered in Class XI.
•• Functions: scope, parameter passing, mutable/immutable properties of data objects,
passing strings, lists, tuples, dictionaries to functions, default parameters, positional
parameters, return values, functions using libraries: mathematical and string functions.
•• File handling: Need for a data file, Types of file: Text files, Binary files and CSV
(Comma separated values) files.
•• Text File: Basic operations on a text file: Open (filename – absolute or relative path,
mode), Close a text file, Reading and Manipulation of data from a text file, Appending
data into a text file, standard input/output and error streams, relative and absolute paths.
•• Binary File: Basic operations on a binary file: Open (filename – absolute or relative
path, mode), Close a binary file, Pickle Module – methods load and dump; Read, Write/
Create, Search, Append and Update operations in a binary file.

(v)
•• CSV File: Import csv module, functions – Open, Close a csv file, Read from a csv file
and Write into a csv file using csv.reader ( ) and csv.writerow( ).
•• Using Python libraries: Import Python libraries.
•• Data-structures: Lists as covered in Class XI, Stacks – Push, Pop using a list.

UNIT II: COMPUTER NETWORKS


•• Evolution of Networking: ARPANET, Internet, Interspace Different ways of sending
data across the network with reference to switching techniques (Circuit and Packet
switching).
•• Data Communication terminologies: Concept of Channel, Bandwidth (Hz, KHz, MHz)
and Data transfer rate (bps, Kbps, Mbps, Gbps, Tbps).
•• Transmission media: Twisted pair cable, coaxial cable, optical fiber, infrared, radio link,
microwave link and satellite link.
•• Network devices: Modem, RJ45 connector, Ethernet Card, Router, Switch, Gateway,
WiFi card.
•• Network Topologies and types: Bus, Star, Tree, PAN, LAN, WAN, MAN.
•• Network Protocol: TCP/IP, File Transfer Protocol (FTP), PPP, HTTP, SMTP, POP3,
Remote Login (Telnet) and Internet, Wireless / Mobile Communication protocol such as
GSM, GPRS and WLL.
•• Mobile Telecommunication Technologies: 1G, 2G, 3G, 4G and 5G; Mobile processors;
Electronic mail protocols such as SMTP, POP3, Protocols for Chat and Video
Conferencing: VoIP, Wireless technologies such as Wi-Fi and WiMax
•• Network Security Concepts:
Threats and prevention from Viruses, Worms, Trojan horse, Spams Use of Cookies,
Protection using Firewall, https;
India IT Act, Cyber Law, Cyber Crimes, IPR issues, hacking.
•• Introduction To Web services: WWW, Hyper Text Markup Language (HTML),
Extensible Markup Language (XML); Hyper Text Transfer Protocol (HTTP); Domain
Names; URL; Website, Web browser, Web Servers; Web Hosting.

UNIT III: DATABASE MANAGEMENT


Database Concepts: Introduction to database concepts and its need.
Relational data model: Concept of domain, relation, tuple, attribute, degree, cardinality, key,
primary key, candidate key, alternate key and foreign key.
Structured Query Language:
General Concepts: Advantages of using SQL, Data Definition Language and Data Manipulation
Language.

(vi)
Data Types: number / decimal, character / varchar / varchar2, date; SQL commands covered in
class XI (2019-20)
SELECT, DISTINCT, FROM, WHERE, IN, BETWEEN, LIKE, NULL / IS NULL, ORDER
BY,GROUP BY, HAVING;
SQL functions: SUM ( ), AVG ( ), COUNT ( ), MAX ( ) and MIN ( );
Joins: equi-join and natural join
Interface of Python with an SQL database
- Connecting SQL with Python
- Creating Database connectivity Applications
- Performing Insert, Update, Delete queries
- Display data by using fetchone(),fetchall(),rowcount

4. Practical
Marks
S.No. Area
(Total=30)
1 Lab Test:
1. Python program (60% logic + 20% documentation + 20% code 7
quality)
2. Small Python program that sends a SQL query to a database 5
and displays the result. A stub program can be provided.
2 Report file: Minimum 20 Python programs. Out of this at least 4 7
programs should send SQL commands to a database and retrieve
the result
3 Project (that uses the concepts that have been learnt in Class 11 8
and 12)
4 Viva voce 3

5. Suggested Practical List:


Python Programming
•• Read a text file line by line and display each word separated by a #.
•• Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.
•• Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.
•• Create a binary file with roll number, name and marks. Input a roll number and update the
marks.
•• Remove all the lines that contain the character `a' in a file and write it to another file.

(vii)
•• Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).
•• Write a Python program to implement a stack and queue using a list data-structure.
•• Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurring word(s)

Database Management
•• Create a student table and insert data. Implement the following SQL commands on the
student table:
ALTER table to add new attributes/modify data type/drop attribute
UPDATE table to modify data
ORDER By to display data in ascending/descending order DELETE to remove tuple(s)
GROUP BY and find the min, max, sum, count and average
•• Similar exercise may be framed for other cases.
•• Integrate SQL with Python by importing the MySQL module.

6. Project
The aim of the class project is to create something that is tangible and useful using Python /
Python and SQL connectivity. This should be done in groups of two to three students and should
be started by students at least 6 months before the submission deadline. The aim here is to find a
real world problem that is worthwhile to solve.
Students are encouraged to visit local businesses and ask them about the problems that they are
facing. For example, if a business is finding it hard to create invoices for filing GST claims, then
students can do a project that takes the raw data (list of transactions), groups the transactions by
category, accounts for the GST tax rates, and creates invoices in the appropriate format. Students
can be extremely creative here. They can use a wide variety of Python libraries to create user
friendly applications such as games, software for their school, software for their disabled fellow
students, and mobile applications, Of course to do some of these projects, some additional learning
is required; this should be encouraged. Students should know how to teach themselves.
The students should be sensitized to avoid plagiarism and violations of copyright issues while
working on projects. Teachers should take necessary measures for this.

(viii)
Additional Matter

 1
1 Mathematical Functions

1.1 MATH MODULE


The math module provides the mathematical function which are define by C standards.
However these functions cannot return a complex number. Some of the most important
functions of this module are as follows.
______________________________________________________________________
To run the following codes import the math module
import math
______________________________________________________________________

math.srt(x)
This function finds the square root of x. However, you cannot pass a negative number in
this function. For example, math.sqrt(-1) will return a domain error.

math.ceil(x)
This function returns the number greater than or equal to the argument. For example,
ceil(2.67) will return 3
ceil(2.001) will return 3
ceil(-4,90) will return -4

math.floor(x)
This function returns the number less than or equal to the argument. For example,
floor(2.67) will return 2
floor(2.001) will return 2
floor(-4,90) will return -5.

math.fabs(x)
This function returns the absolute value of x. for example,
fbs(-5) returns 5
fabs(4) returns 4

2 Computer Science with Python–XII: Supplement


math.factorial(x)
This function returns the factorial of the argument. It raises the ValueError if the
argument is not an integral or is negative.

math.pow(x, y)
This function returns x raised to the power y. It converts both its arguments to float. For
example,
pow(3,4) returns 81
pow(5,3) returns 125

sin, cos, tan
These functions find the sin, cosine and tan of the given argument. For example, in the
following functions, the argument 3.14/2 is passed and the sin, cos and tan of this value
is found using the functions.
Code:
ans_sin=math.sin(3.14/2)
ans_cos=math.cos(3.14/2)
ans_tan=math.tan(3.14/2)
print(ans_sin, ans_cos, ans_tan)
Output:
0.9999996829318346 0.0007963267107332633 1255.7655915007897
Constants: e and pi
The math module also provides us with e and pi constants.
Code:
print(math.pi)
print(math.e)
Output:
3.141592653589793
2.718281828459045

1.2 RANDOM MODULE


This module implements pseudo-random number generators for various distributions.
Some of the most important functions of this module are as follows.
______________________________________________________________________
To run the following codes import the random module
import random
______________________________________________________________________
random.random()
This function produces a random number between 0 and 1.

Mathematical Functions 3
random.ranrange(start, stop)
This function returns an integer between start and stop.
random.randrange(start, stop, step)
This function returns an integer between start and stop with a step. Here stop is not
included.
random.randrange(start, stop, step)
This function returns an integer between start and stop. Here stop is included.
The following examples demonstrate the use of these functions.
Code:
ans1=random.random()
ans2=random.randrange(3,8)#3,4,5,6,7
ans3=random.randrange(3,56,2)#3,5,7,...
ans4=random.randint(5,9)#5,6,7,8,9
print(ans1,ans2, ans3, ans4)
Output:
0.564352337835268 6 47 6

1.3 STATISTICS MODULE


This module helps us to find statistical metrics like mean, median and mode of a given
list or array. Some of the most important functions of this module are as follows.
______________________________________________________________________
To run the following codes import the statistics module
import statistics
______________________________________________________________________
mean, median, mode
These functions find the mean, median and mode of the given list respectively.
Code:
L=[2,3,3,4,5,6,7,7,9,8,10,1,2,2,5]
ans1=statistics.mean(L)
ans2=statistics.median(L)
ans3=statistics.mode(L)
print(ans1, ans2, ans3)
Output:
4.933333333333334 5 2

4 Computer Science with Python–XII: Supplement


2 Networking-I

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
• Understand the concept of Bandwidth
• Learn about bit rate
• Learn about evolution of networking
• Differentiate between Packet Switching and Network Switching

2.1 BANDWIDTH
In signal processing and digital communication, the bandwidth is defined as the difference
between the highest and the lowest frequency constrained to a defined impairment level in
signal power. In computing, however, the maximum rate of data transfer across a path is
called Bandwidth. The bandwidth is may be classified as
•• Networks
•• Data and
•• Digital Bandwidth.
Bandwidth may also be defined as the net bit rate of a communication path in a digital
communication system.
The units of bandwidth are Hz, KHz, MHz, GHz, and so on where
•• 1 Kilohertz or 1 KHz = 103 Hz
•• 1 Megahertz or 1 MHz = 103 KHz
•• 1 Gigahertz or 1 GHz = 103 MHz
•• 1 Terahertz or 1 THz = 103 GHz

Edholm’s law
As per the Edholm’s law, the bandwidth of a telecommunication network doubles every 18
months. The law is found to be correct since 1970’s.

2.2 BIT RATE


The number of bits transferred per unit time is called the bit rate. The units of bit rate are
bits/s, Kilobits/s, Megabits/s and so on.

Networking-I 5
•• 1 Kilobit/s or Kbps = 103 bps
•• 1 Megabit/s or Mbps = 103 Kbps
•• 1 Gigabit/s or Gbps = 103 Mbps
Also, note that there are 8 bits in a byte, therefore 1 byte per second (1 Bps) = 8 bits per
second. So the reader is requested to divide the right side by 8 to get the relation between
KBps, MBps and GBps.

2.3 EVOLUTION OF NETWORKING


Networking is a boon for mankind. It helps us to connect computers, share resources; makes
data transfer easy and most importantly helps us to work together even in the times of a
pandemic. Like “Rome was not built in a day”, networks were also not created in a day. It
took a long time to evolve. Networking started its journey in 1969 with ARPANET.

2.3.1 ARPANET
The full form of ARPANET is Advanced Research Agency Network. It is the foundation
on which the present day networks are built. The agencies involved in the development of
ARPANET are the Advanced Research Projects Agency (ARPA) and US Department
of Defence (DoD). Initially some computers across universities were connected using
ARPANET. The purpose was sharing of information across PC separated by large distances.
The insights from this helped to further the cause of networking.

2.3.2 The National Science Federation Network


The National Science Federation Network or NSFNET was created in 1980’s. As a matter
of fact it was more powerful as compared to the ARPANET. This would, in fact become the
backbone of the public internet.

2.3.3 Internet
Internet is a network of networks. The worldwide presence of Internet is owing to the insights
from the above two networks. Internet uses the Transmission Control protocol or TCP. It has
evolved since its inception. We cannot imagine our life without Internet. It provides us with
•• Information
•• E-transactions
•• Communication and Mailing
•• Entertainment including gaming and movies/series and
•• Social networking
along with many other things.

2.3.4 Interspace
InterSpace is a client/server type software which allows multiple users to communicate online
with real-time audio, video or text chat in dynamic 3D.

6 Computer Science with Python–XII: Supplement


Interspace company was founded in 2013 and is based in Mumbai, India and is one of the
most effective communication agency in the world. As per the official site:
“The focus of interspace is to create simple, effective conversations has got multiple
levels of interactions. Interspace Communications delivers, strategic insight led ideas,
integrated communications with deep-rooted technology play.”

2.4 PACKET SWITCHING V/S CIRCUIT SWITCHING


Data can be transferred across a network by dividing the data into packets or creating a
dedicated path between the source and the destination. This section explains the two modes in
detail.
“Packet-switched networks move data in separate, small blocks called packets, on the
basis of the destination address in each packet.”
[https://www.computerworld.com]
At arrival to the destination, the packets are reassembled in the proper sequence in order
to create the original message.
The Circuit-switched networks, designed in 1878, on the other hand, require dedicated
point-to-point connections during communication. That is, it reserves a dedicated channel for
the entire communication.

2.4.1 Traditional Uses


Traditionally, the two (Circuit-switched networks and packet-switched networks) had
different purposes. The former were used for phone calls and the later for handling the data.
However, the later is caching up with the former in voice communication as well.

2.4.2 Hardware
The private branch exchange (PBX) systems are used in Circuit Switching whereas computer
servers are used in packet-switched networks.

2.4.3 Mechanism
In a circuit-switched network, electronic signals pass through several switches before a
connection is established. In packet-based networks, however, the message gets broken into
small data packets that seek out the most efficient route as circuits become available.

2.4.4 Present state


You may have noticed the increase of the use of Internet for voice and video calls.
Researchers foresee a measured transfer away from circuit-switched networks.
It may be stated that the Circuit Switching systems work well in applications like voice
transfer. However, in case the data to be transferred is large or the data is to be delivered to
multiple locations, this system may not perform. In such cases the data must be broken down
into packets.
The circuit based system may also prove expensive as compared to the Voice-Over-IP
systems. However, the VoIP systems may result in poor voice quality.
One must remember that the packet switching systems have to deal with the dropping of
packets in a congested networks and the arrival of packets at different times.

Networking-I 7
3 Networking-II

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
• Understand the importance and structure of XML
• Learn about Domain Names
• Learn about URL and Web Hosting
• Understand some important modes of communication

3.1 EXTENDIBLE MARKUP LANGUAGE


Markup languages for documents follow the standards of Standard Generalized Markup
Language (SGML). According to SGML, a markup language should be
•• Declarative: It should define the structure and the attributes of a document rather
than the procedures.
•• Rigorous: This is required to take advantage of the programs and databases.

3.1.1 Introduction
Extendible Markup Language or XML is a simple, flexible, format driven language. This
language was initially designed for large scale electronic publishing. It is now being used to
exchange large scale data as well. Some of the important features of XML are as follows:
•• Simplicity
•• Generality
•• Usability
•• Support for Unicode
•• It can be used to represent arbitrary data structures.

3.1.2 Structure of an XML Document


XML declaration
The XML documents may begin with an XML declaration containing information about the
document. An example the following declaration contains the version and the encoding of the
XML document.

8 Computer Science with Python–XII: Supplement


<?xml version=”1.0” encoding=”UTF-8”?>.
Character
An XML document can contain any legal Unicode character. As a matter of fact, an XML
document is a string of characters.
Processor
The processor, or the XML parser, examines the document and transfers the information
to the application. As stated earlier, what must be done by the XML processor is stated by the
specification.
Markup and content
The XML document is then segregated into markup and the content. Markup are the
strings that
•• begin with < and end with a >
•• begin with & and end with
The part of the document that is not markup is called the content.
Tag
It is a markup that begins with a < and ends with a >. Tags can be segregated into the
following types:
•• Start tag, e.g. <root>
•• End tag, e.g. </root>
•• Empty tag, which do not contain content.
Element
It is a unit of an XML document that begins with a start tag and ends with an end tag.
Anything in between the start and the end tag is called the content.
Attribute
An attribute has a name value pair in between the starting and the ending tag. For
example, the following tag specifies the source image and the text that must be displayed
alternatively.
<img src=”jughead.jpg” alt=”Jughead” />,

3.2 DOMAIN NAME SYSTEM


The identification string of a web site is generally referred to as its Domain name. It is used
for addressing purposes and identifies a network domain. The domain names are created
using the rules of the Domain Name System or the DNS.
The DNS follows a hierarchical structure. The root is nameless. The sub-domains of the
root domain are top level domains like
•• com
•• org

Networking-II 9
•• edu
•• info
These are called the Generic Top Level Domains. Domains like “.in” are the Country
Code Top Level Domains. There are more such domains in this level. This is followed by the
second and the third level domains.
A domain name that is completely specified with all labels in the hierarchy of the DNS is
called a Fully Qualified Domain Name (FQDN). The FQDN generally ends in a dot (.). It
may be noted that Labels in the Domain Name System are case-insensitive.

3.3 UNIFORM RESOURCE LOCATOR (URL)


A Uniform Resource Locator (URL) specifies a web resource and helps in the identification
of its location and the mechanism for retrieving it. This web resource can be a web page,
database access, ftp or other application. Consider the following URL
https://us.yahoo.com/biden-says-picked-harris-running-004809811.html
It specifies
•• The protocol, which is https
•• The hostname, which is www.yahoo.com and
•• The file name, which is “biden-says-picked-harris-running-004809811.html”

3.4 WEB HOSTING


It is a service that facilitates the posting of a website or web page on the Internet. Here, a
web host is the one that provides the required technologies and services. Servers are special
computers that host websites. When a website address is typed into a browser, the website is
displayed. It may be stated that generally one need to buy the domain to be able to host with
a hosting companies. Many companies like Go Daddy will help you buy a domain and host
your website. Now, there are many additional feature that are shipped with your website they
include
•• Email accounts
•• FTP access and
•• Word Press support
to name a few. In addition to the above there exist website builders that it allows you to
simply drag and drop content to create your site, and publish your site easily.

3.5 COMMUNICATION
Microwave link
As per the Wikipedia page of Microwave link
“A microwave link is a communications system that uses a beam of radio waves in the
microwave frequency range to transmit video, audio, or data between two locations,
which can be from just a few feet or meters to several miles or kilometers apart.”

10 Computer Science with Python–XII: Supplement


These are used in television broadcasting, communication between a satellite and base
stations, indoor communication and linking telephone exchanges. This technology uses the
line of sight (LOS) communication. However, this type of communication is affected by
environment and is sensitive to solar protons and even pollens.

The Infrared
Communication can also be done using the Infrared Radiation. This radiation is a
electromagnetic radiation that has wavelength higher than the red light. Inspite of the fact that
IR transceivers are quite cheap, they are not popular in communication. This is because the IR
communication has needs line-of-sight. Moreover, it is not able to penetrate walls.

Satellite Link
A satellite link, as the name suggests, is used for satellite communication. According to the
International Telecommunication Union’s (ITU) ITU Radio Regulations, a Satellite link is
defined as
“A radio link between a transmitting earth station and a receiving earth station through
one satellite.”
It has
•• An up link and
•• A down link

The radio Link control


Radio Link Control (RLC) is a layer 2 Radio Link Protocol used. It is used for 5G New Radio
(NR). The key tasks of the RLC protocol are as follows:
•• Error correction
•• Segmentation and reassembly
•• Duplicate detection
•• Protocol error detection and recovery

Networking-II 11
3A Networking-III

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
• Understand the importance WiFi Cards and RJ-45 Connectors
• Learn about remote login and TELNET
• Learn about PAN and PPP
• Understand some important modes of communication

3A.1 WIFI CARDS


You must have observed the availability of Internet in cafes, colleges etc. These WiFi hotspots
provide internet access and you can connect your device using the WiFi card, which is a small
device capable of receiving the radio signals emitted by the hotspot. The WiFi card, in your
laptop, is one of the many adapter cards.
It may be stated here that the WiFi cards are different for laptops, desktops etc. As a
matter of fact, most of the devices have preinstalled WiFi cards. However, they can be bought
and installed easily, in case your device does not have one.
The wireless Internet card communicates with hotspots using the following mechanism.
Wireless Internet uses radio waves to communicate. It does not use a phone line, digital
subscriber line (DSL). The WiFi hotspot after receiving information from the Internet through
wires, translates that data to the radio waves. This is followed by broadcasting these radio
waves to the surrounding area.

3A.2 RJ-45 CONNECTOR


RJ45 is a type of connector generally used for Ethernet. That is, the Ethernet cables have
an RJ45 connector on each end. It refers to “registered jack,” owing to the fact that it is a
standardized networking interface. The RJ45 connector has eight pins. It is generally wired in
two different ways namely: T-568A and T-568B. These are just the wiring standards.

12 Computer Science with Python–XII: Supplement


3A.3 REMOTE LOGIN AND TELNET
A user can interact with a program on another computer using the remote login facility. This
service permits an access to a remote system by extending the login concept used by the
common systems.
TELNET is the Internet’s remote login service. In order to access TELNET, one must
specify the remote machine and invoke a local application program. The program in the user’s
machine becomes a client and connects to the server.
Remote login helps the Internet to provide interactive services. It transfers the data and
permits a user to interact with a program that runs on a remote computer. The remote program
can respond to input from the user, and the user can respond to the output.

3A.4 PERSONAL AREA NETWORK (PAN)


A personal area network (PAN) is a computer network centered on a person’s workspace.
It helps us to communicate with devices like computers, smartphones, tablets and personal
digital assistants. It can also be used for connecting to a higher level. It may be wireless or
wired
As per Wikipedia “A wireless personal area network (WPAN) is a PAN carried over a
low-powered, short-distance wireless network technology Wireless USB, Bluetooth etc. The
reach of a WPAN varies from a few centimeters to a few meters.”

3A.5 POINT-TO-POINT PROTOCOL (PPP)


Two routers can directly communicate with each other, without any other device, using the
Point-to-Point Protocol (PPP). Among many other things it provides
•• Authentication,
•• Transmission encryption and
•• Compression.
The PPP can be used over serial cable, phone line, or even cellular telephone. Earlier this
was used by the internet providers for customer dial-up access to the Internet. It has two types
namely:Point-to-Point Protocol over Ethernet (PPPoE) and Point-to-Point Protocol over ATM
(PPPoA).

3A.6 MOBILE COMMUNICATION PROTOCOLS


Before proceeding further, let us explore the types of multiplexing options available to
communication channels.
The Frequency Division Multiplexing or FDM is the one in which each user is assigned
a different frequency from the given spectrum. This facilitates the simultaneous travel of all
frequencies on the data.

Networking-III 13
The Time Division Multiplexing or TDM, on the other hand, divides a single radio
frequency into multiple slots and each slot is assigned to a different user. This allows multiple
users to access the channel simultaneously.
The Code Division Multiplexing or CDMA allows several users to share the same
frequency spectrum simultaneously. The assignment of a different code to them helps the
system to differentiate between them.
Having seen the protocols, let us now move to the cellular communication protocols:

3A.6.1 GSM
The Global System for Mobile communications or GSM is one of the most widely used
digital wireless telephony system. It was developed in Europe in 1980s and has now become
an international standard. Note that the SIM (Subscriber Identity Module) card that you use
has a unique identification number, some memory and software for communication. A GSM
handset with a SIM card can be used in any country that uses GSM. This technology uses
Time Division Multiple. It also encrypts your data.
The frequencies:
International standard : 900 MHz to 1800 MHz
US : 1900 MHz

3A.6.2 CDMA
In the Code Division Multiple Access or CDMA each user gets the entire spectrum which
makes the voice quality is very high. Also, the data is encrypted in CDMA. It may be stated
that it was first used by the British military

3A.6.3 WLL
The Wireless in Local Loop or WLL is a local telephone service that can be provided in
homes or offices. WLL system consists of user handsets and a base station. Here, the users
connect to their local wirelessly. This reduces the long term cost and the set up time. The
antenna sends out and receives calls from users through microwave links.

3A.6.4 GPRS
The General Packet Radio Services or GPRS is a packet based wireless communication
technology. It is used by the 2G and 3G telephony. This technology charges user based on the
volume of data they send. However, it has a flip side, as the traffic increases, service quality
may go down.
Promised speed: 56 kbps to 114 kbps

14 Computer Science with Python–XII: Supplement


4 File Handling: CSV
Files and Serialization

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
• Understand the structure of a CSV file
• Read from and Write into a csv file
• Use csv.reader ( ) and csv.writerow()
• Understand the importance of the Pickle module

4.1 INTRODUCTION
The Comma Separated Values (CSV) format is one of the most common formats for storing
data. The data stored in this format, can be used for databases, spreadsheets etc. If you are
interested in Data Science and Machine Learning, most of the open source data is available in
the CSV format. Moreover, it requires lesser memory as compared to many other formats.
Broadly, in a CSV file each line contains a record and each record has fields separated
by a separator (mostly comma). However, the processing of data of a CSV file is, at times,
problematic, owing to the differences in the formats and the lack of a well-defined standard.
The csv module implements classes to read and write tabular data in CSV format. This
module also allows us to store and read data in a format preferred by Excel. It may also be
stated that the programmers can also define their own CSV formats.
The reader objects help us to read data from a CSV file. The writer object, on the other
hand, helps us to write data to a CSV file. The DictReader object helps us to read data from
a directory. The DictWriter object helps us to write data to a directory. The reader and writer
methods of the csv module are described as follows.

4.1.1 csv.reader
Arguments: csvfile, dialect=’excel’, **fmtparams
This returns a reader object that iterates over lines in the given csvfile. The csvfile returns
a string each time the __next__() method is called. In case of a file object, it should be opened
with newline=’’. This method also takes an optional dialect parameter to define a set of
parameters specific to a particular CSV dialect.

File Handling: CSV Files and Serialization 15


On calling the reader method, each row read from the csv file is returned as a list of
strings. In order to convert the unquoted fields into floats, QUOTE_NONNUMERIC format
option is specified.

4.1.2 csv.writer (csvfile, dialect=’excel’, **fmtparams)


This object returns a writer object to convert the user’s data into delimited strings on the
given file-like object. This method also takes an optional dialect parameter to define a set of
parameters specific to a particular CSV dialect.

4.2 IMPORTANT METHODS


This section describes the methods of the reader and the writer objects.

4.2.1 Reader Objects


The Reader objects have the following public methods:
csvreader.__next__()
This method returns the next row of the reader’s iterable object as a list or a dictionary.

4.2.2 Writer Objects


Some of the most important public methods of the Writer object are as follows:
csvwriter.writerow(row)
This method writes the row parameter to the writer’s file object, as per the current
dialect.
csvwriter.writerows(rows)
This method write all elements in rows to the writer’s file object, formatted as per the
current dialect.
The following illustrations will help the reader to understand the above methods.

4.3 ILLUSTRATIONS
Consider the following CSV file (results.csv). The file has the following fields
•• Test_ID
•• Student _ID
•• Subject _ID
•• Marks_O
•• Max_Marks
Note that each row has five elements separated by commas.
———————————————————————————————————
Test_ID,Student _ID,Subject _ID,Marks_O,Max_Marks
T1,S1,Sub1,82,100
T2,S2,Sub1,79,100

16 Computer Science with Python–XII: Supplement


T3,S3,Sub1,61,100
T4,S4,Sub1,64,99
T5,S5,Sub1,76,100
T6,S1,Sub2,97,99
T7,S2,Sub2,62,99
T8,S3,Sub2,88,100
T9,S4,Sub2,71,100
T10,S5,Sub2,72,99
T11,S1,Sub3,78,99
T12,S2,Sub3,78,99
T13,S3,Sub3,64,99
T14,S4,Sub3,70,99
T15,S5,Sub3,73,100
T16,S1,Sub4,60,100
T17,S2,Sub4,99,100
T18,S3,Sub4,73,99
T19,S4,Sub4,56,100
T20,S5,Sub4,78,99
T21,S1,Sub5,67,100
T22,S2,Sub5,64,100
T23,S3,Sub5,54,100
T24,S4,Sub5,97,99
T25,S5,Sub5,95,100
————————————————————————————————————

Reading the file


The following code reads the file considering each row as a dictionary.

Code:
import csv
with open(‘results.csv’, newline=’’) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)

File Handling: CSV Files and Serialization 17


Output: (The first three rows of the output)
OrderedDict([(‘Test_ID’, ‘T1’), (‘Student _ID’, ‘S1’),
(‘Subject _ID’, ‘Sub1’), (‘Marks_O’, ‘82’), (‘Max_Marks’, ‘100’)])
OrderedDict([(‘Test_ID’, ‘T2’), (‘Student _ID’, ‘S2’),
(‘Subject _ID’, ‘Sub1’), (‘Marks_O’, ‘79’), (‘Max_Marks’, ‘100’)])
OrderedDict([(‘Test_ID’, ‘T3’), (‘Student _ID’, ‘S3’),
(‘Subject _ID’, ‘Sub1’), (‘Marks_O’, ‘61’), (‘Max_Marks’, ‘100’)])
Reading the values in a field
The following code reads the values in the Student _ID field.
Code:
with open(‘results.csv’, newline=’’) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row[‘Student _ID’])
Reading the file using reader
The following code reads the file using the reader.

Code:
with open(‘results.csv’, newline=’’) as f:
reader = csv.reader(f)
for row in reader:
print(row)

Output:
[‘Test_ID’, ‘Student _ID’, ‘Subject _ID’, ‘Marks_O’, ‘Max_Marks’]
[‘T1’, ‘S1’, ‘Sub1’, ‘82’, ‘100’]
[‘T2’, ‘S2’, ‘Sub1’, ‘79’, ‘100’]
[‘T3’, ‘S3’, ‘Sub1’, ‘61’, ‘100’]
[‘T4’, ‘S4’, ‘Sub1’, ‘64’, ‘99’]
[‘T5’, ‘S5’, ‘Sub1’, ‘76’, ‘100’]
[‘T6’, ‘S1’, ‘Sub2’, ‘97’, ‘99’]
[‘T7’, ‘S2’, ‘Sub2’, ‘62’, ‘99’]
[‘T8’, ‘S3’, ‘Sub2’, ‘88’, ‘100’]
[‘T9’, ‘S4’, ‘Sub2’, ‘71’, ‘100’]
[‘T10’, ‘S5’, ‘Sub2’, ‘72’, ‘99’]
[‘T11’, ‘S1’, ‘Sub3’, ‘78’, ‘99’]

18 Computer Science with Python–XII: Supplement


[‘T12’, ‘S2’, ‘Sub3’, ‘78’, ‘99’]
[‘T13’, ‘S3’, ‘Sub3’, ‘64’, ‘99’]
[‘T14’, ‘S4’, ‘Sub3’, ‘70’, ‘99’]
[‘T15’, ‘S5’, ‘Sub3’, ‘73’, ‘100’]
[‘T16’, ‘S1’, ‘Sub4’, ‘60’, ‘100’]
[‘T17’, ‘S2’, ‘Sub4’, ‘99’, ‘100’]
[‘T18’, ‘S3’, ‘Sub4’, ‘73’, ‘99’]
[‘T19’, ‘S4’, ‘Sub4’, ‘56’, ‘100’]
[‘T20’, ‘S5’, ‘Sub4’, ‘78’, ‘99’]
[‘T21’, ‘S1’, ‘Sub5’, ‘67’, ‘100’]
[‘T22’, ‘S2’, ‘Sub5’, ‘64’, ‘100’]
[‘T23’, ‘S3’, ‘Sub5’, ‘54’, ‘100’]
[‘T24’, ‘S4’, ‘Sub5’, ‘97’, ‘99’]
[‘T25’, ‘S5’, ‘Sub5’, ‘95’, ‘100’]

Writing to a file
The following program writes the list containing three records to a file named “student_data.
csv”, using the writerows method.

Code:
Data=[[‘T23’, ‘S3’, ‘Sub5’, ‘54’, ‘100’], [‘T24’, ‘S4’,
‘Sub5’, ‘97’, ‘99’], [‘T25’, ‘S5’, ‘Sub5’, ‘95’, ‘100’]] with
open(‘student_data.csv’, ‘w’, newline=’’) as f:
writer = csv.writer(f)
writer.writerows(Data)

Output:
This program will create a file called “student_data.csv”.
————————————————————————————————————————————————————————————
student_data.csv
T23,S3,Sub5,54,100
T24,S4,Sub5,97,99
T25,S5,Sub5,95,100
————————————————————————————————————

4.4 SERIALIZATION: PICKLE MODULE


The pickle module is used for serializing and de-serializing objects. Pickling is the process of
converting an object module into byte stream. On the other hand, Unpickling is the process of
converting an object stream into object hierarchy.

File Handling: CSV Files and Serialization 19


It may be noted that the following terms conceptually mean the same, in Python
•• Serialization
•• Marshalling
•• Flattening
•• Pickling
In order to serialize an object the dumps() function can be called. In order to de-serialize
a data stream the loads() function can be called.
————————————————————————————————————
The pickle module provides the following functions to make the pickling process more
convenient:
pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None)
This method returns the pickled representation of the object obj as a bytes object, instead
of writing it to a file.
pickle.load(file,*, fix_imports=True, encoding=”ASCII”, errors=”strict”, buffers=None)
This method reads the pickled representation of an object from the open file object file
and return the reconstituted object hierarchy specified therein.
As per the official documentation, the protocol version of the pickle is detected
automatically; therefore no protocol argument is needed. The programs for serializing and
unpickling the data are provided in the Facebook page.

20 Computer Science with Python–XII: Supplement


UNIT 1
Computational Thinking and
Programming–2

File Handling: CSV Files and Serialization 21


ISBN: 978-81-943696-6-0 Publication Year: 2020 Edition: 1st
Pages: 376 MRP: 475.00 Paperback

Click Here to Buy Main Book Online


Computer Science with Python Programming is a textbook designed for the students of Class XII, CBSE. It covers complete course of
Computer Science. The book has been written in easy to understand language and contains ample examples. However, every attempt has been
made to keep the text as precise as possible.
The code has been tested in Python 3.x on a machine with Windows 10.
Each chapter of the book includes a variety of end-chapter exercises in the form of MCQs with answers, review questions, and programming
exercises to help readers test their knowledge. It may be stated here that the topics in the book have been written considering the fact that some
of the readers may opt Computer Science as their career.
Key Features:
• The book has sections dedicated to Computer System and Organization to help the students to understand the basics.
• Offers in-depth treatment of topics such as Pyplot and functions.
• The book introduces Django.
• Provides points to remember and a Glossary with definitions of the key terms at the end of each chapter which will help readers to
quickly recollect the important concepts.
• Questions, given at the end of each chapter and the Appendices would help students during viva and examinations.
Harsh Bhasin has done his B Tech. in Computer Science and M Tech. in Computers and is currently pursuing PhD. He qualified UGC NET in
2012 and received the Visvesvaraya Fellowship from DIETY in 2016. He was awarded the Young Researcher’s Award by ErNet in 2012. Mr.
Bhasin has authored a few papers, including those published in journals like Soft Computing. He has also authored “Programming in C#”
(2014), “Algorithm Analysis and Design” (2015) and “Theory of Computation”. He has been actively involved in research both as an author
and reviewer for ACM, Pearson, Oxford University Press, Springer etc. Mr. Bhasin was the editor in chief of the special issue on
“Applicability of Soft Computing Techniques in NP Problems,” SciEp, USA.
Professionally, Mr. Bhasin is a programmer and has been involved in the development of many Enterprise Resource Planning Systems while
being the proprietor of a firm based in Faridabad, Haryana, India. He has a vast industrial experience. He was an Assistant Professor in
Department of Computer Science, FMIT, Jamia Hamdard. He has also taught as visiting faculty in many colleges including Delhi
Technological University.
His areas of interest include Genetic Algorithms, Theory of Computation, C#, Python, Algorithms, Cellular Automata and Machine
Learning.
His personal interests include Hindi poetry and Hindustani Classical Music. Mr. Bhasin is also a blogger. You can reach him at his
Facebook page DTU Computation or via email at i_harsh_bhasin@yahoo.com.

LONDON • NEW DELHI • NAIROBI


Bangalore • Chennai • Cochin • Guwahati • Hyderabad • Kolkata • Lucknow • Mumbai
NEW AGE
Visit us at www.newagepublishers.com
5 Lists

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
•• Understand the definition of a list in Python
•• Access the elements of a list
•• Understand slicing and indexing
•• Traverse a list
•• Understand functions of a list

5.1 INTRODUCTION
Python provides us with lists, tuples and dictionaries, all of which have become synonyms
with ease of programming and can be used in diverse applications. A list, in Python, can
contain different types of elements and is mutable. A tuple can contain different types of
elements and is immutable. In a dictionary the items can be accessed using strings as indices
(Figure 5.1). This chapter introduces lists and the next two chapters introduce tuples and
dictionaries.

Figure 5.1: Lists, tuples and dictionaries

22 Computer Science with Python–XII: Supplement


This chapter has been organized as follows. The second section presents the definition
of lists, the third introduces indexing and slicing and the next section discusses mutability.
List operators, traversal, list functions have been discussed in the next three sections. These
sections present a few illustrations and the last section concludes.

5.2 LISTS
In Python, a list is a sequence object. A list can be an empty list ([]). It may contain any
number of elements, which may or may not be of the same type. Also, a list can contain
different types of elements, including a list. A list inherits many properties of a string.
However, unlike strings, they are mutable and may also contain different types of elements.
In the following snippet, L1 is an empty list, L2 contains 2, 4, 8, 16, 32 and 65. L3
contains an integer (2), a string (‘Harsh’), another integer (3), another string (‘Manan’), a
double (5.7865) and another string (‘Ali’). L4 is a list of lists. It contains three lists, each
containing different number of elements.
Code: Creation
#Empty List
L1=[]
#Homogeneous list
L2=[2,4,8,16,32,64]
#Heterogenous list
L3=[2, ‘Harsh’, 3,’Manan’, 5.7865,’Ali’]
#List of Lists
L4=[[1,2],[2,4,8],[3,9,27,81]]
print(‘First List’,L1,’\nSecond List’,L2,’\nThird List’,L3)
Output:
First List []
Second List [2, 4, 8, 16, 32, 64]
Third List [2, ‘Harsh’, 3, ‘Manan’, 5.7865, ‘Ali’]

5.3 ACCESSING ELEMENTS: INDEXING AND SLICING


The elements of a list can be accessed using indexing. The index of the first element of the
list is 0, that of the second element is 1 and so on. The negative index denotes the elements
from the end. For example, L[-1] denotes the last element of the list L, likewise L[-2] denotes
the second last element of a list (Figure 5.2).
L = [1, 3, 5, 7, 9, 11]
L[0] is 1
L[-1] is 11
L[3] is 7

Lists 23
Figure 5.2: Indexing in Python Lists. Note that L[0] denotes the first element, L[1] denotes the
second element and L[-1] (that is L[5]) denotes the last element.

Slicing is generally used to take out a sub-list from a given list. In the above case
L[:2] is a sub-list having all the elements of L starting from the first element till the
element at the first index (not the element at index 2) that is [1, 3].
L[2:] is a sub-list having all the elements of L starting from the element at the second
index (the third element as list is zero based index) till the last element that is [5, 7, 9, 11].
L[1:4] is a sub-list having all the elements of L starting from the element at the first
index till the element at the third index that is [3, 5, 7].
Formally, indexing and slicing have been discussed as follows.

5.3.1 Indexing
Indexing is used to access a particular element by mentioning its index. In Python, lists are 0
indexed, i.e. the first index will always start from 0. For example, L[0] will point to the first
element of the list. The negative indices denote the last elements. For example, L[-1] denotes
the last element of the list.
Code: Indexing
L1=[7, 3, 98, 18, 54]
#Indexing
print(L1[0])
print(L1[-2])
Output:
7
18

5.3.2 Slicing
Some of the elements (or all the elements) from a list can be extracted using slicing. A list
can be sliced, using the square bracket and a colon. In order to understand the concept, let us
consider the following example. In the code that follows, L4 contains all the elements from
the second index till the fourth one (fifth not included). L5 contains all the elements after
index 2, L6 contains all elements before index 5.

24 Computer Science with Python–XII: Supplement


Code: Slicing
L2=[2, 675, 8, 16, 32, 64]
#List slicing
L4=L2[2:5]#Take the elements of L2 at index 2, 3 and 4 and
put them in list L4
print(L4)
#List slicing
L5=L2[2:]#Take all the elements of L2 at end after index 2
and put them in list L5
print(L5)
# List slicing
L6=L2[:4] #Take all the elements before index 4 of list L2
and put them in list L6
print(L6)
# List slicing
Output:
[8, 16, 32]
[8, 16, 32, 64]
[2, 675, 8, 16]

5.4 MUTABILITY
It may be stated that a list is mutable. That is, one can update an element of the list. In
order to understand this, consider the following snippet. The following code sets the second
element of the list as 675. Note that an element of a list can be accessed by a square bracket.
Therefore L2[1] represents the second element of the list L1 (owing to zero based indexing).
Code: Mutability
#Mutable
L2=[2,4,8,16,32,64]
L2[1]=675
#The second element of the list L2 would become 675
print(L2)
Output:
[2, 675, 8, 16, 32, 64]

Lists 25
5.5 OPERATORS
Python provides four operators for lists. These are:+, *, in and not in. The + operator in
L1+L2 concatenates two lists L1 and L2. The * operator in L1*n repeats the elements of
the list L1, n times. The in operator checks if a given element is available in a list. The not
in operator checks if a given element is not available in the list. In order to understand the
functioning of operators, consider the following code. The list L9 is the concatenation of
L2 and L8. The list L4 has elements of L2 repeated thrice. Note that we cannot use the –
operator with a list.
Code: Operator +, *, in and not in
#Using + operator
L8= [90, 80, 70]
#Concatenate two lists
L9=L2+L8
print(L9)
#Using * operator
num=3
#repeat the elements ‘num’ times
L4=L2*num
print(L4)
#- Illegal
L11=L2-L8
print(L11)
Output:
[2, 675, 8, 16, 32, 64, 90, 80, 70]
[2, 675, 8, 16, 32, 64, 2, 675, 8, 16, 32, 64, 2, 675, 8,
16, 32, 64]
-----------------------------------------------------------
TypeError Traceback (most recent call last) <ipython-input-
14-7ccfbd405905> in <module>()1
#- Illegal----> 2 L11=L2-L8 3 print(L9)
TypeError: unsupported operand type(s) for -: ‘list’ and
‘list’

5.6 TRAVERSAL
A list is a sequence. Each element in a list can be accessed using its index in square brackets.
It can be accessed using loops and iterators. Though any loop can be used to accomplish the
said task, for loop’s use make the task easy. The for loop can be used to traverse a list as
shown in the following code which stores each item of the list in i and prints them. In the

26 Computer Science with Python–XII: Supplement


next code, nested loops are used to process lists of lists. The last code processes a list having
different types of elements.
Code: Print each element in a list
L2=[2, 675, 8, 16, 32, 64]
#Print all elements
for i in L2:
print(i)
Output:
2
675
8
16
32
64
Code: Processing list of lists using nested loops
L4=[[1,2],[2,4,8],[3,9,27,81]]
#Print all the lists in list L4
for i in L4:
print(i)
Output:
[1, 2]
[2, 4, 8]
[3, 9, 27, 81]
Code: Processing all elements of a list of lists using nested loops
L4=[[1,2],[2,4,8],[3,9,27,81]]
#All the elements of the lists inside the list L4 are
accessed and printed using nested loops
for i in L4:
print(‘List’, end=’\t’)
for j in i:
print(j, end=’ ‘)
print(‘‘)
Output:
List 1 2
List 2 4 8
List 3 9 27 81
Code: Processing a list containing different types of elements

Lists 27
L3=[2, ‘Harsh’, 3,’Manan’, 5.7865,’Ali’]
#The different types of elements are printed using for loop
for i in L3:
print(i)
Output:
2
Harsh
3
Manan
5.7865
Ali
The above discussion revealed the methods of creation of list, its processing, slicing and
indexing. Having seen the basics, let us now perform slightly more complicated tasks like
displaying a list entered by the user and finding the maximum and the minimum elements
from a list.

5.7 FUNCTIONS
The functions associated with list are shown in Table 5.1. The table enlists some of the most
important methods used for lists and their purpose. Note that the following tasks can also be
accomplished without using the functions, as discussed in the next section. However, these
functions help us to accomplish many tasks efficiently and effectively. The code that follows
demonstrates the use of these functions.
Table 5.1: Functions of List
Function Explanation
list.append(item) The append method adds ‘item’ at the end of the list.
list.extend(iter) The extend method adds the ‘item’ at the end of the list.
list.insert(index, item) The insert function inserts ‘item’ at ‘index’.
list.remove(item) The remove function removes the first instance of ‘item’ from the list.
list.pop(index) The pop function removes the item at the given index in the list. Also,
pop() removes the last element from the list.
list.clear() The clear method removes all the elements from the list.
list.index(item) Return zero-based index in the list of the first item whose value is equal
to item.
list.count(item) The count function counts the number of instances of ‘item’ in the list.
list.sort() The sort function sorts the items of the list. An additional argument
reverse=True sorts the list in the descending order.
list.reverse() The reverse function reverses the ordered of the list.
list.copy() The copy function returns a shallow copy of the list.

28 Computer Science with Python–XII: Supplement


The above functions have been used as follows. Note that the input is prefixed with >>
and that without >> shows the output.
#Functions
>>L13=[1,2,3]
>>L14=[7,8,9,10]
>>L15.extend(L13)
>>print(L14)
[7, 8, 9, 4, 1, 2, 3]
>>L15.remove(4)
>>print(L14)
[7, 8, 9, 1, 2, 3]
>>L15.insert(2,787)
>>print(L14)
[7, 8, 787, 9, 1, 2, 3]
>>L15.index(3)
9
>>L15.count(3)
1
>>L15.pop()
3
>>L15.reverse()
>>print(L14)
[2, 1, 9, 787, 8, 7]
>>L15.sort()
print(L14)
[1, 2, 7, 8, 9, 787]
The following tasks can also be accomplished using the inbuild functions provided by
Python. However, the purpose of presenting the following illustrations is to make the reader
adapted to various controls studied so far.

ILLUSTRATION 5.1
Write a Program to find maximum number from a given list.

SOLUTION
To find the maximum element in a list, ask the user to enter the number of items in the list
(say n).Use for loop to take input from the user and in each iteration, element entered will be
appended to the list. Now, take another variable, say max and store the first element of the list

Lists 29
in it. Compare each element of the list with the max and if a greater number is found, store
that element in max. Finally, print max, which is the maximum element in the list.
Code:
L1=[]
n=int(input(‘Enter the no of elements :’))
for i in range(n):
item=int(input(‘Enter no : ’))
L1.append(item)
max=L1[0]
for i in L1:
if(i>max):
max=i
print(‘List : ’,L1)
print(‘Maximum Element in the list : ’,max)
Output:
Enter the no of elements :4
Enter no : 4
Enter no : 5
Enter no : 6
Enter no : 7
List : [4, 5, 6, 7]
Maximum Element in the list : 7

ILLUSTRATION 5.2
Write a Program to find minimum number from a given list.

SOLUTION
To find the minimum element in a list, ask the user to enter the number of items in the list
(say n).Use for loop to take input from the user and in each iteration, element entered will be
appended to the list.Now, take another variable, say min and store the first element of the list
in it. Compare each element of the list with min and if a smaller number is found, store that
element in min. At last print max to get the maximum element in the list.
Code:
L2=[]
n=int(input(‘Enter the no of elements :’))
for i in range(n):
item=int(input(‘Enter no : ’))
L2.append(item)

30 Computer Science with Python–XII: Supplement


min=L2[0]
for i in L2:
if(i<min):
min=i
print(‘List : ’,L2)
print(‘Minimum Element in the list : ’,min)
Output:
Enter the no of elements :4
Enter no : 2
Enter no : 4
Enter no : 5
Enter no : 6
List : [2, 4, 5, 6]
Minimum Element in the list : 2

ILLUSTRATION 5.3
Write a Program to search a number from a given list.

SOLUTION
To search an element from a given list, ask the user to enter the number of items in the list
(say n). Use for loop to take input from the user and in each iteration, element entered will
be appended to the list. Initialize flag to 0. Now, ask the user to enter the item to be searched.
Compare the item with each element of the list. If the item entered is equal to any of the
element in the list, then set flag=1. After all the comparisons, if flag is still 0, the item is not
found, else the item is found.
Code:
L3=[]
n=int(input(‘Enter the no of elements :’))
for i in range(n):
element=int(input(‘Enter no : ’))
L3.append(element)
item=int(input(‘Enter no to be search :’))
flag=0
for i in L3:
if(item==i):
flag=1
if(flag==1):

Lists 31
print(‘Item found’)
else:
print(‘Item no found’)
Output:
Enter the no of elements :4
Enter no : 2
Enter no : 4
Enter no : 5
Enter no : 6
Enter no to be search :5
Item found

ILLUSTRATION 5.4
Write a Program to reverse the elements of a given list.

SOLUTION
L4=[]
n=int(input(‘Enter the no of elements :’))
for i in range(n):
element=int(input(‘Enter no : ’))
L5.append(element)
print(‘List : ’,L4)
L4=L4[n::-1]
print(‘Reversed List : ‘,L4)

Output
Enter the no of elements :4
Enter no : 2
Enter no : 4
Enter no : 6
Enter no : 8
List : [2, 4, 6, 8]
Reversed List : [8, 6, 4, 2]

ILLUSTRATION 5.5
Write a Program to find max no and its position in a given list.

32 Computer Science with Python–XII: Supplement


SOLUTION
L5=[]
n=int(input(‘Enter the no of elements :’))
for i in range(n):
item=int(input(‘Enter no : ’))
L5.append(item)
max=L5[0]
loc=1
for i in L5:
if(i>max):
max=i
print(‘List : ’,L5)
for i in L5:
if(max==i):
print(‘Max at location : ’,loc)
loc+=1
Output:
Enter the no of elements :4
Enter no : 24
Enter no : 25
Enter no : 28
Enter no : 98
List : [24, 25, 28, 98]
Max at location : 4

ILLUSTRATION 5.6
Write a Program to find sum of all elements of a given list.

SOLUTION
L6=[]
n=int(input(“Enter the no of elements : ”))
sum=0
for i in range(n):
item=int(input(“Enter the item : ”))
L6.append(item)
sum=sum+L6[i]
print(L6)

Lists 33
print(“sum of all elements of list : ”,sum)
Output:
Enter the no of elements : 4
Enter the item : 2
Enter the item : 4
Enter the item : 6
Enter the item : 8
[2, 4, 6, 8]
sum of all elements of list : 20

ILLUSTRATION 5.7
Write a Program to find product of all elements in a given list.

SOLUTION
L7=[]
n=int(input(“Enter the no of elements : ”))
pro=1
for i in range(n):
item=int(input(“Enter the item : ”))
L7.append(item)
pro=pro*L7[i]
print(L7)
print(“Product of all elements of list : ”,pro)
Output:
Enter the no of elements : 4
Enter the item : 2
Enter the item : 4
Enter the item : 6
Enter the item : 8
[2, 4, 6, 8]
Product of all elements of list : 384

ILLUSTRATION 5.8
Write a Program to find second maximum no in a given list?

SOLUTION
L8=[]
n=int(input(‘Enter the no of elements :’))

34 Computer Science with Python–XII: Supplement


for i in range(n):
item=int(input(‘Enter no : ’))
L8.append(item)
max=L8[0]
sec_max=0
for i in L8:
if(i>max):
sec_max=max
max=i
print(‘List : ‘,L8)
print(‘Second Maximum Element in the list : ‘,sec_max)
Output:
Enter the no of elements :5
Enter no : 23
Enter no : 65
Enter no : 45
Enter no : 23
Enter no : 95
List : [23, 65, 45, 23, 95]
Second Maximum Element in the list : 65

ILLUSTRATION 5.9
Write a Program to swap even and odd terms in a given list.

SOLUTION
L9=[]
n=int(input(‘Enter the no of elements :’))
for i in range(n):
item=int(input(‘Enter no : ’))
L9.append(item)
print(‘List : ’,L9)
for i in range(0,n-1,2):
(L9[i],L9[i+1])=(L9[i+1],L9[i])
print(‘swapped list : ’,L9)
Output:
Enter the no of elements : 6

Lists 35
Enter no : 1
Enter no : 2
Enter no : 3
Enter no : 4
Enter no : 5
Enter no : 6
List : [1, 2, 3, 4, 5, 6]
swapped list : [2, 1, 4, 3, 6, 5]

5.8 CONCLUSION
This chapter introduced a very powerful object called List. As we proceed, we will implement
many data structures like Stacks and Queues using Lists. Moreover, lists can also be used
to store one dimensional array and two-dimensional matrices, as discussed in the following
chapters. It may be noted that the reader must make himself familiar with the functions of
lists to accomplish the given task effectively and efficiently. For now, let us move to the
exercises and dwell into lists.

Glossary

List: A Python list is a sequence object. It may contain any number of elements, which
may or may not be of the same type. They are mutable.
Tuples: A tuple can contain different types of elements and are not mutable.
Dictionary: A dictionary maps the index (which may be a string) to a value.

Points to Remember
•• Lists are mutable.
•• A list may contain different types of elements.
•• Tuples are not mutable. Dictionary maps a key to a value.

VERY SHORT ANSWER QUESTIONS


1. Can a list contain different types of elements?
Ans. Yes

36 Computer Science with Python–XII: Supplement


2. Is a list mutable?
Ans. Yes
3. If L=[2, 4, 8, 16, 32, 64], what is
(a) L[2] (b) L[4] (c) L[-1]
Ans. (a) 8 (b) 32 (c) 64
5. In the above question, what is
(a) L[:2] (b) L[2:] (c) L[2:5]
Ans. [2,4]
[8, 16, 32, 64]
[8, 16, 32]
5. If L1 = [2, 4, 8, 16] and L2 = [32, 64], what is L1 + L2?
Ans. [2, 4, 8, 16, 32, 64]
6. In the above question, what is 3*L1?
Ans. [2, 4, 8, 16, 2, 4, 8, 16, 2, 4, 8, 16]
7. What is the result of the following statement?
6 in L1
Ans. False
8. What is the result of the following statement?
16 in L1
Ans. True
9. Is list a sequence?
Ans. Yes

MULTIPLE CHOICE QUESTIONS


1. In Python a list is
(a) Mutable (b) Can contain different types of elements
(c) Both (d) None of the above
2. A list in Python
(a) Is 0 index based (b) Can be accessed by indexing
(c) Negative indices can be used in indexing
(d) All of the above
3. L=[5,4,3,1,2,7,6]
a=L[–1]
print(a)
(a) 6 (b) 5
(c) 1 (d) None of the above

Lists 37
4. L.remove(a)
print(L)
(a) [5,4,3,1,2,7] (b) [4,3,1,2,7,6]
(c) [5,4,3,2,7,6] (d) [5,4,3,1,2,7,6]
5. L.insert(0,L[-1])
L[:-1]
(a) [7, 5, 4, 3, 1, 2] (b) [5, 4, 3, 1, 2, 7, 6]
(c) [5, 4, 3, 1, 2, 7, 0] (d) [5, 4, 3, 1, 2, 7, 6]
6. L_names=[‘Harsh’,’Amit’,’Sahil’,’Viresh’]
L_names.sort()
print(L_names)
(a) [‘Amit’, ‘Harsh’, ‘Sahil’, ‘Viresh’]
(b) [‘Amit’, ‘Sahil’, ‘Viresh’]
(c) [‘Harsh’,’Amit’,’Sahil’,’Viresh’]
(d) Error as sort function cannot be applied on a list having strings as its elements.
7. min(L_names)
(a) ‘Harsh’ (b) ‘Amit’
(c) ‘Viresh’ (d) None of the above
8. max(L_names)
(a) ‘Harsh’ (b) ‘Amit’
(c) ‘Viresh’ (d) None of the above
9. L_names.pop()
(a) ‘Harsh’ (b) ‘Amit’
(c) ‘Viresh’ (d) None of the above
10. L_names.append(‘Raven’)
print(L_names)
(a) [‘Amit’, ‘Harsh’, ‘Sahil’, ‘Raven’]
(b) [‘Amit’, ‘Harsh’, ‘Sahil’, ‘Viresh’]
(c) [‘Amit’, ‘Sahil’, ‘Viresh’]
(d) [‘Harsh’,’Amit’,’Sahil’,’Viresh’]
11. L_names[:2]
(a) [‘Amit’, ‘Harsh’] (b) [‘Sahil’, ‘Raven’]
(c) [‘Harsh’, ‘Sahil’] (d) None of the above
12. L_names[2:]
(a) [‘Amit’, ‘Harsh’] (b) [‘Sahil’, ‘Raven’]
(c) [‘Harsh’, ‘Sahil’] (d) None of the above

38 Computer Science with Python–XII: Supplement


13. L_names[2:4]
(a) [‘Amit’, ‘Harsh’] (b) [‘Sahil’, ‘Raven’]
(c) [‘Harsh’, ‘Sahil’] (d) None of the above
14. L_names[2:3]
(a) [‘Sahil’] (b) [‘Sahil’, ‘Raven’]
(c) [‘Harsh’, ‘Sahil’] (d) None of the above
15. Which function is used to delete a list?
(a) Clear (b) Pop
(c) Append (d) None of the above

THEORY
1. What is a list? Is it mutable?
2. Explain indexing in lists.
3. Explain slicing in lists.
4. Explain the following functions vis-à-vis Python lists
(a) append() (b) extend()
(c) insert() (d) remove()
(e) pop() (f) clear()
(g) index() (h) count()
(i) sort() (j) reverse()
(k) copy()
5. Explain the purpose of the following operators vis-a-vis lists.
(a) + (b) *
(c) in (d) not in

PROGRAMMING EXERCISE
1. Ask the user to enter the names of his batch mates in a list.
2. Sort the above list.
3. Can we apply the min function on the above list?
4. Can we apply the max function on the above list?
5. Create a sub list from above list having elements at the odd positions.
6. Create a sub list from above list having elements at the even positions.
7. Does the list contain any duplicate element?
8. From the above list find the name having maximum number of vowels.
9. Insert an element at the given position in the above list.
10. Create a list having each element of the original list twice.

Lists 39
6 Strings

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
• Understand the concept and importance of strings
• Understand various string operators
• Learn about the build in functions to manipulate strings
• Learn how to solve problems using Strings

6.1 INTRODUCTION
Strings are the sequence of characters. These data structures are used to store text. For
example, if one wants to store the name of a person, or for that matter, his address, then
strings are the most appropriate data structures. As a matter of fact, the knowledge of strings
is essential in the development of many applications like word processor and parser.
Strings, in Python, can be enclosed in single quotes or double quotes, or even in triple
quotes. Though, there is no difference between a string enclosed in single quotes or double
quotes. That is ‘harsh’ is same as “harsh”. Triple quotes are generally used in special cases as
discussed later in this chapter. Strings in Python, come with wide variety of operators and in-
build functions.
The chapter examines various aspects of strings, like non-mutability, traversal, operators
and in-build functions. One of the most prominent difference between a string and a list is
non-mutability. Once a value is given to a string, one cannot change the value of a character
present at a particular position. For the users familiar with ‘C’, ‘C++’, ‘C#’ or ‘Java’, the
operators discussed in the chapter, notably * would be a pleasant surprise. Moreover, Python
provides many build-in functions to help the programmers to handle strings. The indexing
and slicing in strings is same as that of lists and tuples.
This chapter examines the above issues and exemplifies them. The chapter has been
organized as follows. The second section of the chapter explores the use of standard ‘for’
and ‘while’ loops in strings. The third section deals with the operators that can be used with
strings. The in-build functions used for accomplishing various tasks have been dealt within
the fourth section. The last section concludes.

40 Computer Science with Python–XII: Supplement


6.2 LOOPS REVISED
The traversal of a strings has already been discussed in the first section of this book. The
reader is advised to go through the section before starting this section. However, a brief
description of the topic has been presented in this section.
As stated earlier, strings are iterable objects, therefore standard loops (read ‘for’ and
‘while’) can be used to iterate through them. The ‘for’ loop helps to iterate through each
character by storing the character in some variable. The following illustration depicts the use
of a ‘for’ loop to iterate the string.

ILLUSTRATION 6.1
Ask the user to enter a string and print each character using a for loop. Listing:
str1= input(‘Enter a string\t:’)
for i in str1:
print(‘Character \t:’,i)
Output:
============== RUN C:/Python/String/str2.py ================
Enter a string :harsh
Character : h
Character : a
Character : r
Character : s
Character : h
The above procedure can also help us to find the length of string. Note that there is an
in-build function to accomplish the said task. However, the purpose here is to be able to use
the for loop in order to imitate the len function. In the following illustration, a variable called
length is initialized to 0, and is incremented as we proceed.

ILLUSTRATION 6.2
Ask the user to enter a string and find its length.
Listing:
name=input(‘Enter your name\t’);
length=0
for i in name:
length=length +1
print(‘The length of ‘,name,’ is ‘,length)
Output:
============== RUN C:/Python/String/str1.py ================

Strings 41
Enter your name harsh
The length of harsh is 5
The ability to handle each character individually, in a string, makes the tasks like
basic cryptography manageable. In order to understand the concept, consider the following
example. The example that follows, displaces the characters two positions to the right. This is
referred to as transposition. The next example shifts the characters by ‘k’ positions, where ‘k’
is entered by the user.

ILLUSTRATION 6.3
Ask the user to enter a string and displace each character by two positions to the right.

SOLUTION
str1=input(‘Enter the string\t:’)
i=0
str2=””
while i<len(str1):
str2[i]=str1[(i+2)%len(str1)]
print(str2)

ILLUSTRATION 6.4
Ask the user to enter a string and displace each character by k positions to the right

SOLUTION
str1=input(‘Enter the string\t:’)
k=int(input(‘Enter the value of k\t:’))
i=0
str2=””
while i<len(str1):
str2+=str1[(i+k)%len(str1)]
print(str2)
i+=1
print(str2)
>>>
Output:
=========== RUN C:/Python/String/transposition.py ==========
Enter the string :harsh
Enter the value of k :4
h

42 Computer Science with Python–XII: Supplement


hh
hha
hhar
hhars
hhars
Substitution replaces a symbol by some other symbol. This replacement would result in
the formation of another string by a given string. Loops can be used for substitution. The
example that follows implements one of the most basic types of substitutions. Here, each
character is replaced by a character obtained by adding two to the ascii value of the character,
and finding the requisite character.

ILLUSTRATION 6.5
Ask the user to enter a string. Replace each character by that obtained by adding two to the
ascii value of that character.

SOLUTION
str1=input(‘Enter the string\t:’)
k=int(input(‘Enter the value of k\t:’))
i=0
str2=””
while i<len(str1):
str2+=str((ascii(str1[i])+k))
print(str2)
i+=1
print(str2)

6.3 STRING OPERATORS


Python provides the programmer with a wide variety of, extremely useful, operators to
manipulate strings. These operators help a user to perform involved tasks with ease and
efficiency. Here, it may be stated that the replication and membership operators make
Python stand apart from its counterparts. This section briefly introduces and exemplifies the
operators.

6.3.1 The Concatenation Operator (+)


The concatenation operator takes two strings and produces a concatenated string. The
operator acts on values as well as variables. In the examples that follow, the result generated
by applying the concatenation operators’ have been stored in variables called result1 and
str2.
name=input(‘Enter your name\t:’)
result1 = ‘Hi’+’ there’

Strings 43
print(result1)
str1=’Hello’
str2=str1 +‘ ’+name
print(str2)
Output:
============= RUN C:/Python/String/operator1.py ============
Enter your name :Harsh
Hi there
Hello Harsh

6.3.2 The Replication Operator (*)


The replication operator in Python, replicates the strings as many times as the first operand.
The operator operates on two operands: the first being a number and the second being a
string. The result is a string in which the input string is repeated as many times as the first
argument. In the example that follows, the result has been stored in a variable called result1.
name=input(‘Enter your name\t:’)
print(‘Hi’, ‘ ‘, name)
str1=input(‘Enter a string\t:’)
num=int(input(‘Enter a number\t:’))
result1=num*str1
print(result1)
Output:
============== RUN C:/Python/String/operator2.py ===========
Enter your name :harsh
Hi harsh
Enter a string :abc
Enter a number :4
abcabcabcabc

6.3.3 The Membership Operator


The membership operator checks whether a given string is in a given list or not. The operator
returns a True, if the first string is a part of the given list, otherwise it returns a False.
‘Hari’ in [‘Har’, ‘Hari’, ‘Hai’]
Output:
True
Example:
‘Hari’ in [‘Har’, ‘hari’, ‘Hai’]

44 Computer Science with Python–XII: Supplement


Output:
False
It may be noted here that this operator is also used in manipulating iterations. The reader
is advised to go through section I and II, of this book, for a detailed discussion regarding
the use of ‘in’ in for. It may also be noted that the operator can also be used in tuples. In the
listing that follows, the string ‘Hari’ is present in the given tuple and hence ‘True’ is returned.
‘Hari’ in (‘Hari’, ‘Har’)
Output:
True
The reader may also note that corresponding to the ‘in’ operator, there is a ‘not in’
operator which works in the exactly opposite manner vis-a-vis ‘in’.
A string in Python can span over many lines. This can be accomplished by putting a ‘\’
at the end of the line. For example, str2 is “Harsh BhasinAuthorDelhi”. However, it has been
written in three lines, using the ‘\’ character.
str2=”’Harsh Bhasin\
Author\
Delhi’”
print(str2)
Output:
“’Harsh BhasinAuthorDelhi’”

6.4 IN-BUILD FUNCTIONS


This section presents some of the most common functions used to manipulate strings, in
Python. It may be stated here that, though all the following tasks can be done, without the
predefined functions, with varying degree of ease, the presence of these functions help the
programmer to do the task easily and efficiently. Moreover, when one crafts and implements
one’s version of a function, the implementation may not be efficient in terms of time or space
or both. However, while crafting these predefined functions in Python, the issues related
to memory and times have already been dealt with. Let us, now, have a look at the names,
meanings and usage of the pre-defined functions in Python.

6.4.1 len()
Usage:
len(<string>)
Explanation: The function returns the number of characters in a string. For example if a
variable called str1 stores ‘Harsh Bhasin’, then the length of the string can be calculated by
writing len(str1). Note that, the space between ‘Harsh’ and ‘Bhasin’ has also been taken into
account while calculating the length of the string. To summarize, the function takes a string
argument and returns an integer, which is the length of the string.

Strings 45
Example (s):
str1 =’Harsh Bhasin’
len(str1)
Output:
12
Example:
len(‘Harsh Bhasin’)
Output:
12
Example:
len(‘’)
Output:
0

6.4.2 capitalize()
Usage:
capitalize()
Explanation: The function capitalizes the first character of the string. Note that, only the
first character would be capitalized. If one wants to capitalize the first characters of all the
words in the string the title() function can be used.
Example (s):
str2= ‘harsh bhasin’
str2
Output:
‘harsh bhasin’
Example:
str2.capitalize()
Output:
‘Harsh bhasin’

6.4.3 find()
Usage:
<name of the string>.find(<parameter(s)>)
Explanation: The location of a given sub-string in a given string can be found by using
the function ‘find’. Also, if the location of a sub-string after a particular position (and before
a particular index) is to be determined, then three arguments can be passed to the function: the
sub-string, initial index and the final index. The following examples shows the usage of the
function.

46 Computer Science with Python–XII: Supplement


Example(s):
str2.find(‘ha’)
Output:
0
Example:
str2.find(‘ha’,3,len(str2))
Output:
7

6.4.4 count
Usage:
<name of the string>.count(<parameter(s)>)
Explanation:
The number of occurrences of a particular substring can be found by the count function.
The function takes three arguments: the sub-string, the initial index and the final index. The
following examples shows the usage of the function.
Example(s):
str3.count(‘ha’,0,len(str3))
Output:
1
Example:
str3.count(‘ka’,0,len(str3))
Output:
0

6.4.5 endswith()
Usage: <name of the string>.endswith(<parameter(s)>)
Explanation:
One can determine if a string ends with a particular sub-string. This can be done using the
endswith() function. The function returns a True if the given string ends with the given sub-
string, otherwise it returns a False.
Example(s):
str3.endswith(‘n’)
Output:
True

Strings 47
6.4.6 Miscellaneous Functions
Except for the functions discussed above, there are some more functions to accomplish
assorted tasks. The following list presents some of the functions and the code that follows,
presents an example of the usage.
List:
1. isanum()
2. isalpha()
3. isdecimal()
4. isdigit()
5. isidentifier()
6. islower()
7. isupper()
8. swapcase()
9. isspace()
10. lstrip()
11. rstrip()
12. replace()
13. join()
Explanation:
The contents of a given string can be checked using the following functions. The
isalnum() function if the given string is alphanumeric. The other functions like isalpha() and
isdecimal() also check the type of contents in a given string.
Whether a given string contains only digits can be checked using the isdigit() function.
Similarly, whether a given string is an identifier can be checked using the isidentifier()
function. The islower() function checks if the given string contains only the lower case
characters and the isupper() function checks if the given string contains only the upper case
characters. The swapcase() functions, swaps the case of the given string, as in converts the
upper case to lower and lower to upper. The presence of spaces(only) can be checked using
the isspace() function. Extra spaces can be removed from the left and the right hand side by
using the lstrip() and rstrip() functions. The replace() function replaces the instances of the
first argument by the string in the second argument. The split function, splits the given strings
into tokens. The following illustration depicts the use of this function for splitting the string
into constituent words. The function of join() is exactly opposite as that of split.

ILLUSTRATION 6.6
A string str4 contains a sentence ‘I am a good boy’. Split the string into tokens and also
display each token using a for loop.

48 Computer Science with Python–XII: Supplement


SOLUTION
>>> str4=’I am a good boy’
>>> str4.split()
[‘I’, ‘am’, ‘a’, ‘good’, ‘boy’]
>>>
>>> for i in str4.split():
print(‘Token\t:’,i)
Output:
Token : I
Token : am
Token : a
Token : good
Token : boy
Table 6.1 summarizes some of the important functions and the illustrations follow.

Table 6.1: Function of strings

Capitalize() This function capitalizes the string. It makes the first character of the
input string capital.

Find() This function returns the lowest index at which the substring is found
else it returns a -1.

Isalnum() This function returns a True, if the given string is alphanumeric else it
returns a False.

Isaplha() This function returns a True of the given string consists of only
characters.
Isdigit() This function returns a True of the given string consists of only digits.
Isupper() This function Capitalizes the whole string.
Islower() This function converts the string to lower case.
Isspace() This function returns a True if the given string has all white spaces.
Lstrip() This function strips the spaces from the left of the string.
Rstrip() This function strips the spaces from the right of the string.

The examples of the above functions are as follows.


1. Capitalize()
Example:
A= ‘hi there’

Strings 49
A.capitalize()
Output:
‘Hi there’
2. Find()
Input:
A=‘hi there’
A.find(‘th’)
Output:
3
Example:
A=‘hi there’
A.find(‘tr’)
Output:
-1
3. isalnum()
Example:
A=‘hi there12’
A.isalnum()
Output:
False
Example:
A=‘hithere12’
A.isalnum()
Output:
True
4. Isalpha()
Example:
A=‘hithere’
A.isalpha()
Output:
True
Example:
A=‘hi there’
A.isalpha()

50 Computer Science with Python–XII: Supplement


Output:
False
5. Isdigit()
Example:
A=‘12345’
A.isdigit()
Output:
True
Example:
A=‘1 2 3 4 5’
A.isdigit()
Output:
False
6. Isupper()
Example:
A=‘hello world’
A.upper()
Output:
HELLO WORLD
7. Islower()
Example:
A=‘HELLO WORLD’
A.lower()
Output:
hello world
8. Isspace()
Example:
A=’ ‘
A.isspace()
Output:
True
Example:
A=’hi there ‘
A.isspace()

Strings 51
Output:
False
9. Lstrip()
Example:
A=’ 12345’
A.lstrip()
Output:
‘12345’
10. Rstrip()
Example:
A=’12345 ‘
A.lstrip()
Output:
‘12345’

6.5 ILLUSTRATIONS
Having seen the indexing, slicing and basic functions of strings, let us now move to some
illustrations.

ILLUSTRATION 6.7
Ask the user to enter the name of a book. Split the name into words and find the length of
each word. Also, find the indices of those words in the original string.

SOLUTION
The input function takes input from the user. This is followed by the application of the
split function to break the string into different words. Each word’s length is then calculated
using the len function and the index is stored in another list called lens. The task can be
accomplished by using a variable called tot, which is initialized to 0.
Program:
words=book_name.split()
print(words)
lens=[]
Indices=[]
tot=0
for j in range(len(words)):
Indices.append(tot)
l=len(words[j])

52 Computer Science with Python–XII: Supplement


lens.append(l)
tot+=l
print(lens)
print(Indices)
Output:
[‘Programming’, ‘in’, ‘C#’]
[11, 2, 2]
[0, 11, 13]

ILLUSTRATION 6.8
In the above question print each word, the corresponding word in running and in capitals and
the length of each word.

SOLUTION
The for loop would help to iterate through the list and in each iteration the use of upper,
lower and len functions would help us to accomplish the said task.
Program:
for i in words:
print(i.upper(),’\t’, i.lower(),’\t’,len(i))
Output
PROGRAMMING programming 11
IN in 2
C# c# 2

ILLUSTRATION 6.9
Using the indices of the words obtained in the above questions, find the middle word in the
name containing three words, using slicing.

SOLUTION
The task can be accomplished using the following statement
print(book_name[Indices[0]:Indices[1]])
Output:
Programming

ILLUSTRATION 6.10
Ask the user to enter a string. Now ask him to enter a number, less then the length of the
string. Print the character at the position and that at the negative index of the number entered.
Also find everything in between.

Strings 53
SOLUTION
The reader is expected to understand the following, as the code makes use of the things
already discussed.
Program:
# k the alphabet
str1=input(‘Enter string\t:’)
n=len(str1)
str2=’Enter k ( < ‘,n,’)\t:’
k=int(input(str2))
print(str1[k])
print(str1[-1*k])
print(str1[k:(-1*k)])

ILLUSTRATION 6.11
What is the output of the following?
1. str1=‘rohan’
for i in str1:
print(i,end=’/’)
output:
r/o/h/a/n/
2. str1=‘rohan’
for i in str1:
print(i)
Output:
r
o
h
a
n
3. str2=””
n=len(str1)
i=n-1
while(i>=0):
str2+=str1[i]
i-=1
print(str2)

54 Computer Science with Python–XII: Supplement


Output:
nahor
4. str1=‘ha’
str2=‘rsh’
str=str1+str2
print(str)
Output:
harsh
5. str1=31
str2=43
str=str1+str2
print(str)
Output:
74
6. str1=’tarush’
str2=5+str1
print(str2)
Output:
---------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-1c38aea043b9> in <module>
1 str1=’tarush’
---> 2 str2=5-str1
3 print(str2)
TypeError: unsupported operand type(s) for -: ‘int’ and
‘str’
7. str1=’tarush’
str2=str1 + ‘5’
print(str2)
Output:
tarush5
8. str1=’tar’
str=str1*3
print(str)
Output:
‘tartartar’

Strings 55
9. ‘a’ in str1
Output:
True
10. ‘f’ in str1
Output:
False
11. str1=‘har’
str2=6
str=str1+str2
print(str)

Output:
TypeError Traceback (most recent call last)
<ipython-input-18-4205d90a19b8> in <module>
1 str1=‘har’
2 str2=6
---> 3 str=str1+str2
4 print(str)
TypeError: can only concatenate str (not “int”) to str
len(str1)
Output:
3

6.6 CONCLUSION
In C and C++, strings are used to be character arrays. They are a special type of arrays with a
‘\0’ character at the end. Strings, in C, come with a set of inbuilt functions. However, are two
major problems. First, string is not an independent data type in C or C++, second is mutability
of strings in C or C++. In Python the importance of strings has been duly recognized by
creating an object type. Moreover, strings, in Python, are non-mutable. Strings come with
a wide range of built-in functions. Also, there are useful operators, to help the programmer
accomplish a given task easily and efficiently. This chapter introduces the concept, operators
and functions of strings. However, the reader is expected to complete the end-chapter exercise
to be able to understand and use strings.

Glossary
String: Strings are the sequence of characters. These data structures are used to store text.

56 Computer Science with Python–XII: Supplement


Points to Remember
•• Strings in python are non-mutable.
•• The negative index denotes the characters from the right hand.
•• Strings are iterable objects.

VERY SHORT ANSWER QUESTIONS

1. What is a string?
Ans. It is a sequence of characters.
2. Is a string mutable?
Ans. No
3. For a string str1, what does str1[-1] signify?
Ans. The last character of the string str1.
4.
For a string str1, what does str1[3:7] signify?
Ans. It is a sub-string of the given string from index 3 to 6. For example, if str1
=‘Hariharan’ then str1[3:7] is ‘ihara’
5. For a string str1, what is str1[:7]?
Ans. It is a sub-string of the given string from index 0 to 6. For example, if str1
=‘Hariharan’ then str1[:7] is ‘harihara’
6. For a string str1, what is str1[3:]?
Ans. It is a sub-string of the given string from index 3 to the last index. For example, if str1
=’Hariharan’ then str1[3:] is ‘iharan’
7. In writing str1+=”harsh”, given str1 is “harsh”, a new string is created or str1 is
changed?
Ans. A new string having value “harshharsh” is created.
8. What is the purpose of the function len?
Ans. It is used to find the length of the given string.
9. What is the purpose of upper function?
Ans. It is used to convert a string into upper case.
10. What is the purpose of the lower function?
Ans. It is used to convert a string into lower case.

Strings 57
MULTIPLE CHOICE QUESTIONS

1. Which of the following is true?


(a) A string in Python is iterable
(b) A string in Python is not iterable
(c) Iterablity of a string depends upon the situation
(d) None of the above
2. Is a string, in Python mutable?
(a) No (b) Yes
(c) Depends on the situation (d) None of the above
3. If str1=’Hari’, what is the output of print(str1[4])
(a) i (b) \0
(c) Exception is raised (d) None of the above
4. If str1=’Hari’, what is the output of print(str1[-3])
(a) ‘a’ (b) ‘H’
(c) Exception is raised (d) None of the above
5. What is the output of “Hari”==“hari”
(a) True (b) False
(c) An exception is raised (d) None of the above
6. What is the output of ‘a’<>’A’
(a) True (b) False
(c) Exception is raised (d) None of the above
7. What is the output of ‘567’>’989’
(a) True (b) False
(c) An exception is raised (d) None of the above
8. Which of the following helps to find the ASCII value of ‘C’?
(a) ord(‘C’) (b) chr(‘C’)
(c) both (d) None of the above
9. Which of the following helps to find the character represented by ASCII value 67?
(a) ord(67) (b) chr(67)
(c) Both (d) None of the above
10. What are ‘in’ and ‘not in’, in Python?
(a) Relational operators (b) Membership operators
(c) Concatenation operator (d) None of the above
11. What is the output of ‘A’ + ‘B’
(a) ‘A+B’ (b) ‘AB’
(c) 51 (d) None of the above

58 Computer Science with Python–XII: Supplement


12. What is the output of 3*’A’
(a) ‘3A’
(b) Character corresponding to the ascii value 65X3
(C) ‘AAA’
(d) None of the above
13. Which function capitalizes the first character of a given string?
(a) capitalize() (b) titlecase()
(c) toupper() (d) None of the above
14. The find() function, in Python takes
(a) 1 argument (b) 3 arguments
(c) Both (d) None of the above
15. If str1=’hari’, then what would be the output of str1.asalnum()?
(a) True (b) False
(c) Exception is raised (d) None of the above
16. If str1=’hari3’, then what would be the output of str1.asalnum()?
(a) True (b) False
(C) Exception is raised (d) None of the above
17. If str1=’hari feb’, then what would be the output of str1.asalnum()?
(a) True (b) False
(c) Exception is raised (d) None of the above
18. If str1=’123h’, then what would be the output of str1.digit()?
(a) True (b) False
(c) Exception is raised (d) None of the above
19. Which function checks whether all the characters in a given string are in lower case?
(a) lower() (b) islower()
(c) istitle() (d) None of the above
20. Which function checks whether all the characters in a given string are in upper case?
(a) upper() (b) isupper()
(c) istitle() (d) None of the above
21. Which function removes the whitespaces from the right hand of a given string?
(a) rstrip() (b) strip()
(c) lstrip() (d) None of the above

Strings 59
22. Which of the following functions convert a given string into a list of words?
(a) split() (b) break()
(c) breakup() (d) None of the above
23. Which of the following helps in breaking a string into two substrings of desirable length?
(a) slicing (b) splitting
(c) both (d) None of the above
24. Which of the following functions combines the strings given as the argument?
(a) split (b) join
(c) slice (d) None of the above
26. Which of the following is illegal in Python (assume that str1 is a string, having initial
value ‘hari’ )?
(a) str1= ‘Harsh’ (b) str1[0]= ‘t’
(c) str1[0]=str[2] (d) All of the above

PROGRAMMING PROBLEMS
1. Write a program to reverse a string.
2. Write a program to encode a string in UTF format.
3. Write a program to find the sum of ASCII values of the characters of a given string.
4. Write a program to find a particular substring in a given string.
5. Write a program to split a given text into tokens.
6. Write a program to check which of the tokens obtained in the above question are
Keywords of C.
7. Write a program to check how many alphanumeric strings are there in the tokens
obtained in question 6.
8. Write a program to check how many alpha strings are there in the tokens obtained in
question 6.
9. Write a program to check how many numeric strings are there in the tokens obtained in
question 6.
10. Write a program to convert a string entered by a user to that obtained by adding ‘k’ to
each character’s ASCII value.
11. Implement the first phase of complier design (for ‘C’). (Please refer to the Bibliography
for a brief overview of compiler design).
12. In the above question design deterministic finite acceptors for the keywords of C.

60 Computer Science with Python–XII: Supplement


UNIT 2
Computer Networks

Strings 61
ISBN: 978-81-943696-6-0 Publication Year: 2020 Edition: 1st
Pages: 376 MRP: 475.00 Paperback

Click Here to Buy Main Book Online


Computer Science with Python Programming is a textbook designed for the students of Class XII, CBSE. It covers complete course of
Computer Science. The book has been written in easy to understand language and contains ample examples. However, every attempt has been
made to keep the text as precise as possible.
The code has been tested in Python 3.x on a machine with Windows 10.
Each chapter of the book includes a variety of end-chapter exercises in the form of MCQs with answers, review questions, and programming
exercises to help readers test their knowledge. It may be stated here that the topics in the book have been written considering the fact that some
of the readers may opt Computer Science as their career.
Key Features:
• The book has sections dedicated to Computer System and Organization to help the students to understand the basics.
• Offers in-depth treatment of topics such as Pyplot and functions.
• The book introduces Django.
• Provides points to remember and a Glossary with definitions of the key terms at the end of each chapter which will help readers to
quickly recollect the important concepts.
• Questions, given at the end of each chapter and the Appendices would help students during viva and examinations.
Harsh Bhasin has done his B Tech. in Computer Science and M Tech. in Computers and is currently pursuing PhD. He qualified UGC NET in
2012 and received the Visvesvaraya Fellowship from DIETY in 2016. He was awarded the Young Researcher’s Award by ErNet in 2012. Mr.
Bhasin has authored a few papers, including those published in journals like Soft Computing. He has also authored “Programming in C#”
(2014), “Algorithm Analysis and Design” (2015) and “Theory of Computation”. He has been actively involved in research both as an author
and reviewer for ACM, Pearson, Oxford University Press, Springer etc. Mr. Bhasin was the editor in chief of the special issue on
“Applicability of Soft Computing Techniques in NP Problems,” SciEp, USA.
Professionally, Mr. Bhasin is a programmer and has been involved in the development of many Enterprise Resource Planning Systems while
being the proprietor of a firm based in Faridabad, Haryana, India. He has a vast industrial experience. He was an Assistant Professor in
Department of Computer Science, FMIT, Jamia Hamdard. He has also taught as visiting faculty in many colleges including Delhi
Technological University.
His areas of interest include Genetic Algorithms, Theory of Computation, C#, Python, Algorithms, Cellular Automata and Machine
Learning.
His personal interests include Hindi poetry and Hindustani Classical Music. Mr. Bhasin is also a blogger. You can reach him at his
Facebook page DTU Computation or via email at i_harsh_bhasin@yahoo.com.

LONDON • NEW DELHI • NAIROBI


Bangalore • Chennai • Cochin • Guwahati • Hyderabad • Kolkata • Lucknow • Mumbai
NEW AGE
Visit us at www.newagepublishers.com
Safely Accessing Website
7 and Communication Data:
Computer Threats

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
• Understand the definition and types of computer virus
• Understand the difference between a virus and a spyware
• Understand the concept of an Adware
• Understand the idea of eavesdropping, phishing, spamming and trojans

7.1 INTRODUCTION
With the exponential increase in the digital transactions and the growth of companies like
PayTM, Computer Security has become one of the most important topics in recent years.
Moreover, people have started paying their bills, buying electronic items, exploring online
learning systems and even doing bank transactions on the internet. This calls for the basic
knowhow of viruses, spyware, Adware and ways to deal with these problems. This chapter
introduces the reader to computer virus, their types, spyware, adware etc.
The chapter has been organized as follows. The second section introduces viruses. The
third section gives an idea of spyware and the next section introduces Adware. Cookies,
Trojan, spamming, eavesdropping and phishing have been discussed in the next five sections.
The tenth section briefly introduces firewalls, the next section discusses authentication and
the last section concludes.

7.2 VIRUS
We all are aware of the damages caused by computer viruses. The viruses are harmful. They
are known to cause a humongous amount of economic damage. Along with this they may be
used to sabotage systems, send messages, deny services and can even be used for personal
amusement. It is intriguing, however, that the first academic work on viruses was done by
John Von Naumann, who is the founding figure in computing. John Von Naumann is, hence,
also called the father of computer virology.
A computer virus changes other programs. It inserts code in other computer programs.
These programs and the related files are then said to be infected by the virus. The viruses
explore vulnerabilities in the system and explases the fault lines, to increase their impact.

62 Computer Science with Python–XII: Supplement


The Creeper virus was first virus detected on ARPANET.

7.2.1 How does it Work?


The virus, generally causes a system to slow down. A virus has an infection mechanism and
trigger explained as follows.
•• A virus searches files susceptible to infection. Moreover, it must also coordinate with
the software which searches such files.
•• A virus has a predefined infection mechanism which decides how the virus is going
to spread. The search mechanism, stated above, is generally a part of this infection
mechanism.
•• A virus, generally has a trigger, which executes when a certain condition is satisfied.
The virus is then activated and accomplishes its intended task.

7.2.2 Phases of Computer Virus


It may be stated here that the computer virus may not complete its task in one go. A virus,
generally has its life cycle and complete the task in phases. The phases of a virus are as
follows (Figure 7.1).
•• Dormant: In this phase the virus does not do anything
•• Propagation: This is the phase in which it is actually spreading
•• Trigger: In this phase the virus is activated.
•• Execution: This is the phase, where the virus does its task.

Figure 7.1: The phases of computer virus


It may be stated here, that a vast number of viruses are designed to affect the Microsoft
Windows systems. To counter the affect if a virus, anti-virus software are available. Some of
the most famous anti-virus software are:
•• Norton •• McAfee •• AVG •• Kaspersky
As of now no antivirus can detect all the viruses. This is because the virus designer
device strategies to deceive the anti-virus software.

7.3 SPYWARE
A Spyware is a software that extracts information regarding the user, generally without his
consent. The Spyware, at times, share this information with others. This information may be
used for

Safely Accessing Website and Communication Data: Computer Threats 63


•• Tracking the user
•• Monitoring the user
•• And even for displaying the pop-up advertisements
There are many kinds of Spyware, the most prominent of which are as follows.
•• Adware
•• Trojans
•• Tracking cookies
•• System monitors
Except for the above there are others like the keyloggers etc, which can be used to read
the keystrokes. The above points have been summarized in Figure 7.2.

Figure 7.2: Spyware Examples and uses


Some of the most prominent anti-Spywares are:
•• Gator
•• Zlob
•• CoolWebSearch

64 Computer Science with Python–XII: Supplement


7.3.1 Problems
Invasion of privacy: As stated earlier, spywares are used for tracking and monitoring the
user.
Finding surfing habits: Some spywares may also find the surfing habits of a user, which
can later be used for ulterior motives.
Getting financial information: Spywares can also be used to extract the credit card
number, bank account details etc. from the computer.
Redirecting browsers: Spywares can also be used to redirect the browsers and even to
display pop-ups etc.
Compromise security: Some Spywares are known to disable the antivirus software also,
which makes a system suspectable to viruses.
Slowing down the system: The spyware, generally slows down the system owing to
multiple reasons.
Again, it may be stated that the Spywares generally affect the Windows systems and
hence if you have a Windows Machine, it is advisable to install an anti-spyware software.
If you are woking on a Windows system and using Internet Explorer, the probability of your
being affected by a spyware is quite high.
It may also be noted that some of the known companies and websites take your
information and use it for commercial purposes. Such cases have been reported by the Wall
Street Journal.

7.3.2 Difference between Spyware and Virus


A Spyware, installs itself on the system by exploring the fault lines. However, generally, it
does not try to make copies of itself or transfer itself to the other systems. In this sense it is
inherently different from a virus.

7.4 ADWARE
An Adware is actually a software that shows online advertisements and hence generates
revenue for the developer of that software. It may be stated here, that the term adware is not
just used in bad sense (Figure 7.3).

Figure 7.3: Adware

Safely Accessing Website and Communication Data: Computer Threats 65


The software which show online advertisements on the user interface come under the
category of adware. These advertisements are placed in the user interface and may hamper
the normal working of the software. They may, however, generate revenue for the developer,
either by “pay per click” method or by some other protocol. This software can be both the
application software and the SaaS (Software as a Service).
In the other sense, an adware is a type of software, which shows online advertisements
to the user but is installed without the prior permission of the user. It may be stated here that
Adware is generally considered a type of Spyware and hence can be dangerous, due to the
reasons stated in the previous section.

7.5 COOKIES
Cookies are small files stored in the computer having data specific to a user and the website.
A cookie contains key value pairs like (firstname, harsh), (lastname, bhasin) and so on. They
can be accessed from the server side or the client side. The websites may have code which use
cookies to tailor the interface as per the user. The cookies can also be used to pass information
from one session to another. It may be stated here that since cookies can be used for tracking,
one can disable cookies in the browser.

Steps to enable disable cookies (Internet Explorer)


Go to settings-> Advanced settings and enable or disable cookies as per the requirments
(Figure 7.4).

Figure 7.4: Enable/ disable Cookies

66 Computer Science with Python–XII: Supplement


7.6 TROJANS
A trojan is a software that appears as if it is an authentic software. However, they are used to
access information by hackers. As per the official Norton website, it prompts you to install a
malware and then accomplishes its intended task. For example, you may get an e-mail asking
you to click on a link to install a popular software. But this installation, installs a malware
into your computer and then steals your information.
Trojans may be very harmful. For example, a trojan called the Distributed Denial of
Service attack trojan, floods the network and takes it down. The name of this malware comes
from the ancient Greek story in which the city of Troy fell due to a deceptive wooden horse
(Figure 7.5).

Figure 7.5: The city of Troy fell due to a deceptive wooden horse.
The name of the malware comes from this story

7.7 SPAMMING
When you get a message without asking for it, that is an unsolicited message, it is referred
to as spamming. Even sending messages repeatedly is a type of spamming. Each one of you
must have observed a dedicated folder in your e-mail account called the “spam mails”, which
stores mails of the people who send mass mail or send way too many mails. However, e-mail
spamming is not the only for spamming. The other types of spamming are:
•• Instant Message
•• Wiki Spams
•• Social spams etc.
The problems with spamming is that it not only irritates you but you may miss out on
some important message due to spams. Moreover, it slows down your computer.
The word “spamming” is due to one of the sketches in the “Monty Python and the Flying
Circus”. The person who generates a spam is called a spammer. In 90’s and early 2000’s, the

Safely Accessing Website and Communication Data: Computer Threats 67


spammers used to write somethings in the chat rooms. The term was also used for the abusive
gamers in MUDs and finally for the unwanted mails in the mail box.

7.8 EAVESDROPPING
Secretary listening to private communication is called Eavesdropping. As per the technical
literature “It is unauthorized real time interception of private communication.” It is definitely
unethical. In some of the countries, this act is also illegal. The digital communication
including e-mails, if not encrypted can be interpreted by others. However, it does not affect
the communication.
A special type of attack called Network Attack scans the packets going from/coming to a
network and hence listens to the communication. This may lead to the use of this information
for ulterior motives.
It may also be stated here that VoIP systems are more susceptible to eavesdropping. So,
think before using the VoIP systems.

7.9 PHISHING
Have you heard about the fraudulent sites of famous banks? Such sites prompt the users to
enter the account details or credit card details and use this information. Obtaining sensitive
information by posing as a trustworthy entity is called Phishing. The user is, at times,
prompted to enter the information using e-mails or messages.
Phishing can be classified as Spear, Whaling and Cloning (Figure 7.6). The Spear
phishing are aimed at specific individuals or companies. Whaling is a type of Spear Phishing
aimed at high profile targets. The Clone Phishing aims to create almost identical or cloned
messages as sent by a trustworthy entity.

Figure 7.6: Types of Phishing

68 Computer Science with Python–XII: Supplement


7.10 INTRODUCTION TO FIREWALLS
A security system that controls the network traffic, both incoming as well as outgoing, is
called a Firewall. The system is based on a set of predefined safety rules. The work actually
symbolizes a barrier between the internal secure network and the external network.
The name of the software comes from the mechanism which protect a structure or region
using fire. The first generation of firewalls used to check each and every packet coming in the
network. If the packet did not follow the set rules, it was not allowed in the system. The next
generation of firewalls were stateful as they sustained the knowhow of conversation between
the endpoints. The third generation of Firewalls used to work in the application layers, which
is a layer in the TCP/IP model.

7.11 AUTHENTICATION
The meaning of the work authentication is the process of confirming the identity of an entity.
It may be by validating documents or some digital identity proof.
The process of authentication may involve asking some trusted identity to verify the
person. This type may involve peer-based trust system and is used in Pretty Good Privacy
(PGP) etc. Another type of authentication involves checking the attributes of the object.
The authentication may also be done by using external documents like in the court of law
(Figure 7.7).

Figure 7.7: Types of authentication


In the case of digital systems, the administrator provides a username and password to the
user. As a matter of fact, even the user can choose this combination from amongst the set of
available combinations. However, in such cases another person may get the username and
password of the actual user and hence intrude in the system.
The authentication mechanism can also make use of the knowledge, ownership and the
inheritance of the person. This is the reason that the page, which you fill to retrieve your
password may ask you to state your
•• Maiden name
•• First school
•• Pet’s name etc.

Safely Accessing Website and Communication Data: Computer Threats 69


7.12 CONCLUSION
This chapter introduced the most important topics in today’s scenario. In order to be secure,
you need to understand how to deal with security threats and to be able to do so, one must
understand the concept of virus, spyware, adware, trojans, spamming, eavesdropping,
phishing etc. The next chapter discusses ways to deal with these threats.

Points to Remember
•• Viruses may be used to sabotage systems, send messages, deny services and
can even be used for personal amusement.
•• John Von Naumann is called the father of computer virology.
•• A computer virus changes other programs. It inserts code in other computer
programs.
•• The virus, generally causes a system to slow down.
•• A virus has an infection mechanism and trigger.
•• A virus has a predefined infection mechanism which decides how the virus is
going to spread.
•• A virus, generally has a trigger, which executes when a certain condition is
satisfied. The virus is then activated and accomplishes its intended task.
•• The phases of the life cycle of a virus are Dormant, Propagation, Trigger and
execution.
•• No anti-virus is known to remove all the viruses.
•• An Adware is a software that shows online advertisements and hence
generates revenue for the developer of that software.
•• Cookies are small files stored in the computer having data specific to a user
and the website.
•• A trojan is a software that appears as if it is an authentic software.
•• Phishing can be classified as Spear, Whaling and Cloning.

VERY SHORT ANSWER QUESTIONS


1. Who is called the father of virology?
Ans. John Von Neuman.
2. Does a virus slow down a system?
Ans. Yes, generally it does.
3. What are the two most important components of a virus?
Ans. Trigger and infection mechanism.

70 Computer Science with Python–XII: Supplement


4. A virus generally communicates with which software?
Ans. Software which searches file.
5. What is search mechanism with respect to a virus?
Ans. A virus has a predefined infection mechanism which decides how the virus is going to
spread. The search mechanism is generally a part of this infection mechanism.
6. What is a trigger with respect to a virus?
Ans. A virus, generally has a trigger, which executes when a certain condition is satisfied. The
virus is then activated and accomplishes its intended task.
7. What are the four phases in the life cycle of a virus?
Ans. Dormant, propagation, trigger and execution.
8. Can any antivirus remove all the viruses?
Ans. No
9. What is a Spyware?
Ans. A Spyware is a software that extracts information regarding the user, generally without
his consent.
10. Name the types of Spyware (at least four).
Ans. • Adware
• Trojans
• Tracking cookies
• System monitors
11. Name at least one anti-Spyware.
Ans. Gator
12. What does a cookie contain?
Ans. A cookie contains key value pairs like (firstname, harsh), (lastname, bhasin) and so on.

MULTIPLE CHOICE QUESTIONS


1. Which of the following is true?
(a) A virus searches files susceptible to infection.
(b) A virus coordinate with the software which searches such files.
(c) A virus has an infection mechanism
(d) All of the above
2. Which of the following are the phases of life cycle of a virus?
(a) Dormant (b) Propagation
(c) Trigger (d) All of the above
3. Which of the following can remove all the viruses?
(a) Norton (b) McAFee
(c) AVG (d) None of the above
4. What can a Spyware do?
(a) Tracking the user (b) Monitoring the user
(c) Displaying the pop-up advertisements (d) All of the above
5. Which of the following are anti-virus software?
(a) Norton (b) AVG
(c) McAFee (d) All of the above

Safely Accessing Website and Communication Data: Computer Threats 71


6. Which of the following is a Spyware?
(a) Adware (b) Trojans
(c) Tracking cookies (d) System monitors
(e) All of the above
7. What is Gator?
(a) Anti-Spyware (b) Anti-virus
(c) Virus (d) None of the above
8. Which of the following is a software that shows online advertisements and hence
generates revenue for the developer of that software?
(a) Adware (b) Spyware
(c) Anti-virus (d) None of the above
9. The word spamming comes from
(a) Writings of John Von Neuman (b) Monty Python and Flying Circus
(c) Paper of Alan Turing (d) None of the above
10. Which of the following are the types of Spamming?
(a) Instant Message (b) Wiki Spams
(c) Social spams etc. (d) All of the above

THEORY
1. What is a virus? Explain its working mechanism.
2. Explain trigger and infection mechanism with respect to a virus.
3. What the phases in the life cycle of a virus?
4. Name any three anti-virus software.
5. What is a Spyware? What are the problems caused by a spyware installed in your system?
6. What are the various types of Spyware?
7. Name a few prominent anti-Spyware.
8. What is the difference between Spyware and Virus?
9. What is an Adware? What are its types?
10. What is a cookie? How can you disable cookies in Internet Explorer?
11. What is a Trojan? How is it harmful?
12. What is spamming? Name the types of spamming. How is it harmful?
13. Explain the term eavesdropping.
14. Define Phishing. What are the various types of Phishing?
15. What is a Firewall?
16. What are the types of firewalls?
17. Define Authentication.
18. What are the various methods of authentication?
19. How can you make your computer secure?
20. What are the factors that must be kept in mind before deciding a password?

72 Computer Science with Python–XII: Supplement


8 Introduction to
Computer Networks-II

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
•• Understand the difference between a Website and a Web Page
•• Understand the importance of a Web Browser

8.1 WEBSITE
It is a collection of WebPages, having a common domain name. When you load a Website,
the home page loads and you can visit other pages in the site by exploring the links, which
takes you to the required locations. A Website is published in a Web server. The collection
of all the Websites in the world is referred to as the World Wide Web (WWW). These
Websites generally fall in the following categories:
•• News: The Websites providing NEWS e.g. https://edition.cnn.com/ is the official
web site of CNN.
•• Government: The Websites of Government departments e.g. https://delhi.gov.in/ is
the official Website of the Delhi Government.
•• Organizations: The official Web sites of Companies e.g. https://www.charitywater.
org/.
•• Gaming and Entertainment: The Web sites providing online Gaming and
entertainment e.g. https://www.gematsu.com/.
There are many more categories, only some of the most important ones have been stated.
Websites may also be classified as free or paid. The free websites can be seen by everyone,
whereas the paid websites require users to pay the subscription fees. Let us now understand
the difference between a Static and a Dynamic Page.

8.2 WEB SERVERS


A Web Server handles client requests and may contain more than one Website. The client
requests some page from a Server and the Server delivers the page to the client, if possible.

Introduction to Computer Networks-II 73


This communication between the client and the server is carried out using some set of rules
(protocols) like Hyper Text Transfer Protocol (HTTP). A Web Server may be software or
hardware. The following steps take you through the process of fetching a website from a
web server and showing it on a web browser.
•• The client enters the name of a Website in the Browser.
•• The Browser, here, acts as a user agent and interacts with the server.
•• The Server delivers the request if possible.
•• The Browser shows the content considering the environment.
The next section talks about a Web Browser.

8.3 WEB BROWSER


A Web Browser helps us to access information from a Web Site on WWW. The user enters
the name of the site in the Browser. The Browser, in turn, asks for the page from the Server.
The Server delivers the page, which is then shown by the Browser.
The word Browser originates from browsing, which refers to hovering without a
meticulous intention. Some of the examples of Web Browsers are:
•• Google Chrome
•• Mozilla Firefox
•• Safari
•• Edge
•• Internet Explorer
•• iCab etc.
Google chrome is currently the most used browser in the world. In Windows, a Browser
called Microsoft Edge is pre-installed on all new Windows. It is a replacement for Internet
Explorer and is faster and better as compared to Internet Explorer. Let us now have a look
at how to change settings in the two most common browsers.

8.3.1 Settings: Edge


The settings of a browser can be changed as per the requirement. The following steps take
you through the process of changing the settings of Microsoft Edge.
•• Open Add or remove Programs (Figure 8.1).
•• Go to Apps & features (Figure 8.2).
•• Move to Microsoft Edge and then to Advanced Options (Figure 8.3).
•• Change the settings as per the requirements (Figure 8.4).

74 Computer Science with Python–XII: Supplement


Figure 8.1: Open add or remove programs

Figure 8.2: Open add or remove programs and go to apps & features

Introduction to Computer Networks-II 75


Figure 8.3: Click on advanced options in Microsoft Edge

Figure 8.4: This interface lets you set the properties of Microsoft Edge.

76 Computer Science with Python–XII: Supplement


You can turn on/off the Camera, the Microphone, Location, and Background Apps using
this interface. You can also repair your Edge if you are facing problems with your browser.

8.3.2 Settings in Google Chrome


The following steps will teach you how to change the setting of a Chrome Browser.
•• Click on the ellipses on the top right side of the Browser.
•• Go to Settings (Figure 8.5).
•• You will find the following sections in the settings.

Figure 8.5: Changing settings in Google Chrome

Google and You: This lets you sync and manage your Google accounts. You can also
change your name and picture from this. This section also provides an interface to import
bookmarks and settings from other browsers.
Autofill: You can change the settings pertaining to the filled data. The stored passwords,
payment methods, and addresses can be managed from this section.
Privacy and Security: You can clear your browsing data and change your site settings
from this section.
Appearances: This section helps you to manage themes, font size, page zoom, etc.
Search engine: This lets you select your search engine used in the address bar of the
Browser.
Default Browser: You can select your default browser from here.

Introduction to Computer Networks-II 77


On setup: You can choose whether to open a new tab or continue from where you left or
open a specific page using this.
The advanced options let you change the settings pertaining to the following:
•• Downloads
•• Printing
•• Accessibility
•• System
•• Reset and clean up

78 Computer Science with Python–XII: Supplement


UNIT 3
Database Management

Introduction to Computer Networks-II 79


ISBN: 978-81-943696-6-0 Publication Year: 2020 Edition: 1st
Pages: 376 MRP: 475.00 Paperback

Click Here to Buy Main Book Online


Computer Science with Python Programming is a textbook designed for the students of Class XII, CBSE. It covers complete course of
Computer Science. The book has been written in easy to understand language and contains ample examples. However, every attempt has been
made to keep the text as precise as possible.
The code has been tested in Python 3.x on a machine with Windows 10.
Each chapter of the book includes a variety of end-chapter exercises in the form of MCQs with answers, review questions, and programming
exercises to help readers test their knowledge. It may be stated here that the topics in the book have been written considering the fact that some
of the readers may opt Computer Science as their career.
Key Features:
• The book has sections dedicated to Computer System and Organization to help the students to understand the basics.
• Offers in-depth treatment of topics such as Pyplot and functions.
• The book introduces Django.
• Provides points to remember and a Glossary with definitions of the key terms at the end of each chapter which will help readers to
quickly recollect the important concepts.
• Questions, given at the end of each chapter and the Appendices would help students during viva and examinations.
Harsh Bhasin has done his B Tech. in Computer Science and M Tech. in Computers and is currently pursuing PhD. He qualified UGC NET in
2012 and received the Visvesvaraya Fellowship from DIETY in 2016. He was awarded the Young Researcher’s Award by ErNet in 2012. Mr.
Bhasin has authored a few papers, including those published in journals like Soft Computing. He has also authored “Programming in C#”
(2014), “Algorithm Analysis and Design” (2015) and “Theory of Computation”. He has been actively involved in research both as an author
and reviewer for ACM, Pearson, Oxford University Press, Springer etc. Mr. Bhasin was the editor in chief of the special issue on
“Applicability of Soft Computing Techniques in NP Problems,” SciEp, USA.
Professionally, Mr. Bhasin is a programmer and has been involved in the development of many Enterprise Resource Planning Systems while
being the proprietor of a firm based in Faridabad, Haryana, India. He has a vast industrial experience. He was an Assistant Professor in
Department of Computer Science, FMIT, Jamia Hamdard. He has also taught as visiting faculty in many colleges including Delhi
Technological University.
His areas of interest include Genetic Algorithms, Theory of Computation, C#, Python, Algorithms, Cellular Automata and Machine
Learning.
His personal interests include Hindi poetry and Hindustani Classical Music. Mr. Bhasin is also a blogger. You can reach him at his
Facebook page DTU Computation or via email at i_harsh_bhasin@yahoo.com.

LONDON • NEW DELHI • NAIROBI


Bangalore • Chennai • Cochin • Guwahati • Hyderabad • Kolkata • Lucknow • Mumbai
NEW AGE
Visit us at www.newagepublishers.com
9 Structured Query
Language II

LEARNING OBJECTIVES
After reading this chapter, the reader will be able to
• Understand the SELECT statement
• Understand the UPDATE statement
• Understand Cartesian Product and JOIN

9.1 INTRODUCTION
The last chapter introduced SQL and this chapter takes the discussion forward. This chapter
introduces the SELECT statements, the concept of indexes and joins. The chapter has been
organized as follows.
Section 9.2 explains the statements for viewing table in a database and their description.
The third section introduces the SELECT statement. The next section discusses the UPDATE
statement. Section 9.5 introduces the concept of Cartesian Product, section 9.6 introduces
JOIN and the discussion on JOIN continues in the next three sections. The last section
concludes.

9.2 VIEWING ALL TABLES


In order to go into a database, we use the USE<database> command. To show all the tables
in the database, the Show Tables command can be used. The syntax of the command is as
follows.

Syntax
SHOW TABLES;
Now, to see the structure of a table including
•• the type of the fields
•• whether a particular field is NULL or not
•• the key and
•• the default value of a field
•• the DESC command is issued. The Syntax of the command is as follows.

80 Computer Science with Python–XII: Supplement


Syntax
DESC <table name>
For example, to describe the table named emp, the following command can be issued.
DESC emp;
Now that we have learnt the creation of a table, insertion of records and viewing its
description in SQL, let us now move to the SELECT statements.

9.3 SELECT STATEMENTS


In order to retrieve, manipulate and add data in a Relation Database Management System, we
need queries. The SELECT statement helps us to retrieve and show desired data from table(s)
of a database. The following discussion concentrates on the SELECT query.

9.3.1 Prerequisite
As stated in the previous chapter, we need to open database and, if required, log in to the
database, to be able to see and manipulate the data. In order to do so, the following command
needs to be issued.
Use <database name>
For example, to use the employee database the following command can be issued:
mysql> USE employee;
This takes you the employee database. Now, one can issue the required SQL command to
accomplish the desired task.

9.3.2 The Statement


The SELECT statement helps us to select required subset of data from a given database. The
syntax of the command is as follows.

Syntax
SELECT <Column name1>, <Column name2>…
FROM <table name>
WHERE <condition>;

9.3.4 Selecting all Columns and all Rows


In order to select all the rows and all the columns of a given table, the following SQL
command needs to be issued.

Syntax
SELECT * FROM <tablename>
For example, in order to select all columns and records from the employee table, the
following commands need to be issued.
SELECT * FROM employee;

Structured Query Language II 81


9.3.5 Selecting some Columns and all Rows
In order to select some columns and all rows from a given table, we can issue the following
command.

Syntax
SELECT <Column name1>, <Column name2>…
FROM <table name>
For example, to select FirstName and LastName from the employee table, the following
commands needs to be issued.
SELECT FirstName, LastName
From employee;

9.3.6 Distinct Records


Suppose one issues a query to see the First name all the employees. Since many employees
can have the same First name, many rows in the result will have same values. However, if it is
desired to see only the distinct values, then the DISTINCT command can be used.
In order to select Distinct records from the database the DISTINCT keyword can be used.
The syntax of the corresponding command is as follows.

Syntax
SELECT DISTINCT <Column name1>…
FROM <table name>
For example, to select distinct First Name from the employee table, following command
can be issued.
SELECT DISTINCT FirstName from employee;

9.3.7 ALL
The ALL keyword works in the exactly opposite manner vis-à-vis the DISTINCT keyword. It
shown all the records of a given field. For example, in order to display all FirstName from the
employee table, the following command can be issued.
SELECT ALL FirstName FROM employee;

9.3.8 Expressions
If one wants to perform calculations on a field and show the required result, the columns can
be subjected to arithematic manipulations and displayed.
For example, a table called GeneticAlgo has a field called cor which is between 0 and 9.
To display the crossover percentage, the following command can be issued.
SELECT cor*100
FROM GeneticAlgo;
One can use the following operators while in the commands containing expressions.
•• + •• – •• * •• / •• %

82 Computer Science with Python–XII: Supplement


9.3.9 Aliases
One can also give another name to a column by using the AS keyword. For example, if the
above example if the resultant field is to be called percentage then, the following command
can be issued
SELECT cor* 100 As ‘percentage’
FROM GeneticAlgo

9.3.10 Where
If we want to view the records which satisfy the given condition, the WHERE clause can be
used with the select statement. The Syntax of WHERE is as follows.

Syntax
SELECT <column_name1, column_name2 ...>
FROM <table_name>
WHERE <condition>;
The following points are noteworthy as regards the WHERE clause.
1. The condition of the WHERE clause can have the following comparison operators.
•• =
•• >
•• <
•• >=
•• <=
•• <>
2. Apart from the arithmetic operators, the WHERE BETWEEN clause is used to
specify the range of values.
Syntax
SELECT <column_name1, column_name2, ...>
FROM <table_name>
WHERE <condition> BETWEEN <value1> AND <value2>;
3. WHERE clause can be combined with the following operators to filter the records:
3.1 The AND operator
The AND operator displays a record if all the given conditions are TRUE.
Syntax
SELECT <column_name1, column_name2, ...
FROM <table_name>
WHERE <condition1> AND <condition2> AND <condition3> ...;
3.2 The OR operator
The OR operator displays a record if any of the given conditions is TRUE.

Structured Query Language II 83


Syntax
SELECT <column_name1, column_name2, ...>
FROM <table_name>
WHERE <condition1> OR <condition2> OR <condition3> ...;
3.3 NOT operator
The NOT operator displays a record if the given condition is NOT TRUE.
Syntax
SELECT <column_name1, column_name2, ...>
FROM <table_name>
WHERE NOT <condition>;
4. If a value is to be selected from a set of values the in operator can be used as shown
in Illustration X.4.
5. The not in operator works in exactly opposite manner vis-à-vis the in operator
(Illustration X.5).
6. In order to match pattern % and _ are used. The % is used to matching any number of
characters and _ for exactly one character. Illustrations X.6 and X.7 exemplify their
usage.
The following illustrations exemplify the statements containing WHERE. In order to
see the output you need to have some tables and records. Though, there are many
open source databases available which you can use to run queries and see results.
Consider using the customer table at the official MySQL site https://dev.mysql.
com/doc/sakila/en/sakila-structure-tables-customer.html. The table has the following
structure.
•• customer_id: Primary key
•• store_id: The ID of the store at which the customer visits frequently.
•• first_name: The first name of the customer.
•• last_name: The last name of the customer.
•• email: The e-mail ID of the customer.
•• address_id: The address has been stored in another table and this fields relates the
customer table with the address table.
•• active: The field depicts if the customer is active.
•• create_date: date of creation.
•• last_update: The time of most recent update.
The following illustrations are based on the exercises which you must do to run the
queries that follow.

EXERCISE 1:
Create a table called customer having the following fields:
•• CustomerID

84 Computer Science with Python–XII: Supplement


•• CustomerName
•• ContactName
•• Address
•• City
•• PostalCode
•• Country
You can decide the data type, the default values and the issues regarding NULL. Now,
insert around 50 records in the table. Note that the “city” of all the customers should not be
same. Write queries to carry out the stated tasks.

ILLUSTRATION 9.1
Select all the details of the Customers where city =‘Berlin’.

SOLUTION
SELECT * FROM [Customers]
WHERE city = 'Berlin';

ILLUSTRATION 9.2
Select all the details of the Customers where city =‘Berlin’ or country = ‘UK’

SOLUTION
SELECT * FROM [Customers]
WHERE city = 'Berlin' or Country = ‘UK’;

ILLUSTRATION 9.3
Select all the details of the Customers where city =‘Berlin’ and country = ‘UK’

SOLUTION
SELECT * FROM [Customers]
WHERE city = 'Berlin' and Country = ‘UK’;
Hint: This query will not return any row.

ILLUSTRATION 9.4
Select all the details of the Customers where city is either Berlin or ‘London’ or ‘Covas’.

SOLUTION
SELECT * FROM [Customers]
WHERE city in ('Berlin', 'London', 'Covas') ;

Structured Query Language II 85


ILLUSTRATION 9.5
Select all the details of the Customers where city is neither Berlin nor ‘London’ or ‘Covas’.

SOLUTION
SELECT * FROM [Customers]
WHERE city not in ('Berlin', 'London', 'Covas') ;

ILLUSTRATION 9.6
Select all the details of the Customers whose name start with ‘Maria’.

SOLUTION
SELECT * FROM [Customers]
WHERE ContactName like 'Maria%' ;

ILLUSTRATION 9.7
Select all the details of the Customers whose country name start with ‘GER’ followed by four
characters.

SOLUTION
SELECT * FROM [Customers]
WHERE Country like 'Ger____' ;

EXERCISE 9.2
Create a table called OrderDetail having the following fields
•• OrderDetailID
•• OrderID
•• ProductID and
•• Quantity
Insert 50 records in the table. Now, write queries to carry out the following tasks.

ILLUSTRATION 9.8
Select the records where the Quantity is greater than 10.

SOLUTION
SELECT * FROM [OrderDetails]
WHERE Quantity >10;

ILLUSTRATION 9.9
Select the records where the Quantity is not equal to 10.

SOLUTION
SELECT * FROM [OrderDetails]
WHERE Quantity <>10;

86 Computer Science with Python–XII: Supplement


ILLUSTRATION 9.10
Select the records where the Quantity is between 10 and 20.

SOLUTION
SELECT * FROM [OrderDetails]
WHERE Quantity BETWEEN 10 and 20;
Kindly note that in the solved problem section, a sample table is given and the outputs of
the SQL statements have been shown.

9.4 UPDATING TABLES


Once you have inserted data in a table and you want to change some part of it or all of it,
the UPDATE command can be used. The UPDATE command requires name of the table
<table name>, the fields to be updated and the WHERE clause, if only those records are to be
updated which satisfy the given condition. The syntax of the command is as follows.

Syntax
UPDATE <table name>
SET <<column name>=<value>
WHERE
<condition>
For example to set the salary of all the employees to 20000, the following SQL statement
can be issued.
UPDATE EMPLOYEE
SET
SALARY =10000;
The UPDATE statement can also have a WHERE clause. For example to set the salary of
all the employees to 20000, of all the employees whose name begin with “H”, the following
SQL statement can be issued.
UPDATE EMPLOYEE
SET
SALARY =10000
WHERE FirstName=“H%”;
The following discussion would help us to retrieve data from more than one table.

9.5 CARTESIAN PRODUCT


The Cartesian Product of two sets A and B can be defined as follows.
A × B = {(x, y)| x ∈ A and y ∈ B}.
If the Cartesian Product of two tables is taken, all possible combinations of values would
be generated. In order to understand this, consider the following example, two Tables, Table

Structured Query Language II 87


9.1 and Table 9.2, have fields F1 and F2 respectively. The first has three records and the
second has two records respectively.
Table 9.1
F1
A
B
C

Table 9.2
F2

If the following query is issued all 6 combinations of values would be generated.


SELECT F1, F2 from
Table 9.1, Table 9.2;
F1 F2
A D
A E
B D
B E
C D
C E

Consider another example; the two Tables, Table 9.3 and Table 9.4 have four and three
records respectively. Table 9.3 have fields Field1, Field2 and Fields3 and Table 4 have fields
Field4 and Field5.
Table 9.3
Field1 Field2 Field3
F11 F21 F31
F12 F22 F32
F13 F23 F33
F14 F24 F34

88 Computer Science with Python–XII: Supplement


Table 9.4
Field4 Field5
F31 F41
F32 F42
F33 F43

If the following query is issued all 12 combinations of values would be generated.


SELECT Field1, Field2, Field3, Field4, Field5
From
Table 9.3, Table 9.4;

Field1 Field2 Field3 Field4 Field5


F11 F21 F31 F31 F41
F11 F21 F31 F32 F42
F11 F21 F31 F33 F43
F12 F22 F32 F31 F41
F12 F22 F32 F32 F42
F12 F22 F32 F33 F43
F13 F23 F33 F31 F41
F13 F23 F33 F32 F42
F13 F23 F33 F33 F43
F14 F24 F34 F31 F41
F14 F24 F34 F32 F42
F14 F24 F34 F33 F43

9.6 JOIN
Note the repetition in the above result. The above problem can be handled using the join. A
join on two tables is written as
<table1>.<column1> = <table2>.<column1>
Where, Table 9.1 is the table from where data is to be fetched and column1 is the field
common to both the tables. In order to understand the premise, consider the following tables

Structured Query Language II 89


Table 9.5
F1 F2 F3
X A L
Y B M
Z C N

Table 9.6
F2 F4
A P
B Q
C R

If we want to join the two tables using the field F2, the following command can be
issued.
SELECT F1, F3, F4
FROM Table 9.5, Table 9.6
WHERE
Table 15.F2 = Table 9.6. F2
The output would be as follows.
F1 F3 F4
X L P
Y M Q
Z N R

Consider another example of JOIN. Suppose you have two tables


Student (StudID, FName, LName, Email, Phone, Add) and
Fees (FeesID, StudID, Amount, Date).
It is desired to fetch the Fname and LName of the students whose Fees is more than
10,000. In order to accomplish this task, the following SQL command can be issued.
SELECT FName, LName from Students.
Students, Fees
Where
Students.StudID = Fees.FeedID
AND (Fees.Amount>10000)

90 Computer Science with Python–XII: Supplement


ILLUSTRATION 9.11
A database has a few tables, two of which are
Products (ProductID, ProductName, SupplierID, CategoryID, Unit, Price) and
And OrderDetails(OrderDetailID, OrderID, ProductID, Quantity)
It is desired to JOIN the two tables using the ProductID. Write the required command.

SOLUTION
SELECT * FROM Products,OrderDetails
WHERE
Products.ProductID = OrderDetails.ProductID;

9.7 TYPES OF JOINS


Joins can be classified as equijoins and non-equijoins. The following discussion gives a very
brief description of the first.

Equijoins
Equijoins are also called simple joins or inner joins. In the above example, to determine
the first name of the students having fees greater than 10,000, you compare the value in the
StudID column in the Students table with the StudID values in the Fees table.
The relationship between the Students and Fees table is an equijoin. This means that
the values in the DEPTNO column on both tables must be equal. Generally, this type of join
involves primary and foreign key complements.
The other types of Joins are non-equijoins. In the next year, different types of joins would
be taught.

9.8 INDEX
The indexes on tables can be created using the CREATE INDEX command. The indexes
allow duplicate values and are used to efficiently fetch data from a given database. One may
not see the indexes but they do speed up the searches. However, a table which has index takes
more time to update as compared to one that does not have index.
The following SQL creates an index named index1 on the LastName column in the
Students table.
CREATE INDEX index1
ON Students (LName);
An index can also be created on a combination of columns by listing the column names
within the parentheses, separated by commas.
CREATE INDEX index2
ON students (LName, FName);

Structured Query Language II 91


9.9 DROP INDEX
In order to drop an index in a table, the DROP INDEX command is used. The syntax of the
command is as follows.
DROP INDEX <index_name> ON <table_name>;
Note that the above syntax varies from database to database.

9.10 CONCLUSION
This chapter introduced the SELECT statement. This statement is important as it helps
retrieve data. The following examples would help to understand the concept, in a better
manner.

SOLVED EXAMPLES
Consider Table 1 and write the SQL statements and the expected output for questions stated in
Illustrations 9.12 to 9.22.
Table 1: Employee
Employeeid Firstname Lastname Salary Dateofbirth City
Emp001 Rajesh Arora 10,00,000 30-08-1982 Faridabad
Emp002 Pratiksha Malya 12,00,000 24-11-1978 Delhi
Emp003 Jitendra Pathak 11,00,000 13-09-1980 Delhi
Emp004 Ananya Rajput 13,50,000 05-05-1976 Delhi
Emp005 Joushua Masih 10,70,000 31-11-1984 Noida
Emp006 Abhiraj Jain 10,70,000 22-01-1985 Gurugram

ILLUSTRATION 9.12
Select FIRSTNAME and LASTNAME from EMPLOYEE

SOLUTION
SELECT FIRSTNAME, LASTNAME
FROM EMPLOYEE;
Output:
FIRST NAME LAST NAME
RAJESH ARORA
PRATIKSHA MALYA
JITENDRA PATHAK
ANANYA RAJPUT
JOUSHUA MASIH
ABHIRAJ JAIN

92 Computer Science with Python–XII: Supplement


ILLUSTRATION 9.13
Select all rows and columns from the Employee table.

SOLUTION
SELECT * FROM EMPLOYEE;

Output:
Employee id First name Last name Salary Date of birth City
Emp001 Rajesh Arora 10,00,000 30-08-1982 Faridabad
Emp002 Pratiksha Malya 12,00,000 24-11-1978 Delhi
Emp003 Jitendra Pathak 11,00,000 13-09-1980 Delhi
Emp004 Ananya Rajput 13,50,000 05-05-1976 Delhi
Emp005 Joushua Masih 10,70,000 31-11-1984 Noida
Emp006 Abhiraj Jain 10,70,000 22-01-1985 Gurugram

ILLUSTRATION 9.14
Display distinct values from the salary field from the above table.

SOLUTION
SELECT DISTINCT SALARY
FROM EMPLOYEE;
Output:
SALARY (P.A)
10,00,000
12,00,000
11,00,000
13,50,000
10,70,000

ILLUSTRATION 9.15
Count the number of salary amounts in the above table.

SOLUTION
SELECT COUNT (DISTINCT SALARY)
FROM EMPLOYEE;
Output:
5

Structured Query Language II 93


ILLUSTRATION 9.16
Select the first name and last name of all the employees whose salary is greater than
11,00,000.

SOLUTION
SELECT FIRSTNAME, LASTNAME
FROM EMPLOYEE
WHERE SALARY > 11,000,00;
Output:
FIRST NAME LAST NAME
PRATIKSHA MALYA
ANANYA RAJPUT

ILLUSTRATION 9.17
Select the EmployeeID of the employees whose salary is between 10,00,0000 and 11,00,000.

SOLUTION
SELECT EMPLOYEE ID
FROM EMPLOYEE
WHERE SALARY BETWEEN 10,00,000 AND 11,00,000;
Output:
EMPLOYEE ID
EMP005
EMP006

ILLUSTRATION 9.18
Select the details of the employees having salary = 10,70,000 and city = ‘Noida’.

SOLUTION
SELECT *
FROM EMPLOYEE
WHERE SALARY=10,70,000 AND CITY=NOIDA ;
Output:
EMPLOYEEID FIRSTNAME LASTNAME SALARY DATEOFBIRTH CITY
EMP005 JOUSHUA MASIH 10,70,000 31-11-1984 NOIDA

ILLUSTRATION 9.19
Select the details of the employees having salary = 10,00,000 or city = ‘DELHI’.

94 Computer Science with Python–XII: Supplement


SOLUTION
SELECT *
FROM EMPLOYEE
WHERE SALARY = 10,00,000 OR CITY=’DELHI’;
Output:
Employeeid Firstname Lastname Salary Date of birth City
Emp001 Rajesh Arora 10,00,000 30-08-1982 Faridabad
Emp002 Pratiksha Malya 12,00,000 24-11-1978 Delhi
Emp003 Jitendra Pathak 11,00,000 13-09-1980 Delhi
Emp004 Ananya Rajput 13,50,000 05-05-1976 Delhi

ILLUSTRATION 9.20
Select the details of the employees having city not = ‘DELHI’.

SOLUTION
SELECT *
FROM EMPLOYEE
WHERE NOT CITY=‘DELHI’;
Output:
Employee Id First Name Last Name Salary (P.a) Date of birth City
Emp001 Rajesh Arora 10,00,000 30-08-1982 Faridabad
Emp005 Joushua Masih 10,70,000 31-11-1984 Noida
Emp006 Abhiraj Jain 10,70,000 22-01-1985 Gurugram

ILLUSTRATION 9.21
Select the details of the employees having salary=11,00,000 or 12,00,000 and city = ‘DELHI’.

SOLUTION
SELECT * FROM EMPLOYEE
WHERE CITY=’DELHI’ AND (SALARY=12,00,000 OR SALARY=11,00,000);
Output:
Employeeid Firstname Lastname Salary Date of birth City
Emp002 Pratiksha Malya 12,00,000 24-11-1978 Delhi
Emp003 Jitendra Pathak 11,00,000 13-09-1980 Delhi

Structured Query Language II 95


ILLUSTRATION 9.22
Select the details of the employees and show the results in order of Salary.

SOLUTION
SELECT *
FROM EMPLOYEE
ORDER BY SALARY;

Output:

Employee id First name Last name Salary Date of Birth City

Emp001 Rajesh Arora 10,00,000 30-08-1982 Faridabad

Emp005 Joushua Masih 10,70,000 31-11-1984 Noida

Emp006 Abhiraj Jain 10,70,000 22-01-1985 Gurugram

Emp003 Jitendra Pathak 11,00,000 13-09-1980 Delhi

Emp002 Pratiksha Malya 12,00,000 24-11-1978 Delhi

Emp004 Ananya Rajput 13,50,000 05-05-1976 Delhi

ILLUSTRATION 9.23
Select the details of the employees and show the results in the descending order of Salary.

SOLUTION
SELECT *
FROM EMPLOYEE
ORDER BY SALARY DESC;

Employeeid First name Lastname Salary Date of birth City

Emp004 Ananya Rajput 13,50,000 05-05-1976 Delhi

Emp002 Pratiksha Malya 12,00,000 24-11-1978 Delhi

Emp003 Jitendra Pathak 11,00,000 13-09-1980 Delhi

Emp006 Abhiraj Jain 10,70,000 22-01-1985 Gurugram

Emp005 Joushua Masih 10,70,000 31-11-1984 Noida

Emp001 Rajesh Arora 10,00,000 30-08-1982 Faridabad

96 Computer Science with Python–XII: Supplement


Points to Remember
1. Selecting some columns from a table:
Syntax:
SELECT column_name, column_name, ...
FROM table_name;
2. Selecting all the columns from the table:
Syntax:
SELECT * FROM table_name;
3. SELECT DISTINCT statement:
Syntax:
SELECT DISTINCT column_name, column_name, ...
FROM table_name;
4. SELECT DISTINCT COUNT:
Syntax:
SELECT COUNT (DISTINCT column_name)
FROM table_name;
5. WHERE
Syntax:
SELECT column_name, column_name, ...
FROM table_name
WHERE condition
6. ORDER BY
OREDR BY clause is used to sort the records in ascending or descending
order. The default sorting order is ascending order.
Syntax:
SELECT column_name, column_name, ...
FROM table_name
ORDERBY column_name, column_name, ... ASC/DESC;

MULTIPLE CHOICE QUESTIONS


1. Which one of the following is used to show all the tables of a given database?
(a) Show tables (b) Desc
(c) Describe (d) None of the above
2. Which one of the following is used to describe the fields of a given table?
(a) Show tables (b) Desc
(c) Describe (d) None of the above

Structured Query Language II 97


3. Which of the following is needed to be able to use the database?
(a) Use <Database Name> (b) Login <Database Name>
(c) Show <Database Name> (d) None of the above
4. Which statement helps to select required subset of data from a given database?
(a) Select (b) Project
(c) Neglect (d) None of the above
5. To select all rows and columns from table called GA, which of the following commands
should be issued?
(a) SELECT * FROM GA (b) SELECT ALL FROM GA
(c) SELECT Distinct FROM GA (d) None of the above
6. To select cor and mr fields from table called GA, which of the following commands
should be issued?
(a) SELECT cor, mr FROM GA (b) SELECT cor and mr FROM GA
(c) SELECT cor or mr FROM GA (d) None of the above
7. To select all the rows from the table called GA, where mr>0.5, which of the following
commands should be issued?
(a) SELECT * FROM GA WHERE mr>0.5
(b) SELECT cor, mr FROM GA WHERE mr>0.5
(c) SELECT cor or mr FROM GA WHERE mr>0.5
(d) None of the above
8. To select all the rows from the table called GA, where cor is in (0.2, 0.4, 0.8, which of
the following commands should be issued?
(a) SELECT * FROM GA WHERE cor in (0.2, 0.4, 0.8)
(b) SELECT cor, mr FROM GA WHERE cor>0.5
(c) SELECT cor or mr FROM GA WHERE cor <>0.2
(d) None of the above
9. Which of the following is used to change the values in a table?
(a) UPDATE (b) ALTER
(c) SELECT (d) None
10. Which of the following is used to change the data type of a field?
(a) UPDATE (b) ALTER
(c) SELECT (d) None

THEORY
1. Define Cartesian product. Exemplify the concept by taking two tables having two and
three fields respectively. Each table should have three records.
2. What are various types of Joins?
3. What is an equijoin?
4. What is an Index?
5. What are the advantages and disadvantages of having an index on a given table?

98 Computer Science with Python–XII: Supplement


6. Write the syntax of dropping an index.
7. What is the difference between Cartesian product and join?
8. Explain the WHERE clause. Give example to explain its usage.
9. Explain the SELECT statement. Explain the use of in operator in the select statement.
10. Explain the use of the UPDATE statement.

PRACTICAL
1. For the table given in Solved problems, write the SQL queries to accomplish the
following tasks.
2. Show the details of all the employees whose last name is ‘Arora’.
3. Show the details of all the employees who live in ‘NOIDA’.
4. Show the details of all the employees who have salary 10,00,000.
5. Show the details of all the employees who have salary greater than 10,00,000.
6. Show the details of all the employees who have salary less than 10,00,000.
7. Show the details of all the employees who have salary between 10,00,000 and 15,00,000.
8. Show the details of all the employees who have salary not between 10,00,000 and
15,00,000.
9. Show the details of all the employees who were born after 1-8-1982.
10. Show the details of all the employees who were born before 1-8-1982.
11. Show the details of all the employees who were born on 1-8-1982.
Consider the following tables.

Field1 Field2 Field3


F11 F21 F31
F12 F22 F32

Field4 Field5
F41 F51
F42 F52
F43 F53
F44 F54
F45 F55

Find the Cartesian product.


12. Find the join of the above two tables.
13. Two tables Table1 and Table2 have the following fields
Table1: A, B, C, D
Table2: D, A, E

Structured Query Language II 99


14. Write a command to see the values of D for which B is ‘abc’.
Suppose you have two tables
Student (StudID, FName, LName, Email, Phone, Add) and
Fees (FeesID, StudID, Amount, Date).
It is desired to fetch the Fname and LName of the students whose Fees is between 1,000
and 10,000.
15. A database has a few tables, two of which are
Products (ProductID, ProductName, SupplierID, CategoryID, Unit, Price) and
And OrderDetails (OrderDetailID, OrderID, ProductID, Quantity)
It is desired to join the two tables using the ProductID and select the OrderID for which
Price is less than 1,000. Write the required command.

100 Computer Science with Python–XII: Supplement


ISBN: 978-81-943696-6-0 Publication Year: 2020 Edition: 1st
Pages: 376 MRP: 475.00 Paperback

Click Here to Buy Main Book Online


Computer Science with Python Programming is a textbook designed for the students of Class XII, CBSE. It covers complete course of
Computer Science. The book has been written in easy to understand language and contains ample examples. However, every attempt has been
made to keep the text as precise as possible.
The code has been tested in Python 3.x on a machine with Windows 10.
Each chapter of the book includes a variety of end-chapter exercises in the form of MCQs with answers, review questions, and programming
exercises to help readers test their knowledge. It may be stated here that the topics in the book have been written considering the fact that some
of the readers may opt Computer Science as their career.
Key Features:
• The book has sections dedicated to Computer System and Organization to help the students to understand the basics.
• Offers in-depth treatment of topics such as Pyplot and functions.
• The book introduces Django.
• Provides points to remember and a Glossary with definitions of the key terms at the end of each chapter which will help readers to
quickly recollect the important concepts.
• Questions, given at the end of each chapter and the Appendices would help students during viva and examinations.
Harsh Bhasin has done his B Tech. in Computer Science and M Tech. in Computers and is currently pursuing PhD. He qualified UGC NET in
2012 and received the Visvesvaraya Fellowship from DIETY in 2016. He was awarded the Young Researcher’s Award by ErNet in 2012. Mr.
Bhasin has authored a few papers, including those published in journals like Soft Computing. He has also authored “Programming in C#”
(2014), “Algorithm Analysis and Design” (2015) and “Theory of Computation”. He has been actively involved in research both as an author
and reviewer for ACM, Pearson, Oxford University Press, Springer etc. Mr. Bhasin was the editor in chief of the special issue on
“Applicability of Soft Computing Techniques in NP Problems,” SciEp, USA.
Professionally, Mr. Bhasin is a programmer and has been involved in the development of many Enterprise Resource Planning Systems while
being the proprietor of a firm based in Faridabad, Haryana, India. He has a vast industrial experience. He was an Assistant Professor in
Department of Computer Science, FMIT, Jamia Hamdard. He has also taught as visiting faculty in many colleges including Delhi
Technological University.
His areas of interest include Genetic Algorithms, Theory of Computation, C#, Python, Algorithms, Cellular Automata and Machine
Learning.
His personal interests include Hindi poetry and Hindustani Classical Music. Mr. Bhasin is also a blogger. You can reach him at his
Facebook page DTU Computation or via email at i_harsh_bhasin@yahoo.com.

LONDON • NEW DELHI • NAIROBI


Bangalore • Chennai • Cochin • Guwahati • Hyderabad • Kolkata • Lucknow • Mumbai
NEW AGE
Visit us at www.newagepublishers.com

You might also like