Professional Documents
Culture Documents
PYTHON
SUPPLEMENT
For the new topics introduced by CBSE in
the latest Syllabus issued in July, 2020
CLASS XII
IN INDIA
Visit us at www.newagegolden.com
Dear Students
Use this free Supplement
along with the
Main 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
•• 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.)
•• Web Scripting Client side (VB Script, Java Script, PHP) and Server side (ASP,
JSP, PHP), Web 2.0 (for social networking)
CREATE TABLE, DROP TABLE, ALTER TABLE, UPDATE ....SET, INSERT, DELETE
(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
(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.
(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
(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
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
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
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.
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.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.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.
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.
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.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.
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.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.”
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
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
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
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.
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
Code:
import csv
with open(‘results.csv’, newline=’’) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
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’]
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
————————————————————————————————————
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.
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’]
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.
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
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.
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)
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.
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 :’))
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.
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
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.
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
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)
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.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.
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.
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.
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()
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])
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)
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.
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
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.
Strings 61
ISBN: 978-81-943696-6-0 Publication Year: 2020 Edition: 1st
Pages: 376 MRP: 475.00 Paperback
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.
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
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).
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.
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
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.
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).
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.
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?
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.
Figure 8.2: Open add or remove programs and go to apps & features
Figure 8.4: This interface lets you set the properties of Microsoft Edge.
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.
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.
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.
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.
Syntax
SELECT <Column name1>, <Column name2>…
FROM <table name>
WHERE <condition>;
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;
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;
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.
•• + •• – •• * •• / •• %
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.
EXERCISE 1:
Create a table called customer having the following fields:
•• CustomerID
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') ;
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;
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.
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.
Table 9.2
F2
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
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
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
SOLUTION
SELECT * FROM Products,OrderDetails
WHERE
Products.ProductID = OrderDetails.ProductID;
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);
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
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
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’.
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
SOLUTION
SELECT *
FROM EMPLOYEE
ORDER BY SALARY;
Output:
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;
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?
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.
Field4 Field5
F41 F51
F42 F52
F43 F53
F44 F54
F45 F55