Pythonsupplement Merged Compressed
Pythonsupplement Merged Compressed
Pythonsupplement Merged Compressed
2024-25
250.00
Publication Team
Head, Publication : Anup Kumar Rajput
Division
2024-25
Computer science as a discipline has evolved over the years and has
emerged as a driving force of our socio-economic activities. It has made
continuous inroads into diverse areas — be it business, commerce, science,
technology, sports, health, transportation or education. With the advent
of computer and communication technologies, there has been a paradigm
shift in teaching-learning at the school level. The role and relevance of this
discipline is in focus because the expectations from the school pass-outs
have grown to be able to meet the challenges of the 21st century. Today, we
are living in an interconnected world where computer-based applications
influence the way we learn, communicate, commute or even socialise!
There is a demand for software engineers in various fields like
manufacturing, services, etc. Today, there are a large number of successful
startups delivering different services through software applications. All
these have resulted in generating interest for this subject among students
as well as parents.
Development of logical thinking, reasoning and problem-solving skills
are fundamental building blocks for knowledge acquisition at the higher
level. Computer plays a key role in problem solving with focus on logical
representation or reasoning and analysis.
This textbook focuses on the fundamental concepts and
problem-solving skills while opening a window to the emerging and
advanced areas of computer science. The newly developed syllabus
has dealt with the dual challenge of reducing curricular load as well as
introducing this ever evolving discipline. This textbook also provides space
to Computational Thinking and Artificial Intelligence, which envisaged in
National Education Policy, 2020.
As an organisation committed to systemic reforms and continuous
improvement in the quality of its products, NCERT welcomes comments and
suggestions which will enable us to revise the content of the textbook.
Hrushikesh Senapaty
Director
New Delhi National Council of Educational
August 2020 Research and Training
2024-25
chapters are required to be solved in a computer and verify with the given
outputs.
Box items are pinned inside the chapters either to explain related
concepts or to describe additional information related to the topic covered
in that section. However, these box-items are not to be assessed through
examinations.
Project Based Learning given as the end includes exemplar projects
related to real-world problems. Teachers are supposed to assign these or
similar projects to be developed in groups. Working in such projects may
promote peer-learning, team spirit and responsiveness.
The chapters have been written by involving practicing teachers
as well as subject experts. Several iterations have resulted into this
book. Thanks are due to the authors and reviewers for their valuable
contribution. I would like to place on record appreciation for Professor
Om Vikas for leading the review activities of the book as well as for his
guidance and motivation to the development team throughout. Comments
and suggestions are welcome.
2024-25
Chief Advisor
Om Vikas, Professor (Retd.), Former Director, ABV-IIITM, Gwalior, M.P.
Members
Anju Gupta, Freelance Educationist, Delhi
Anuradha Khattar, Assistant Professor, Miranda House, University of Delhi
Chetna Khanna, Freelance Educationist, Delhi
Faheem Masoodi, Assistant Professor, Department of Computer Science,
University of Kashmir
Harita Ahuja, Assistant Professor, Acharya Narendra Dev College, University
of Delhi
Mohini Arora, HOD, Computer Science, Air Force Golden Jubilee Institute,
Subroto Park, Delhi
Mudasir Wani, Assistant Professor, Govt. College for Women Nawakadal,
Sri Nagar, Jammu and Kashmir
Naeem Ahmad, Assistant Professor, Madanapalle Institute of Technology
and Science, Madanapalle, Andhra Pradesh
Purvi Kumar, Co-ordinator, Computer Science Department, Ganga
International School, Rohtak Road, Delhi
Priti Rai Jain, Assistant Professor, Miranda House, University of Delhi
Sangita Chadha, HOD, Computer Science, Ambience Public School,
Safdarjung Enclave, Delhi
Sharanjit Kaur, Associate Professor, Acharya Narendra Dev College,
University of Delhi
Member-coordinator
Rejaul Karim Barbhuiya, Assistant Professor, CIET, NCERT, Delhi
2024-25
2024-25
Foreword iii
Preface v
Chapter 1 Exception Handling in Python 1
1.1 Introduction 1
1.2 Syntax Errors 1
1.3 Exceptions 3
1.4 Built-in Exceptions 3
1.5 Raising Exceptions 4
1.6 Handling Exceptions 7
1.7 Finally Clause 13
Chapter 3 Stack 39
3.1 Introduction 39
3.2 Stack 40
3.3 Operations on Stack 42
3.4 Implementation of Stack in Python 43
3.5 Notations for Arithmetic Expressions 46
3.6 Conversion from Infix to Postfix Notation 47
3.7 Evaluation of Postfix Expression 49
Chapter 4 Queue 53
4.1 Introduction to Queue 53
4.2 Operations on Queue 55
2024-25
Chapter 5 Sorting 67
5.1 Introduction 67
5.2 Bubble Sort 68
5.3 Selection Sort 71
5.4 Insertion Sort 74
5.5 Time Complexity of Algorithms 77
Chapter 6 Searching 81
6.1 Introduction 81
6.2 Linear Search 82
6.3 Binary Search 85
6.4 Search by Hashing 90
2024-25
In this Chapter
»» Introduction
»» Syntax Errors
»» Exceptions 1.1 Introduction
»» Built-in Exceptions Sometimes while executing a Python program, the
»» Raising Exceptions program does not execute at all or the program
executes but generates unexpected output or
»» Handling Exceptions
behaves abnormally. These occur when there are
»» Finally Clause syntax errors, runtime errors or logical errors in
the code. In Python, exceptions are errors that
get triggered automatically. However, exceptions
can be forcefully triggered and handled through
program code. In this chapter, we will learn about
exception handling in Python programs.
2024-25
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
Output:
Summary
• Syntax errors or parsing errors are detected when
we have not followed the rules of the particular
programming language while writing a program.
Exercise
1. “Every syntax error is an exception but every exception
cannot be a syntax error.” Justify the statement.
2. When are the following built-in exceptions raised? Give
examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError
3. What is the use of a raise statement? Write a code to
accept two numbers and display the quotient. Appropriate
exception should be raised if the user enters the second
number (denominator) as zero (0).
4. Use assert statement in Question No. 3 to test the
division expression in the program.
5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception
6. Explain catching exceptions using try and except block.
7. Consider the code given below and fill in the blanks.
print (" Learning Exceptions...")
try:
num1= int(input ("Enter the first number"))
num2=int(input("Enter the second number"))
quotient=(num1/num2)
print ("Both the numbers entered were correct")
except _____________: # to enter only integers
print (" Please enter only numbers")
except ____________: # Denominator should not be zero
print(" Number 2 should not be zero")
else:
print(" Great .. you are a good programmer")
___________: # to be executed at the end
print(" JOB OVER... GO GET SOME REST")
In this Chapter
»» Concept of Communication
»» Components of Data
Communication 11.1 Concept of Communication
»» Measuring Capacity of The term “Data Communication” comprises two
Communication Media words: Data and Communication. Data can be
»» Types of Data any text, image, audio, video, and multimedia
Communication files. Communication is an act of sending or
»» Switching Techniques receiving data. Thus, data communication refers
»» Transmission Media to the exchange of data between two or more
networked or connected devices. These devices
»» Mobile Telecommunication
Technologies must be capable of sending and receiving data
over a communication medium. Examples of
»» Protocol
such devices include personal computers, mobile
phones, laptops, etc. As we can see in Figure
11.1, four different types of devices — computer,
printer, server and switch are connected to form
the network. These devices are connected through
a media to the network, which carry information
from one end to other end.
2024-25
Switch
Sender
Solution:
OR
Both Directions
A B
Figure 11.5: Full duplex transmission of data
Metal Shield
Protective Insulating
Plastic Covering Material
Glass
Sender Receiver
Cladding of less
dense material
Figure 11.11: Fiber optic cable
11.8 Protocol
In communication, Protocol is a set of standard rules
that the communicating parties — the sender, the
receiver, and all other intermediate devices need
to follow. We know that the sender and receiver can
be parts of different networks, placed at different
geographic locations. Besides, the data transfer rates in
different networks can vary, requiring data to be sent in
different formats.
11.8.1 Need for Protocols
We need protocols for different reasons such as flow
control, access control, addressing, etc. Flow control is
required when the sender and receiver have different
speeds of sending and receiving the data. Figure 11.14
shows that Computer A is sending data at the speed
of 1024 Mbps and computer B is receiving data at the
speed of 512 Mbps. In this case, Computer B must be
able to inform computer A about the speed mismatch
so that computer A can adjust its data transmission
rate. Otherwise some data will be lost, as shown in
Figure 11.14.
Access control is required to decide which nodes in
a communication channel will access the link shared
among them at a particular instant of time. Otherwise,
the transmitted data packets will collide if computers
are sending data simultaneously through the same link
resulting in the loss or corruption of data.
Received Packets
Loss Packets
Figure 11.14: Speed mismatch between two computers can result into
loss of data
Summary
• Data communication refers to the exchange of
data between two or more networked or connected
devices like laptops, PC, printers, routers etc.
• Sender, receiver, messages, channel and protocols
are major components of data communication.
• In data communication, transmission media are
the links that carry messages between two or
more communicating devices. These are broadly
classified into guided and unguided media.
• In guided transmission, there is a physical link
made of wire/cable through which data in terms
of signals are propagated between the nodes.
These are usually metallic cable, fiber-optic cable,
etc. They are also known as wired media.
• In unguided transmission, data travels in air in
terms of electromagnetic waves using an antenna.
They are also known as wireless media.
• The capacity of channels is measured in
bandwidth. The unit of bandwidth is Hertz.
• Communication can be done in three different
modes — simplex, half-duplex, and full-duplex
communication.
• Switching techniques are alternative to dedicated
lines whereby data is routed through various
nodes in a network. It forms a temporary route
for the data to be transmitted. Two commonly
used switching techniques are – circuit switching
and packet switching.
• Electromagnetic spectrum of frequency ranging
from 3 KHz to 900 THz is available for wireless
communication. This spectrum range (3KHz to
900THz) can be divided into four categories- Radio
Exercise
1. What is data communication? What are the main
components of data communication?
2. Which communication mode allows communication in
both directions simultaneously?
3. Among LAN, MAN, and WAN, which has the highest
speed and which one can cover the largest area?
— Clifford Stoll
In this Chapter
»» Threats and Prevention
»» Malware
»» Antivirus
»» Spam 12.1 Threats and Prevention
»» HTTP vs HTTPS Being alone is the most ideal situation for an
»» Firewall individual in terms of security. It applies to
»» Cookies computers as well. A computer with no link to
an external device or computer is free from the
»» Hackers and Crackers
security threats arising otherwise. However,
»» Network Security Threats it is not an ideal solution for a human being
or a computer to stay aloof in order to mitigate
any security threats, as the world at present
is on its way to become fully connected. This
connectedness of various devices and computers
has brought into our focus the various network
threats and its prevention.
Network security is concerned with protection
of our device as well as data from illegitimate access
or misuse. Threats include all the ways in which
one can exploit any vulnerability or weakness in
a network or communication system in order to
cause harm or damage one’s reputation.
2024-25
12.2.4 Trojan
Since the ancient Greeks could not infiltrate the city
of Troy using traditional warfare methods, they gifted
the king of Troy with a big wooden horse with hidden
soldiers inside and eventually defeated them. Borrowing
12.2.5 Spyware
It is a type of malware that spies on a person or an
organisation by gathering information about them,
without the knowledge of the user. It records and sends
the collected information to an external entity without
consent or knowledge of the user.
Spyware usually tracks internet usage data and sells
them to advertisers. They can also be used to track and
capture credit card or bank account information, login
and password information or user’s personal identity.
12.2.6 Adware
An Adware is a malware that is created to generate
revenue for its developer. An adware displays
online advertisements using pop-ups, web pages, or
installation screens. Once an adware has infected a
substantial number of computer systems, it generates
revenue either by displaying advertisements or using
“pay per click” mechanism to charge its clients against
the number of clicks on their displayed ads. Adware
12.3 Antivirus
Antivirus is a software, also known as anti-malware.
Initially, antivirus software was developed to detect
and remove viruses only and hence the name anti-
virus. However, with time it has evolved and now comes
bundled with the prevention, detection, and removal of
a wide range of malware.
12.3.1 Methods of Malware Identification used by
Antivirus
(A) Signature-based detection
In this method, an antivirus works with the help of
a signature database known as “Virus Definition File
(VDF)”. This file consists of virus signatures and is
updated continuously on a real-time basis. This makes
the regular update of the antivirus software a must. If
there is an antivirus software with an outdated VDF, it
is as good as having no antivirus software installed, as
Virus Signature the new malware will infect the system without getting
A virus signature detected. This method also fails to detect malware that
is a consecutive
sequence of bytes that
has an ability to change its signature (polymorphic) and
is commonly found the malware that has some portion of its code encrypted.
in a certain malware
sample. That means (B) Sandbox detection
it’s contained within In this method, a new application or file is executed
the malware or the in a virtual environment (sandbox) and its behavioural
infected file and not in fingerprint is observed for a possible malware. Depending
unaffected files.
on its behaviour, the antivirus engine determines if it
is a potential threat or not and proceeds accordingly.
Although this method is a little slow, it is very safe as
the new unknown application is not given access to
actual resources of the system.
(C) Data mining techniques
This method employs various data mining and machine
learning techniques to classify the behaviour of a file as
either benign or malicious.
12.4 Spam
Spam is a broad term and applies to various digital
platforms like messaging, forums, chatting, emailing,
advertisement, etc. However, the widely recognised
form is email spam. Depending on their requirements,
organisations or individuals buy or create a mailing
list (list of email addresses) and repeatedly send
advertisement links and invitation emails to a large
number of users. This creates unnecessary junk in the
inbox of the receiver’s email and often tricks a user into
buying something or downloading a paid software or
malware.
Nowadays, email services like Gmail, Hotmail, etc.
have an automatic spam detection algorithm that filters
emails and makes things easier for the end users. A
user can also mark an undetected unsolicited email as
“spam”, thereby ensuring that such type of email is not
delivered into the inbox as normal email in future.
LAN
WAN
Firewall
00
1000001111
000
101010101
111
11
11
11
01
11
01 11
01 000
10101 01
Summary
• Malware is a software developed with an intention
to damage computer hardware, software, steal
data, or cause any other trouble to a user.
• A virus is a piece of software code created
to perform malicious activities and hamper
resources of a computer system.
• The Worm is also a malware that incurs
unexpected or damaging behaviour on an infected
computer system.
• Worms are standalone programs that are capable
of working on its own.
• Ransomware is a type of malware that targets
user data.
• Ransomware either blocks the user from
accessing their own data or threatens to publish
their personal data online and demands ransom
payment against the same.
• Trojan is a malware, that looks like a legitimate
software and once it tricks a user into installing
it, it acts pretty much like a virus or a worm.
• Spyware records and sends the collected
information to an external entity without the
consent or knowledge of a user.
• An adware displays unwanted online
advertisements using pop-ups, web pages, or
installation screens.
• A keylogger makes logs of daily keyboard usage
and may send it to an external entity as well.
• The on-screen keyboard is an application software
that uses a fixed QWERTY key layout.
• Online virtual keyboard is a web-based or a
standalone software with a randomised key
layout every time it is used.
• A malware can take many routes to reach your
computer, which include: Downloaded from the
Exercise
1. Why is a computer considered to be safe if it is not
connected to a network or Internet?
2. What is a computer virus? Name some computer viruses
that were popular in recent years.
3. How is a computer worm different from a virus?
4. How is Ransomware used to extract money from users?
5. How did a Trojan get its name?
6. How does an adware generate revenue for its creator?
7. Briefly explain two threats that may arise due to a
keylogger installed on a computer.
8. How is a Virtual Keyboard safer than On Screen
Keyboard?
9. List and briefly explain different modes of malware
distribution.
10. List some common signs of malware infection.
11. List some preventive measures against malware
infection.
12. Write a short note on different methods of malware
identification used by antivirus software.
13. What are the risks associated with HTTP? How can we
resolve these risks by using HTTPS?
14. List one advantage and disadvantage of using Cookies.
15. Write a short note on White, Black, and Grey Hat
Hackers.
16. Differentiate between DoS and DDoS attack.
17. How is Snooping different from Eavesdropping?
— Gautam Buddha
In this Chapter
»» Introduction
»» Approaches for Solving
Projects
»» Teamwork 13.1 Introduction
»» Project Descriptions Project based learning gives a thorough practical
exposure to students regarding a problem upon
which the project is based. Through project based
learning, students learn to organise their project
and use their time effectively for successful
completion of the project. Projects are developed
generally in groups where students can learn
various skills such as working together, problem
solving, decision making, and investigating
activities. Project based learning involves the
steps such as analysing the problem, formulating
the problem into small modules, applying the
mechanism or method to solve each module and
then integrating the solution of all the modules
to arrive at the complete solution of the problem.
To solve a problem, it is required that those who
work on it gather the relevant data and process
it by applying a particular method. Data may
2024-25
Outcome
of project
13.3 Teamwork
Many real-life tasks are very complex and require a lot
of individuals to contribute in achieving them. Efforts
made by individuals collectively to accomplish a task is
called teamwork.
For example, in many sports, there is a team of
players. These players play together to win a match.
Take an example of a cricket team. We find that even if
a bowler bowls a good ball but if the fielder cannot take
Description
A new restaurant “Stay Healthy” is coming up in your
locality. The owner/management of the restaurant
wants to use a computer to generate bills and maintain
other records of the restaurant. Your team is asked to
develop an application software to automate the order
placing and associated processes.
Specifications
Make a group of students to undertake a project on
automating the order processing of the restaurant
‘Stay Healthy’. The owner of the restaurant wants the
following specific functionalities to be made available in
the developed application:
• There should be two types of Login options — one for
the manager of the joint and other for the customer.
• Kiosk(s) running the software for customers will be
placed at reception for placing the order. On the
opening screen, menu for placing orders will be
displayed.
• To place orders, customers will enter Item Code(s)
and quantity desired.
• After placing an order, a soft copy of the bill will be
displayed on the kiosk, having an Order Number.
• Every bill will have a unique identification (such as
combination of date, and order number of the day)
and should be saved in the data file/database.
• Order Number starts from 1 every day.
Description
Implement a puzzle solving game in Python. The game
presents a grid board composed of cells to the player, in
which some cells have Bomb. Player is required to clear
the board (of the bomb), without detonating any one of
them with the help of clue(s) provided on the board.
Specifications
For clearing the board, the player will click a cell on the
board, if the cell contains a bomb, the game finishes. If
the cell does not contain a bomb, then the cell reveals
a number giving a clue about the number of bombs
hidden in adjacent cells.
Before you start coding the game, play any
Minesweeper game five times. This will help you in
proper understanding of your project. To reduce the
complexity of the program you can fix the grid size to
6x6 and number of bombs to 6.
Note: Do ensure to handle various exception(s) which may
occur while playing the game, in your code.
Description
You are a member of the ICT club of your school. As a club
member, you are given the responsibility of identifying
ways to improve mathematical skills of kids, in the age
group of 5-7 years. One of the club members suggested
developing an Edutainment Game named “Match the
Sum” for it. Match the Sum will hone summing skills
of student(s), by allowing them to form number 10 by
adding 2/3 digits.
— Stewart Kirkpatrick
In this Chapter
»» Introduction to Computer
Networks
»» Evolution of Networking 10.1 Introduction to Computer Networks
»» Types of Networks
We are living in a connected world. Information
»» Network Devices is being produced, exchanged, and traced across
»» Networking Topologies the globe in real time. It's possible as almost
»» Identifying Nodes everyone and everything in the digital world is
in a Networked interconnected through one way or the other.
Communication
»» Internet, Web and the
Internet of Things
»» Domain Name System
Networking
Device
1969 1983
1990
1974 Domain Name System
ARPANET became introduced
functional by
connecting UCLA and
SRI
The term Internet was The Berners-Lee at
coined, CERN developed HTML
and URL, thus giving
First commercial use of birth to World Wide Web
ARPANET, was started (www)
in the name of Telenet
LAN 1
Networking LAN 3
Device
LAN 2
Telephone Line
Modem Modem
10.4.3 RJ45
RJ 45 or Registered Jack-45 is an
eight-pin connector (Figure 10.10)
that is used exclusively with
Ethernet cables for networking.
It is a standard networking
interface that can be seen at
the end of all network cables.
Basically, it is a small plastic plug
that fits into RJ-45 jacks of the
Ethernet cards present in various
Figure 10.10: RJ 45
computing devices.
Activity 10.3
1 2 3 4 5 6 7 8 Find and list a
few ISPs in your
region.
10.4.5 Switch
A switch is a networking device (Figure 10.12) that
plays a central role in a Local Area Network (LAN). Like
a hub, a network switch is used to connect multiple
computers or communicating devices. When data
arrives, the switch extracts the
destination address from the data
packet and looks it up in a table to
see where to send the packet. Thus,
it sends signals to only selected
devices instead of sending to all.
It can forward multiple packets at
the same time. A switch does not
forward the signals which are noisy
or corrupted. It drops such signals
and asks the sender to resend it. Figure 10.12: Cables connected to a network switch
PC 4 PC 5 PC 4 PC 5
PC 1 PC 2 PC 3 PC 1 PC 2 PC 3
Activity 10.4
Explore how can you
find the MAC 10.6.2 IP Address
address of your
computer
IP address, also known as Internet Protocol address,
system. is also a unique address that can be used to uniquely
identify each node in a network. The IP addresses
http://www.ncert.nic.in/textbook/textbook.htm
URL
wikipedia.org 198.35.26.96
Summary
• A computer network is an interconnection among
two or more computers or computing devices.
• A computer network allows computers to share
data and resources among each other.
• Networking devices are used to connect multiple
computers in different settings.
Exercise
1. Expand the following:
a) ARPANET
b) MAC
c) ISP
d) URI
2. What do you understand by the term network?
3. Mention any two main advantages of using a network of
computing devices.
4. Differentiate between LAN and WAN.
5. Write down the names of few commonly used networking
devices.
6. Two universities in different States want to transfer
information. Which type of network they need to use for
this?
7. Define the term topology. What are the popular network
topologies?
8. How is tree topology different from bus topology?
9. Identify the type of topology from the following:
a) Each node is connected with the help of a single cable.
b) Each node is connected with central switching
through independent cables.
In this Chapter
»» Introduction
»» Linear Search
»» Binary Search 6.1 Introduction
»» Search by Hashing
We store many things in our home and find them
out later as and when required. Sometimes we
remember the exact location of a required item.
But, sometimes we do not remember the exact
location and in that case we need to search for
the required item. A computer also stores lots of
data to be retrieved later as and when demanded
by a user or a program.
Searching means locating a particular
element in a collection of elements. Search result
determines whether that particular element is
present in the collection or not. If it is present,
we can also find out the position of that element
in the given collection. Searching is an important
technique in computer science. In order to design
algorithms, programmers need to understand the
different ways in which a collection of data can be
searched for retrieval.
2024-25
Index in numList 0 1 2 3 4 5 6
Value 8 -4 7 17 0 2 19
Index in numList 0 1 2 3 4 5 6
Value 17 8 -4 7 0 2 19
Table 6.4 Linear search for key 17 in numList given in Table 6.3
numList[index]=
index index < n index=index+1
key
0 0 < 7 ? Yes 17 = 17? Yes 1
SearcHinG 83
2024-25
Output
How many elements in your list? 4
Enter each element and press enter:
12
23
3
-45
The List contents are: [12, 23, 3, -45]
Enter the number to be searched:23
Number 23 is present at position 2
SearcHinG 85
2024-25
Table 6.6 Working of binary search using steps given in Algorithm 6.2.
first <=
first last mid numList [mid] == K key < L mid?
last
0 14 (0+14)// Not known Not known 0 <= 14?
At Start
2=7 True
0 14 7 17 = 17? Key is
Iteration Yes found. The
1 search
terminates
SearcHinG 87
2024-25
Output
Create a list by entering elements in ascending order
press enter after each element, press -999 to stop
1
3
4
5
-999
Enter the number to be searched: 4
4 is found at position 3
SearcHinG 89
2024-25
Element 34 16 2 93 80 77 51
index 0 1 2 3 4 5 6 7 8 9
SearcHinG 91
2024-25
position = hashFind(key,hashTable)
if position is None:
print("Number",key,"is not present in the hash table")
else:
print("Number ",key," present at ",position, " position")
Output:
We have created a hashTable of 10 positions:
[None, None, None, None, None, None, None, None, None, None]
The given list is [34, 16, 2, 93, 80, 77, 51]
The hash table contents are:
hashindex= 0 , value = 80
hashindex= 1 , value = 51
hashindex= 2 , value = 2
hashindex= 3 , value = 93
hashindex= 4 , value = 34
hashindex= 5 , value = None
hashindex= 6 , value = 16
hashindex= 7 , value = 77
hashindex= 8 , value = None
hashindex= 9 , value = None
Enter the number to be searched:16
Number 16 present at 7 position
6.4.1 COLLISION
The hashing technique works fine if each element of the
list maps to a unique location in the hash table. Consider
a list [34, 16, 2, 26, 80]. While applying the
hash function say, list [i]%10, two elements (16 and
26) would have a hash value 6. This is a problematic
situation, because according to our definition, two or
more elements cannot be in the same position in the
list. This situation is called collision in hashing.
We must have a mechanism for placing the other
items with the same hash value in the hash table. This
process is called collision resolution. Collision can be
resolved in many ways, but it is beyond the scope of this
book to discuss collision resolution methods.
Summary
• Searching means trying to locate a particular
element called key in a collection of elements.
Search specifies whether that key is present in the
collection or not. Also, if the key is present, it tells
the position of that key in the given collection.
• Linear search checks the elements of a list, one at
a time, without skipping any element. It is useful
when we need to search for an item in a small
unsorted list, but it is slow and time-consuming
when the list contains a large number of items.
The time taken to search the list increases as the
size of the list increases.
• Binary search takes a sorted/ordered list and
divides it in the middle. It then compares the
middle element with the key to be searched. If
the middle element matches the key, the search
is declared successful and the program ends. If
the middle element is greater than the key, the
search repeats only in the first half of the list.
If the middle element is lesser than the key, the
search repeats only in the second half of the list.
SearcHinG 93
2024-25
Exercise
1. Using linear search determine the position of 8, 1, 99
and 44 in the list:
[1, -2, 32, 8, 17, 19, 42, 13, 0, 44]
SearcHinG 95
2024-25
CountryCapital= {'India':'New Delhi','UK':
'London','France':'Paris',
'Switzerland': 'Berne',
'Australia': 'Canberra'}
Let us presume that our hash function is the length
of the Country Name. Take two lists of appropriate size:
one for keys (Country) and one for values (Capital). To put
an element in the hash table, compute its hash code by
counting the number of characters in Country, then put
the key and value in both the lists at the corresponding
indices. For example, India has a hash code of 5. So, we
store India at the 5th position (index 4) in the keys list,
and New Delhi at the 5th position (index 4) in the values
list and so on. So that we end up with:
hash index = length
List of Keys List of Values
of key - 1
0 None None
1 UK London
2 None None
3 Cuba Havana
4 India New Delhi
5 France Paris
6 None None
7 None None
8 Australia Canberra
9 None None
10 Switzerland Berne
In this Chapter
»» Introduction to Data
»» Data Collection
»» Data Storage
7.1 IntrodUCtion to Data
»» Data Processing Many a time, people take decisions based on
certain data or information. For example, while
»» Statistical Techniques for
Data Processing choosing a college for getting admission, one looks
at placement data of previous years of that college,
educational qualification and experience of the
faculty members, laboratory and hostel facilities,
fees, etc. So we can say that identification of a
college is based on various data and their analysis.
Governments systematically collect and record
data about the population through a process
called census. Census data contains valuable
information which are helpful is planning and
formulating policies. Likewise, the coaching staff
of a sports team analyses previous performances
of opponent teams for making strategies. Banks
maintain data about the customers, their account
details and transactions. All these examples
highlight the need of data in various fields. Data
are indeed crucial for decision making.
2024-25
Understanding Data 99
2024-25
A website
A website handling
handling online
online filling
filling of
of student
student details
details for
for a
a competitive
competitive examination
examination and
and generating
generating admit
admit card
card
ATM PIN number, account type, Checking for valid PIN number,
account number, card number, existing bank balance, if satisfied, Currency notes, printed slip with
ATM location from where money then deduction of amount from that transaction details
was withdrawn, date and time, and account and counting of rupees and
amount to be withdrawn. initiate printing of receipt
Issue
Issue of
of train
train ticket
ticket
Journey start and end stations, Verify login details and check
date of journey, number of tickets availability of berth in that class. If
required, class of travel payment done, issue tickets and Generate ticket with berth and
(Sleeper/AC/other), berth deduct that number from the total coach number, or issue ticket with
preference (if any), passenger available tickets on that coach. a waiting list number
name(s) and age(s), mobile and Allocate PNR number and berths or
email id, payment related details, generate a waiting number for that
etc. ticket.
(C) Mode
Value that appears most number of times in the given
data of an attribute/variable is called Mode. It is
computed on the basis of frequency of occurrence of
distinct values in the given data. A data set has no mode
if each value occurs only once. There may be multiple
modes in the data if more than one values have same
highest frequency. Mode can be found for numeric as
well as non-numeric data.
Example 7.3
In the list of height of students, mode is 110 as its
frequency of occurrence in the list is 3, which is larger
than the frequency of rest of the values.
7.5.2 Measures of Variability
The measures of variability refer to the spread or variation
of the values around the mean. They are also called
measures of dispersion that indicate the degree of diversity
in a data set. They also indicate difference within the group.
Two different data sets can have the same mean, median
or mode but completely different levels of dispersion, or
vice versa. Common measures of dispersion or variability
are Range and Standard Deviation.
(A) Range
It is the difference between maximum and minimum
values of the data (the largest value minus the
smallest value). Range can be calculated only for
numerical data. It is a measure of dispersion and
tells about coverage/spread of data values. For
Example 7.5
Let us compute the standard deviation of the height
of nine students that we used while calculating
Mean. The Mean (x) was calculated to be 101.33 cm.
Subtract each value from the mean and take square
of that value. Dividing the sum of square values by
total number of values and taking its square not
gives the standard deviation in data. See Table 7.3
for details.
Table 7.3 Standard deviation of attendance of 9 students
_ _
Height (x) in cm x_x (x _ x )2
90 -11.33 128.37 n
(X i − X )2
102 0.67 0.36 = i =1
n
110 8.67 75.17
115 13.67 186.87
n
110 8.67 75.17
_ _2
n=9 ∑(x-x) = 0.03 ∑(x-x) = 938.00
_
x =101.33
Teacher wants to know about the average performance of the whole class in
a test.
Compare height of residents of two cities
Find the popular color for car after surveying the car owners of a small city.
SUMMarY
• Data refer to unorganised facts that can be
processed to generate meaningful result or
information.
• Data can be structured or unstructured.
• Hard Disk, SSD, CD/DVD, Pen Drive, Memory
Card, etc. are some of the commonly used storage
devices.
EXerCise
1. Identify data required to be maintained to perform the
following services:
a) Declare exam results and print e-certificates
b) Register participants in an exhibition and issue
biometric ID cards
c) To search for an image by a search engine
d) To book an OPD appointment with a hospital in a
specific department
2. A school having 500 students wants to identify
beneficiaries of the merit-cum means scholarship,
achieving more than 75% for two consecutive years
and having family income less than 5 lakh per annum.
Briefly describe data processing steps to be taken by the
to beneficial prepare the list of school.
3. A bank ‘xyz’ wants to know about its popularity among
the residents of a city ‘ABC’ on the basis of number of
bank accounts each family has and the average monthly
account balance of each person. Briefly describe the
steps to be taken for collecting data and what results
can be checked through processing of the collected data.
In this Chapter
»» Introduction
»» File System
»» Database Management
System 8.1 Introduction
»» Rational Data Model After learning about importance of data in the
»» Keys in a Relational previous chapter, we need to explore the methods
Database to store and manage data electronically. Let us
take an example of a school that maintains data
about its students, along with their attendance
record and guardian details.
The class teacher marks daily attendance of the
students in the attendance register. The teacher
records ‘P’ for present or ‘A’ for absent against
each student’s roll number on each working day.
If class strength is 50 and total working days
in a month are 26, the teacher needs to record
50 × 26 records manually in the register every
month. As the volume of data increases, manual
data entry becomes tedious. Following are some
of the limitations of manual record keeping in
this example:
2024-25
ry
Query Result
Qu
Query Result
e
Qu
er
y
Student
Database
Guardian Catalog
Attendance
Table 8.7 Relation schemas along with its description of Student Attendance
database
Relation Scheme Description of attributes
STUDENT(RollNumber, RollNumber: unique id of the student
SName, SDateofBirth, SName: name of the student
GUID) SDateofBirth: date of birth of the student
GUID: unique id of the guardian of the student
ATTENDANCE AttendanceDate: date on which attendance is taken
(AttendanceDate, RollNumber: roll number of the student
RollNumber, AttendanceStatus: whether present (P) or absent(A)
AttendanceStatus) Note that combination of AttendanceDate and RollNumber will be unique
in each record of the table
GUARDIAN(GUID, GUID: unique id of the guardian
GName, GPhone, GName: name of the guardian
GAddress) GPhone: contact number of the guardian
GAddress: contact address of the guardian
Relation
State
101010101010 Himanshu Shah 4726309212 26/77, West Patel Nagar, Ahmedabad
333333333333 Danny Dsouza S -13, Ashok Village, Daman
466444444666 Sujata P. 3801923168 HNO-13, B- block, Preet Vihar, Madurai
Figure 8.5: STUDENTATTENDANCE database with the primary and foreign keys
Summary
• A file in a file system is a container to store data in a computer.
• File system suffers from Data Redundancy, Data Inconsistency, Data
Isolation, Data Dependence and Controlled Data sharing.
• Database Management System (DBMS) is a software to create and manage
databases. A database is a collection of tables.
• Database schema is the design of a database.
• A database constraint is a restriction on the type of data that that can be
inserted into the table.
Exercise
1. Give the terms for each of the following:
a) Collection of logically related records.
b) DBMS creates a file that contains description about
the data stored in the database.
c) Attribute that can uniquely identify the tuples in
a relation.
d) Special value that is stored when actual data value is
unknown for an attribute.
e) An attribute which can uniquely identify tuples of the
table but is not defined as primary key of the table.
f) Software that is used to create, manipulate and
maintain a relational database.
2. Why foreign keys are allowed to have NULL values?
Explain with an example.
3. Differentiate between:
a) Database state and database schema
b) Primary key and foreign key
c) Degree and cardinality of a relation
In this Chapter
»» Introduction
»» Structured Query Language
(SQL) 9.1 Introduction
»» Data Types and
Constraints in MySQL
We have learnt about Relational Database
Management Systems (RDBMS) and its purpose
»» SQL for Data Definition
in the previous chapter. There are many
»» SQL for Data RDBMS such as MySQL, Microsoft SQL Server,
Manipulation PostgreSQL, Oracle, etc. that allow us to create
»» SQL for Data Query a database consisting of relations. These RDBMS
»» Data Updation and also allow us to store, retrieve and manipulate
Deletion data on that database through queries. In this
»» Functions in SQL chapter, we will learn how to create, populate and
»» GROUP BY Clause in SQL
query databases using MySQL.
»» Operations on Relations
9.2 Structured Query Language (SQL)
»» Using Two Relations in a
Query One has to write application programs to access
data in case of a file system. However, for database
management systems there are special kinds of
languages called query language that can be used
to access and manipulate data from the database.
The Structured Query Language (SQL) is the most
popular query language used by major relational
2024-25
Table 9.4 Data types and constraints for the attributes of relation GUARDIAN
Attribute Name Data expected to be stored Data type Constraint
GUID Numeric value consisting of 12 digit Aadhaar CHAR (12) PRIMARY KEY
number
GName Variant length string of maximum 20 VARCHAR(20) NOT NULL
characters
GPhone Numeric value consisting of 10 digits CHAR(10) NULL UNIQUE
GAddress Variant length String of size 30 characters VARCHAR(30) NOT NULL
Table 9.5 Data types and constraints for the attributes of relation ATTENDANCE.
Attribute Name Data expected to be stored Data type Constraint
AttendanceDate Date value DATE PRIMARY KEY*
RollNumber Numeric value consisting of maximum 3 INT PRIMARY KEY*
digits FOREIGN KEY
AttendanceStatus ‘P’ for present and ‘A’ for absent CHAR(1) NOT NULL
*means part of composite primary key.
Example 9.19
a) Let us now add a new column Commission to the
SALE table. The column Commission should have
a total length of 7 in which 2 decimal places to
be there.
mysql> ALTER TABLE SALE ADD(Commission
Numeric(7,2));
Query OK, 6 rows affected (0.34 sec)
Records: 6 Duplicates: 0 Warnings: 0
b) Let us now calculate commission for sales agents as
12% of the SalePrice, Insert the values to the newly
added column Commission and then display records
of the table SALE where commission > 73000.
mysql> UPDATE SALE SET
Commission=12/100*SalePrice;
Query OK, 6 rows affected (0.06 sec)
Rows matched: 6 Changed: 6 Warnings: 0
SUM(column) Returns the sum of the values mysql> SELECT SUM(Price) FROM
for the specified column. INVENTORY;
Output:
4608733.00
COUNT(*) Returns the number of records mysql> SELECT COUNT(*) from
in a table. MANAGER;
+----------+
Note: In order to display the | count(*) |
+----------+
number of records that matches
| 4 |
a particular criteria in the table, +----------+
we have to use COUNT(*) with
WHERE clause. 1 row in set (0.00 sec)
Example 9.22
a) Display the total number of records from table
INVENTORY having a model as VXI.
mysql> SELECT COUNT(*) FROM INVENTORY WHERE
Model=”VXI”;
+----------+
| COUNT(*) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
Summary
• Database is a collection of related tables. MySQL
is a ‘relational’ DBMS.
• DDL (Data Definition Language) includes SQL
statements such as, Create table, Alter table and
Drop table.
• DML (Data Manipulation Language) includes SQL
statements such as, insert, select, update and
delete.
• A table is a collection of rows and columns, where
each row is a record and columns describe the
feature of records.
• ALTER TABLE statement is used to make changes
in the structure of a table like adding, removing
or changing datatype of column(s).
• UPDATE statement is used to modify existing
data in a table.
• WHERE clause in SQL query is used to enforce
condition(s).
• DISTINCT clause is used to eliminate repetition
and display the values only once.
Exercise
1. Answer the following questions:
a) Define RDBMS. Name any two RDBMS software.
b) What is the purpose of the following clauses in a
select statement?
i) ORDER BY
ii) GROUP BY
c) Site any two differences between Single Row Functions
and Aggregate Functions.
d) What do you understand by Cartesian Product?
e) Differentiate between the following statements:
In this Chapter
»» Introduction
»» Stack
»» Operations on Stack 3.1 Introduction
»» Implementation of Stack We have learnt about different data types in
in Python Python for handling values in Class XI. Recall
»» Notations for Arithmetic that String, List, Set, Tuple, etc. are the sequence
Expressions data types that can be used to represent collection
»» Conversion From Infix To of elements either of the same type or different
Postfix Notation types. Multiple data elements are grouped in a
particular way for faster accessibility and efficient
»» Evaluation of Postfix
Expression storage of data. That is why we have used different
data types in python for storing data values. Such
grouping is referred as a data structure.
A data structure defines a mechanism to store,
organise and access data along with operations
(processing) that can be efficiently performed on
the data. For example, string is a data structure
containing a sequence of elements where each
element is a character. On the other hand, list is
a sequence data structure in which each element
may be of different types. We can apply different
operations like reversal, slicing, counting of
2024-25
3.2 Stack
We have seen piles of books in the library or stack of
plates at home (Figure 3.1). To put another book or
another plate in such a pile, we always place (add to
the pile) the object at the top only. Likewise, to remove
a book or a plate from such a pile, we always remove
(delete from the pile) the object from the top only. This
is because in a large pile, it is inconvenient to add or
remove an object from in between or bottom. Such an
arrangement of elements in a linear order is called a
A data structure
in which elements stack. We add new elements or remove existing elements
are organised from the same end, commonly referred to as the top of
in a sequence is the stack. It thus follows the Last-In-First-out (LIFO)
called linear data principle. That is, the element which was inserted last
structure. (the most recent element) will be the first one to be taken
out from the stack.
StacK 41
2024-25
StacK 43
2024-25
StacK 45
2024-25
StacK 47
2024-25
Example 3.1
Let us now use this algorithm to convert a given infix
expression (x + y)/(z*8) into equivalent postfix expression
using a stack. Figure 3.3 shows the steps to be followed
on encountering an operator or an operand in the
given infix expression. Note here that stack is used
to track the operators and parentheses, and a string
variable contains the equivalent postfix expression.
Initially both are empty. Each character in the given
infix expression is processed from left to right and the
appropriate action is taken as detailed in the algorithm.
When each character in the given infix expression has
been processed, the string will contain the equivalent
postfix expression.
SYMBOL : ( x + y
Initial
Stack + +
(Empty) ( ( ( (
POSTFIX empty x x xy
STRING (postExp)
StacK 49
2024-25
Example 3.2
Figure 3.4 shows the step-by-step process of evaluation
of the postfix expression 7 8 2 * 4 / + using Algorithm
3.2 .
SYMBOL : 7 8 2
ACTION : PUSH PUSH PUSH
Initial
Stack 2
(Empty) 8 8
7 7 7
SYMBOL : * 4 /
ACTION : POP two PUSH POP two
Write an algorithm to elements, apply elements, apply
evaluate any prefix the operator the operator and
expression using a and push back push back the
stack. the result result
4
16 16 4
7 7 7
SYMBOL : + End of
Input
Expression
Final
Stack Result = 11
(Empty)
11
EMPTY
StacK 51
2024-25
In this Chapter
»» Introduction to Queue
»» Operations on Queue
»» Implementation of Queue 4.1 Introduction to Queue
using Python
In the previous chapter we learned about a data
»» Introduction to Deque structure called Stack, which works on Last-In-
»» Implementation of Deque First-Out (LIFO) principle. In this chapter, we will
using Python learn about another data structure called Queue
which works on First-In-First-Out (FIFO) principle.
Queue is an ordered linear list of elements, having
different ends for adding
and removing elements
Cashier Next in it.
Examples of queue in
our everyday life include
students standing in
a queue for morning
assembly, customers
forming a queue at the
cash counter in a bank
(Figure 4.1), vehicles
queued at fuel pumps
Figure 4.1: Queue of people at a bank (Figure 4.2), etc.
2024-25
Queue 55
2024-25
enqueue(c) F Z X C R
dequeue() F X C R
enqueue(v) F X C V R
dequeue() F C V R
dequeue() F V R
Queue 57
2024-25
Program 4-1
myQueue = list()
# each person to be assigned a code as P1, P2, P3,...
element = input("enter person’s code to enter in queue :”)
enqueue(myQueue,element)
element = input("enter person’s code for insertion in queue :")
enqueue(myQueue,element)
print("person removed from queue is:", dequeue(myQueue))
print(“Number of people in the queue is :”,size(myQueue))
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
Front Rear
Figure 4.4: Basic deque structure displaying head and tail to implement stack or queue.
Queue 59
2024-25
m a d a insertrear
(m)
Front Rear
Figure 4.5: Status of Deque after 4th iteration
removefront a d a insertrear
(m) (m)
Front Rear
Figure 4.6: Status of Deque after removing one character from both
the ends.
Queue 61
2024-25
def insertFront(myDeque,element):
myDeque.insert(0,element)
def getFront(myDeque):
if not (isEmpty(myDeque)):
return myDeque[0]
else:
print("Queue underflow")
def getRear(myDeque):
if not (isEmpty(myDeque)):
return myDeque[len(myDeque)-1]
else:
print ("Queue underflow")
def insertRear(myDeque,element):
myDeque.append(element)
def isEmpty(myDeque):
if len(myDeque) == 0:
return True
else:
return False
def deletionRear(myDeque):
if not isEmpty(myDeque):
return myDeque.pop()
else:
print("Queue underflow")
def deletionFront(myDeque):
if isEmpty(myDeque):
Queue 63
2024-25
def main():
dQu = list()
choice = int(input('enter 1 to use as normal queue 2 otherwise
: '))
if choice == 1:
element = input("data for insertion at rear ")
insertRear(dQu,element)
element = getFront(dQu)
print("data at the beginning of queue is ", element)
element = input("data for insertion at front ")
insertRear(dQu,element)
print('data removed from front of queue is ', deletionFront(dQu))
print('data removed from front of queue is ', deletionFront(dQu))
Output
enter 1 to use as normal queue 2 otherwise : 1
data for insertion at rear 23
data at the beginning of queue is 23
data for insertion at rear 45
data removed from front of queue is 23
data removed from front of queue is 45
Queue underflow
data removed from front of queue is None
Summary
• Queue is an ordered linear data structure,
following FIFO strategy.
• Front and Rear are used to indicate beginning
and end of queue.
• In Python, the use of predefined methods takes
care of Front and Rear.
Exercise
1. Fill in the blank
a) ____________________ is a linear list of elements
in which insertion and deletion takes place from
different ends.
b) Operations on a queue are performed in
__________________ order.
c) Insertion operation in a queue is called ______________
and deletion operation in a queue is called
____________________.
d) Deletion of elements is performed from _______________
end of the queue.
e) Elements ‘A’,’S’,’D’ and ‘F’ are present in the queue, and
they are deleted one at a time, ________________________
is the sequence of element received.
f) _______________ is a data structure where elements
can be added or removed at either end, but not in the
middle.
g) A deque contains ‘z’,’x’,’c’,’v’ and ‘b’ . Elements
received after deletion are ‘z’,’b’,’v’,’x’ and ‘c’. ________
__________________________ is the sequence of deletion
operation performed on deque.
Queue 65
2024-25
In this Chapter
»» Introduction
»» Bubble Sort
»» Selection Sort
»» Insertion Sort 5.1 Introduction
»» Time Complexity of Sorting is the process of ordering or arranging a
Algorithms given collection of elements in some particular
order. We can sort a collection of numbers in
ascending (increasing) or descending (decreasing)
order. If the collection is of strings, we can sort it
in an alphabetical order (a-z or z-a) or according
to the length of the string. For example, words in a
dictionary are sorted in alphabetical order; seats
in an examination hall are ordered according to
candidates’ roll number. We can also sort a list of
students based on their height or weight.
Imagine finding the meaning of a word from
a dictionary that is not ordered. We will have to
search for the word on each page till we find the
word, which will be very tedious. That is why
dictionaries have the words in alphabetical order
and it ease the process of searching.
2024-25
8 7 13 1 -9 4 7 8 1 -9 4 13
No Change Swap
7 8 13 1 -9 4 7 8 1 -9 4 13
Swap Swap
7 8 13 1 -9 4 7 1 8 -9 4 13
Swap Swap
7 8 1 13 -9 4 7 1 -9 8 4 13
Swap Swap
7 8 1 -9 13 4 7 1 -9 4 8 13
7 8 1 -9 4 13
7 1 -9 4 8 13 1 -9 4 7 8 13
Swap No Change
1 7 -9 4 8 13 -9 1 4 7 8 13
Swap
1 -9 7 4 8 13 -9 1 4 7 8 13
Swap
1 -9 4 7 8 13
Sorting 69
2024-25
-9 1 4 7 8 13
def bubble_Sort(list1):
n = len(list1)
for i in range(n): # Number of passes
for j in range(0, n-i-1):
# size -i-1 because last i elements are already sorted
#in previous passes
if list1[j] > list1[j+1] :
# Swap element at jth position with (j+1)th position
list1[j], list1[j+1] = list1[j+1], list1[j]
numList = [8, 7, 13, 1, -9, 4]
bubble_Sort(numList)
Sorting 71
2024-25
8 7 13 1 -9 4 -9 8 7 13 1 4
8 7 13 1 -9 4 -9 8 7 13 1 4
8 7 13 1 -9 4 -9 8 7 13 1 4
8 7 13 1 -9 4 -9 8 7 13 1 4
8 7 13 1 -9 4 -9 8 7 13 1 4
Swap
8 7 13 1 -9 4
-9 1 7 13 8 4
Swap
-9 8 7 13 1 4
-9 1 7 13 8 4 -9 1 4 13 8 7
-9 1 7 13 8 4 -9 1 4 13 8 7
-9 1 7 13 8 4 -9 1 4 13 8 7
Swap
-9 1 7 13 8 4 -9 1 4 7 8 13
Swap
-9 1 4 13 8 7
-9 1 4 7 8 13 Sorted List
Unsorted List
Sorting 73
2024-25
Output:
The sorted list is :
-9 1 4 7 8 13
numList 8 7 13 1 -9 4
Index
0 1 2 3 4 5
8 7 13 1 -9 4 7 8 13 1 -9 4
Swap
8 7 13 1 -9 4 7 8 13 1 -9 4
7 8 13 1 -9 4
7 8 13 1 -9 4 1 7 8 13 -9 4
Swap Swap
7 8 1 13 -9 4 1 7 8 -9 13 4
Swap Swap
7 1 8 13 -9 4 1 7 -9 8 13 4
Swap
1 7 8 13 -9 4 -9 1 7 8 13 4
-9 1 7 8 13 4
Sorting 75
2024-25
-9 1 7 8 4 13
Swap
-9 1 7 4 8 13
No Change
-9 1 4 7 8 13
-9 1 4 7 8 13
Activity 5.4
Step 3: temp = numList[i]
Consider a list of 10 Step 4: SET j = i-1
elements:
Array = Step 5: WHILE j> = 0 and numList[j]>temp,REPEAT
[7,11,3,10,17,23,1,4,21,5] STEPS 6 to 7
Determine the partially
sorted list after Step 6: numList[j+1] = numList[j]
three complete
passes of Step 7: SET j=j-1
insertion sort.
Step 8: numList[j+1] = temp #insert
temp at position j
Step 9: set i=i+1
def insertion_Sort(list3):
n= len(list3)
for i in range(n): # Traverse through all elements
temp = list3[i]
j = i-1
while j >=0 and temp< list3[j] :
list3[j+1] = list3[j]
j = j-1
list3[j+1] = temp
Output:
The sorted list is :
-9 1 4 7 8 13
Sorting 77
2024-25
Summary
• The process of placing or rearranging a collection
of elements into a particular order is known as
sorting.
• Bubble sort is the simplest sorting algorithm
that works by repeatedly swapping the adjacent
elements in case they are unordered in n-1 passes.
• In Selection Sort, the smallest element is selected
from the unsorted array and swapped with the
Exercise
1. Consider a list of 10 elements:
numList =[7,11,3,10,17,23,1,4,21,5].
Display the partially sorted list after three complete
passes of Bubble sort.
List 1 : 63 42 21 9
List 1: 2 3 5 7 11
List 2: 11 7 5 3 2
If the lists are sorted using Insertion sort then
which of the lists List1 or List 2 will make the minimum
number of comparisons? Justify using diagrammatic
representation.
4. Write a program using user defined functions that
accepts a List of numbers as an argument and finds its
median. (Hint : Use bubble sort to sort the accepted list.
If there are odd number of terms, the median is the
center term. If there are even number of terms, add the
two middle terms and divide by 2 get median)
Sorting 79
2024-25
In this Chapter
»» Introduction to Files
»» Types of Files
»» Opening and Closing a 2.1 Introduction to Files
Text File We have so far created programs in Python that
»» Writing to a Text File accept the input, manipulate it and display the
»» Reading from a Text File output. But that output is available only during
»» Setting Offsets in a File
execution of the program and input is to be
entered through the keyboard. This is because the
»» Creating and Traversing a
variables used in a program have a lifetime that
Text File
lasts till the time the program is under execution.
»» The Pickle Module What if we want to store the data that were input
as well as the generated output permanently so
that we can reuse it later? Usually, organisations
would want to permanently store information
about employees, inventory, sales, etc. to avoid
repetitive tasks of entering the same data. Hence,
data are stored permanently on secondary storage
devices for reusability. We store Python programs
written in script mode with a .py extension. Each
program is stored on the secondary device as a
file. Likewise, the data entered, and the output
can be stored permanently into a file.
2024-25
<r+> or <+r> Opens the file in both read and write mode. Beginning of the file
<w> Opens the file in write mode. If the file already exists, all the Beginning of the file
contents will be overwritten. If the file doesn’t exist, then a
new file will be created.
<wb+> or Opens the file in read,write and binary mode. If the file Beginning of the file
<+wb> already exists, the contents will be overwritten. If the file
doesn’t exist, then a new file will be created.
<a> Opens the file in append mode. If the file doesn’t exist, then End of the file
a new file will be created.
<a+> or <+a> Opens the file in append and read mode. If the file doesn’t End of the file
exist, then it will create a new file.
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
In the output, each string is returned as elements
of a list. However, if splitlines() is used instead of split(),
then each line is returned as element of a list, as shown
in the output below:
>>> for line in d:
words=line.splitlines()
print(words)
['Hello everyone']
['Writing multiline strings']
['This is the third line']
Let us now write a program that accepts a string
from the user and writes it to a text file. Thereafter,
the same program reads the text file and displays it on
the screen.
Program 2-1 Writing and reading to a text file
fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line)
fileobject.write('\n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'): break
print("The byte position of file object is ",fileobject.tell())
fileobject.seek(0) #places file object at beginning of file
print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()
In Program 2-5, the file will be read till the time end
of file is not reached and the output as shown in below
is displayed.
Output of Program 2-5:
>>>
RESTART: Path_to_file\Program2-5.py
WRITING DATA IN THE FILE
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Program 2-8 To perform basic operations on a binary file using pickle module
RECORD No. 1
Employee number : 11
Employee Name : D N Ravi
Basic Salary : 32600
Allowances : 4400
TOTAL SALARY : 37000
Do you wish to enter more records (y/n)? y
RECORD No. 2
Employee number : 12
Employee Name : Farida Ahmed
Basic Salary : 38250
Allowances : 5300
TOTAL SALARY : 43550
Do you wish to enter more records (y/n)? n
Record entry OVER
Record Number : 1
[11, 'D N Ravi', 32600, 4400, 37000]
Record Number : 2
[12, 'Farida Ahmed', 38250, 5300, 43550]
>>>
As each employee record is stored as a list in the
file empfile.dat, hence while reading the file, a list is
displayed showing record of each employee. Notice that
in Program 2-8, we have also used try.. except block to
handle the end-of-file exception.
Summary
• A file is a named location on a secondary storage
media where data are permanently stored for
later access.
• A text file contains only textual information
consisting of alphabets, numbers and other
Exercise
1. Differentiate between:
a) text file and binary file
b) readline() and readlines()
c) write() and writelines()
3. Write the file mode that will be used for opening the
following files. Also, write the Python statements to open
the following files:
a) a text file “example.txt” in both read and write mode
b) a binary file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
d) a binary file “btry.dat” in read only mode.
PREETI ARORA
DOEACC ‘A’ level, M.Sc–IT, M.Tech–IT
Sr. Computer Science Teacher
Happy learning!
COMPARATIVE ANALYSIS OF CLASS XII OLD AND NEW CBSE CURRICULUM
Computer Science (083)
UNIT OLD CURRICULUM (2019-20) NEW CURRICULUM (2020-21) CHANGES
Total weightage of this unit
30 Marks 40 Marks
increased by 10 Marks
Revision of the Basics of Python Revision of the Basics of Python No change
Functions: scope, parameter Functions: scope, parameter passing, mutable/
passing, mutable/immutable immutable properties of data objects, passing
properties of data objects, strings, lists, tuples, dictionaries to functions, math and string functions to
pass arrays to functions, return default parameters, positional parameters, be added
values, functions using libraries: return values, Functions using libraries:
mathematical and string functions. 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
(1) CSV Files– open, read
data from a text file, Appending data into a text
I: Computational Thinking File handling: open and close a file, and write functions
file, standard input/output and error streams,
and Programming read, write, and append to a file,
relative and absolute paths. Binary File: Basic
standard input, output, and error (2) Read from a csv file
operations on a binary file: Open(filename –
streams, relative and absolute and Write into a csv file
absolute or relative path, mode) / Close a binary
paths. using csv.reader ( ) and
file, pickle Module – methods load and dump;
csv.writerow( )
Read, Write/Create, Search, Append and Update
operations in a binary file.
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: create and Using Python libraries: create and import Python
No change
import Python libraries libraries.
Recursion: simple algorithms with Recursion: simple algorithms with recursion:
recursion: factorial, Fibonacci print a message forever, sum of first n natural
No change
numbers; recursion on arrays: numbers, factorial, Fibonacci numbers; recursion
binary search on arrays: binary search
Idea of efficiency: performance
defined as inversely proportional
to the wall clock time, count the
number of operations a piece of
code is performing, and measure Idea of efficiency: performance measurement in
No change
the time taken by a program. terms of the number of operations.
Example: take two different
programs for the same problem,
and understand how the efficient
one takes less time.
Data visualization using Pyplot: line
Entire Chapter removed
chart, pie chart, and bar chart.
Data-structures: Lists as covered in Class XI, Stacks –
Data-structures: lists, stacks,
Push, Pop using a list, Queues – Insert, Delete No change
queues.
using a list.
Total weightage of this unit
15 Marks 10 Marks
reduced by 5 marks
Evolution of Networking: ARPANET, Internet,
Interspace Different ways of sending data
across the network with reference to switching
(1) Evolution of
Structure of a network: Types of techniques (Circuit and Packet switching). Networking
networks: local area and wide Data Communication terminologies: Concept of
area (web and internet), new Channel, Bandwidth (Hz, KHz, MHz) and Data (2) Switching Techniques
II: Computer Networks technologies such as cloud and IoT, transfer rate (bps, Kbps, Mbps, Gbps, Tbps). (3) Data Communication
(Entire Unit reframed) public vs. private cloud, wired and Terminologies
wireless networks; concept of a Transmission media: Twisted pair cable,
client and server. coaxial cable, optical fibre, infrared, radio link,
microwave link and satellite link.
Network Topologies and types: Bus, Star, Tree,
(4) Topologies
Types of Network: PAN, LAN, WAN, MAN.
Network devices such as a NIC, Network devices: Modem, RJ45 connector,
(1) Three more Network
switch, hub, router, and access Ethernet Card, Router, Switch, Gateway, WiFi
devices added
point. card.
Network stack: amplitude and
frequency modulation, collision
in wireless networks, error Topics removed:
checking, and the notion of a MAC Network Protocol: TCP/IP, File Transfer Protocol (1) AM & FM
address, main idea of routing. IP (FTP), PPP, HTTP,SMTP, POP3,Remote Login (2) CSMA/CA & CD
addresses: (v4 and v6), routing (Telnet) and Internet, Wireless / Mobile
table, router, DNS, and web URLs, Communication protocol such as GSM, GPRS (3) Error Checking
TCP: basic idea of retransmission, and WLL. (4) Idea of Routing
and rate modulation when there (5) Network Congestion
is congestion (analogy to a road
network),
Protocols: 2G, 3G, 4G, Wi-Fi. What
makes a protocol have a higher
bandwidth?
Mobile Telecommunication Technologies: 1G,
Application layer: HTTP (basic 2G, 3G, 4G and 5G; Mobile processors; Electronic
idea), working of email, secure mail protocols such as SMTP, POP3, Protocols No major changes
communication: encryption and for Chat and Video Conferencing: VoIP, Wireless
certificates (HTTPS), network technologies such as Wi-Fi and WiMax
applications: remote desktop,
remote login, HTTP, FTP, SCP, SSH,
POP/IMAP, SMTP, VoIP, NFC.
Basic network tools: traceroute,
ping, ipconfig, nslookup, whois, Entire Topic removed
speed-test.
Network Security Concepts: Threats and
Mentioned Topics have been
prevention from Viruses, Worms, Trojan
added to this unit; taken
horse, Spams. Use of Cookies, Protection using
from Unit-4 (Society Law
Firewall, https; India IT Act, Cyber Law, Cyber
and Ethics)—old curriculum
Crimes, IPR issues, hacking.
Introduction to Web services: WWW, Hyper
Text Markup Language (HTML), Extensible
Markup Language (XML); Hyper Text Transfer
Newly-added topics
Protocol (HTTP); Domain Names; URL; Website,
Web browser, Web Servers; Web Hosting, Web
Scripting
E-commerce payment transactions using online
banking, mobile banking, payment apps and Newly-added topics
services.
Total weightage of this unit
15 Marks 20 Marks
increased by 5 marks
Write a minimal Django-based web
application that parses a GET and
Complete Chapter removed
POST request, and writes the fields
to a file—flat file and CSV file.
Interface of Python with an SQL database
Connecting SQL with Python Creating Database
Interface Python with an SQL
connectivity Applications Performing Insert, No change
database
Update, Delete queries Display data by using
fetchone(), fetchall(), rowcount()
Database Concepts: Introduction to database
concepts and its need. Relational data model:
III: Data Management 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
SQL commands: aggregation Manipulation Language; Data Types: number / The mentioned topics have
functions – having, group by, order decimal, character / varchar / varchar2, date; been added from Class XI
by. SQL commands: CREATE TABLE, DROP TABLE, previous curriculum
ALTER TABLE, UPDATE ....SET , INSERT, DELETE;
SELECT, DISTINCT, FROM, WHERE, IN, BETWEEN,
LIKE, NULL / IS NULL, ORDER BY, GROUP BY,
HAVING;
SQL Aggregate functions: SUM (), AVG (),
COUNT (), MAX () and MIN (); Joins: equi-join and
natural join
10 Marks 0 Marks No weightage
Intellectual property rights,
plagiarism, digital rights
management, and licensing
(Creative Commons, GPL and
Apache), open source, open data,
privacy.
Privacy laws, fraud; cyber-crime— Major Topics of this Unit
phishing, illegal downloads, have been added to
child pornography, scams; cyber Computer Networks.
IV: Society, Law and Ethics forensics, IT Act, 2000.
This Unit has been
Technology and society: completely removed.
understanding of societal issues
and cultural changes induced by
technology. E-waste management:
proper disposal of used electronic
gadgets.
Identity theft, unique ids, and
biometrics.
Gender and disability issues while
teaching and using computers.
RED - Removed Topics GREEN – Detailed added topics PURPLE – No Change BLUE - Added Topics
CONTENTS
For example,
To convert an imputed angle of 50 degrees to radians and vice versa.
Supplement – Computer Science with Python–XII
Practical Implementation–5
Write a Python program to calculate the area of a regular polygon.
For solving this problem, we have to understand the formula to be used first, which is given as:
Area of a Regular Polygon
n = number of sides
s = length of a side
s ns
Area =
π
4 tan
n
3.2
Practical Implementation–6
Write a Python program to find the roots of a quadratic function.
A quadratic equation is represented as: ax2 + bx + c = 0
Here, a, b and c are numbers, where a ≠ 0; and
x is to be calculated.
The roots of any quadratic equation are given by the formula:
x = [–b +/– sqrt(b^2 – 4ac)]/2a.
3.3
Practical Implementation–7
Write a Python program to calculate arc length of an angle.
In a planar geometry, an angle is a figure formed by two rays called the sides of the angle, sharing
a common endpoint known as the vertex of the angle. Angles formed by two rays lie in a plane, but
this plane does not have to be a Euclidean plane.
Ar
c
le
ng
th
q
θ
Arc length = 2pr
360
Supplement – Computer Science with Python–XII
Practical Implementation–8
Write a Python program to convert a binary number to decimal number.
A binary number is a number which is represented in the form of 0 and 1 (binary digits) only
and decimal number system, the contemporary number system used mathematically, constitutes
numbers from 0 to 9.
3.4
Also, a binary number system has 2 as its base while the decimal system has 10 as its base.
The method of conversion of a binary number to its decimal equivalent is:
1 1 0 1 1 0 1 1 Binary to Decimal
1 × 20 = 1 × 1 = 1
1 × 21 = 1 × 2 = 2
0 × 22 = 0 × 4 = 0
1 × 23 = 1 × 8 = 8
1 × 24 = 1 × 16 = 16
0 × 25 = 0 × 32 = 0
1 × 26 = 1 × 64 = 64
1 × 27 = 1 × 128 = 128
1 + 2 + 8 + 16 + 64 + 128 = 219
(11011011)2=(219)10
In the above program, the input taken from the user is converted to a list using the function list()
and gets stored inside variable b_num. The loop gets executed up to the length of the list, i.e., the
number of list elements. With every iteration, each digit is extracted or popped from the list using
Using Python Libraries (Additions)
function pop(). This extracted digit is checked for character as 1 and is raised to the power of 2.
Finally, the value gets printed which is in decimal format. In case the digit is 0, no execution takes
place since the product of any value with 0 results in 0 itself. Hence, the output is obtained as 219.
3.5
Practical Implementation–9
Write a Python function that takes a list of words and returns the length of the longest one.
“JSP”,”Computers”,”Python3”
Length 3 9 7
“Computers”
Supplement – Computer Science with Python–XII
In the above program, two inbuilt string functions, append() and sort(), have been used for adding
elements to an empty list, word_len, and the list elements are sorted in ascending order using
sort() method.
3.6
Practical Implementation–10
Write a Python program to capitalize first and last letters of each word of a given string.
Practical Implementation–11
Write a Python program to swap each character of a given string from lowercase to uppercase and
vice versa.
3.7
SOLVED QUESTIONS
40. Write a program that performs the following operations on a string:
(a) Prompt the user to input a string.
(b) Extract all the digits from the string.
(c) If there are digits in the inputted string:
• Calculate and display the sum of the digits.
• Also display:
▪ The original string
▪ The digits
▪ The sum of the digits
(d) If there are no digits:
• Display the original string along with the appropriate message: “No Digits are present”
Ans. str1 = input("Enter the string: ")
sum = 0
num = 0
if str1.isalpha() == False:
for i in str1:
if i.isdigit() == True:
num =num*10 + int(i)
sum += int(i)
print("Original String: ",str1)
print("Digits: ",num)
print("Sum of digits is: ",sum)
else:
print("Original String: ", str1, "has no digit")
41. Write a program with a user-defined function with string as a parameter which replaces all vowels in the
string with ‘*’.
Ans. #Function to replace all vowels in the string with '*'
def replaceVowel(st):
#Create an empty string
newstr = ''
for character in st:
#Check if next character is a vowel
if character in 'aeiouAEIOU':
#Replace vowel with *
newstr += '*'
else:
Supplement – Computer Science with Python–XII
newstr += character
return newstr
#End of function
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:", st)
print("The modified String is:", st1)
UNSOLVED QUESTIONS
27. Write a user-defined function to calculate the area of a triangle.
28. Write a user-defined function to convert a string with more than one word into title case string where
string is passed as parameter. (Title case means that the first letter of each word is capitalized.)
29. Write a function deleteChar() which takes two parameters—one is a string and the other is a character.
The function should create a new string after deleting all occurrences of the character from the string
and return the new string.
30. Write a program to print the number of occurrences of a substring into a line using built-in string function
find().
3.8
4 Data File Handling
(Additions)
Practical Implementation–19
Program to insert/append a record in the binary file “student.dat”.
Supplement – Computer Science with Python–XII
As shown in the above program, inserting and adding a record in student file begins with importing
pickle module. Then, iterating for the number of records to be added is done using while loop.
Input is accepted from the user for roll number, name and marks. These fetched values are saved
as a list to be appended. Once the record is created, it is appended to the binary file “student” using
the dump() method, which writes the object onto the opened file.
Finally the file is closed explicitly and the record is added into the student.dat file as shown in
the output. Since binary file contains unreadable characters, it becomes difficult to read and
understand, but it is directly used and understood by the computer.
4.2
Reading a record from a binary file
The following practical implementation illustrates how a record is read from a binary file.
Practical Implementation–20
Program to read a record from the binary file “student.dat”
The above program deals with reading the contents from binary file student using load() method
of pickle module. It is used to read the object from the opened file. The syntax for this is given by
the statement—
object = pickle.load(file)
Once the contents are read, it gets stored inside the object, stud_rec. All the data of the respective
fields from this object is held in the respective variables—roll_no, name and marks—and are finally
displayed as the output.
successful, appropriate message is displayed to the user as shown in the practical implementation
that follows.
4.3
Practical Implementation–21
Program to search a record from the binary file “student.dat” on the basis of roll number.
Once the record is found, the file pointer is moved to the beginning of the file using seek(0)
statement, and then the changed name is written to the file and the record is updated. seek()
method is used for random access to the file.
We will be learning more about it in the next section.
4.4
Practical Implementation–22
Write a menu-driven program to perform all the basic operations using dictionary on student
binary file such as inserting, reading, updating, searching and deleting a record.
4.5
Supplement – Computer Science with Python–XII
4.6
4.12 RANDOM ACCESS IN FILES USING TELL() AND SEEK()
Till now, in all our programs we laid stress on the sequential processing of data in a text and
binary file. But files in Python allow random access of the data as well using built-in methods
seek() and tell().
seek()—seek() function is used to change the position of the file handle (file pointer) to a given
specific position. File pointer is like a cursor, which defines from where the data has to be read
or written in the file.
Python file method seek() sets the file’s current position at the offset. This argument is optional
and defaults to 0, which means absolute file positioning. Other values are: 1, which signifies seek is
relative (may change) to the current position, and 2, which means seek is relative to the end of file.
There is no return value.
The reference point is defined by the “from_what” argument. It can have any of the three values:
0: sets the reference point at the beginning of the file, which is by default.
1: sets the reference point at the current file position.
2: sets the reference point at the end of the file.
seek() can be done in two ways:
• Absolute Positioning
• Relative Positioning
Absolute referencing using seek() gives the file number on which the file pointer has to position
itself. The syntax for seek() is—
f.seek(file_location) #where f is the file pointer
For example, f.seek(20) will give the position or file number where the file pointer has been placed.
This statement shall move the file pointer to 20th byte in the file no matter where you are.
Relative referencing/positioning has two arguments, offset and the position from which it has to
traverse. The syntax for relative referencing is:
f.seek(offset, from_what) #where f is file pointer
For example,
f.seek(–10,1) from current position, move 10 bytes backward
f.seek(10,1) from current position, move 10 bytes forward
f.seek(–20,1) from current position, move 20 bytes backward
f.seek(10,0) from beginning of file, move 10 bytes forward
Data File Handling (Additions)
POINT TO REMEMBER
It must be remembered that Python 3.x only supports text file seeks from the beginning of the file. seek()
with negative offset only works when the file is opened in binary mode.
tell()—tell() returns the current position of the file read/write pointer within the file. Its syntax is:
f.tell() #where f is file pointer
4.7
When you open a file in reading/writing mode, the file pointer rests at 0th byte.
When you open a file in append mode, the file pointer rests at the last byte.
This is illustrated in the practical implementation that follows:
Practical Implementation–23
Program to read byte by byte from a file using seek() and tell().
Contents of “test.txt”
Supplement – Computer Science with Python–XII
4.8
Files in the CSV format can be imported Spreadsheet
to and exported from programs that store
data in tables, such as Microsoft Excel or X
OpenOffice Calc.
Already defined, CSV stands for “comma CSV
separated values”. Thus, we can say DATA
that a comma separated file is a delimited
Database
text file that uses a comma to separate
Fig. 4.9: CSV Storage Format
values.
CSV
Each line in a file is known as data/record. Each record consists of one or more fields, separated
by commas (also known as delimiters), i.e., each of the records is also a part of this file. Tabular data
is stored as text in a CSV file. The use of comma as a field separator is the source of the name for
this file format. It stores our data into a spreadsheet or a database.
CTM: The most commonly used delimiter in a CSV file is usually a comma.
4.9
The solution to the above problem is CSV (Fig. 4.11(b)). Thus, CSV organizes data into a structured
form and, hence, the proper and systematic organization of this large amount of data is done by
CSV. Since CSV file formats are of plain text format, it makes it very easy for website developers to
create applications that implement CSV.
CSV files are commonly used because they are easy to read and manage, small in size, and fast
to process/transfer. Because of these salient features, they are frequently used in software
applications, ranging anywhere from online e-commerce stores to mobile apps to desktop tools.
For example, Magento, an e-commerce platform, is known for its support of CSV.
Thus, in a nutshell, the several advantages that are offered by CSV files are as follows:
• CSV is faster to handle.
• CSV is smaller in size.
• CSV is easy to generate and import onto a spreadsheet or database.
• CSV is human readable and easy to edit manually.
• CSV is simple to implement and parse.
• CSV is processed by almost all existing applications.
Supplement – Computer Science with Python–XII
After understanding the concept and importance of using CSV files, we will now discuss the read
and write operations on CSV files.
4.10
Like other files (text and binary) in Python, there are two basic operations that can be carried out
on a CSV file:
1. Reading from a CSV file
2. Writing to a CSV file
Let us discuss these CSV operations.
student.csv
student.xls
Data File Handling (Additions)
In student.csv (notepad) file, the first line is the header and remaining lines are the data/
records. The fields are separated by comma, or we may say the separator character. In general,
the separator character is called a delimiter, and the comma is not the only one used. Other
popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters.
4.11
Practical Implementation–24
Write a program to read the contents of “student.csv” file.
Explanation:
As seen from the above output, every record is stored in reader object in the form of a List.
In the above code, we first open the CSV file in READ mode. The file object is named f. The
file object is converted to csv.reader object. We save the csv.reader object as csv_reader. The
reader object is used to read records as lists from a csv file. Now, we iterate through all the
rows using a for loop. When we try to print each row, one can find that row is nothing but a list
containing all the field values. Thus, all the records are displayed as lists separated by comma.
Supplement – Computer Science with Python–XII
In the next implementation, we will count the number of records present inside the student.csv
file.
Practical Implementation–25
Write a program to read the contents of “student.csv” file using with open().
4.12
The above modified code uses “with open()” function, the only difference being that the file being
opened using with open() gets automatically closed after the program execution gets over, unlike
open() where we need to give close() statement explicitly.
Practical Implementation–26
Write a program to count the number of records present in “student.csv” file.
Explanation:
In the above program, a special type of object is created to access the CSV file (reader object), which
is csv_reader using the reader() function. The reader object is an iterable that gives us access to
each line of the CSV file as a list of fields. The function next() is used to directly point to this list of
fields to read the next line in the CSV file. .next() method returns the current row and advances the
iterator to the next row.
The variable ‘c’ is used as a counter variable to count the number of rows/records present in this
file, which is finally printed and thus the output is so obtained.
One of the important observations from the output is the number of records which is being
displayed as 11 instead of 10. This is so because the header (first line) in the student csv file is also
Data File Handling (Additions)
CTM: .next() method returns the current row and advances the iterator to the next row.
4.13
Practical Implementation–27
Program to count the exact number of records present in the csv file excluding the header.
In the above program we have used line_num object of CSV file. Our csv_reader_object has a method
called line_num that returns the number of lines in our CSV.
Then, if statement checks if the line is the first line or not. If the condition is true, i.e., if it is the
header line, then it is ignored using continue statement and the counting of records is resumed
from the second line onwards. Also, line_num object always stores the current line in consideration
and, hence, the correct output for 10 records is so obtained.
CTM: line_num is nothing but a counter which returns the number of rows which have been iterated.
Practical Implementation–28
Program to print the records in the form of comma separated values, instead of lists.
Supplement – Computer Science with Python–XII
4.14
In the above program, we have used a new function join(). join() is a string method that joins
all values of each row with comma separator. Thus, all the records are displayed as a string
separated by a comma separator and not as a list and hence the output is so obtained.
Practical Implementation–29
Program to search the record of a particular student from CSV file on the basis of inputted
name.
Till now we have covered the basics of how to use the CSV module to read the contents of a CSV file.
Now, we will discuss how to write to a CSV file in Python.
4.15
Let us write data onto a CSV file using writerow() method.
Practical Implementation–30
Program to write data onto “student” CSV file using writerow() method.
Supplement – Computer Science with Python–XII
4.16
Contents of “marks.csv” created:
Explanation:
In the above program, the very first line is for importing csv file into your program. Next, whatever
are the column headings for our data are mentioned as a list in the variable called fields. All the
data stored inside these fields is placed inside the variable called rows.
Now give the name of your file, let us say, student.csv. This will be created and stored inside
your current working directory or the path that you mentioned (as we have given for D:/) for the
attribute “filename”.
‘w’ stands for write mode and we are using the file by opening it using “with open”, since using
with open does not require the file to be closed explicitly. The next statement comprises the most
important function used for writing onto csv file, viz. csv.writer(), to obtain a writer object and
store it in the variable csv_w as the name of the variable, and this is the CSV object. writer() takes
the name of file object ‘f’ as the argument. By default, the delimiter is comma (,).
writerow(fields) is going to write the fields which are the column headings into the file and have to be
written only once. Using for loop, rows are traversed from the list of rows from the file. writerow(i)
is writing the data row-wise in the for loop and in the end the file is automatically closed.
Also, while giving csv.writer(), the delimiter taken is comma. We can change the delimiter whenever
and wherever required by changing the argument passed to delimiter attribute.
For example, delimiter = "|" (pipe symbol). You can put any character as delimiter and if nothing is
Data File Handling (Additions)
4.17
Practical Implementation–31
Program to write data onto "student" csv file using writerows() method (modification of Practical
Implementation–30).
Supplement – Computer Science with Python–XII
MEMORY BYTES
Files in Python are interpreted as a sequence or stream of bytes stored on some storage media.
The close() method of a file object flushes any unwritten information and closes the file object.
The rename() method is used to rename the file or folder.
SOLVED QUESTIONS
35. Write a Python code to find out the size of the file in bytes, number of lines and number of words.
Ans. # reading data from a file and find size, lines, words
f = open('Lines.txt', 'r')
str = f.read()
size = len(str)
print('size of file n bytes ', size)
f.seek(0)
L = f.readlines()
word = L.split()
print('Number of lines ', len(L))
print('Number of words ', len(word))
f.close()
36. Consider the following code:
f = open("test", "w+")
f.write("0123456789abcdef")
f.seek(-3,2) //Statement 1
print(f.read(2)) //Statement 2
Explain statement 1 and give output of statement 2.
Ans. Statement 1 uses seek() method that can be used to position the file object at a particular place in the file.
Its syntax is:
fileobject.seek(offset [, from_what])
So, f.seek(–3,2) positions the fileobject to 3 bytes before end of file.
Output of Statement 2 is:
de
It reads 2 bytes from where the file object is placed.
37. Yogendra intends to position the file pointer to the beginning of a text file. Write Python statement for
the same assuming “F” is the Fileobject.
Ans. F.seek(0)
Supplement – Computer Science with Python–XII
38. Differentiate between file modes r+ and rb+ with respect to Python.
Ans. r+ opens a file for both reading and writing. The file pointer is placed at the beginning of the file.
rb+ opens a file for both reading and writing in binary format. The file pointer is placed at the beginning
of the file.
39. In which of the following file modes will the existing data of the file not be lost?
rb, ab, w, w+b, a+b, wb, wb+, w+, r+
Ans. In file modes rb, ab, a+b and r+, data will not be lost.
In file modes w, w+b, wb, wb+ and w+, data will be truncated, i.e., lost.
40. Write a statement in Python to perform the following operations:
(a) To open a text file “Book.txt” in read mode
(b) To open a binary file “Book.dat” in write mode
Ans. (a) f = open("Book.txt", "r") (b) f = open("Book.dat", "wb")
41. What is a CSV file?
Ans. CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet
or database. A CSV file stores tabular data (numbers and text) in plain text.
4.20
42. What are the advantages of CSV file formats?
Ans. Advantages:
(a) A simple, compact and ubiquitous format for data storage.
(b) A common format for data interchange.
(c) It can be opened in popular spreadsheet packages like MS Excel, Cal, etc.
(d) Nearly all spreadsheets and databases support import/export to CSV format.
43. Differentiate between a text file and a binary file.
Ans. A text file stores data as ASCII/UNICODE characters whereas a binary file stores data in binary format
(as it is stored in memory). Internal conversion is required in text file and, hence, it is slower but binary
file does not need any translation and so is faster.
44. Write a program to add (append) Employee records onto a CSV file.
Ans. import csv
with open('myfile.csv',mode = 'a') as csvfile:
mywriter = csv.writer(csvfile, delimiter = ',')
ans = 'y'
while ans.lower() == 'y':
eno = int(input("Enter Employee Number:"))
name = input("Enter Employee Name:")
salary = int(input("Enter Employee Salary:"))
mywriter.writerow([eno,name,salary])
print("## Data Saved… ##")
ans = input("Add More?")
45. Write user-defined functions to perform read and write operations onto a student.csv file having fields
roll number, name, stream and marks.
Ans. import csv
row = ['2','Akshat Chauhan','Commerce','98']
def readcsv():
with open("D:/student.dat", 'r') as f:
data = csv.reader(f)
# reader function to generate a reader object
for row in data:
print(row)
def writecsv():
with open("D:/student.dat", 'w', newline='') as fobj:
# write new record in file
csv_w = csv.writer(fobj, delimiter=',')
csv_w.writerow(row)
print("Press-1 to Read Data and Press-2 to Write data: ")
a = int(input())
if a == 1:
readcsv()
elif a == 2:
writecsv()
else:
Data File Handling (Additions)
print("Invalid value")
46. Write a Python program to read specific columns from a “department.csv” file and print the content of
the columns, department id and department name.
Ans. import csv
with open('departments.csv', newline=") as csvfile:
data = csv.reader(csvfile)
print("ID Departmentalize")
print("---------------------------------")
for row in data:
print(row[0], row[1])
4.21
47. Explain briefly the CSV format of storing files.
Ans. The acronym CSV is short for Comma Separated Values, which refers to tabular data saved as plain text
where data values are separated by commas. In CSV format:
Each row of the table is stored in one row, i.e., the number of rows in a CSV file are equal to the
number of rows in the table (or sheet or database table, etc.).
The field values of a row are stored together with commas after every field value; but after the last
field’s value, no comma is given, just the end of line.
48. Write a menu-driven program implementing user-defined functions to perform different functions on a
csv file “student” such as:
(a) Write a single record to csv. (b) Write all the records in one single go onto the csv.
(c) Display the contents of the csv file.
Ans. import csv
# To create a CSV File by writing individual lines
def CreateCSV1():
# Open CSV File
Csvfile = open('student.csv', 'w', newline='')
# CSV Object for writing
Csvobj = csv.writer(Csvfile)
while True:
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Line = [Rno, Name, Marks]
# Writing a line in CSV file
Csvobj.writerow(Line)
Ch = input("More(Y/N)?")
if Ch == 'N':
break
Csvfile.close() # Closing a CSV File
# To create a CSV File by writing all lines in one go
def CreateCSV2():
# Open CSV File
Csvfile = open('student.csv', 'w', newline='')
# CSV Object for writing
Csvobj =csv.writer(Csvfile)
Lines = []
while True:
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Supplement – Computer Science with Python–XII
UNSOLVED QUESTIONS
31. Write appropriate statements to do the following:
(a) To open a file named “RESULT.DAT” for output.
(b) To go to the end of the file at any time.
32. Write a program to add two more employees’ details to the file “emp.txt” already stored in disk.
33. How are the following codes different from one another?
(a) fp = open("file.txt", 'r')
fp.read()
(b) fp=open("file.txt", 'r')
34. What is the output of the following code fragment? Explain.
fout = file("output.txt", 'w')
Data File Handling (Additions)
fout.write("Hello, world!\n")
fout.write("How are you?")
fout.close()
file("output.txt").read()
35. Write the output of the following code with justification if the contents of the file ABC.txt are:
Welcome to Python Programming!
f1 = file("ABC.txt", "r")
size = len(f1.read())
print(size)
data = f1.read(5)
print(data) 4.23
36. Anant has been asked to display all the students who have scored less than 40 for Remedial Classes. Write
a user-defined function to display all those students who have scored less than 40 from the binary file
“Student.dat”.
37. Give the output of the following snippet:
import pickle
list1, list2 = [2, 3, 4, 5, 6, 7, 8, 9, 10], []
for i in list1:
if (i%2==0 and i%4==0):
list2.append(i)
f = open("bin.dat","wb")
pickle.dump(list2, f)
f.close()
f = open("bin.dat", "rb")
data = pickle.load(f)
f.close()
for i in data:
print(i)
38. Following is the structure of each record in a data file named “PRODUCT.DAT”.
{"prod_code": value, "prod_desc": value, "stock": value}
The values for prod_code and prod_desc are strings and the value for stock is an integer.
Write a function in Python to update the file with a new value of stock. The stock and the product_code,
whose stock is to be updated, are to be inputted during the execution of the function.
39. Given a binary file “STUDENT.DAT”, containing records of the following type:
[S_Admno, S_Name, Percentage]
Where these three values are:
S_Admno – Admission Number of student (string)
S_Name – Name of student (string)
Percentage – Marks percentage of student (float)
Write a function in Python that would read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75.
40. Write a statement to open a binary file C:\Myfiles\Text1.txt in read and write mode by specifying for file
path in two different formats.
41. What are the advantages of saving data in : (i) binary form (ii) text form?
42. When do you think text files should be preferred over binary files?
43. Write a statement in Python to perform the following operations: [CBSE D 2016]
Supplement – Computer Science with Python–XII
(a) To open a text file “BOOK.TXT” in read mode (b) To open a text file “BOOK.TXT” in write mode
44. What is the following code doing?
File = open("contacts.csv", "a")
Name = input("Please enter name: ")
Phno = input("Please enter phone number: ")
File.write(name + ", " + phno + "\n")
45. Write code to open the file in the previous question and print it in the following form:
Name : <name> Phone: <phone number>
46. Consider the file “contacts.csv” created in the question above and figure out what the following code is
trying to do?
name = input("Enter name:")
file = open("contacts.csv", "r")
for line in file:
if name in line:
print(line)
47. Create a CSV file “Groceries” to store information of different items existing in a shop. The information is
to be stored w.r.t. each item code, name, price, qty. Write a program to accept the data from user and
4.24 store it permanently in CSV file.
8 Computer Networks
8.1 INTRODUCTION
The greatest breakthrough in technology and communication over the past 20 years has been the
development and advancement of the computer network. From emailing a friend, to online bill
payment, to downloading data from the internet, to e-commerce, networking has made our world
much smaller and forever changed the way we communicate.
Network provides salient features which have made our life easy and comfortable, be it sending an
email, withdrawing money from an ATM machine, online railway or airline reservation, or sharing
audio and video files. Apart from these, the most extensively-used feature is the Print command
sent from a computer to get a printout from a printer attached to some other computer. All this
involves a network.
It is the network that connects various computers to each other and handles a large volume of data.
CTM: A computer network is a collection of interconnected computers and other devices to share data and
other resources (hardware and software resources).
8.2.1 Advantages of Computer Networks
Internet
Domain
DNS & Data Storage
Firewall
Wi-Fi
Router
Server
User PC
Printer
Printer
other system. This allows printing of documents by several users and, hence, the printer is
shared by multiple users on the network. Other resources like hard disk, DVD drive, scanner,
etc., can also be shared on a computer network. For example, sharing database, audio and
video files, antivirus software, application software, printers and scanners, etc.
(b) Improved Communication: A computer network enables fast, reliable and secure
communication between users. It saves time and offers easy communication methods.
For example, in an organization, managers work at different locations to make financial reports.
While working on a network, any change made by one manager on his/her computer can easily
be seen by other managers and employees. Thus, a network allows managers to easily update
information. This increases their efficiency and allows them to complete their work quickly.
(c) Reduced Communication Cost: Sharing resources also reduces communication cost. Using
public networks, we can send a large quantity of data at a low cost. Internet and mobile
networks are playing a very important role in sending and receiving text, image, audio and
video data at a low cost.
(d) Reliability of Data: Reliability means backing up of data, i.e., data can be copied and
stored on multiple computers. In a network system, all computers are connected to each
8.2
other. Thus, the information or message which is shared by each device is stored on their
respective workstations (computers). If, due to some reason (hardware crash, etc.), the data
gets corrupted and, thus, becomes unavailable on one computer, a copy of the same data can
be accessed from another workstation for future use. This leads to smooth functioning and
further processing without disruption.
(e) Central Storage of Data: Files can be stored on a central node (the file server) that can
be shared and made available to each and every user in an organization. With centralized
processing, data is stored and retrieved from a single central location. Thus, there is no
duplication of data and almost no data redundancy.
Before we learn about the basic underlying structure of the internet, e.g., domain name servers,
network access points and backbones, we first need to understand how our computer connects
to others.
8.4
Every computer that is connected to the internet is part of a network, even the one in our home.
For example, we may use a modem and dial a local number to connect to an Internet Service
Provider (ISP). At work, a computer may be part of a Local Area Network (LAN), but it most
likely still connects to the internet using an ISP that the company has contracted with. When
it connects to the ISP, it becomes part of their network. The ISP may then connect to a larger
network and become part of their network. The internet is simply a network of networks.
Most large communication companies have their own dedicated backbones connecting various
regions. In each region, the company has a Point of Presence (POP). The POP is a place for
local users to access the company’s network, often through a local phone number or dedicated
line. The amazing thing here is that there is no overall controlling network. Instead, there are
several high-level networks connecting to each other through Network Access Points or NAPs.
Backbone
Internet
T3 Line
ISP NAP
LAN
Home Business
Computer
Printer
iPad
Supplement – Computer Science with Python–XII
8.6
(c) Parallel Communication
• When data is transmitted through multiple wires, with each wire carrying each bit, it
is called parallel communication.
(d) Serial Communication
• When bits are sent one after another in a series along a wire, it is called serial
communication.
10001----------------10001
(e) Synchronous or Asynchronous Transmission
• When sender and receiver synchronize their checks before transmission, i.e., the
sender first sends control characters to the receiver and then sends the actual data,
it is called synchronous transmission.
Advantage—Faster than asynchronous mode.
Disadvantage—Costly and complex set-up required.
• In asynchronous transmission, data is preceded and succeeded by a start bit and stop
bit respectively. No synchronization is required.
Advantage—Hardware required is simple and cheap.
Disadvantage—Slower than synchronous mode.
CTM: The technique of sending data across the network is known as Switching technique. The three types
of techniques used are circuit switching, packet switching and message switching.
8.7
1. Circuit Switching
Circuit switching provides end-to-end connection between two computers. It is established
usually in a telephone network where one person is making a call and another is receiving a call.
In a telephone system, the communication must be established between the two participants,
i.e., the sender and the receiver. The circuit is established between these two participants
before the transfer of data takes place.
Receiver Caller
Fig. 8.6: Circuit Switching
In this technique, the entire link remains dedicated and no other user can use it even if the
path remains idle. The following actions take place during circuit switching:
(a) A request signal is sent by the sender to set up the connection with the receiver. It establishes
a physical connection between the two participants.
(b) All intermediate nodes are identified. These nodes are also called switching nodes.
(c) If the destination node is available, it sends back the acknowledgement of receiving a signal.
Hence, data transmission begins.
(d) When the data transmission is complete, the call can be terminated.
CTM: Circuit switching is a connection-oriented service. In this technique, there is a dedicated link between
the sender and the receiver and no other call can be made during this link, even if the link remains idle.
2. Packet Switching
In packet switching technique, the entire data is divided into small fragments called packets.
Each packet is of a fixed size, usually 128 bytes or 512 bytes. Packet switching is similar to post
Supplement – Computer Science with Python–XII
office operation. Each packet has a source address as well as destination address (IP address)
for being transmitted, in the same way as a postman delivers a letter to a specific destination
address.
As there is no direct connection established between the sender and the receiver, each
packet follows different routes and, therefore, the packets are delivered in a random order
at the destination address. It is the TCP protocol which then arranges all received packets in
a sequential order. During the transfer of packets, each packet has to pass through several
intermediate nodes, so each intermediate node checks for destination IP address. If the packet
matches with the node address, it is received; otherwise, it is passed on to the next node until
it reaches the destination IP address.
8.8
Mainframe
Caller
Receiver
CTM: Packet switching offers a connectionless service. Data is fragmented into small packets and each
packet is of fixed size in packet switching technology.
3. Message Switching
In message switching, the sender sends the data to a switching office first, which is then stored
in its buffer. It then checks the available link and, if it is free, the data is relayed to another
switching office. This process goes on until the data is sent to the destination (receiver). As the
data is first stored in a buffer and then sent to the next switching office, it is also called store
and forward switching technique.
CTM: Message switching is a store and forward switching technique where there is no direct connection
between the sender and the receiver.
the same order as it is originally sent. In packet switching, the message is broken into
small packets which are randomly sent from source and received in random order at
destination, which is then sequentially arranged.
8.9
8.8 DATA COMMUNICATION TERMINOLOGIES
1. Channel: A channel is a communication path through which the data is transmitted from
the sender device to the receiver device.
2. Baud: The number of changes in a signal per second is known as baud. It is the measuring
unit of the data transfer rate. Technically, baud refers to a number of discrete signal
elements transmitted per second. 1 baud represents only 1 signal change per second and
is equivalent to 1 bit per second.
3. Bandwidth: The amount of data that can be passed along a communication channel in a
given period of time (1 second) is termed as bandwidth. The measuring unit is hertz (Hz),
where 103 Hz = 1 Kilo Hertz (KHz), 103 KHz = 1 Mega Hertz (MHz).
4. Data and Signals: Information that is stored within computer systems and transferred
over a computer network can be divided into two categories—data and signals. Data are
entities that are stored in the form of 0’s and 1’s, which convey some special meaning
to the computer system. When this data is transmitted from one place to another, it is
converted into signal. Signals are the electric or electromagnetic encoding of data and are
used to transmit data.
5. Communication/Transmission Media: It is a means of communication or access (lines
of communication) set up between two organizations to exchange data/information.
Communication media is the way of transmitting the signal from one place to another.
Communication media is also known as transmission media. It plays an important role in
sending and receiving of data to and from the sender and receiver.
6. Data Transfer Rate: It is the amount of data transferred in one direction over a link divided
by the time taken to transfer it in bits per second (bps). The various measuring units are
bits per second (bps) and bytes per second (Bps) or baud, kilobits per second (kbps),
megabits per second (mbps), gigabits per second (gbps), terabits per second (tbps.)
CTM: RJ-45 is a short term for Registered Jack-45. It is an eight-wire connector used to connect computers
on LANs, especially Ethernets.
3. Ethernet Card: It is a hardware device that helps in the connection of nodes within a network.
Ethernet card is also known as a network card, network adapter or NIC (network interface
card). It is a card that allows computers to communicate over a computer network. On
Ethernet card, a physical address of each communicating computer is mentioned. Physical
address is known as MAC address.
8.10
4. Hub: It is multi-port and unintelligent network device which simply transfers data from
one port of the network to another. A hub is a hardware device used to connect several
computers together with different ports. When the packet reaches one port, it is copied to
all other ports of the hub without changing the destination address in the frame. Rather,
it simply copies the data to all of the nodes connected to the hub.
Hubs can be either active or passive. Hubs can usually support 8, 12 or 24 RJ-45 ports.
But the problem with hub is that it is not an intelligent device. It shares bandwidth with
all the attached devices and broadcasts the data, i.e., sends the data frames to all the
connected nodes, as it does not remember devices/computers connected to it. Also, it
cannot filter the data and causes unnecessary traffic jams.
A hub can both send as well as receive information, but only one task at a time. However, a
hub is an inexpensive way to connect multiple nodes/devices to network.
CTM: Hub is a device used to connect several computers with each other.
5. Switch: A switch (switching hub) is a network device which is used to interconnect computers
or devices on a network. It filters and forwards data packets across a network. It is also a
multi-port device but with some intelligence and so the data packets received from one port
of network are refreshed and delivered to the other port of the network. The main difference
between hub and switch is that hub replicates what it receives on one port onto all the other
ports, while switch keeps a record of the MAC addresses of the devices attached to it.
6. Bridge: A bridge is a device that works on the physical layer as well as on data link layer. A
network bridge connects multiple network segments at the data link layer (layer 2) of the
OSI model. Bridges relay frames between two originally separate segments. When a frame
enters a bridge, the bridge not only regenerates the signal but also checks the physical
address of the destination and forwards the new copy only to that port.
8.11
An important advantage of using a bridge is that it is a smarter hub as it can filter network
traffic on the basis of the MAC addresses.
PC 4 PC 5 PC 4 PC 5
PC 1 PC 2 PC 3 PC 1 PC 2 PC 3
Fig. 8.10: Ethernet Bridge
CTM: A bridge is a device that links two segments together of the original network.
7. Gateway: A gateway is a device that connects dissimilar networks. In internet, several networks
are communicating with each other and each network has a different configuration. In
order to make reliable communication, there must be a device that helps in communicating.
Gateway is a device which establishes an intelligent connection between a local area network
and external networks with completely different structures.
******** Workstation
Supplement – Computer Science with Python–XII
Gateway
8. Repeater: A repeater is a device that operates only on the physical layer of the OSI model. As
a signal travels a fixed distance, before attenuation of the signal, a repeater is used which
amplifies and restores signals for long-distance transmission. A repeater is an electronic
device that receives a signal before it becomes too weak and regenerates the original
signal. Also, it is a two-port network device that strengthens the signal intensity and
connects two identical networks. In most twisted pair Ethernet configurations, repeaters
are required for cable runs longer than 100 metres. A repeater does not change the
functionality of the network; instead, it makes the signal strong before it degrades.
Repeaters are also extensively used in broadcasting where they are termed as translators
8.12 or boosters.
Weakened Signal Regenerated Signal
Repeater
Repeater
No signal
through the hill
CTM: Repeater is a device that amplifies a signal that is transmitted across the network so that the signal is
received in the same way as it is sent.
9. Router: A router is a networking device that forwards data packets from the source
machine to the destination machine by using the shortest path. Routers are used at the
network layer, which is the third layer of the OSI model.
INTERNET EXTENDING A NETWORK USING
A LAN CABLE CONNECTION AND A SECOND ROUTER
Secondary
Main Router Router
LAPTOP LAPTOP
MOBILE TAB TAB MOBILE
CTM: A router is a networking device that helps in forwarding packets from one machine to another.
10. Wi-Fi Card: A Wi-Fi card is either an internal or external Local Area Network adapter with a
Computer Networks
built-in wireless radio and antenna. A Wi-Fi card is used in a desktop computer that enables
a user to establish an internet connection. Wi-Fi cards are known as wireless fidelity cards
as they allow the user to set up connection without any wire. Wireless Fidelity (Wi-Fi)
cards are widely used in notebook computers due to their highly portable nature. The most
common Wi-Fi cards used in desktop computers are PCI-Express Wi-Fi cards made to fit
the PCI-Express card slots on the motherboard. 8.13
8.10 TYPES OF NETWORKS
A computer network may be small or big depending upon the number of computers and other
network devices linked together. Thus, networks vary in size, complexity and geographical spread.
A computer network can be on a table, in a room, building, city, country, across continents or
around the world.
On the basis of geographical spread, networks may be classified as:
1. PAN
2. LAN
3. MAN
4. WAN
10 Metres
Supplement – Computer Science with Python–XII
CTM: The network that belongs to a single person or user is known as PAN.
CAMPUS
LAN in Building
LAN in Campus
Data transfer rate speed over a Local Area Network can vary from 10 mbps to 1 gbps.
SOHO
Base station customer
Residential
customer
Multi-tenant
customers
Computer Networks
Repeater
SME
customer
Base station
Wide Area
Network (WAN)
Satellite
Metropolitan
Area Network
(MAN)
Local Area
Personal Area Network (LAN)
Network (PAN)
The following table summarizes the characteristics of PANs, LANs, MANs and WANs.
Parameter PAN LAN MAN WAN
Area covered Small area A building or campus A city (up to Entire country,
(up to 10 m (up to 10 km) 100 km radius) continent or globe
Supplement – Computer Science with Python–XII
radius)
Networking Negligible Inexpensive Expensive Very expensive
cost
Transmission High speed High speed Moderate speed Low speed
speed
Error rate Lowest Lowest Moderate Highest
Network WLAN, USB LAN/WLAN, Hub/ Router, Gateway Router, Gateway
devices used Dongle Switch, Repeater,
Modem
Technology/ Infrared, Bluetooth Ethernet, Wi-Fi Optical fibre, Microwave Satellite
media used Radio-wave,
Microwave
CTM: LAN and WAN are the two primary and best-known categories of area networks; the others have
emerged with technological advances.
8.16
Comparing LAN and WAN
As we have seen, computer networks can be classified into LAN, MAN and WAN categories on
the basis of their geographical domains. A WAN extends over a large geographical area, such as
states or countries. A LAN is confined to relatively smaller areas, such as an office, a building,
etc. A MAN usually covers an entire city. It uses the LAN technology. The most common example
of MAN is the cable television network. Thus, the basic points of difference between LAN and
WAN are as follows:
1. The distance between the nodes in a LAN connection is limited to a specific range. The upper
limit is approximately 10 kilometres and the lower limit is one metre. On the other hand,
WANs are spread across thousands of kilometres in different countries or regions.
2. LANs operate between speeds of 1 mega bit per second (mbps) and 10 mbps while WANs
operate at speeds of less than 1 mbps. To achieve speeds of several hundred mbps, it is
advisable to use the optical fibre technology.
3. The error rate in LANs is lower than that in WANs because of the short distances involved in
LANs. The error rate in LANs is approximately one thousand times less than that in WANs.
4. As LANs are limited by distance, an entire LAN is usually under the control of a single entity,
such as an organization. On the other hand, WANs are usually operated and controlled by
multiple organizations.
Thus, we can say that in comparison to WANs, LANs cover a limited area but they operate with
high speed and low error rates.
CTM: Topology is a way of connecting several devices with each other on a network.
Types of Topologies
Basically, there are five types of topologies and each topology has some advantages and disadvantages.
Types of Topology
Mesh Topology Star Topology Bus Topology Ring Topology Tree Topology
point link between each dedicated node (workstation). In this type of topology, the link carries
traffic only between the two connected devices. A fully connected mesh network has n(n–1)/2
links, where n is the total number of connecting nodes.
For example, if there are five computers and each is connected with the other one, then there
will be 5(5–1)/2=10 links.
8.17
Fig. 8.19: Mesh Topology
CTM: When there is a point-to-point link between each computer in a network, it forms mesh topology.
Supplement – Computer Science with Python–XII
BACKBONE
Nodes
Dropline
Computer Networks
Therefore, there should be a limited number of nodes connected to a line. Ethernet is a common
example of bus topology.
8.19
Advantages of Bus Topology
(a) Nodes can be connected or removed easily from bus network.
(b) It requires less cable length than a star topology.
(c) Bus network is easy to implement and can be extended up to a certain limit.
(d) It works well for small networks.
CTM: There is a main cable which is connected to several workstations through taps. Collision of data can
take place in bus topology.
CTM: In ring topology, each workstation is connected with the predecessor node as well as with the
successor node and, thus, forms a ring. Data is transmitted only in one direction.
(b) Owing to its size and complexity, maintenance is not easy and costs are high. Also,
configuration is difficult in comparison to other topologies.
(c) Though it is scalable, the number of nodes that can be added depends on the capacity of the
central bus and on the cable type.
8.21
CTM: In tree topology, the main central hub is connected to the secondary hub through which all devices
are connected with each other. Tree topology is just like a parent-child relationship.
The decision to select a particular topology for a network does not take place in isolation as
the topology determines the type of media and access methods that would be used on the
network. Therefore, several factors are taken into consideration before selecting a topology
which are as follows:
Cost: Cost signifies that the network should be cost-effective. For this, it is required to
minimize the installation cost. This can be done by selecting an economical transmission
medium (that is, wires) for data exchange between the network nodes. The network cost
can also be minimized by reducing the distances between the nodes.
Flexibility: Flexibility signifies that the network must be flexible enough, i.e., it should be
easy to reconfigure. Reconfiguring a network means to rearrange the existing nodes or add
new ones on the network.
Reliability: It refers to the degree of trust that can be placed on a network. Like any
other system, a network can also encounter failure. A network failure can occur due to the
following causes:
1. When an individual node stops working.
2. When the entire network fails. This is caused by a more serious fault that stops the
working of an individual node.
A B
Supplement – Computer Science with Python–XII
Receive Transmit
Fig. 8.24: A Point-to-Point Link
For better performance, the transmit and receive operations can occur over separate cables or
wires, or they can occur in turns over the same wire by using different transmission techniques.
A P-P link can be established in several ways. The simplest way is to install a P-P link between
each pair of computers over a network.
CTM: Communication media is a transmission media used for sending data or signal across the network.
8.22
Types of Communication/Transmission Media
All communication/transmission media can be divided into two categories:
Communication
Media
Guided Media (Wired Media): Guided media are also known as physical or conducted
media. These media use wires for transmitting data. Various wired connections are twisted
pair wire, coaxial cable and fibre optic cable.
Unguided Media (Wireless Media): A transmission media that does not require the use of
cables for transmission of data is known as unguided media. Wireless transmission is also
known as unguided media or non-physical media as the transmission takes place through
various types of electromagnetic waves, such as radio waves, terrestrial microwave
transmissions, satellite transmissions, cellular radio systems, infrared transmissions, etc.
use. In computer networks, mostly Cat-5, Cat-5E and Cat-6 cables are used. UTP cables
are connected by RJ-45 connectors.
2. Coaxial Cable
A coaxial cable is generally called a coax wire. It consists braided shield foil shield
of insulated copper wires surrounded by a braided centre
metal shield and covered in a plastic jacket. Coax cables conductor
are capable of carrying higher frequency signals than
twisted pair cables. The wrapped structure provides
it a good shield against noise and crosstalk. Coaxial
cables provide high bandwidth rates of up to 450 mbps. outer jacket dielectric
Coaxial cable also comes in two primary physical types: Fig. 8.27: Coaxial Cable
thin coaxial cable and thick coaxial cable. There
are three categories of Coax cables, namely RG-59 (Cable TV), RG-58 (Thin Ethernet) and
RG-11 (Thick Ethernet). RG stands for Radio Guide. Coax cables are widely used for internet
connections and cable televisions.
(a) Coaxial cable can support greater cable lengths between network devices than twisted pair
cable.
(b) It is useful for transmitting analog as well as digital data across the network. For analog
data transmission, 75 ohm broadband coaxial is used and for digital transmission, 50 ohm
baseband cable is used.
(c) It is widely used for cable television and internet connections.
(d) Coax are used for transmitting several channels simultaneously, i.e., they are helpful in
broadband transmission.
(e) Coaxial cable has excellent noise immunity because of thick covering outside the insulated
wires.
(f) Thick coaxial cable has an extra protective plastic cover that helps keep moisture away.
(g) It is relatively inexpensive as compared to fibre optic cable.
8.24
Disadvantages of Coaxial Cable
(a) A thick coaxial cable does not bend easily and thus is difficult to install.
(b) It is expensive as compared to twisted pair cable.
Jacket
Cladding
Buffer
Coating Core
1. Microwave
Microwave signals are used to transmit data without the use of cable. It is a line-of-sight
transmission as signal travels in a straight line. In microwave communication, two directional
parabolic antennas are mounted on towers, buildings or hills to send and receive signals
through air. However, they must be properly aligned with each other, otherwise the signal will
not be focused well at the receiving antenna.
Secondary
Path
Direct Path
(a) It is a cheaper source of communication as it avoids using cables and maintaining repeaters.
(b) Communication through microwave is much easier over difficult terrain.
(c) Microwave system permits data transmission rate of about 16 gigabits per second.
8.26
2. Radio Waves Radio
Tower
Radio waves use radio frequencies which
are allocated to private businesses for direct
voice communication. A radio set-up uses
transmitter and receiver. A transmitter sends
radio waves and encodes them into sine
waves which, when received by a receiver, are
decoded and the message is received. Both
the transmitter and receiver use antennas
to radiate and fetch radio signals. They are
Sender Receiver
not line-of-sight transmission and, hence, can
penetrate buildings easily.
(b) They are omnidirectional and can travel Fig. 8.30: Radio Waves
in any direction.
(c) Transmitter and receiver antenna do not need to be physically aligned.
(d) Radio wave transmission offers mobility.
(e) It is cheaper than laying cables and fibres.
(f) It offers ease of communication over difficult terrain.
3. Satellite Link
Satellite transmission is also a kind of line-of-sight
transmission that is used to transmit signals
throughout the world. When the frequency is
greater than 3 GHz, the transmission is known as Receiving
Transmitting signal
microwave. Satellite is a special type of microwave signal 35000 km
transmission medium.
Up-link Down-link
It provides various types of services such as
transmitting fax, voice data, video, email and other
Transmitting Receiving
internet applications. In satellite communication, Antenna Antenna
an earth station has a satellite dish, which functions
as an antenna to transmit and receive data from
Fig. 8.31: Satellite Link
satellites.
Computer Networks
When data is transmitted from an earth station to a satellite, it is known as uplink and when
transmission takes place from a satellite to an earth station, it is known as downlink. In satellite,
there are transponders that send and receive signals from/to the earth station.
8.27
Advantages of Satellite Link
(a) The area covered is quite large.
(b) No line-of-sight restrictions such as natural mountains, tall buildings, towers, etc.
(c) Earth station which receives the signals can be at a fixed position or can be relatively mobile.
4. Infrared
The type of transmission that uses infrared light to send data is known as infrared transmission.
The data is transmitted through air and can propagate in the open space; however, it cannot
penetrate the walls of the room. It is an example of short range wireless network. Infrared
speed varies from 2.4 kbps to 16 mbps. A very good example of infrared transmission is a
handheld remote control such as remote control of a TV or AC, etc.
Housing Shield
Transmitter Transmitter
Receiver Receiver
Supplement – Computer Science with Python–XII
Lens
8.28
5. Wireless Technology
Wireless technology is the process of sending information through invisible waves in the
air. Information such as data, voice and video are carried through the radio frequency of
the electromagnetic spectrum. Thus, wireless communication is the transfer of information
between two or more points that are not connected by an electrical conductor. The various
wireless technologies available are described as follows:
(a) Wi-Fi (Wireless Fidelity): Wi-Fi is wireless fidelity where communication takes place
without wires. The users share the data with each other by connecting to the broadband
internet service without using cables. As it is not a secured media of transmitting data, the
user must use privacy methods such as using passwords and make the connection security
enabled so that it does not become susceptible to hackers. For transmission of data through
Wi-Fi, a user must have a broadband connection, a wireless router and a laptop or desktop.
(b) Wi-Max (Worldwide Interoperability for Microwave Access): Wi-Max is a wireless
communication system that provides broadband internet accessibility up to 30 miles. The
data transmission takes place without wires. It provides data rates up to 30 to 40 megabit-
per-second and up to 1 Gbit/s for fixed stations. Wi-Max is based on standard IEEE
802.16 technology that provides users with access to high-speed voice, data and internet
connectivity. Wi-Max uses broadband internet connection and requires a tower known as
base station to communicate with the user. Instead of wires, it uses a microwave link to
establish a connection. Internet connectivity to end-user is provided by a microwave link
between the tower and the end-user.
Types of Protocols
Protocol specifies what is communicated and how. Let us take an example to explain this
concept. In India, different people speak different languages. Now, a person from Tamil
Nadu and a person from Punjab may not be able to communicate with each other because
of the language difference. However, they can exchange their ideas and communicate with
Supplement – Computer Science with Python–XII
each other using English as their common language. Similarly, in case of computers, the
hardware, software or even a combination of the two might be required to implement and
carry out the protocol. Thus, the protocol will help in setting up a channel of communication
or a connection between two computers; in other words, a hardware connection between
two computers.
There are multiple protocols defined for computer networks, which are as follows:
(a) TCP (Transmission Control Protocol)
(b) IP (Internet Protocol)
(c) FTP (File Transfer Protocol)
(d) PPP (Point-to-Point Protocol)
(e) SMTP (Simple Mail Transfer Protocol)
(f) POP3 (Post Office Protocol)
(g) TELNET (Remote Login)
8.30
(a) TCP/IP (Transmission Control Protocol/Internet Protocol)
TCP is one of the main protocols in TCP/IP networks. The IP protocol deals only with
packets but TCP enables two hosts to establish a connection and exchange streams
of data. TCP works with the Internet Protocol (IP), which defines how computers
send packets of data to each other. The packets are delivered not in a sequential
order; instead, they are delivered randomly. Now, TCP at the receiver side collects
all packets and arranges them in a sequential order. TCP is a reliable stream delivery
service that guarantees that all bytes received will be identical with bytes sent and
in the correct order. Since packets are transferred over many networks and, thus,
not reliable, a technique known as positive acknowledgement with retransmission
is used to guarantee reliability of packet transfers.
(b) IP (Internet Protocol)
IP is the primary protocol present in the internet layer of the internet protocol suite.
It is responsible for delivering packets from the source host to the destination host
based on the IP addresses mentioned in the packet headers. IP forwards each packet
based on a four byte destination address (the IP number). The packets are moved
randomly from source to destination, which are then assembled in a sequential
order at the destination computer. IP stores destination addresses in the form of IP
addresses so that the packets will move to the destined address only by following
the shortest route.
(c) FTP (File Transfer Protocol)
FTP is the simplest and most secure way to exchange files over the internet. The main
objectives of FTP are:
• Transmitting and sharing of files (computer programs and/or data).
• Indirect or implicit use of remote computers.
• To shield a user from variations in file storage systems among different hosts.
• To transfer data reliably and efficiently.
• FTP uses the internet’s TCP/IP protocols to enable data transfer.
FTP is most commonly used to download a file from a server using the internet or to
upload a file to a server (e.g., uploading a web page file to a server).
While sharing files from one system to another, we may encounter several problems—
two systems may have different directory structures, two systems may have different
file-naming conventions, or two systems may have different ways to represent text
and data. All these problems are solved by FTP.
CTM: File transfer protocol is used to transfer files from server system to requesting node, primarily for
information sharing.
Computer Networks
The POP (Post Office Protocol 3) is a simple and standard method to access mailbox
and download messages to the local computers. The user can receive messages with
the help of POP protocol. The advantage is that once the messages are downloaded,
an internet connection is no longer needed to read the mail. A user can read all
emails offline as these are saved on the computer’s hard disk.
Just like with the SMTP protocol, the POP protocol (POP2 and POP3) sends text
commands to the POP server. There are two main versions of this protocol—POP2
and POP3—to which ports 109 and 110 respectively are allocated and which operate
using radically different text commands. To get a mail from POP server, a user must
enter a valid username and password for their email account. The POP3 protocol
thus manages authentication using the user name and password; however, it is not
secure because the passwords, like the email, circulate in plain text over the network.
POP3 protocol blocks inbox during its access which means that simultaneous access
to the same inbox by two users is impossible.
8.32
(g) TELNET (Remote Login)
Telnet is a remote login that helps a user to log on to another user’s terminal without
being its original user. A user who is logging in to their own system can also get
access to log on to another user system and perform various functions such as
accessing files or sharing files to/from the remote system. With TELNET, a user logs
in as a regular user with whatever privileges that may have been granted to the
specific application and data on that computer.
Working of Telnet
(i) A user is logged in to the local system and invokes a TELNET program (the
TELNET client) by typing telnet<host address> or telnet <IP address>
(ii) The TELNET client is started on the local machine (if it isn’t already running).
The client then establishes a TCP connection with the TELNET server on the
destination system.
(iii) Once the connection has been established, the client program accepts characters
from the keyboard feed by the user and passes one character at a time, to the
TELNET server.
(iv) The server on the destination machine accepts the characters sent to it by the
client and passes them to a terminal server.
(v) The terminal server gives outputs back to the TELNET server and displays them
on the user’s screen.
The user can terminate the telnet session by typing LOGOFF or LOGOUT on the
system prompt.
CTM: GSM is a wireless communication medium that provides the user with roaming facility, good voice
quality, SMS, etc., through digital signals.
CDMA stands for Code Division Multiple Access. CDMA is an example of multiple access, where
several transmitters can send information simultaneously over a single communication channel.
It is a channel access method used by various radio communication technologies. It allows the
division of transmission medium into different channels so that transmission from different
8.33
stations is separated from each other. It employs spread spectrum digital technology where
the data is fragmented into small chunks over a number of different frequencies available for
use. Analog to digital conversion takes place where audio input is first digitized into binary
elements. The CDMA system works directly on 64 kbit/sec digital signals.
CTM: CDMA is a digital cellular technology that uses spread spectrum technique where the entire
bandwidth is divided among several users for transmission of data.
CTM: GPRS provides high speed data transfer. A user is allowed to download video streaming, audio files,
email messages, etc.
order to get better voice quality. It employs the use of electromagnetic radiation to connect
subscribers to the local exchange without the use of wires. The user can use wireless phone,
speaker phone and parallel phones for communication with each other. In traditional telephone
networks, phone would be connected to the nearest exchange through a pair of copper wires.
But in Wireless Local Loop (wireless in local loop) technology, the subscriber is connected to
the nearest exchange through a radio link instead of copper wires. Wireless in local loop is
cheaper and quicker than copper wire connectivity. As the cost of copper along with the cost
of digging increases over time, this method proves cheaper than using copper wires. It is used
in remote areas where digging for copper wires is not possible.
There are various technologies like Frequency Division Multiple Access (FDMA), Time Division
Multiple Access (TDMA) and Code Division Multiple Access (CDMA) used for wireless in local
loop. In crowded urban localities where permission to dig may be almost impossible to get,
wireless technology is advised. However, there are also some disadvantages of using wireless
in local loop. First, as the distance between a receiver and transmitter increases in a wireless
8.34
system, the strength of the signal at the receiving end decreases even if there are no obstacles
in the way. Second, as the electromagnetic waves are propagated through air, a signal travelling
from a transmitter may take alternative paths on its way to the receiver. These paths may cause
delays in the received signal due to the extra distance travelled.
CTM: Wireless in local loop is a system that is similar to telephone system which provides wireless
telecommunication by deploying a multiplicity of multichannel transceivers.
2G Technology
2G technology is the first digital cellular system that was launched in the early 1990’s that
provides high data transmission rate in digital format. 2G also introduced data services
for mobiles, starting with SMS. For example, D-AMPS, GSM/GPRS, CDMAOne.
Salient features of 2G technology:
• Good quality of sound.
• Higher data rates up to 64 kbps.
• Improved security mechanism.
• Transmission of data such as text messages in digital format.
• Support transfer of picture messages and MMS.
• It does not support transfer of complex data such as videos.
• It allows multiple users per radio channel with each user talking one at a time.
• Digital transmissions enable compressed voice and multiplexing multiple users per channel.
3G Technology
3G technology was introduced in the year 2000 and provides much higher data rates with
Computer Networks
8.35
Salient features of 3G technology:
• It has introduced more efficient ways of carrying data with faster web services.
• Live chat, fast downloading, video conferencing, etc., are also possible over mobile phones.
• It allows the user to play 3D games.
• A user can see live streaming on smartphones.
• It provides broadband internet services.
• It allows the user to send and receive large email messages.
• High bandwidth is required.
• Splits channel into time intervals enabling a single user to get all the resources at once.
4G Technology
Unlike previous generations of mobile technology, 4G mobile technology uses ultra-high
broadband internet services with much faster data speed, typically between 100 mbps–
1gbps. Now, 4G rules the mobile market. Unlike previous generations of mobile technology,
4G mobile technology is used for internet access on computers also, and it is totally wireless.
4G provides internet access, high quality streaming video and “anytime, anywhere” voice
and data transmission at a much faster speed than 3G. The “anytime, anywhere” feature of
4G is also referred to as “MAGIC” (Mobile multimedia; Anytime/anywhere; Global mobility
support; Integrated wireless solution; Customized personal services).
Salient features of 4G technology:
• It is used for internet access on computers also and is totally wireless.
• 4G provides internet access, high quality streaming video and “anytime, anywhere” voice
and data transmission at a much faster speed than 3G.
• It delivers faster and better mobile broadband experiences.
• It provides more data capacity for richer content and more connections.
The “anytime, anywhere” feature of 4G is also referred to as “MAGIC” (Mobile multimedia)
anytime/anywhere.
• Apple W series is used in headphones for wireless audio connectivity. The current series,
Apple W1, is used in wireless headphones and AirPods.
• Apple T series is designed to be used in TouchID sensors in MacBook Pro. The only version
released till date is Apple T1.
8.37
8.16.3 Intel Atom and Core M Processors
Intel is an American multinational company synonymous with PC and
microprocessors. Atom is the brand name given for the low power-
consuming and low-cost 32-bit and 64-bit chips manufactured for
smartphones and tablets.
Intel processors are based on X86 architecture which is more powerful
than ARM but consumes more power compared to ARM architecture. The
latest versions of Intel processors have reduced the power consumption,
bringing it down to less than 5 watts, which is ideal for all mobile devices.
Though Atom processors in the beginning supported only Windows, they
now support all major mobile operating systems.
Intel Atom processors are currently used in Atom X5 and X7 series. These chips are 64-bit
quad core processors in 14 nm size with speeds of up to 1.6 GHz that can be scaled up to 2.4
Ghz. Intel also released Intel Core M ultra low-voltage microprocessors designed for ultra-thin
notebooks, mobile devices and 2-in-1 convertibles. The processor consumes 4.5 watts or less
power, making it ideal for long battery life. These are dual core processors with a speed of
about 1.5 GHz which can be scaled up to 3.2 GHz. Intel Core M processors offer 40% boost in
CPU and graphics performance as compared to the earlier versions.
The Tegra processors mainly used in smartphones and tablets are Tegra 4, Tegra 4i and Tegra
K1.
8.16.5 MediaTek
MediaTek is a Taiwanese semiconductor company providing chips
for mobile devices, HDTVs and other electronic devices.
MediaTek processors are built on 64-bit ARM architecture. The
latest MediaTek processor supports up to 3 GHz speed. They
come in a variety of cores such as dual core (2 core), quad core
(4 core), hexa core (6 core) and deca core (10 core).
The latest processors from MediaTek, Helio X20 and Helio X25, are used in smartphones and
tablets. MediaTek processors are mostly popular with Chinese manufacturers. Xiaomi, Meizu,
8.38
LeEco Le, Yu, etc., use them in smartphones. Acer, Asus, Lenovo, Amazon Fire HD, QMobile are
some of the other manufacturers that use MediaTek processors in their tablets.
Helio X30 and Helio X27, the latest from the company’s stable, use 10 nm and 20 nm processors
respectively. Both are deca core with 2 dual core and a single dual core built inside the processor.
8.16.6 HiSilicon
HiSilicon is a Chinese company specializing in semiconductor
technology. The company, owned by Huawei, creates chips based
on ARM architecture. It is the largest domestic integrated circuit
designer in China.
Some of the processors released by HiSilicon are K3V1, K3V2, K3V2E, Kirin 620, Kirin 650,
Kirin 910, Kirin 920, Kirin 930, Kirin 950 and Kirin 960. Some of the devices with Kirin 950
are Honor 8, Huawei mate 8 and Huawei MediaPad M3.
Kirin 960 is the latest model to be released in the series. It is built on 64-bit ARM architecture
on 16 nm FinFET technology. The processor is quad core capable of attaining a speed of 2.4GHz.
the Undernet provide servers and help us download an IRC client on our PC.
The IRC protocol was developed over four years since it was first implemented as a means for
users on a BBS to chat amongst themselves.
CTM: IRC is used for chatting by sending and receiving text messages. The sender sends request to IRC
server, which then forwards this request to another client to communicate with each other.
8.40
intranets and Local Area Networks (LAN). As the data is transmitted in the form of packets, VoIP
uses packet switching technology where each packet follows best route to reach its destination.
VoIP allows both voice and data communications to be run over a single network, which can
significantly reduce infrastructure costs.
There are 3 main causes for the evolution of the voice-over IP market:
1. Low-cost phone calls
2. Add-on services and unified messaging
3. Merging of data/voice infrastructures
Services provided by VoIP are:
Phone to phone, PC to phone, phone to PC, fax to email, email to fax, fax to fax, voice to email, IP
Phone, transparent CCS (TCCS), toll free number (1-800), class services, call centre applications,
VPN, Unified Messaging, Wireless Connectivity, IN Applications using SS7, IP PABX and soft
switch implementation.
The various protocols used for VoIP are:
1. H.323
2. Session Initiation Protocol (SIP)
CTM: VoIP is a protocol that is used for transmitting voice data and multimedia data over internet protocol.
It uses high speed broadband internet connection.
service to the users, so that a user can communicate with more than one person at a time. Other
SIP applications include streaming multimedia distribution, instant messaging and information,
file transfer, fax over IP and online games. SIP transparently supports name mapping and
redirection services which support personal mobility.
8.41
8.21 NETWORK SECURITY CONCEPTS
Network is used for sharing, messaging and collaboration of data. However, the more network is
used for this purpose, the lesser is the security of data, either in terms of viruses or hacking and
other cyberattacks. To prevent the network from these malicious and/or unethical practices,
various strategies and choices are available that work as building blocks of network security.
These include password authentication, digital signature, challenge handshake authentication
protocol, etc.
Characteristics of Viruses:
(a) Speed of a computer system becomes slower than normal.
(b) Computer system frequently hangs up.
(c) Computer restarts automatically after every few minutes.
(d) Various applications of computer do not function properly.
(e) Dialog boxes, menus and other error message windows are distorted.
CTM: A virus is a malicious program that damages data and files of a system and can also corrupt the file
allocation table.
8.42
2. Worms
A worm is a self-replicating program that runs independently and travels across network
connections. The characteristics of viruses and worms are more or less same, but a worm
causes more damage.
CTM: A worm is a computer program which can self-replicate and propagate over the network, with or
without human intervention, and has malicious content.
Characteristics of Worm:
(a) It replicates itself.
(b) Unlike virus, worm does not require host and it is self-contained.
(c) It spreads across networks through email, instant messaging or junk mails.
(d) Worms run independently.
The various types of Worms are:
(a) Email Worms: Worms spread through any email which contains any file attachment or link
to any infected website.
(b) Instant Messaging Worms: Worms spread through instant messaging across the network
by sending mails to infected website.
(c) Internet Worms: The infected worm will use the contact list of the user’s chat-room profile
or instant-message program to send links to infected websites. These are not as effective
as email worms as the recipient needs to accept the message and click the link. The users
of the particular program are affected by it.
(d) File Sharing Network Worms: These types of worms are downloaded along with the
required files downloaded by the user. A user is not aware about this worm and, therefore,
when the user downloads any file, the worm will copy itself into a shared folder with an
unassuming name. When another user on the network downloads files from the shared
folder, the worm gets downloaded on their system also. In this way, the worm copies itself
and repeats the process. In 2004, a worm called “Phatbot” infected millions of computers
in this way and had the ability to steal personal information, including credit card details,
and send spam on a large scale.
Damage caused by Worms:
(a) A worm may corrupt the files on the host computer.
(b) It may affect communication between the host and other systems.
(c) It may disable the antivirus software on the host, which will enable it to cause more damage.
(d) Bulk email chaining can be created with an intention to guess email passwords.
(e) A worm consumes too much system memory (or network bandwidth), causing web servers,
network servers and individual computers to stop responding.
3. Trojan Horse
Computer Networks
A Trojan horse is a kind of virus that looks safe but has hidden effects. It is a hidden code in
a program such as a game or a spreadsheet that can damage the system when running these
applications. It can destroy or alter information on a computer system in the background. Unlike
viruses, Trojans do not replicate themselves but they are destructive. Trojans are executable
programs, which means that when a user runs any application or plays games, they work
behind that application and can damage the system completely.
8.43
There are several types of Trojan Horse:
(a) Remote access Trojan horse
(b) Data sending Trojans
(c) Destructive Trojans
(d) Proxy Trojans
(e) FTP Trojans
(f) Denial-of-service attack Trojans
Trojans are generally spread through email attachments and exchange of disks and information
between computers. Worms can also spread Trojans. The damage caused by Trojans is similar
to that caused by viruses. Sometimes the user is unaware about a Trojan because of its masking
effect as it runs as a hidden code.
CTM: Trojan horse is a hidden code that looks safe but it has some hidden effects while running
applications.
4. Spams
Spam is an unwanted bulk mail which is sent by an unauthorized or unidentified person in order
to eat the entire disk space. In non-malicious form, it floods the internet with many copies of
the same message to be sent to a user which he may not otherwise receive. Generally, it is in the
form of pampering the user with various discount schemes, or commercial advertising, often
for dubious products, get rich quick schemes, etc. Mobile phone spam is a form of spamming
that uses text message service of mobile phone.
Spams can be avoided by using email filtering, spam traps, etc.
CTM: Spam refers to electronic junk mail that eats up the entire computer’s space.
8.23 COOKIES
A cookie is also known as an HTTP cookie, web cookie, internet cookie or browser cookie.
When the user browses any website, a cookie identifies users and prepares web pages for them
Supplement – Computer Science with Python–XII
which are then sent to the web server for later use. Cookie is basically a piece of data that is
stored by the website on the user’s hard disk. The information is stored in the form of name
value pair. Generally, the cookies folder is stored in c:\windows\cookies.
Working of Cookies
1. The user enters the name of the website on the browser.
2. The browser contacts the DNS server to convert the domain name into IP address. The
browser looks for the cookies on the hard disk.
3. The IP address is used to contact the corresponding server along with cookies data.
4. If no cookies data is supplied, then the website comes to know that the user is visiting the
website for the first time.
5. The server creates an ID of a person which is then stored by cookies on the hard disk.
8.44
The information which is stored by a website is known as state information. The information
can be of the following types:
1. How many visitors have visited the site
2. How many are new visitors
3. How many are repeat visitors
4. What is the frequency of a particular visitor
CTM: Cookies are the messages which are stored by the website on a user’s hard disk whenever they visit
any website.
8.24 FIREWALL
A firewall is a software that protects the private network from unauthorized user access. The
firewall filters the information coming from the internet to the network or a computer to
protect the system. Firewall exists both as a software solution and as a hardware application. In
the form of hardware firewall such as router, it protects the network, and in terms of software
firewall, it helps in preventing the spread of virus from one computer to another. A firewall
is a network security system, either hardware- or software-based, that controls incoming
and outgoing network traffic based on a set of rules. Various examples of firewalls are CISCO
firewall, NetGear firewall, Netscreen 25, etc.
A firewall can use various methods for filtering the information such as:
1. Packet filtering: In packet filtering, the data, which is outgoing or incoming in the form
of packets, is filtered. Packet filter looks at each packet entering or leaving the network
and accepts or rejects it based on user-defined rules. Packet filtering is fairly effective
and transparent to users, but it is difficult to configure. In addition, it is susceptible to IP
spoofing.
2. Proxy service: The information which is requested is not directly sent to the person who
makes the request; rather, the information is first received in firewall and then sent to the
proxy server. The proxy server intercepts all messages entering and leaving the network
and effectively hides the true network addresses.
3. IP address blocking: If the data is coming from a network or website that contains some
unwanted data, then the data from that particular IP address or domain name is blocked
by firewall.
4. Protocol blocking: The firewall can be set to disallow a particular protocol service to a
particular user or group of users.
5. Application Gateway: It applies security mechanisms to specific applications, such as FTP
and Telnet servers. This is very effective but can impose performance degradation.
6. Circuit-level Gateway: It applies security mechanisms when a TCP or UDP connection is
established. Once the connection has been made, packets can flow between the hosts
Computer Networks
8.45
Firewall protects the user from the following:
1. Remote login by others who are not authorized to gain access to the system
2. Application backdoors
3. SMTP session hijacking
4. Email bombs
5. Viruses and macros
6. Spam or junk mails
CTM: Firewall is a system that is designed to protect the network from illegal use by an unauthorized
person.
imprisonment and fine. A large number of cyber-criminal activities such as hacking passwords
or accessing files by an unauthorized person or getting private information, etc., have been
prevented by implementing cyber laws.
As the usage of internet has been growing at an exponential rate, it has become very important
to protect individual users and organizations from unauthorized intruders into the system.
CTM: Cyber law defines all the legal and regulatory aspects of internet and the World Wide Web.
a computer are denied access or use of the resources of that computer. Generally, DoS
attacks do not allow the attacker to modify or access information on the computer. A DoS
attack can be of the following types:
• Denial of Access to Information: Refers to an attack in which information sought by
a legitimate user is either destroyed or changed to some unsubtle form.
8.47
• Denial of Access to Applications: Refers to an attack that denies a user from accessing
an application by making it either unusable or unavailable. This is usually done to
prevent the user (or organization) from using applications to perform any task.
• Denial of Access to Systems: Refers to the unavailability of the system, including all
the applications installed on the system or any data stored on the system.
• Denial of Access to Communications: Refers to a common type of attack that can
range from cutting wires and jamming radio communications to flooding networks
with excessive traffic. An example of this type of attack is flooding a computer with
junk mail.
person access to a network for legal use. It is an act of giving authority or legal identity
to a user to become an authorized user of the system. Authorization checks can also be
implemented to a program or process to make data free of risk, such as entering of viruses,
worms or Trojan horse.
2. Authentication: To determine the identity of a person before granting access to private
or sensitive data or information is known as authentication. Verifying the identity of an
intruder or a person is difficult and needs complex protocols based on cryptography.
3. Privacy: The data which is accessible only to an authorized person is known as private data.
4. Secrecy: Hiding some relevant information from an unauthorized person is called secrecy.
5. Biometric System: Biometric system forms the most secure level of authorization. It
involves digital signature, finger prints, retinal patterns, etc., to establish identity.
6. Password Protection: To protect the system or network from an unauthorized person, a
system must be password protected. A password protected system allows access to resources
based upon a secret word entered by the user.
8.48
7. File Permission: A user can give access to a person to read a file, write to a file, open a file,
modify a file, etc. Different types of permissions can be given to a specific person according
to their authorization. Each file has an access control list attribute that describes which user
or group accounts have what type of access to the file.
Three types of file access permissions that are granted to a user:
(a) Read: Allows a user to view and read a file.
(b) Write: Allows a user to edit and write on a file.
(c) Execute: Allows a user to execute a file.
File access permission is granted to three types of users:
(a) Owner: Refers to the user who has created the file.
(b) Group: Refers to the group of users which is working with the file owner.
(c) Others: Refers to all other users.
8. Firewall: A firewall is a part of a computer system or network that is designed to block
unauthorized access while permitting authorized communication. It is a programmer
software or device or set of devices configured to permit, deny, encrypt, decrypt, or proxy
wall (in and out) computer traffic between different security domains based upon a set of
rules and other criteria.
9. Proper Security Policy: An organization’s security policy is a formal statement consisting
of the rules that its employees need to follow to access information about the organization.
The policy should clearly communicate the security goals to all the users, administrators
and managers of the organization. A good security policy must be:
enforced with adequate security tools.
able to define the areas of responsibility for a user, an administrator or a manager.
able to adjust itself according to the changing configurations of computer networks.
8.29 HACKING
Hacking is the practice of modifying the features of a system in order to accomplish a goal
outside the creator’s original purpose. A person who consistently engages in hacking activities
and has accepted hacking as a lifestyle and philosophy of their choice is called a hacker.
Computer hacking is the most popular form of hacking nowadays, especially in the field of
computer security. However hacking exists in many other forms also, such as phone hacking,
brain hacking, etc., and it is not limited to either of them.
Due to the mass attention given to black hat hackers by the media, the whole hacking term is
often mistaken for any security-related cyber crime.
Internet offers several important and extensively used features or services which are described
as follows:
8.49
8.30.1 WWW (World Wide Web)
WWW is an information service that can be used for sending and receiving information over
the internet through interlinked hypertext documents. Web pages may contain text, images,
videos and other multimedia components as well as web navigation features consisting of
hyperlinks. The documents are formatted in a markup language called HTML (Hyper Text
Markup Language) that provides links to other documents as well as graphics, audio and video
files. The World Wide Web is based upon client-server architecture where a client sends a
request and the server processes that request and sends responses. A WWW client is called a
web browser and a WWW server is called a web server.
CTM: WWW is a set of programs and protocols that allows the user to create and display multimedia web
pages and is linked to the internet.
CTM: HTML is a Markup language that enables users to create web pages and format them using predefined
tags. Tags are called coded elements.
</xml>
CTM: XML is a Markup Language for creating documents in a structured format. Users can create their own
tags along with predefined tags already defined by HTML.
8.51
8.30.4 Hyper Text Transfer Protocol (HTTP)
HTTP is used to transfer all files and other data (collectively called resources) from one computer
to another on the World Wide Web. This protocol is used to transfer hypertext documents over
the internet. HTTP defines how the data is formatted and transmitted over the network. When
an HTTP client (a browser) sends a request to an HTTP server (web server), the server sends
responses back to the client. This transfer of requests and responses is done following HTTP
protocol.
The main features of an HTTP document are:
1. It is a stateless protocol; this means that several commands are executed simultaneously
without knowing the command which is already executing before another command.
2. It is an object-oriented protocol that uses client server model.
3. The browser (client) sends request to the server, the server processes it and sends responses
to the client.
4. It is used for displaying web pages on the screen.
8.52
Country Specific Domain Names
.in - India
·au - Australia
·ca - Canada
.ch - China
.nz - New Zealand
.pk - Pakistan
.jp - Japan
.us - United States of America
8.30.6 URL
URL stands for uniform resource locator that helps in locating a particular website or a web
page, for example, http://www.cbse.nic.in/academics.html is a URL for a specific website. In
this URL, ‘http’ stands for hypertext transfer protocol, and ‘www.cbse.nic.in’ indicates the IP
address or the domain name where the source is located. ‘academics.html’ specifies the name
of the specified html document on the website of CBSE.
CTM: URL stands for uniform resource locator that stores the address of a web page.
8.30.7 IP Address
The computers connected to a network also need to follow some rules to communicate with
each other. These sets of rules are known as protocols. Several types of protocols are used for
communication over networks. However, the most common one is the Transmission Control
Protocol/Internet Protocol or TCP/IP. A network using TCP/IP is known as a TCP/IP network.
The internet is an example of the TCP/IP network. Therefore, it becomes important that each
device should have a unique address to identify it on a TCP/IP network. This unique address is
known as IP address. IP address is short for Internet Protocol (IP) address. An IP address is an
identifier for a computer or device on a TCP/IP network. Networks using the TCP/IP protocol
route messages based on the IP address of the destination. The format of IP address is a 32-bit
numeric address written as four numbers separated by periods. Each number can be 0 to 255.
Some examples of IP addresses are: 192.168.1.2, 10.324.1.3 and 109.134.2.2.
As seen in the above examples, the numbers in an IP address are in the decimal form. When
an IP address is processed, the computer converts these numbers into binary form internally.
The following is an example of IP address in the decimal form: 192.168.1.10
The preceding IP address in its binary form is: 11000000.10101000.00000001.00001010
The IP address of a computer is assigned by the Internet Service Provider (ISP) whose internet
connection is used on that computer.
You can find out the IP address of your computer by performing the following steps:
Computer Networks
1. Click the Start button. A pop-up menu containing various options appears.
2. Open the Run dialog box.
Type cmd in the Run dialog box and press Enter. The command prompt (cmd) window
opens.
8.53
3. Type ipconfig and press Enter. The output appears, displaying the IP address of your
computer (as shown in the output window given below).
8.30.8 Website
A website is a collection of various web pages, images, videos, audios or other kinds of digital
assets that are hosted on one or several web servers. The first page of a website is known as
home page where all the links related to other documents are displayed. The web pages of a
website are written using HTML and the information is transferred over the internet through
HTTP protocol. The HTML documents consist of several hyperlinks that are accessed through
HTTP protocol. Examples of various websites are: cbse.nic.in, google.com, amazon.in, etc.
CTM: A website is a collection of several web pages which are related to each other through hyperlinks.
visits it is known as a static web page. A static web page generally has .htm or .html as
extension.
Dynamic web page: An interactive web page is a dynamic web page. A dynamic web
page uses scripting languages to display changing content on the web page. Such a page
generally has .php, .asp, or .jsp as extension.
CTM: A web browser is a WWW client that navigates through the WWW and displays web pages.
8.54
8.30.11 Web Server
A web server is a server that stores web pages and when a web client sends any request to a
server, the server responds to the request and displays the requested web pages. A web server
is a program that runs on a computer connected to the internet. Web server waits for a request,
finds the documents and generates information, if required, and sends it back to the browser
that requested for it. A single web server may support multiple websites, or a single website
may be hosted on several linked or mirrored web servers.
Sends request
WEB WEB
Sends response
Some popular web servers are: Apache web server, Netscape enterprise web server, Microsoft
internet information server, etc.
CTM: A web server stores web documents and responds to the requests made by web browsers.
CTM: Web hosting is a service that is provided by the company to users to create web-based applications.
1. Enter the domain name of the website that you want to access in the Web browser.
2. The Web browser issues a command to the operating system of your computer to generate
the IP address of the given domain name.
8.55
The domain name is resolved according to the configuration of the operating system you are
using. Different operating systems, such as Windows XP, Windows 7, Linux and Unix have
different configurations.
This is done in the following manner:
Generally, the operating system maintains a HOSTS file, which contains a list of the IP
addresses of some domain names. Therefore, the operating system first checks this file to
find the IP address of the given domain name.
If the IP address is not found in the HOSTS file, the operating system connects to the DNS
server on a network. The DNS server maintains a directory containing a list of all the
domain names and IP addresses that are registered on the internet. The DNS server finds
the IP address of the given domain name and returns it to the operating system.
3. After obtaining the IP address, the operating system sends it to the Web browser that has
requested it.
CTM: A script is a list of commands embedded in a web page which are executed by a certain program or
scripting engine.
8.56
Example of Java Script is as follows:
<HTML>
<HEAD>
<TITLE>My first java script</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
document.write("Welcome")
</SCRIPT>
</BODY>
</HTML>
JavaScript allows the user to perform several functions such as:
(i) Add scrolling or changing messages to the browser’s status line.
(ii) Update the contents of a form by using validation checks and make calculations.
(For example, on entering the marks of 5 subjects of a student, it will calculate total
marks and percentage.)
(iii) Display messages to the user, either in a new web page, which is a sub-part of the main
web page, or in alert boxes.
(iv) Create and animate images that change when the user hovers the mouse over them.
(v) Detect the browser in use and display different contents for different browsers.
(vi) Detect installed plug-ins and notify the user if a plug-in is required.
8.57
Example of VBScript is as follows:
<HTML>
<HEAD>
<TITLE>My first VBScript</TITLE>
</HEAD>
<BODY>
<SCRIPT TYPE="text/vbscript">
document.write("Welcome")
</SCRIPT>
</BODY>
</HTML>
(c) PHP (Hypertext Pre-Processor)
PHP stands for Hypertext Pre-processor. It is a server-side scripting language that is used
to enhance web pages. With PHP, a user can do things like create username and password
login pages, check details from a form, create forums, picture galleries, etc. It was created
in 1994 by Rasmus Lerdorf to add dynamic content to an HTML page. PHP initially stood
for ‘Personal Home Page’, but now it is translated as ‘PHP Hypertext Pre-processor’. The
PHP code is embedded within the HTML code between special tags. When the page is
accessed, the server processes the PHP code and then sends the output from the script as
HTML code to the client.
The salient features of PHP are as follows:
(i) A user can create dynamic web pages with the PHP scripting language.
(ii) It is a server-side scripting language and, therefore, the PHP scripts are executed on
the server.
(iii) PHP is free and an open source software product.
(iv) PHP provides connectivity with many databases (MySQL, Sybase, Oracle and many
others).
(v) PHP runs on different platforms (UNIX, Linux, Windows).
Supplement – Computer Science with Python–XII
(vi) PHP is compatible with almost all web-servers used today (Apache, IIS, etc.).
(vii) PHP commands are embedded within a standard HTML page.
(viii) Its syntax is similar to that of C and Perl languages which makes it easy to use.
(ix) PHP files can have one of the following extensions: PHP, PHP3 or PHTML.
The structure of PHP Script is as follows:
<HTML>
<HEAD>
<TITLE>PHP Test</TITLE>
</HEAD>
<BODY>
<?php echo'<p>Hello World</p>'?>
</BODY>
8.58 </HTML>
2. Server-Side Script
Server-side scripting gets executed on the server before displaying the information requested.
CTM: Scripting languages are also often used by applications as control or configure languages. An
example: Firefox is written in C/C++ and can be controlled with JavaScript.
Computer Networks
8.59
Table: 8.1: Difference between Client-Side Scripting and Server-Side Scripting
S.No. Client-Side Scripting Server-Side Scripting
1. Scripting runs through web browser. Scripting runs through web server.
2. The processing takes place on the end-user’s The processing takes place on the server side.
computer.
3. The browser receives the page sent by the server Server executes server-side scripts to send out a
and executes the client-side scripts. page but it does not execute client-side scripts.
4. Client-side scripting cannot be used to connect to Server-side scripting is used to connect to the
the databases on the web server. databases that reside on the web server.
5. Client-side scripting can be blocked by the user. Server-side scripting cannot be blocked by the
user.
6. Response from a client-side script is faster as Response from a server-side script is slower as
compared to a server-side script because the compared to a client-side script because the
scripts are processed on the local computer. scripts are processed on the remote computer.
7. Examples of client-side scripting languages are Examples of server-side scripting languages are
Javascript, VBScript, etc. PHP, JSP, ASP, ASP.Net, Ruby, Perl, etc.
8.60
Applications supported by Web 2.0 are as follows:
• Blogging
• Social bookmarking
• RSS
• Wikis and other collaborative applications
• Interactive encyclopaedias and dictionaries
• Advanced Gaming
CTM: Web 2.0 refers to added features and applications that make the web more interactive and easy to
provide information using newsgroups, social networking sites, RSS, etc.
8.32 E-COMMERCE
E-commerce (electronic commerce or EC) is the buying and selling of goods and services, or the
transmitting of funds or data over an electronic network, primarily the internet. These business
transactions occur either as business-to-business, business-to-consumer, consumer-to-consumer
or consumer-to-business. The terms e-commerce and e-business are often used interchangeably.
E-commerce is conducted using a variety of applications, such as email, online catalogues
and shopping carts, EDI, File Transfer Protocol and web services. This includes business-to-
business activities and outreach such as using email for unsolicited ads (usually viewed as
spam) to consumers and other business prospects, as well as to send out e-newsletters to
subscribers. More companies now try to entice consumers directly online, using tools such as
digital coupons, social media marketing and targeted advertisements.
SELF PRODUCTS
E-COMMERCE BANK
CUSTOMERS
BANK PAYMENT
SHIPPING WAREHOUSE
The advantages of e-commerce include its round-the-clock availability, speed of access, wide
availability of goods and services to the consumer, easy accessibility and international reach.
1. Online Banking
Online banking, also known as internet banking, e-banking
or virtual banking, is an electronic payment system that
enables customers of a bank or a financial institution to
conduct a range of financial transactions through the financial
institution’s website. 8.61
2. Mobile Banking
Mobile banking is a service provided by a bank or a financial institution
that allows its customers to conduct a range of financial transactions
remotely using a mobile device such as a mobile phone or tablet,
and using software, usually called an app, provided by the financial
institution for the purpose.
Identity
Queue
Object Storage Runtime Database
Infrastructure
Computer Network
Block Storage
Phones Tablets
Platform as a Service
Infrastructure as a Service
Server
6. This interconnection will ensure that each building is directly connected to Administrative
block.
7. This way, internet connection will be available in each building irrespective of the status of
the other building.
8. Server (if any) of the school may be placed in the Administrative block so that it remains
safe (physically) and a firewall can be set up so that the whole network remains safe from
any kind of virus or intrusion attacks.
There is no need to put in any extra efforts or expenses to link the school to its head office.
This can be taken care of using the internet connections.
Tips to solve technical questions based on Networking
Where Server should be placed: Server should be placed in the building where the number
of computers is maximum.
1. Suggest a suitable cable layout of connection: A suitable cable layout can be suggested
in the following two ways:
(a) On the basis of Server: First, the location of the Server is found out. Server should be
placed in that building where the number of computers is maximum (according to
the 80:20 rule). After finding the server position, each building distance is compared
with the Server building directly or indirectly (taking other building(s) in between).
The shortest distance is counted, whether it is directly or indirectly calculated.
(b) On the basis of distance from each building: The distance between each building is
compared to all other buildings, either directly or indirectly. The shortest distance
is calculated, whether it is direct or through some other building.
2. Where the following devices should be placed:
Server : Large number of computers in the building
HUB/Switch : Each building
Modem : In the server room
Repeater : It is used if the distances are higher than 70m. It regenerates
data and voice signals.
Router : When one LAN is required to be connected to the other LAN
Best Layout : Star (from Server), BUS topology
Computer Networks
Best Cable
: Twisted Pair, Ethernet Cable, Coaxial cable (when distance is
in metres);
For large distances—Fibre optics cable.
Best connecting technique : In hilly regions, radio waves should be used and city-to-city,
state-to-state satellite should be used.
8.65
MEMORY BYTES
Internet is a network of networks that spreads all over the world.
ARPANET was the first internet followed by NSFNET and other small networks.
A gateway is a device that connects dissimilar networks.
A backbone is a central interconnecting device that connects two or more computers.
Topology is a way of connecting computers physically or logically.
Star topology uses a central hub where each computer indirectly connects with the other computer on the network.
A set of rules that governs internet is called protocol.
TCP protocol is responsible for sequential arrangement of packets.
IP protocol is responsible for fragmentation of data into packets and sends those packets in random order.
FTP protocol is used to share files across networks.
TELNET is a remote login where a user can login on another user’s system.
HTTP is used for displaying web pages.
Web browser is an application program that helps in opening web pages.
The first page of any website is known as home page.
Communication media is a transmission media for transmitting data across the network.
Guided media is also known as wired media while unguided media is also known as wireless media.
LAN, MAN, WAN and PAN are the four types of networks.
Viruses are malicious programs that can damage files, disks, file allocation table, etc.
Spams are unsolicited mails that eat up the disk space.
Hub refers to a networking component which acts as a convergence point of a network allowing the transfer of
data packets.
Switch refers to a device which filters and forwards data packets across the network.
Web hosting service is a type of internet hosting service that allows individuals and organizations to host their own
website and users with online systems to store information such as images, videos, etc.
A data channel is the medium used to carry information or data from one point to another.
(a) Through ................................ you can establish contact with anyone in the world.
(b) The main function of ................................ is to divide the message or data into packets of a definite
size on the source computer.
(c) ....................... refers to wireless fidelity which enables us to connect to the ISP without any cable.
(d) ................................ is a software that enables us to access the internet and explore websites.
(e) Web page constitutes the ................................ .
(f) A ................................ is someone with a strong interest in how things work, who likes to create and
modify things for their own enjoyment.
(g) A computer ................................ is a small software program that spreads from one computer to
another and interferes with the normal functioning of computer.
(h) Electronic junk mail or junk newsgroup postings are known as ................................ .
(i) Digital signature meets the need for ................................ and integrity.
(j) The first network that planted the seed of internet was ................................ .
(k) The protocol used for internet is ................................ .
(l) A device used to connect dissimilar networks is called ................................ .
(m) ................................ is responsible for handling the address of the destination computer so that each
8.66 packet is delivered to its proper destination.
(n)Tricking people through authentic-looking emails or websites is called ................................ .
(o)A program designed to replicate and eat up a computer’s storage is called ................................ .
(p)A digital document issued to a site by a certification authority of the internet is called a ................ .
(q)To connect computers located in a specific building or campus is known as ................................ .
(r)
Wi-Fi, infrared and Bluetooth are examples of ................................ .
(s)Interspace is a ................................ .
(t)
A server that provides its services to other workstations on a network is a ................................ .
(u)The technique of switching in which data is divided into smaller fragments is called .............. .
(v)................................ is a dedicated link between the sender and the receiver.
(w) ................................ is the measuring unit of speed at which the data transfer takes place.
(x)All the computers are connected with each other in an unorganized manner in topology
................................ .
(y) In ................................, all computers share equivalent responsibility for processing data.
Answers: (a) Internet (b) TCP (c) Wi-Fi
(d) Browser (e) World Wide Web (f) Hacker
(g) Virus (h) SPAM (i) Authentication
(j) ARPANET (k) TCP/IP (l) Gateway
(m) IP (n) Hacking (o) WORM
(p) Digital certificate (q) LAN
(r) Communication Mediums (s) Network (t) Dedicated server
(u) Packet switching (v) Circuit switching (w) bits/second
(x) Mesh (y) Peer-to-peer network
2. State whether the following statements are True or False.
(a) A set of rules that governs internet is called protocol.
(b) A repeater handles different protocols.
(c) A hub is known as an intelligent device on the network.
(d) A location on a net server is called a website.
(e) A document that uses HTTP is called a web page.
(f) A switch is a device used to segment networks into sub-networks or subnets.
(g) Email helps us to send and receive messages through video conferencing.
(h) The degeneration of a signal over a distance on a network is called attenuation.
(i) Coaxial cable possesses higher tensile strength than optical fibre.
(j) When two entities are communicating and do not want a third party to listen, this situation is defined
as secure communication.
Answers: (a) True (b) False (c) False (d) True (e) True (f) True
(g) False (h) True (i) False (j) True
3. Multiple Choice Questions (MCQs)
(a) A computer network:
(i) Is a collection of hardware components and computers
(ii) Is interconnected by communication channels
(iii) Allows sharing of resources and information
(iv) All of the above
(b) What is a firewall in computer network?
(i) The physical boundary of network
Computer Networks
SOLVED QUESTIONS
1. Define a network. What is its need?
Ans. A network is an interconnected collection of autonomous computers that can share and exchange
information.
Need for networking:
(a) Resource sharing: Resources are shared by all computers over the network for effective utilization.
(b) File sharing: A file in a network can be accessed from anywhere.
2. Write two advantages and two disadvantages of network.
Ans. Advantages of network:
(a) We can share resources such as printers and scanners.
(b) We can share data and access files from any computer.
Disadvantages of network:
(a) If there is any problem in the server, then no communication can take place.
(b) Network faults can cause loss of data.
(c) If there is no privacy mechanism used, then the entire network can be accessed by an unauthorized
Supplement – Computer Science with Python–XII
person.
3. What is ARPANET? What is NSFNET?
Ans. ARPANET (Advanced Research Project Agency Network) is a project sponsored by US Department of Defence.
NSFNET, developed by the National Science Foundation, was a high capacity network and strictly used for
academic and engineering research.
4. What are the various types of networks?
Ans. A network is an interconnection of several nodes through some communication media with the goal of
sharing data, files and resources. There are three types of networks:
(a) Local Area Network (LAN)
(b) Metropolitan Area Network (MAN)
(c) Wide Area Network (WAN)
5. Name the various layers of coaxial cable.
Ans. Coaxial cable consists of the following layers:
(a) A metallic rod-shaped inner conductor (b) An insulator covering the rod
(c) A metallic outer conductor called shield (d) An insulator covering the shield
(e) A plastic cover
8.68
6. What is a spam mail? [CBSE D 2015]
Ans. Spam is the abuse of electronic messaging systems (including most broadcast media, digital delivery
systems) to send unsolicited bulk messages indiscriminately.
7. Differentiate between FTP and HTTP. [CBSE D 2015]
Ans. FTP is a protocol to transfer files over the internet. HTTP is a protocol which allows the use of HTML to
browse web pages in the World Wide Web.
8. Out of the following, which is the fastest (a) Wired, and (b) Wireless medium of communication? Infrared,
Coaxial Cable, Ethernet Cable, Microwave, Optical Fibre. [CBSE D 2015]
Ans. (a) Wired: Optical Fibre
(b) Wireless: Infrared or Microwave
9. What is a worm? How is it removed? [CBSE D 2015]
Ans. A worm is a self-replicating computer program. It uses a network to send copies of itself to other computers
on the network and it may do so without any user intervention. Most of the common antivirus (anti-
worm) software remove worm.
10. Illustrate the layout for connecting five computers in a Bus and a Star topology of Networks.
Ans. Bus topology
Server
BACKBONE
Nodes
Dropline
Star topology
Computer
Computer Computer
HUB
Computer Printer
11. In networking, what is WAN? How is it different from LAN? [CBSE D 2011]
Ans. Internet is an example of WAN (Wide Area Network). Most WANs exist to connect LANs that are not in
the same geographical area. WAN is different from LAN due to its network range. WAN is for connecting
computers anywhere in the world without any geographical limitation whereas LAN is confined within
Computer Networks
8.71
36. Write two advantages of using an optical fibre cable over an Ethernet cable to connect two service
stations which are 200m away from each other. [CBSE D 2013]
Ans. Optical fibre cable guarantees secure transmission and a very high transmission capacity. Optical fibre
cable is immune to electrical and magnetic interference.
37. Write two characteristics of Wi-Fi. [CBSE D 2014]
Ans. (a) It allows an electronic device to exchange data or connect to the internet wirelessly using microwaves.
(b) Network range of Wi-Fi is much less than other network technologies like wired LAN.
38. What is the difference between Email and Chat? [CBSE D 2014]
Ans. (a) Chat is a type of software while Email is a protocol.
(b) Chat requires the permission of both parties while Email does not.
(c) Chat is typically software dependent while Email is not.
(d) Chat needs accounts on the same provider while Email does not.
39. What are VoIP?
Ans. VoIP are communication protocols and transmission technologies for delivery of voice communication
and multimedia sessions over Internet Protocol (IP) networks, such as the internet. Also, we can say that
VoIP are IP technology, internet telephony and broadband telephony.
40. Expand the following terms:
(a) XML (b) GSM
(c) SMS (d) MAN
Ans. (a) XML–Extensible Markup Language
(b) GSM–Global System for Mobile communication
(c) SMS–Short Messaging Service
(d) MAN–Metropolitan Area Network
41. How many switching techniques are there? Explain any one.
Ans. There are three switching techniques:
(a) Circuit Switching (b) Packet Switching
(c) Message Switching
Circuit Switching: In this technique, first the complete physical connection between two computers is
established and then data is transmitted from the source computer to the destination computer. The
entire dedicated line is used by the caller and the receiver and no other user can use it even if the line
becomes idle. When the data transmission is over, the line is disconnected and is available for the next
communication.
42. How are Trojan horses different from Worms? Mention any one difference. [Sample Paper]
Ans. A Trojan horse is a term used to describe malware that appears to the user to perform a desirable function
Supplement – Computer Science with Python–XII
but which, in fact, facilitates unauthorized access to the user’s computer system.
A computer Worm is a self-replicating program. It uses a network to send copies of itself to other nodes
and that too without human intervention.
43. What is a communication channel? Name the basic types of communication channels available.
Ans. A communication channel is also known as communication media or transmission media. Communication
media can be wireless or wired. Wireless media is also known as unguided media while wired media is
also known as guided media.
Following are three basic types of communication channels available:
(a) Twisted Pair Cables (b) Coaxial Cables
(c) Fibre-optic Cables
44. Define baud, bps and Bps. How are these interlinked?
Ans. Baud is a unit of measurement for the information-carrying capacity of a communication channel.
bps (bits per second) refers to a thousand bits transmitted per second.
Bps (Bytes per second) refers to a thousand bytes transmitted per second.
All these terms are measurement units used to refer to the amount of information travelling through a
single channel at any one point of time.
8.72
45. Differentiate between star topology and bus topology.
Ans. The main points of difference between star topology and bus topology are:
Star topology Bus topology
A central hub is required to connect all computers with A long cable known as backbone is used to connect all
each other. computers with each other.
The data is transmitted from the sender to the receiver The data is transmitted through a long cable from the
by passing through the hub. sender to the receiver.
No collision takes place through transmission of data. Collision can take place as the data can be transmitted
from both ends at the same time.
If the central hub fails, the entire network shuts down. If there is a break in a cable, no transmission takes place.
46. Define the following terms:
(a) RJ-45 (b) Ethernet (c) Ethernet card
(d) Hub (e) Switch
Ans. (a) RJ-45: RJ-45 is a standard type of connector for network cables and networks. It is an 8-pin connector
usually used with Ethernet cables.
(b) Ethernet: Ethernet is a LAN architecture developed by Xerox Corp. along with DEC and Intel. It uses
a bus or star topology and supports data transfer rates of up to 10 mbps.
(c) Ethernet card: The computer parts of Ethernet are connected through a special card called Ethernet
card. It contains connections for either coaxial or twisted pair cables
(d) Hub: In computer networking, a hub is a small, simple, low-cost device that joins multiple computers
together.
(e) Switch: A switch is a small hardware device that joins multiple computers together within one local
area network (LAN).
47. Define the following data communicating devices:
(a) Repeater (b) Bridge
(c) Router (d) Gateway
Ans. (a) Repeater: It is a device that amplifies and restores the signal before it gets degraded and transmits the
original signal back to the destination. A repeater is a regenerator and not an amplifier.
(b) Bridge: A bridge is a device designed to connect two LAN segments. The purpose of a bridge is to filter
traffic on a LAN. Bridge relays frames between two originally separate segments. When a frame
enters a bridge, the bridge not only regenerates the signal but also checks the physical address of
the destination and forwards the new copy only to that port.
(c) Router: Routers operate in the physical, data link and network layers of the OSI model. They decide
the path a packet should take. A router is a networking device whose software and hardware are
usually tailored to the tasks of routing and forwarding data packets across network.
(d) Gateway: A gateway operates on all the seven layers of OSI model. A network gateway is a computer
which has internet-working capability of joining together two networks that use different base protocols.
Gateway converts one protocol to another and can, therefore, connect two dissimilar networks.
48. What is HTML? Where is it used?
Ans. HTML (Hyper Text Markup Language) is used to create Hypertext documents (web pages) for websites.
HTML is the static mark-up language which is used for the following purposes:
• It is used to create web pages.
• It tells the browser how to display text, pictures and other support media.
• It supports multimedia and new page layout features.
• It provides many tags for controlling the presentation of information on the web pages, such as:
<BODY>, <LI>, <HR>, etc.
49. Define GSM, CDMA and WLL.
Computer Networks
Ans. GSM: Global system for mobile communication (GSM) is a wide area wireless communications system that
uses digital radio transmission to provide voice data and multimedia communication services. A GSM
system coordinates the communication between mobile telephones, base stations and switching systems.
CDMA: Code Division Multiple Access (CDMA) is a digital wireless telephony transmission technique which
allows multiple frequencies to be used simultaneously—Spread Spectrum.
WLL: Wireless in Local Loop (WLL) is a system that connects the subscriber to the public switched telephone
network (PSTN) using radio signals as alternative to other connecting media.
8.73
UNSOLVED QUESTIONS
1. What is internet?
2. What is network?
3. What are the various types of topologies?
4. Describe bus topology and star topology.
5. Define the following terms:
(a) Baud (b) Communication channel
(c) Hubs (d) Repeaters
6. Define GSM and GPRS wireless communication system.
7. What is modem? Define the functioning of internal modem and external modem.
8. Expand and explain the following terms:
(a) PPP (b) POP3
(c) VoIP (d) IRC
9. What is the significance of cyber law?
10. Describe the following networking devices:
(a) Hubs (b) Repeaters (c) Routers
(d) Bridges (e) Gateways
11. What are Wi-Fi cards? Explain.
12. What is the significance of using firewalls and authentication?
13. What is a communication protocol? What is its role in networking?
14. What is https? How does it work?
15. What is Ethernet? What is Ethernet Card?
16. What are hubs? How are active hubs different from passive hubs?
17. What are the facilities provided by the Server in a network environment?
18. Which communication medium is to be suggested for very effective and fast communication in guided
medium?
19. In a harsh industrial environment, which cable would you like to use?
20. Which media have the ability to communicate over oceans?
21. What is the difference between microwave and radio wave transmission?
22. Which transmission medium is useful for sparsely populated areas?
23. Which network is easy to expand?
24. Which device filters the data and which device can handle different protocol?
25. What is a network? What are its goals and applications?
Supplement – Computer Science with Python–XII
12.1 INTRODUCTION
When we speak about an organization, large amount of data is required to be processed and handled.
This data handling is performed by arranging data in the form of tables and databases.
A database is defined as an organized collection of data (information) about an entity (something
that exists) or things. It is a shared collection of related data/information used to support the
activities and decision-making of a particular organization. It also allows the users to enter, access
and analyze their data quickly and easily. It serves as a container which may contain various
database objects. Database is integrated as well as shared. For example, all files belonging to
one organization will be treated as the database of that organization. A database, therefore, is
considered as a repository of stored data. We will now discuss some components like files, tables,
records, fields, etc., that are an important part of a database.
It is the network that connects various computers to each other and handles a large volume of data.
Database
Application DBMS
CTM: Database is an organized collection of interrelated data that serves many applications.
Consider the example of a “School” database. This database shall constitute tables related to student,
teacher, result, etc. The data is arranged inside a database as per the file organization hierarchy as
shown in Fig. 12.2.
Database
Table/File
Record
Data-item/Field
Data/Character
A field is a set of characters which are used together to represent specific data elements.
It is also termed as a data item. A specific or an individual data item within a record is
known as a field.
For example, roll number, name, age and marks are the fields in a student’s record.
A collection of fields is termed as a Record. For example, a student record consists of the
fields Roll No, Name, Age and Marks as shown in Fig. 12.3.
Field/Data-item
Data
A collection of logically related records is called a file. A file is also termed as a table or
Supplement – Computer Science with Python–XII
a relation. A table has rows and columns, where rows represent records or tuples and
columns represent the attributes or fields. For example, the entire information about all
the students (in the form of records) in a class is kept in a file or table named “student”
(Fig. 12.3).
Database is, therefore, a place where related information is stored and various operations
can be performed on it. It is the highest unit of file organization.
These databases are generally managed by special software known as Database Management
System (DBMS).
12.2
A DBMS stores data in such a manner that it becomes
Database
easier and highly efficient to retrieve, manipulate and Data technology
and
produce information. Thus, a DBMS is an electronic administration
management
or computerized record-keeping system. It maintains
the various pieces of information in an integrated
and summarized form instead of keeping them in Database
Management
separate independent files. System
End Users
Database Applications
Database
12.4
2. Data Consistency: A DBMS provides data consistency to a larger extent as the changes made
at one place are reflected at all other places or to all the users.
3. Sharing of Data: By using a DBMS, not only can existing applications share data in the
database, but new applications can also be developed to operate against the same stored
data.
4. Reduced Programming Effort: A DBMS saves a lot of programming effort since a user
need not write programs for query processing involving several tables or files, report
generation, addition, modification and deletion of data, etc. Thus, it provides easy retrieval
of data.
5. Database Enforces Standards: With centralized control of the database, the DBA (Database
Administrator) can ensure that all applicable standards are followed in the representation
of data, i.e., format, documentation standards and conventions, etc.
6. Improved Data Integrity: Data integrity refers to the validity and consistency of stored
data. For example, the system itself checks for the correct information to be entered by
the user in the correct format. It consists of various constraints.
7. Privacy and Security: Data security refers to protection of data against accidental or
intentional disclosure to unauthorized persons. Since there is centralized control, the data
is protected.
8. Economical: Combining all the organization’s operational data into one database and
creating a set of applications that work on this single source of data can result in cost
savings. The overall maintenance cost of data is reduced.
9. Improved Backup and Recovery System: A database system provides facilities for recovery
from hardware or software failures.
10. Meeting Enterprise Requirements than Individual Requirements: Since many types of
users with varying levels of technical knowledge use a database, a DBMS should provide
a variety of user interfaces.
CTM: The repetition (duplication) of same data at multiple places in a database is known as data
redundancy.
Data models define how data is connected and how it is processed and stored inside the
system. They organize data for various users. A data model should be able to give best data
representation and should possess the following desirable characteristics:
1. Data models should be presented graphically using diagrams and symbols.
2. Data representation in a data model should have no data redundancy.
3. A data model should be made available and shared by various applications.
4. Data represented should be consistent, stable and valid in all aspects.
12.5
12.3.1 Types of Data Models
Data models are categorized into three different categories:
DATA MODELS
From Fig. 12.8, we can see that the student database contains various files related to a student.
In this kind of arrangement, a file higher in the hierarchy is known as parent of the files
contained inside it. Here, Student is a parent of the Library, Fees and Exam files respectively.
Thus, this model represents a one-to-many relationship between a parent and its children in
the form of a hierarchical (upside-down) tree. The advantages of this model are:
1. It is simple in operation and in concept.
2. It promotes data sharing.
3. Parent-child relationship promotes data integrity.
4. It is efficient and can be naturally mapped for 1:M (one-to-many) relationships.
The limitations of this model are as follows:
1. It is suitable for hierarchical relationships only; otherwise, it is inflexible for non-hierarchical
relationship mapping.
2. Implementation is complex and difficult since it is done using pointers from a parent to its
children which require extra memory space.
12.6
3. Dependency on parent node, which is the root node, and its deletion can cause deletion of
all child nodes and, in turn, the entire model.
4. Changes in the structure require changes in all the applications.
IBM’s IMS (Information Management System) and system2000 are examples of hierarchical
database management system.
LIBRARY (Child)
Roll Ticket No. Book_issued
number
STUDENT (Parent)
FEES (Child)
Links Roll Tuition_fee Dev_fee Total_fees
number
Links
From Fig. 12.9, it is clear that this model represents many-to-many relationships. It can be
observed that the file EXAM is associated with three tables, viz. LIBRARY, FEES and STUDENT.
Thus, the figure shows that a child can have more than one parent. This model is an improved
version of hierarchical model having records along with pointers. These pointers establish
many-to-many relationships and are termed as Links. Each record has its respective pointer
or link with which it is associated.
The advantages of network model are:
1. It can handle more relationship types, i.e., M:M (many-to-many) multi-parent relationships.
Relational Database and SQL
2. Changes made in the table structure do not affect the data access or other application programs.
3. It is represented in the form of tables; so, it is simple and easier to understand.
4. Tabular view also provides easier database design, use, implementation and management.
5. Built-in query support based on SQL is provided by RDBMS (Relational Database Management
System).
6. Data organization and manipulation is easy, flexible and faster.
7. Powerful structure designing and processing capabilities of RDBMS isolate the end-user
from physical-level details and, thus, improve implementation and management simplicity.
8. Mathematical operations can be successfully carried out using RDBMS.
The limitations of relational model are:
1. RDBMS incurs hardware and system software overheads.
2. The size of database becomes very large.
12.8
12.4 RELATIONAL DATABASE
Attributes
A relational database is a type of database that stores and
provides access to data points that are related to one another.
Relational databases are based on the relational model, an
intuitive, straightforward way of representing data in tables. In Tuples
- - - M
Attributes domain
- - - F
Primary key
Relational Database and SQL
degree
combined together and can be declared as a primary key in the relation Student. In
the table Item given below, Item_id is the primary key while Supp_id (supplier id) is
the primary key in the table Supplier.
Table: Item Table: Supplier
Item_id Item_name Qty Supp_id Area
I101 Printer 400 S01 Ashok-Vihar
I102 CD 200 S02 Noida
I104 DVD 150 S04 CP
I105 Mouse 300 S05 Punjabi Bagh
I103 Keyboard 180
I109 Cable 500 Candidate Keys
In the above table, Desig_code is the primary key in the table Department which, when
related with the table Employee, becomes a foreign key to it.
This was all about the database concepts. Now, we will be moving on to their implementation
using SQL.
Online Electricity
is no organization which does not manage its data
Telephone Directory Billing System
and records using some type of DBMS. An online
telephone directory uses DBMS to store data
pertaining to people, phone numbers and other
contact details. Apart from this, your electricity
service provider uses a DBMS to manage billing,
client-related issues, to handle fault data, etc. Not
to forget, Facebook—it needs to store, manipulate and present data related to its members,
their friends, member activities, messages, advertisements and a lot more.
12.11
All these real-life applications require a DBMS to manipulate and handle this enormous data. A
DBMS requires some language to handle and manipulate its data, which is known as Structured
Query Language (SQL). The following topic deals exclusively with relational databases, their
tables and retrieving data using Structured Query Language (SQL).
the databases (relations). In other words, these languages describe what data is to be retrieved,
inserted and updated or deleted from a database.
It has the following salient features and strong processing capabilities:
It can retrieve data from a database through Query processing.
It can insert records in a database.
It can update records in a database.
It can create new databases and modify the existing ones.
It can create new tables in a database.
It can create views in a database.
It allows modifying the security settings of the system.
CTM: SQL (Structured Query Language) is a unified, non-procedural language used for creating, accessing,
handling and managing data in relational databases.
12.12
12.9 ADVANTAGES OF SQL
SQL has the following advantages:
1. Ease of use: It is very easy to learn and use and does not require high-end professional
training to work upon it.
2. Large volume of databases can be handled quite easily.
3. No coding required: It is non-procedural and a unified language, i.e., we need not specify the
procedures to accomplish a task but only need to give a command to perform the activity.
4. SQL can be linked to most of the other high-level languages which makes it the first choice
for database programmers.
5. Portable: It is compatible with other database programs like Dbase IV, FoxPro, MS Access,
DB2, MS SQL Server, Oracle, Sybase, etc.
6. SQL is not a case-sensitive language, i.e., both capital and small letters are recognized.
SQL statements
DCL and TCL are beyond the scope of this book. So, we shall be discussing only DDL and DML
commands in detail.
DDL DML
SELECT
DROP CREATE
INSERT
ALTER UPDATE
DELETE
Fig. 12.15: Most Commonly Used SQL Commands 12.13
Examples of DDL commands in SQL are:
CREATE DATABASE: creates a new database.
USE command: to select and open an already existing database.
CREATE TABLE: creates a new table.
ALTER TABLE: modifies a table.
DROP TABLE: deletes a table.
CTM: The DDL command lets us define the database structure and its related operations.
The DDL provides a set of definitions to specify the storage structure and access methods used
by the database system and also defines proper and relevant data types.
12.14
Let us start implementing SQL using MySQL as the platform.
12.11 MySQL
MySQL is an open-source and freely available Relational Database Management System (RDBMS)
that uses Structured Query Language (SQL). It provides excellent features for creating, storing,
maintaining and accessing data, stored in the form of databases and their respective tables. A
single MySQL database can store several tables at a time and can store thousands of records
in it.
Being an open-source software, it can be freely and easily downloaded from the site
www.mysql.org. MySQL is developed and supported by a Sweden-based company, MySQL AB.
It is fully secured, reliable, and fast, and possesses far better functionalities than many other
commercial RDBMs available in the market.
MySQL database system works upon Client/Server architecture. It constitutes a MySQL server
which runs on a machine containing the databases and MySQL databases (clients), which are
connected to these server machines over a network.
F Advantages of MySQL: MySQL provides the following salient features and advantages:
1. Reliability and Performance: MySQL is a very reliable and high performance
Relational Database Management System.
2. Modifiable: Being an open-source software, MySQL comes with its source code; so, it
is easily modifiable and we can recompile its associated source code.
3. Multi-Platform Support: MySQL supports several different platforms like UNIX,
Linux, Mac OS X and Microsoft Windows.
4. Powerful Processing Capabilities: MySQL is a powerful, easy, compatible and fast
Relational Database Management System. It can handle complicated corporate
applications and processing requirements.
5. Integrity (Checks): MySQL provides various integrity checks in order to restrict the
user input and processing.
6. Authorization: MySQL provides DDL commands to check for user authentication and
authorization by restricting access to relations and views.
7. Powerful Language: All SQL operations are performed at a prescribed and fixed level,
i.e., one SELECT command can retrieve data from multiple rows and one MODIFY
command can edit multiple rows at a time. These features make SQL a very powerful
language as compared to other languages where one command can process only a
single record at a time.
Relational Database and SQL
8. Reliable: SQL provides a high level of well-defined set of commands that provides the
desirable results without any ambiguity.
9. Freedom of Data Abstraction: SQL provides a greater degree of abstraction freedom
compared to any other procedural language.
10. Complete Language for a Database: Apart from being a strong query processing
language, it can also be used to create, insert, delete and control access to data in
databases.
12.15
12.11.1 Starting MySQL Database
MySQL is an open-source database system. You can download and install it directly from the
internet. After installing, you need to start working with MySQL by following the given steps:
Start
All Programs
MySQL
MySQL Server
After opening MySQL, the screen of the MySQL command prompt appears where you need to
specify a password to work with it.
After entering the password, the MySQL prompt appears, where you start typing the SQL
commands, as shown in Fig. 12.17. In order to come out of MySQL application, you can type
quit in front of the mysql> command prompt, as shown in Fig. 12.18.
Learning Tips:
1. Some database systems require a semicolon (;) at the end of each SQL statement.
2. Semicolon is the standard way to separate each SQL statement in database systems that allows more
than one SQL statement to be executed in the same call to the server.
3. SQL is NOT case-sensitive; select is the same as SELECT.
12.17
DECIMAL DECIMAL(x,y) Numbers stored in the DECIMAL format, where x is the size, i.e., total
or number of digits, and y is precision, i.e., it is the number of places to
DECIMAL(size, the right of the decimal point.
precision) For example, Decimal(8,2)
In the above example, decimal datatype stores a number that has 6
decimal point digits before the decimal and 2 digits after the decimal.
Decimal holds up to 19 significant digits. A negative number uses
one place for its sign (–).
6 digits 2 digits
8 digits
CHARACTER CHAR(x) This datatype stores ‘x’ number of characters in the string which has
(fixed length) or a fixed length. A maximum of 254 characters can be stored in a string.
CHAR(size) If you store strings that are not as long as the ‘size’ or ‘x’ parameter
value,the remaining spaces are left unused. For example, if you specify
CHAR(10), strings such as “ram” and “technology” are each stored as
10 characters. However, a student admission_no is 6 digits long in a
school, so CHAR(6) would be appropriate to store the admission_no
of all the students. This datatype is suitable where the number of
characters to store is fixed. The value for CHAR data type has to be
enclosed in single or double quotation marks.
CHARACTER VARCHAR(x) This datatype is used to store variable length alphanumeric data.
(variable length) or For example, address of a student can be declared as VARCHAR(25)
VARCHAR2(x) to store the address up to 25 characters long. The advantage of
using this datatype is that VARCHAR will not leave unused spaces. It
releases the unused memory spaces.
DATE DATE This datatype is used to store a date in ‘yyyy/mm/dd’ format. It stores
year, month and date values. DATE values can be compared with each
other only. The date values to be entered are to be enclosed in { } or
with single quotation marks.
TIME TIME This datatype is used to store time in hh:mm:ss format. It stores hour,
minute and second values. For example, a time of day can be taken as
12:30:45p.m. where 12 means hours, 30 means minutes and 45 refers
Supplement – Computer Science with Python–XII
to seconds.
BOOLEAN (logical) BOOLEAN This datatype is used for storing logical values, either true or false.
In both upper and lower case, T or Y stands for logical true and F or
N stands for logical false. The fields with Boolean (logical) datatype
can be compared only with other logical columns or constants.
BLOB/RAW/ LONG BLOB This datatype can store data up to a maximum length of 65535
RAW or RAW characters. BLOBs are “Binary Large Objects” and used to store a large
or amount of data such as images, animations, clips or other types of
LONG RAW files. For example, image raw(2000);
MEMO/LONG MEMO This datatype allows storing characters or remarks up to 2 GB per
or LONG record.
12.18
Table 12.2 Difference between CHAR and VARCHAR datatypes
CHAR VARCHAR
1. CHAR datatype provides fixed length memory 1. VARCHAR datatype provides variable length
storage. It specifies a fixed length character string. memory storage. It specifies a variable length
string (changeable).
2. The CHAR datatype can store a maximum of 0 to 2. The VARCHAR datatype can store a maximum
255 characters. number up to 65,535.
3. CHAR datatype is used when the data entries in a 3. VARCHAR datatype is used when the data entries
column are expected to be of the same size. in a column are expected to vary considerably in
size.
4. CHAR(x) will take x characters of storage even if 4. VARCHAR(x) will take only the required storage for
you enter less than x characters to that column. the actual number of characters entered to that
column.
5. If a value entered is shorter than its length x, then 5. No blanks are added if the length is shorter than
blanks are added. the maximum length, x.
6. CHAR datatype takes memory space of 1 byte per 6. VARCHAR takes up memory space of 1 byte
character. per character, +2 bytes to hold variable length
information.
7. Search operation is faster with CHAR datatype 7. Search operation works slower in VARCHAR
column. datatype column as compared to CHAR type.
8. For example, name char(10); 8. For example, name varchar(10);
name="anu"; name="anu";
name field occupies 0 bytes, with the first three then name occupies only 3+2=5 bytes, the first
bytes with values and the rest with blank data. three bytes for value and the other two bytes for
variable length information.
CTM: While defining datatype for columns or attributes in a relation, two points should be kept in mind:
1. When using fixed length data in columns like phone number, area code, use character datatype.
2. When using variable length data in columns like name, address, designation, use varchar datatype.
arguments complete or modify the meaning of a clause, which is salary in the given example.
A statement or command is a combination of two or more clauses. Statements are basically
the instructions given to SQL database for executing any task. For example, SELECT * FROM
employee is an SQL statement. An important point to remember here is that all the statements
in SQL terminate with a semi-colon (;). Also, SQL is not case sensitive; therefore, we can type
commands in either upper case or lower case.
12.19
Let us now learn how a database and tables in a database are created in SQL. A database is
used to house data in the form of tables. Therefore, before creating a table, it is mandatory to
create a database first.
We shall create a sample database School and then create a table Student in it.
Database: School
Tables_in_School
Student
Fees
To get started on our own database, we can first check which databases currently exist in MySQL
server. Use the SHOW DATABASES statement to find out which databases currently exist on the
server:
mysql> show databases;
+---------------+
| Database |
+---------------+
| mysql |
Supplement – Computer Science with Python–XII
| test |
+---------------+
2 rows in set (0.01 sec)
1. Creating Databases
The CREATE DATABASE command is used to create a database in RDBMS.
Syntax for creating a database:
CREATE DATABASE <database_name>;
For example,
mysql> create database school; Creates database with the name school.
When the above-mentioned command gets executed, a database with the name school will be
created on the system.
12.20
2. Opening Databases
Once a database has been created, we need to open it to work on it. For this, USE command is
required.
Syntax for opening a database:
USE <database_name>;
For example,
mysql> use school;
Database changed
3. Removing Databases
To physically remove/delete a database along with all its tables, DROP command is used.
Syntax for removing a database:
DROP DATABASE <database_name>;
For example,
mysql> drop database school;
Database deleted
4. Creating a Table
The CREATE TABLE statement is used to create a table in a database. Tables are organized into
rows and columns, and each table must have a name. It is the most extensively used DDL command.
A table must have at least one column.
Syntax for creating a table:
CREATE TABLE <table_name>
(
<column_name1><data_type> [(size)],
<column_name2><data_type> [(size)],
<column_name3><data_type> [(size)],
....
);
For example,
mysql> create table student
( Rollno integer NOT NULL PRIMARY KEY,
Name varchar(20) NOT NULL,
Relational Database and SQL
Gender char(1),
Marks integer(11)
DOB date );
Query OK, 0 rows affected (0.04 sec)
For each column, a name and a datatype must be specified and the column name must be unique
within the table definition. Column definitions are separated by comma. Upper case and lower case
letters make no difference in column names; the only place where upper and lower case letters
matter are string comparisons.
12.21
5. Viewing a Table
To verify that the table has been created, SHOW TABLES command is used.
mysql> show tables;
+------------------------+
| Tables_in_school |
+------------------------+
| student |
| fees |
+------------------------+
2 rows in set (0.01 sec)
12.22
While inserting a row, if we are adding value for all the columns of the table, we need not
specify the column(s) name in the SQL query. But we need to make sure that the order of
the values is in the same order as the columns represented in the structure of the table. The
following points should be kept in mind while inserting data in a relation:
• When values are inputted using INSERT INTO command, it is termed as single row
insert since it adds one tuple at a time into the table.
• The INTO clause specifies the target table and the VALUES clause specifies the data
to be added to the new record of the table.
• The argument/values of character datatype are always enclosed in double or single
quotation marks.
• Column values for the datatype of a column are provided within curly braces { } or
single quotes.
• NULL values are stored and displayed as NULL only without any quotes.
• If the data is not available for all the columns, then the column-list must be included
following the table name.
CTM: In SQL, we can repeat or re-execute the last command typed at SQL prompt by typing “/” key and
pressing enter.
(b) Inserting data directly into a table: The second form specifies both the column names
and the values to be inserted.
Syntax:
INSERT INTO <table_name> (column1,column2,columnN,...)
VALUES (value1,value2,valueN,...);
Here, column1, column2, ...columnN—the names of the columns in the table for which you
want to insert data.
For example, insert into student(RollNo, Name, Gender, Marks, DOB)
values(2,'Deep Singh', 'M', 98, '1996-08-22');
CTM: When adding a row, only the characters or date values should be enclosed within single quotes.
12.23
(d) Inserting NULL values into a table: If a column in a row has no value or missing value,
then the column is said to be null or holding NULL value. Null value can be given to any
column other than being assigned as primary key or Not Null constraint. It is advisable
to use Null when the actual value is not defined or unavailable. NULL values are treated
differently from other values as they represent missing unknown data. By default, a column
in a table can hold NULL values.
If a column in a table is optional, we can insert a new record or can modify an existing tuple
without adding values to this column. In other words, the values in every record for this
column/field shall be stored as NULL. We can insert NULL value into any column in a table.
It can be done by typing NULL without quotes.
Null is not equivalent to 0, i.e., NULL ≠ 0. It acts as a placeholder for unknown or inapplicable
values.
For example, insert into student(Rollno, Name, Gender, Marks, DOB)
values(12, 'Swati Mehra', 'F', NULL, NULL);
After the execution of the above command, NULL value shall be inserted for the fields
Marks and DOB respectively.
CTM: Null means unavailable or undefined value. Any arithmetic expression containing a NULL always
evaluates to null.
12.24
(b) Updating to NULL values
The values for the attributes in a relation can also be entered as NULL using UPDATE command.
For example, update student
set Marks = NULL
where Rollno = 9;
The above statement shall change the value of the field Marks to 0 for the student whose
roll number is 9.
(c) Updating using an expression or formula
For example, update student
set Marks = Marks + 10
where (Rollno = 5 or Rollno =10);
The above statement shall increment the value of Marks by 10 for all the records with Roll
number 5 or 10.
POINT TO REMEMBER
The WHERE clause in the SQL delete command is optional and it identifies the rows in the column that get
deleted. If you do not include the WHERE clause, all the rows in the table are deleted.
To delete all the rows from student table, the statement will be:
truncate table student;
Difference between DELETE and TRUNCATE Statements
DELETE Statement: This command deletes only the rows from the table based on the condition
given in the where clause or deletes all the rows from the table if no condition is specified. But it
does not free the space containing the table.
TRUNCATE Statement: This command is used to delete all the rows from the table and free the
space containing the table. 12.25
10. ALTER TABLE Command
The ALTER TABLE command is used to modify the definition (structure) of a table by modifying the
definition of its columns. The ALTER TABLE command is used to perform the following operations:
To add a column to an existing table.
To rename any existing column.
To change the datatype of any column or to modify its size.
To remove or physically delete a column.
(a) Adding a column to an existing table
Once a table has been created, new columns can be added later on, if required. The new
column is added with NULL values for all the records/rows in the table. It is possible to
add, delete and modify columns with ALTER TABLE statement.
Syntax for adding a new column:
ALTER TABLE <table_name> ADD(<column_name><datatype> [size]);
For example, to add a new column Mobile_no of type integer in the table student:
alter table student add (Mobile_no integer);
Thus, the above statement shall add a new column Mobile_no into the table student with
NULL value in it.
POINT TO REMEMBER
We have just added a column and there will be no data (NULL) under this attribute. UPDATE command can
be used to supply values/data to this column.
The above command will add a new column City with default value as “DELHI” to the
student table.
Resultant table: student
Rollno Name Gender Marks DOB Mobile_no City
1 Raj Kumar M 93 17-Nov-2000 NULL DELHI
2 Deep Singh M 98 22-Aug-1996 NULL DELHI
3 Ankit Sharma M 76 02-Feb-2000 NULL DELHI
4 Radhika Gupta F 78 03-Dec-1999 NULL DELHI
5 Payal Goel F 82 21-April-1998 NULL DELHI
6 Diksha Sharma F 80 17-Dec-1999 NULL DELHI
7 Gurpreet Kaur F 65 04-Jan-2000 NULL DELHI
8 Akshay Dureja M 90 05-May-1997 NULL DELHI
9 Shreya Anand F 70 08-Oct-1999 NULL DELHI
10 Prateek Mittal M 75 25-Dec-2000 NULL DELHI
12.26
(c) Modifying an existing column definition
The MODIFY clause can be used with ALTER TABLE command to change the datatype,
size, constraint related to any column of the table.
Syntax for modifying existing column datatype:
ALTER TABLE <table_name>
MODIFY([column_name1] <datatype1>);
For example,
alter table student modify (Name varchar(25));
The above command will modify the datatype size for the Name field from 20 to 25
characters.
(d) Renaming a column
The existing column in a relation can be renamed using ALTER TABLE command.
Syntax for renaming an existing column:
ALTER TABLE <table_name>
CHANGE [COLUMN] <old-column-name> <new-column-name> column_definition;
For example,
alter table student change City State varchar(10);
The above command shall rename the City column to State.
Rollno Name Gender Marks DOB Mobile_no State
1 Raj Kumar M 93 17-Nov-2000 NULL DELHI
2 Deep Singh M 98 22-Aug-1996 NULL DELHI
3 Ankit Sharma M 76 02-Feb-2000 NULL DELHI
4 Radhika Gupta F 78 03-Dec-1999 NULL DELHI
5 Payal Goel F 82 21-April-1998 NULL DELHI
6 Diksha Sharma F 80 17-Dec-1999 NULL DELHI
7 Gurpreet Kaur F 65 04-Jan-2000 NULL DELHI
8 Akshay Dureja M 90 05-May-1997 NULL DELHI
9 Shreya Anand F 70 08-Oct-1999 NULL DELHI
10 Prateek Mittal M 75 25-Dec-2000 NULL DELHI
12.27
Resultant table: student
Rollno Name Gender Marks DOB Mobile_no
1 Raj Kumar M 93 17-Nov-2000 NULL
2 Deep Singh M 98 22-Aug-1996 NULL
3 Ankit Sharma M 76 02-Feb-2000 NULL
4 Radhika Gupta F 78 03-Dec-1999 NULL
5 Payal Goel F 82 21-April-1998 NULL
6 Diksha Sharma F 80 17-Dec-1999 NULL
7 Gurpreet Kaur F 65 04-Jan-2000 NULL
8 Akshay Dureja M 90 05-May-1997 NULL
9 Shreya Anand F 70 08-Oct-1999 NULL
10 Prateek Mittal M 75 25-Dec-2000 NULL
screen. Retrieving information from the tables is done mainly using the SELECT command. The
SQL SELECT statement is used to fetch data from one or more database tables. It is used to
select rows and columns from a database/relation.
12.28
1. Selection
This capability of SQL returns the tuples from a relation with all the attributes.
Syntax:
SELECT <column-name1> [, <column-name2>…]
FROM <table-name>;
OR
SELECT <what_to_select>
FROM <which_table>
WHERE <conditions_to_satisfy>;
For example,
select Name, Gender from student;
The above command displays only name and gender attributes from the student table.
2. Projection: Selecting Specific Rows—WHERE Clause
This is the capability of SQL to return only specific attributes from the relation. Use of WHERE
clause is required when specific tuples are to be fetched or manipulated. To select all the
columns from a table, the asterisk (*) can be used.
For example,
select * from student;
The above command will display all the tuples (rows) from the relation student.
CTM: The asterisk (*) means “All”. SELECT * means displaying all the columns from a relation.
defined in the table structure. The salient features of SQL SELECT statement are as follows:
SELECT command displays the columns of the table in the same order in which they are
selected from the table.
In order to retrieve all the columns in the column-list from a table using SELECT command,
asterisk (*) is used and the columns are displayed in the same order in which they are
stored in the table.
All the statements (inclusive of SELECT statement) in SQL are terminated with a semicolon
(;). Use of semicolon is dependent on the version in use. 12.29
Using WHERE clause
select * from student where Rollno<=8;
The above command shall display only those records whose Rollno is less than or equal to 8.
Resultant table: student
Rollno Name Gender Marks DOB Mobile_no
1 Raj Kumar M 93 17-Nov-2000 NULL
2 Deep Singh M 98 22-Aug-1996 NULL
3 Ankit Sharma M 76 02-Feb-2000 NULL
4 Radhika Gupta F 78 03-Dec-1999 NULL
5 Payal Goel F 82 21-April-1998 NULL
6 Diksha Sharma F 80 17-Dec-1999 NULL
7 Gurpreet Kaur F 65 04-Jan-2000 NULL
8 Akshay Dureja M 90 05-May-1997 NULL
8 rows in a set (0.02 sec)
When a WHERE clause is used with a SELECT statement, the SQL query processor goes through
the entire table one row/record at a time and checks each row to determine whether the condition
specified is true with respect to that row or not. If it evaluates to True, the corresponding row
is selected, retrieved and displayed, else it returns an empty set (i.e., no data found).
CTM: SQL is case-insensitive, which means keywords like SELECT and select have same meaning in SQL
statements. On the contrary, MySQL makes difference in table names. So, if you are working with MySQL,
then you need to give table names as they exist in the database.
the field Stream from student table: 10 rows in a set (0.02 sec)
Relational Database and SQL
POINT TO REMEMBER
In the above statement, DUAL is the default table in MySQL. It is a one-row, one-column dummy table.
4 Radhika Gupta 88
5 Payal Goel 92
6 Diksha Sharma 90
7 Gurpreet Kaur 75
8 Akshay Dureja 100
9 Shreya Anand 80
10 Prateek Mittal 85
10 rows in a set (0.02 sec)
12.33
(b) Relational Operators
A relational (comparison) operator is a mathematical symbol which is used to compare two
values. It is used to compare two values of the same or compatible data types. Comparison
operators are used for conditions where two expressions are required to be compared with
each other, which results in either true or false. They are used with WHERE clause.
The following table describes different types of comparison operators in SQL:
OPERATOR DESCRIPTION
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<>, != Not equal to
For comparing character data type values, < means earlier in the alphabetical sequence and
> means later in the alphabetical sequence.
For example, mysql> select Rollno, Name, Marks from student where Marks>=90;
The above command shall display the Rollno, Name and Marks of all the students with
marks either equal to or greater than 90.
Resultant table: student
Rollno Name Marks
1 Raj Kumar 93
2 Deep Singh 98
3 Akshay Dureja 90
3 rows in a set (0.02 sec)
For example, mysql> select * from student
where Stream <> ‘Commerce’;
The above command shall display the records of all the students who are not from
Commerce stream.
Resultant table: student
Supplement – Computer Science with Python–XII
1. AND operator
The AND operator displays a record and returns a true value if all the conditions
(usually two conditions) specified in the WHERE clause are true.
As shown in the table, when both condition 1 and condition 2 are true, then only is
the result true. If either of them is false, the result becomes false.
For example, to list the details of all the students who have secured more than 80
marks and are male.
mysql> select * from student
where Marks > 80 and Gender= ‘M’;
Resultant table: student
Rollno Name Gender Marks DOB Mobile_no Stream
1 Raj Kumar M 93 17-Nov-2000 9586774748 Science
2 Deep Singh M 98 22-Aug-2000 8988886577 Commerce
8 Akshay Dureja M 90 05-May-1997 9560567890 Commerce
3 rows in a set (0.02 sec)
Relational Database and SQL
2. OR operator
The OR operator displays a record and returns a true value if either of the conditions
(usually two conditions) specified in the WHERE clause is true.
Condition 1 Condition 2 Result (OR operation)
True True True
True False True
False True True
False False False
12.35
As shown in the table, when either condition 1 or condition 2 is true, the result is
true. If both of them are false, then only the result becomes false.
For example, to display the roll number, name and stream of all the students who are
in either Science or Commerce stream.
mysql> select Rollno, Name, Stream from student where
Stream= ‘Science’ or Stream= ‘Commerce’;
Resultant table: student
Rollno Name Stream
1 Raj Kumar Science
2 Deep Singh Commerce
3 Ankit Sharma Science
7 Gurpreet Kaur Science
8 Akshay Dureja Commerce
10 Prateek Mittal Science
6 rows in a set (0.02 sec)
3. NOT operator
NOT operator is also termed as a negation operator. Unlike the other two operators,
this operator takes only one condition and gives the reverse of it as the result. It
returns a false value if the condition holds true and vice versa.
The NOT operator displays a record and returns a true value if either of the conditions
(usually two conditions) specified in the WHERE clause is true.
Condition 1 Result (NOT operation)
True False
False True
As shown in the table, when the condition is true, the result is false. If the condition
is false, then the result becomes true.
For example, to display the name and marks of all the students who are not in the
vocational stream.
mysql> select Name, Marks from student
Supplement – Computer Science with Python–XII
12.36
12.14.3 Comments in SQL
A comment is a text which is ignored by the SQL compiler and is not executed at all. It is given
for documentation purpose only. A comment usually describes the purpose of the statement
given within an application.
SQL Comments are used to understand the functionality of the program without looking into
it. The comments give us an idea about what is written in the given SQL statement and how it
works. The comments can make an application or code easier to read as well as to maintain.
A comment can be placed between any keywords, parameters or punctuation marks in a
statement. Comments can be either single-line comments or multiple-line comments.
SQL or MySQL supports three comment styles:
F Comments beginning with –– (followed by a space): The two dash lines indicate a single-
line comment in SQL statements. These single-line comments are basically used to show
the comments at the start and end of a program. A user can easily use this comment type
to explain the flow of program. This text cannot extend to a new line and ends with a line
break.
F Comments beginning with #: The comments begin with ‘#’ symbol followed by the text
to be displayed for the user’s information. This text cannot extend to a new line and ends
with a line break.
F Comments beginning with /*: Multi-line comments begin with a slash and an asterisk
(/*) followed by the text of the comment. This text can span multiple lines. The comment
ends with an asterisk and a slash (*/). The opening and terminating characters need not
be separated from the text by a space or a line break.
For example,
select Rollno, Name, Stream
/* This statement shall display the records of all those students who are in Science stream and
have secured marks more than 75. */
from student # student table in use
Stream= ‘Science’ and Marks > 75; --condition for projection
12.37
Using column alias name, we can give different name(s) to column(s) for display (output)
purpose only. They are created to make column names more readable. SQL aliases can be used
both for tables as well as columns.
• COLUMN ALIASES are used to make column headings in the query result set easier to read.
• TABLE ALIASES are used to shorten a table name by giving an easy alternate name, making
it easier to read or when performing a self-join (i.e., listing the same table more than once
in the FROM clause).
Syntax for table alias:
SELECT <columnname1>, <columnname2>.....
FROM <table_name> AS <alias_name>;
WHERE [<condition>];
Syntax for column alias:
SELECT <column-name> AS <“alias_name”>
FROM <table_name>
WHERE [<condition>];
For example,
Table: Student
Student_name Date-of-birth SELECT Name AS “Student_name”, DOB AS “Date_of_birth”
Ankit Sharma 02-Feb-2000 Alias name for fields, Name and DOB
POINTS TO REMEMBER
• If the alias_name contains spaces, you must enclose it in quotes.
• It is acceptable to use spaces when you are aliasing a column name. However, it is not generally a good
practice to use spaces when you are aliasing a table name.
• The alias_name is only valid within the scope of the SQL statement.
The above command, on execution, shall display the text “was born on” with every record
(tuple) of the table.
Resultant table: student
Rollno Name was born on DOB
1 Raj Kumar was born on 17-Nov-2000
2 Deep Singh was born on 22-Aug-1996
3 Ankit Sharma was born on 02-Feb-2000
4 Radhika Gupta was born on 03-Dec-1999
5 Payal Goel was born on 21-April-1998
6 Diksha Sharma was born on 17-Dec-1999
7 Gurpreet Kaur was born on 04-Jan-2000
8 Akshay Dureja was born on 05-May-1997
9 Shreya Anand was born on 08-Oct-1999
10 Prateek Mittal was born on 25-Dec-2000
10 rows in a set (0.02 sec)
FROM <table_name>
WHERE <column_name> BETWEEN <value1> AND <value2>;
For example,
mysql> select Rollno, Name, Marks from student where Marks between 80 and 100;
The above command displays Rollno, Name along with Marks of those students whose Marks
lie in the range of 80 to 100 (both 80 and 100 are included in the range).
12.39
Resultant table: student
Rollno Name Marks
1 Raj Kumar 93
2 Deep Singh 98
5 Payal Goel 82
6 Diksha Sharma 80
8 Akshay Dureja 90
5 rows in a set (0.02 sec) NOT BETWEEN
The NOT BETWEEN operator works opposite to the BETWEEN operator. It retrieves the rows
which do not satisfy the BETWEEN condition.
For example,
mysql> select Rollno, Name, Marks from student where Marks not between 80 and 100;
Resultant table: student
Rollno Name Marks
3 Ankit Sharma 76
4 Radhika Gupta 78
9 Shreya Anand 70
10 Prateek Mittal 75
4 rows in a set (0.02 sec)
12.42
Syntax for ORDER BY clause:
SELECT <column-list> FROM <table_name> [WHERE Rollno Name Marks
<condition>] ORDER BY <column_name> [ASC|DESC]; 8 Akshay Dureja 90
Here, WHERE clause is optional. 3 Ankit Sharma 76
2 Deep Singh 98
For example,
6 Diksha Sharma 80
Ø To display the roll number, name and marks of students 7 Gurpreet Kaur NULL
on the basis of their marks in the ascending order. 5 Payal Goel 82
Ø mysql> select Rollno, Name, Marks from student order by 10 Prateek Mittal 75
Name; 4 Radhika Gupta 78
1 Raj Kumar 93
Ø To display the roll number, name and marks of all the
9 Shreya Anand 70
students in the descending order of their marks and
ascending order of their names.
Ø mysql> select Rollno, Name, Marks from student order by Marks desc, Name;
Sorting on Column Alias
If a column alias is defined for a column, it can be used for displaying rows in ascending or
descending order using ORDER BY clause.
For example, select Rollno, Name, Marks as Marks_obtained
from student
Alias name
order by Marks_obtained;
12.19 GROUP BY
The GROUP BY clause can be used in a SELECT statement to collect data across multiple records
and group the results by one or more columns. It groups the rows on the basis of the values
present in one of the columns and then the aggregate functions are applied on any column of
these groups to obtain the result of the query.
This clause can be explained with reference to the table student; the rows can be divided into
four groups on the basis of the column Stream. One group of rows belongs to “Science” stream,
another belongs to “Commerce” stream, the third group belongs to “Humanities” stream and
the fourth belongs to “Vocational” stream. Thus, by using GROUP BY clause, the rows can be
divided on the basis of the stream column.
FROM <tables>
WHERE <conditions>
GROUP BY <column1>, <column2>, ... <column_n>;
Here, column_names must include the columns on the basis of which grouping is to be done.
aggregate_function can be a function such as sum(), count(), max(), min(), avg(), etc.
12.43
For example, to display the name, stream, marks and count the total number of students who
have secured more than 90 marks according to their stream.
mysql> select Name, Stream, count(*) as "Number of students"
from student
where marks>90
group by Stream;
Resultant table: student
Name Stream Number of students Marks
Raj Kumar Science 1 93
Deep Singh Commerce 2 98
2 rows in a set (0.02 sec)
For example,
mysql> select Stream, SUM(marks) as "Total Marks"
from student
group by Stream
having max(Marks) <85;
CTM: SELECT statement can contain only those attributes which are already present in the GROUP BY
clause.
Consider a table Employee (employee code, employee name, salary, job and city) with the following
structure:
Ecode Name Salary Job City
E1 Ritu Jain 5000 Manager Delhi
E2 Vikas Verma 4500 Executive Jaipur
E3 Rajat Chaudhary 6000 Clerk Kanpur
E4 Leena Arora 7200 Manager Bangalore
E5 Shikha Sharma 8000 Accountant Kanpur
12.45
• MAX()
MAX() function is used to find the highest value among the given set of values of any column
or expression based on the column. MAX() takes one argument which can be either a column
name or any valid expression involving a particular column from the table.
For example,
mysql> select max(Salary) from EMPLOYEE;
Output:
+----------------+
| MAX(Salary)|
+----------------+
| 8000 |
+----------------+
This command, on execution, shall return the maximum value from the specified column
(Salary) of the table Employee, which is 8000.
• MIN()
MIN() function is used to find the lowest value among the given set of values of any column
or expression based on the column. MIN() takes one argument which can be either a column
name or any valid expression involving a particular column from the table.
For example,
mysql> select min(Salary) from EMPLOYEE;
Output:
+----------------+
| MIN(Salary) |
+----------------+
| 4500 |
+----------------+
This command, on execution, shall return the minimum value from the specified column
(Salary) of the table Employee, which is 4500.
Supplement – Computer Science with Python–XII
• SUM()
SUM() function is used to find the total value of any column or expression based on a column.
It accepts the entire range of values as an argument, which is to be summed up on the basis of a
particular column, or an expression containing that column name. The SUM() function always
takes argument of integer type only. Sums of String and Date type data are not defined.
For example,
mysql> select sum(Salary) from EMPLOYEE;
Output:
+----------------+
| SUM(Salary) |
+----------------+
| 30700 |
+----------------+
This command, on execution, shall return the total of the salaries of all the employees from the
12.46 specified column (Salary) of the table Employee, which is 30700.
• AVG()
AVG() function is used to find the average value of any column or expression based on a column.
Like sum(), it also accepts the entire range of values of a particular column to be taken average of,
or even a valid expression based on this column name. Like SUM() function, the AVG() function
always takes argument of integer type only. Average of String and Date type data is not defined.
For example,
mysql> select avg(Salary) from EMPLOYEE;
Output: Ecode Name Salary Job City
+----------------+ E1 Ritu Jain NULL Manager Delhi
| AVG(Salary) | E2 Vikas Verma 4500 Executive Jaipur
+----------------+ E3 Rajat Chaudhary 6000 Clerk Kanpur
| 6140 | E4 Leena Arora NULL Manager Bangalore
+----------------+ E5 Shikha Sharma 8000 Accountant Kanpur
This command, on execution, shall return the average of the salaries of all the employees from
the specified column (Salary) of the table Employee, which is 6140.
• COUNT()
COUNT() function is used to count the number of values in a column. COUNT() takes one
argument, which can be any column name, or an expression based on a column, or an asterisk
(*). When the argument is a column name or an expression based on the column, COUNT()
returns the number of non-NULL values in that column. If the argument is asterisk (*), then
COUNT() counts the total number of records/rows satisfying the condition, if any, in the table.
For example,
mysql> select count(*) from EMPLOYEE;
Output:
+----------------+
| COUNT(*) |
+----------------+
|5 |
+----------------+
This command, on execution, shall return the total number of records in the table Employee,
which is 5.
mysql> select count(distinct City) from EMPLOYEE;
Output:
+-------------------------------+
| COUNT(DISTINCT City) |
Relational Database and SQL
+-------------------------------+
|4 |
+-------------------------------+
This command, on execution, shall return the total number of records on the basis of city with
no duplicate values, i.e., Kanpur is counted only once; the second occurrence is ignored by
MySQL because of the DISTINCT clause. Thus, the output will be 4 instead of 5.
12.47
• Aggregate Functions & NULL Values
Consider the table Employee given in the previous section with NULL values against the
Salary field for some employees.
None of the aggregate functions takes NULL into consideration. NULL values are simply
ignored by all the aggregate functions as clearly shown in the examples given below:
mysql> select sum(Salary) from Employee;
Output: 18500
mysql> select min(Salary) from Employee;
Output: 4500 (NULL values are not considered.)
mysql> select max(Salary) from Employee;
Output: 8000 (NULL values are not ignored.)
mysql> select count(Salary) from Employee;
Output: 3 (NULL values are not ignored.)
mysql> select avg(Salary) from Employee;
Output: 6166.66 (It will be calculated as 18500/3, i.e., sum/total no. of records, which
are 3 after ignoring NULL values.)
mysql> select count(*) from Employee;
Output: 5
mysql> select count(Ecode) from Employee;
Output: 5 (No NULL value exists in the column Ecode.)
mysql> select count(Salary) from Employee;
Output: 3 (NULL values are ignored while counting the total number of records
on the basis of Salary. )
You may use any condition on group, if required. HAVING <condition> clause is used to apply
a condition on a group.
mysql> select Job, sum(Pay) from EMP group by Job having sum(Pay)>=8000;
mysql> select Job, sum(Pay) from EMP group by Job having avg(Pay)>=7000;
mysql> select Job, sum(Pay) from EMP group by Job having count(*)>=5;
mysql> select Job, min(Pay), max(Pay), avg(Pay) from EMP
group by Job having sum(Pay)>=8000;
mysql> select Job, sum(Pay) from EMP where city='Dehradun'
group by Job having count(*)>=5;
12.48
WHERE vs HAVING
WHERE clause works in respect to the whole table but HAVING clause works on Group only.
If WHERE and HAVING both are used, then WHERE will be executed first. Where is used to
put a condition on individual row of a table whereas HAVING is used to put a condition on an
individual group formed by GROUP BY clause in a SELECT statement.
Aggregate Functions and Group (GROUP BY Clause): Other Combinations
Consider the following table Employee with NULL values against the Salary field for some
employees:
Employee
Ecode Ename Salary Job City
E1 Ritu Jain NULL Manager Delhi
E2 Vikas Verma 4500 Executive Jaipur
E3 Rajat Chaudhary 6000 Clerk Kanpur
E4 Leena Arora NULL Manager Bengaluru
E5 Shikha Sharma 8000 Accountant Kanpur
None of the aggregate functions takes NULL into consideration. NULL values are simply ignored
by all the aggregate functions as clearly shown in the examples given below.
An Aggregate function may be applied on a column with DISTINCT or * (ALL) symbol. If nothing
is given, ALL scope is assumed.
12.49
Using avg (<Column>)
This function returns the Average value in the given column.
mysql> select avg(Salary) from Employee;
mysql> select avg(Salary) from Employee group by City;
(1,a)
(1,b)
(1,c)
A B (2,a)
(2,b)
1 a
(2,c)
(3,a)
2 X b = (3,b)
(3,c)
3 c
two tables, i.e., it returns the rows which are common in both
the tables.
table 1 table 2
mysql> select student.Rollno, Name, fee from student, fees
where student.Rollno = fees.Rollno order by student.Rollno;
OR
mysql> select A.Rollno, Name, fee from student A, fees B
where A.Rollno = B.Rollno order by A.Rollno;
12.51
Thus, the output for the given command will be:
Resultant Table
Rollno Name Fee
2 Jaya 5500
3 Teena 5000
4 Diksha 4500
2. Outer Join: The Outer Join keyword returns all rows from the right table (table 2), with the
matching rows in the left table (table 1). The result is NULL in the left side when there is no
match.
mysql> select A.Rollno, Name, fee
from student A, fees B where OUTER JOIN
A.Rollno = B.Rollno order by B.fee desc;
Resultant Table
Rollno Name Fee table 1 table 2
2 Jaya 5500
3 Teena 5000
4 Diksha 4500
Note: Self, Non-equi and Natural join are beyond the scope of this book.
Table: Vehicle
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
Note:
• PERKM is Freight Charges per kilometre
Supplement – Computer Science with Python–XII
12.52
Note:
• NO is Traveller Number
• KM is Kilometres travelled
• NOP is number of travellers in vehicle
• TDATE is Travel Date
(a) To display NO, NAME, TDATE from the table TRAVEL in descending order of NO.
Ans. select NO, NAME, TDATE from TRAVEL order by NO desc;
(b) To display the NAME of all the travellers from the table TRAVEL who are travelling by
vehicle with code 101 or 102.
Ans. select NAME from TRAVEL
where CODE=‘101’ or
CODE=’102’;
OR
select NAME from TRAVEL
where CODE=101 or
CODE=102;
(c) To display the NO and NAME of those travellers from the table TRAVEL who travelled
between ‘2015–12–31’ and ‘2016–04–01’.
Ans. select NO, NAME from TRAVEL
where TDATE >= ‘2016-04-01’ and TDATE <= ‘2015-12-31’;
OR
select NO, NAME from TRAVEL
where TDATE between '2016-04-01' and '2015-12-31';
(d) To display the CODE, NAME, VTYPE from both the tables with distance travelled (Km) less
than 90Km.
Ans. select A.CODE, NAME,
VTYPE from TRAVEL A,
VEHICLE B JOIN Operation using
Table alias names
where A.CODE=B.CODE and KM<90;
(e) To display the NAME and amount to be paid for vehicle code as 105. Amount to be paid is
calculated as the product of KM and PERKM.
Relational Database and SQL
12.53
12.22 UNION
The UNION operator is used to combine the result-set of two or more SELECT statements.
The UNION operation is used to return all the distinct rows selected by either query.
For executing Union between two tables, the number of columns selected from each table
should be the same. Also, the datatypes of the corresponding columns selected from each table
should be the same.
MEMORY BYTES
SQL is a language that is used to create, modify and access a database.
The various processing capabilities of SQL are Data Definition Language (DDL), Data Manipulation Language (DML)
and Data Control Language (DCL).
DDL is used to create and delete tables, views or indexes.
DML is used to modify and update the database.
DESCRIBE or DESC is used to show the structure of a table.
The SELECT statement is used to fetch data from one or more database tables.
SELECT * means display all columns.
The WHERE clause is used to select specific rows.
The DESCRIBE statement is used to see the structure of a table.
12.54
We can change the structure of a table, i.e., add, remove or change its column(s) using the ALTER TABLE statement.
The keyword DISTINCT is used to eliminate redundant data from display.
Logical operators OR and AND are used to connect relational expressions in WHERE clause.
Logical operator NOT is used to negate a condition.
The BETWEEN operator defines the range of values that the column values must fall within to make the condition
true.
The IN operator selects values that match any value in the given list of values.
% and _ are two wild card characters. The percent (%) symbol is used to represent any sequence of zero or more
characters. The underscore (_) symbol is used to represent a single character.
NULL represents a value that is unavailable, unassigned, unknown or inapplicable.
The results of the SELECT statement can be displayed in the ascending or descending order of a single column or
columns using ORDER BY clause.
DROP DATABASE drops all tables in the database and deletes the database. Once the DROP command is used,
then we cannot use that database. So, we should be careful with this command.
The CREATE statement is used to create a table in MySQL with constraint. A constraint is a restriction on the
behaviour of a variable.
INSERT query is used for inserting new rows or data into an existing table.
The ORDER BY keyword in MySQL is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order,
use the DESC keyword.
HAVING clause is used in combination with GROUP BY clause.
GROUP BY clause is used whenever aggregate functions by group are required.
The HAVING clause is used to place conditions on groups created by GROUP BY clause because here the WHERE
clause is not usable.
An aggregate function is a function where the values of multiple rows are grouped together as input based on
certain criteria to form a single value of more significant meaning.
The COUNT() function returns the number of rows that matches a specified criteria.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.
(d) Patterns in MySQL are described using two special wild card characters such as ................................
and ................................ .
(e) The keyword ................................ is used to select rows that do not match the specified pattern of
characters.
(f) The default order of ORDER BY clause is ................................ .
(g) The ................................ function is used to count the number of records in a ……………………… column.
(h) The rows of the table (relation) are referred to as ................................ .
(i) A virtual table is called a ................................ .
12.55
(j) The non-key attribute which helps to make relationship between two tables is known as
................................ .
(k) To specify filtering condition for groups, the ................................ clause is used in MySQL.
Answers: (a)
MySQL (b) dual (c) distinct
(d) % (percent), _ (Underscore) (e) not like (f) ascending
(g) count() (h) tuples (i) view
(j) foreign key (k) having
2. State whether the following statements are True or False.
(a) Duplication of data is known as Data Redundancy.
(b) An Attribute is a set of values of a dissimilar type of data.
(c) MySQL supports different platforms like UNIX and Windows.
(d) UPDATE TABLE command is used to create table in a database.
(e) Null (unavailable and unknown) values are entered by the following command:
INSERT INTO TABLE_NAME VALUES (“NULL”);
(f) ALTER TABLE command is used to modify the structure of the table.
(g) Each SQL table must have at least one column and one row.
(h) Foreign key column derives its value from the primary key of the parent table.
(i) DISTINCT clause is used to remove redundant rows from the result of the SELECT statement.
(j) SELECT MIN (salary) FROM Employee will return the highest salary from the table.
(k) Group functions can be applied to any numeric values, some text types and DATE values.
Answers: (a) True
(b) False (c) True (d) False (e) False (f) True
(g) False (h) True (i) True (j) False (k) True
3. Multiple Choice Questions (MCQs)
(a) The .................. allows us to perform tasks related to data definition.
(i) DDL (ii) DML (iii) TCL (iv) None of these
(b) The .................. allows us to perform tasks related to data manipulation.
(i) DDL (ii) DML (iii) TCL (iv) None of these
(c) A .................. is a text that is not executed.
(i) Statement (ii) Query (iii) Comment (iv) Clause
(d) .................. are words that have a special meaning in SQL.
(i) Keyword (ii) Literal (iii) Variable (iv) Table
Supplement – Computer Science with Python–XII
Ans. An attribute or a set of attributes which is used to identify a tuple (row) uniquely is known as
Primary Key.
Table: Students
Admission_No First Name Last Name DOB
27354 Jatin Kumar 05-02-1998
25350 Mona Sinha 24-09-2004
26385 George Moun 19-05-1997
16238 Mukesh Kumar 24-09-2004
Admission_No. is the Primary Key because this column will contain unique data for each record. 12.57
(b) Write a query that displays city, salesman name, code and commission from salesman table.
Ans. select city, salesman_name, code, commission from salesman;
(c) Write a query that selects all orders except those with zero or NULL in the amount field from table
orders.
Ans. select * from orders where amount is not NULL;
(d) Write a command that deletes all orders for the customer SOHAN from table customer.
Ans. delete from customer where customer_name is like ‘SOHAN’;
(e) Differentiate between DROP and DELETE command.
Ans. DROP command is used to drop a table along with all the records stored in it whereas DELETE command
is used to delete all the records or some of the records from a table without deleting the table.
(f) How can you add a new column or a constraint in a table?
Ans. If you want to add a new column in an existing table, ALTER command is used. For example, to add a
column bonus in a table emp, the statement will be given as:
alter table emp add(bonus Integer);
(g) Can you add more than one column in a table by using the ALTER TABLE command?
Ans. Yes, we can add more than one column by using the ALTER TABLE command. Multiple column names are
given, which are separated by commas, while giving with ADD. For example, to add city and pin code in
a table employee, the command can be given as:
alter table employee
add(city char(30), PINCODE integer);
(h) What are JOINS?
Ans. A JOIN is a query that combines tuples from more than one table. In a join query, the table names are
given with FROM clause, separated by a comma. For example,
select name, salary from emp1, emp2;
In this statement, the two tables are emp1 and emp2 from which the column name and salary are
extracted.
11. How can you eliminate duplicate records in a table with select query?
Ans. The DISTINCT clause is used with SELECT statement to hide duplicate records in a table. For example, to
display cities from table suppliers.
select distinct city from suppliers;
12. Consider a database LOANS with the following table:
Table: LOANS
Supplement – Computer Science with Python–XII
12.58
(v) Display the Interest-wise details of Loan Account Holders.
(vi) Display the Interest-wise details of Loan Account Holders with at least 10 instalments remaining.
Ans. (i) Mysql> select sum(Loan_Amount) from LOANS where Interest >10;
(ii) Mysql> select max(Interest) from LOANS;
(iii) Mysql> select count(*) from LOANS where Cust_Name like ‘%Sharma’;
(iv) Mysql> select count(*) from LOANS where Interest is NULL;
(v) Mysql> select * from LOANS group by Interest;
(vi) Mysql> select * from LOANS group by Interest having Instalment>=10;
13. Consider the table ‘HOTEL’ given below: [CBSE D 2016]
EMPID CATEGORY SALARY
E101 MANAGER 60000
E102 EXECUTIVE 65000
E103 CLERK 40000
E104 MANAGER 62000
E105 EXECUTIVE 50000
E106 CLERK 35000
Mr. Vinay wanted to display average salary of each category. He entered the following SQL statement.
Identify error(s) and rewrite the correct SQL statement.
select CATEGORY, SALARY from HOTEL group by CATEGORY;
Ans. select CATEGORY, avg(SALARY) from HOTEL group by CATEGORY;
14. What is an ORDER BY clause and GROUP BY clause?
Ans. ORDER BY clause is used to display the result of a query in a specific order (sorted order).
The sorting can be done in ascending or in descending order. However, the actual data in the database is
not sorted but only the results of the query are displayed in sorted order. If order is not specified then,
by default, the sorting will be performed in ascending order.
For example,
SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in ascending or descending
order.
For example,
SELECT * FROM student ORDER BY city DESC;
It displays all the records of table student ordered by city in descending order.
GROUP BY clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group
the results by one or more columns.
For example,
SELECT name, COUNT(*) as “Number of employees”
FROM student WHERE marks>350 GROUP BY city;
Relational Database and SQL
15. Consider the following tables Product and Client. Write SQL commands for the statements (i) to (iii) and
give outputs for SQL queries (iv) to (vi).
Table: PRODUCT
P_ID Product Name Manufacturer Price
TP01 Talcum Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
12.59
Table: CLIENT
C_ID Client Name City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
16 Dreams Bengaluru TP01
(i) To display the details of those Clients whose city is Delhi.
(ii) To display the details of Products whose Price is in the range of 50 to 100 (both values included).
(iii) To display the details of those products whose name ends with ‘Wash’
(iv) select distinct City from CLIENT;
(v) select Manufacturer, max(Price), min(Price), count(*) from PRODUCT group by Manufacturer;
(vi) select Product Name, Price * 4 from PRODUCT;
Ans. (i) select * from CLIENT where City="Delhi";
(ii) select * from PRODUCT where Price is between 50 and 100;
(iii) select * from PRODUCT where Name like '%Wash';
(iv) City
-----
Delhi
Mumbai
Bengaluru
(v)
Manufacturer Max(Price) Min(Price) Count(*)
LAK 40 40 1
ABC 55 45 2
XYZ 120 95 2
(vi)
Product Name Price*4
Talcum Powder 160
Face Wash 180
Bath Soap 220
Shampoo 480
Supplement – Computer Science with Python–XII
12.60
18. Define the various SQL Constraints.
Ans. Constraints are the rules enforced on data or columns on a table. These are used to restrict the values that
can be inserted in a table. This ensures data accuracy and reliability in the database.
Following are the most commonly used constraints available in SQL:
(a) NOT NULL Constraint: Ensures that a column cannot have NULL value.
(b) DEFAULT Constraint: Provides a default value for a column when no value is specified.
(c) UNIQUE Constraint: Ensures that all values in a column are unique. There should not be any redundant
value in a column which is being restricted.
(d) PRIMARY Key: Uniquely identifies each row/record in a database table.
(e) FOREIGN Key: Uniquely identifies a row/record in any other database table.
(f) CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain conditions.
For example, to restrict the salary column that it should contain salary more than ` 10,000.
19. Consider the following tables: COMPANY and MODEL.
Table: Company
Comp_ID CompName CompHO ContactPerson
1 Titan Okhla C.B. Ajit
2 Ajanta Najafgarh R. Mehta
3 Maxima Shahdara B. Kohli
4 Seiko Okhla R. Chadha
5 Ricoh Shahdara J. Kishore
Note:
Comp_ID is the Primary Key.
Table: Model
Model_ID Comp_ID Cost DateOfManufacture
T020 1 2000 2010-05-12
M032 4 7000 2009-04-15
M059 2 800 2009-09-23
A167 3 1200 2011-01-12
T024 1 1300 2009-10-14
Note:
Model_ID is the Primary Key.
Comp_ID is the Foreign Key referencing Comp_ID of Company table.
Write SQL commands for queries (i) to (iv) and output for (v) and (vi).
(i) To display details of all models in the Model table in ascending order of DateOfManufacture.
(ii) To display details of those models manufactured in 2011 and whose Cost is below 2000.
(iii) To display the Model_ID, Comp_ID, Cost from the table Model, CompName and ContactPerson
from Company table, with their corresponding Comp_ID.
Relational Database and SQL
(iv) To decrease the cost of all the models in Model table by 15%.
(v) select count(distinct CompHO) from Company;
(vi) select CompName, contact(‘Mr.’,ContactPerson) from Company where CompName ends with ‘a’;
Ans. (i) select * from Model
order by DateOfManufacture;
(ii) select * from Model
where year(DateOfManufacture) = 2011 and Cost < 2000;
(iii) select Model_ID, Comp_ID, Cost, CompName, ContactPerson from Model, Company
where Model.Comp_ID = Company.Comp_ID;
12.61
(iv) update Model
set Cost = Cost – 0.15*Cost;
(v) 3
(vi) Ajanta Mr. R. Mehta
Maxima Mr. B. Kohli
20. Consider the following two tables: PRODUCT and CLIENT.
Table: Product
P_ID ProductName Manufacturer Price ExpiryDate
TP01 Talcum Powder LAK 40 2011-06-26
FW05 Face Wash ABC 45 2010-12-01
BS01 Bath Soap ABC 55 2010-09-10
SH06 Shampoo XYZ 120 2012-04-09
FW12 Face Wash XYZ 95 2010-08-15
Note:
P_ID is the Primary Key.
Table: Client
C_ID ClientName City P_ID
1 Cosmetic Shop Delhi FW05
6 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty One Delhi FW05
16 Dreams Bengaluru TP01
14 Expressions Delhi NULL
Note:
C_ID is the Primary Key.
P_ID is the Foreign Key referencing P_ID of Client table.
Write SQL statements for the queries (i) to (iv) and output for (v) and (vi):
(i) To display the ClientName and City of all Mumbai- and Delhi-based clients in Client table.
(ii) Increase the price of all the products in Product table by 10%.
(iii) To display the ProductName, Manufacturer, ExpiryDate of all the products that expired on or before
Supplement – Computer Science with Python–XII
‘2010-12-31’.
(iv) To display C_ID, ClientName, City of all the clients (including the ones that have not purchased a
product) and their corresponding ProductName sold.
(v) select count(distinct Manufacturer) from Product;
(vi) select C_ID, Client_Name, City from Client where City like ‘M%’;
Ans. (i) select ClientName, City from Client
where City = ‘Mumbai’ or City = ‘Delhi’;
(ii) update Product
set Price = Price + 0.10 * Price;
(iii) select ProductName, Manufacturer, ExpiryDate from Product
where ExpiryDate < = ‘2010-12-31’;
(iv) select C_ID, ClientName, City, ProductName from Client Left Join Product
on Client. P_ID = Product.P_ID;
(v) 3
(vi) 6 Total Health Mumbai
12.62
21. Consider the following two tables: STATIONERY and CONSUMER.
Table: Stationery
S_ID StationeryName Company Price StockDate
DP01 Dot Pen ABC 10 2011-03-31
PL02 Pencil XYZ 6 2010-01-01
ER05 Eraser XYZ 7 2010-02-14
PL01 Pencil CAM 5 2009-01-09
GP02 Gel Pen ABC 15 2009-03-19
Note:
S_ID is the Primary Key.
Table: Consumer
C_ID ConsumerName Address P_ID
01 Good Learner Delhi PL01
06 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
16 Motivation Bengaluru PL01
Note:
C_ID is the Primary Key.
P_ID is the Foreign Key referencing S_ID of Stationery table.
Write SQL statements for the queries (i) to (iv) and output for (v) and (vi):
(i) To display details of all the Stationery Items in the Stationery table in descending order of
StockDate.
(ii) To display details of that Stationery item whose Company is XYZ and price is below 10.
(iii) To display ConsumerName, Address from the table Consumer and Company and Price from
Stationery table, with their corresponding S_ID.
(iv) To increase the price of all the stationery items in Stationery table by ` 2.
(v) select count(distinct Address) from Consumer;
(vi) select StationeryName, price * 3 from Stationery
where Company = ‘CAM’;
Ans. (i) select * from Stationery
order by StockDate desc;
(ii) select * from Stationery
where Company = ‘XYZ’ and Price < 10;
(iii) select ConsumerName, Address, Company, Price from Stationery, Consumer
where Stationery. S_ID = Consumer.P_ID;
(iv) Update Stationery
Relational Database and SQL
12.63
22. Consider the following tables: STOCK and DEALER.
Table: Stock
ItemNo Item Dcode Qty UnitPrice StockDate
5005 Ball Pen 0.5 102 100 16 2011-03-31
5003 Ball Pen 0.25 102 150 20 2010-01-01
5002 Gel Pen Premium 101 125 14 2010-02-14
5006 Gel Pen Classic 101 200 22 2009-01-09
5001 Eraser Small 102 210 5 2009-03-19
5004 Eraser Big 102 60 10 2010-12-12
5009 Sharpener Classic 103 160 8 2010-01-23
Note:
ItemNo is the Primary Key.
Dcode is the Foreign Key referencing Dcode of Dealer table.
Table: Dealer
Dcode DName
101 Reliable Stationers
103 Class Plastics
104 Fair Deals
102 Clear Deals
Note:
Dcode is the Primary Key.
Write SQL statements for the queries (i) to (iv) and output for (v) and (vi):
(i) To display details of all the Items in the Stock table in ascending order of StockDate.
(ii) To display details of those Items in Stock table whose Dealer Code(Dcode) is 102 or quantity in
Stock(Qty) is more than 100.
(iii) To insert a record in the Stock table with the values:
(5010, ‘Pencil HB’, 102, 500, 10, ‘2010-01-26’)
(iv) To display Dcode, Dname from Dealer table and Item, UnitPrice from Stock table of all the Dealers
(including the dealer details that have not sold any item)
(v) select count(distinct Dcode) from Stock;
(vi) select Qty * UnitPrice from Stock where ItemNo=5006;
Supplement – Computer Science with Python–XII
12.64
23. (a) Explain the concept of Cartesian product between two tables with the help of example.
Note: Answer questions (b) and (c) on the basis of the following tables SHOP and ACCESSORIES.
Table: SHOP
Id SName Area
S01 ABC Computronics CP
S02 All Infotech Media GK II
S03 Tech Shoppe CP
S04 Geek Tenco Soft Nehru Place
S05 Hitech Tech Store Nehru Place
Table: ACCESSORIES
No Name Price Id
A01 Motherboard 12000 S01
A02 Hard Disk 5000 S01
A03 Keyboard 500 S02
A04 Mouse 300 S01
A05 Motherboard 13000 S02
A06 Keyboard 400 S03
A07 LCD 6000 S04
T08 LCD 5500 S05
T09 Mouse 350 S05
T010 Hard Disk 450 S03
Ans. When you join two or more tables without any condition, it is called Cartesian product or Cross Join.
Example: SELECT * FROM SHOP, ACCESSORIES;
(b) Write the SQL queries:
(i) To display Name and Price of all the Accessories in ascending order of their Price.
(ii) To display Id and SName of all Shops located in Nehru Place.
(iii) To display Minimum and Maximum Price of all the accessories.
Ans. (i) select Name, Price from ACCESSORIES order by Price;
(ii) select Id, SName from SHOP where Area=’Nehru Place’;
(iii) select max(Price), min(Price) from ACCESSORIES;
(c) Write the output of the following SQL commands:
(i) select distinct NAME from ACCESSORIES where PRICE>=5000;
(ii) select AREA, count(*) from SHOP group by AREA;
(iii) select count(distinct AREA) from SHOP;
Ans. (i) Name
Motherboard
Hard Disk
Relational Database and SQL
LCD
(ii) AREA COUNT
CP 2
GK II 1
Nehru Place 2
(iii) COUNT
3
12.65
24. (a) Define a candidate key with example. Write SQL queries for (b) to (f) and write the output for the
SQL queries mentioned in parts (g1) to (g3) on the basis of tables PRODUCTS and SUPPLIERS.
Table: PRODUCTS
PID PName QTY Price COMPANY SUPCODE
101 DIGITAL CAMERA 14X 120 12000 RENIX S01
102 DIGITAL PAD 11i 100 22000 DIGI POP S02
104 PEN DRIVE 16 GB 500 1100 STOREKING S01
106 LED SCREEN 32 70 28000 DISPEXPERTS S02
105 CAR GPS SYSTEM 60 12000 MOVEON S03
Table: SUPPLIERS
SUPCODE SNAME CITY
S01 GET ALL INC KOLKATA
S03 EASY MARKET CORP DELHI
S02 DIGI BUSY GROUP CHENNAI
Ans. (a) A table may have more than one such attribute/group of attributes that identifies a tuple uniquely;
all such attribute(s) is/are known as Candidate Keys.
Table: Item
Ino Item QTY
101 Pen 560
102 Pencil 780
104 CD 450
109 Floppy 700
105 Eraser 300
Candidate Keys
103 Duster 200
(b) To arrange and display all the records of table Products on the basis of product name in the ascending
order.
Ans. select * from PRODUCTS order by PNAME;
Supplement – Computer Science with Python–XII
(c) To display product name and price of all those products whose price is in the range of 10000 and 15000
(both values inclusive).
Ans. select PNAME, PRICE from PRODUCTS where PRICE>=10000 and PRICE<=15000;
(d) To display the price, product name and quantity (i.e., qty) of those products which have quantity more
than 100.
Ans. select PRICE, PNAME, QTY from PRODUCTS where QTY>100;
(e) To display the names of those suppliers who are either from DELHI or from CHENNAI.
Ans. select SNAME from SUPPLIERS where CITY=”DELHI” or CITY=”CHENNAI”;
(f) To display the names of the companies and the names of the products in descending order of company
names.
Ans. select COMPANY, PNAME from PRODUCTS order by COMPANY desc;
(g) Obtain the outputs of the following SQL queries based on the data given in tables PRODUCTS and
SUPPLIERS above.
(g1) select distinct SUPCODE from PRODUCTS;
(g2) select max(PRICE), min(PRICE) from PRODUCTS;
12.66 (g3) select PRICE*QTY AMOUNT from PRODUCTS where PID=104;
Ans. (g1)
DISTINCT SUPCODE
S01
S02
S03
(g2)
MAX (PRICE) MIN (PRICE)
28000 1100
(g3)
PRICE*QTY
550000
25. (a) Give a suitable example of a table with sample data and illustrate Primary and Alternate Keys in it.
Ans. Primary Key: Primary key is a set of one or more fields/columns of a table that uniquely identifies a record
in a database table. It cannot accept null, duplicate values. Only one Candidate Key can be
the Primary Key.
Alternate key: Alternate key is a key that can work as a primary key. Basically, it is a candidate key that
currently is not a primary key.
Example: In the table given below, AdmissionNo becomes the Alternate Key when we define
RegistrationNo as the Primary Key.
Student Registration Table
RegistrationNo AdmissionNo Name Phone Gender DOB
CBSE4554 215647 Mihir Ranjan 9568452325 Male 1992-04-15
CBSE6985 265894 Amita Guha 8456985445 Female 1993-03-24
CBSE5668 458961 Rajesh Singh 9654212440 Male 1992-12-04
CBSE3654 469799 Mohit Patel 7421589652 Male 1992-05-16
Primary Key – RegistrationNo
Alternate Key – AdmissionNo
(b) Consider the following table CARDEN given below:
Table: CARDEN
Ccode CarName Make Color Capacity Charges
501 A-Star Suzuki RED 3 14
503 Indigo Tata SILVER 3 12
502 Innova Toyota WHITE 7 15
509 SX4 Suzuki SILVER 4 14
510 C Class Mercedes RED 4 35
Write SQL commands for the following statements:
Relational Database and SQL
12.67
(c) Give the output of the following SQL queries:
(i) select count(distinct Make) from CARDEN;
(ii) select max(Charges), min(Charges) from CARDEN;
(iii) select count(*), Make from CARDEN;
(iv) select CarName from CARDEN where Capacity=4;
Ans. (i) COUNT(DISTINCT Make)
4
(ii) MAX(Charges) MIN(Charges)
35 12
(iii) COUNT(*) Make
5 Suzuki
(iv) CarName
SX4
C Class
26. Consider the tables EMPLOYEE and SALGRADE given below and answer (a) and (b) parts of this question.
Table: EMPLOYEE
ECODE NAME DESIG SGRADE DOJ DOB
101 Abdul Ahmad EXECUTIVE S03 23-Mar-2003 13-Jan-1980
102 Ravi Chander HEAD-IT S02 12-Feb-2010 22-Jul-1987
103 John Ken RECEPTIONIST S03 24-Jun-2009 24-Feb-1983
105 NazarAmeen GM S02 11-Aug-2006 03-Mar-1984
108 PriyamSen CEO S01 29-Dec-2004 19-Jan-1982
Table: SALGRADE
SGRADE SALARY HRA
S01 56000 18000
S02 32000 12000
S03 24000 8000
(a) Write SQL commands for the following statements:
(i) To display the details of all EMPLOYEEs in descending order of DOJ.
(ii) To display NAME and DESIG of those EMPLOYEEs whose SALGRADE is either S02 or S03.
(iii) To display the content of the entire EMPLOYEEs table, whose DOJ is in between ‘09-Feb-2006’
Supplement – Computer Science with Python–XII
and ‘08-Aug-2009’.
(iv) To add a new row with the following content:
109,‘Harish Roy’,‘HEAD-IT’,‘S02’,‘9-Sep-2007’,‘21-Apr-1983’
Ans. (i) select * from EMPLOYEE order by DOJ desc;
(ii) select NAME, DESIG from EMPLOYEE where SGRADE=S02 OR SGRADE=S03;
(iii) select * from EMPLOYEE where DOJ between ‘09-Feb-2006’ and ‘08-Aug-2009’;
(iv) insert into EMPLOYEE values(109, ‘Harish Roy’, ‘HEAD-IT’, ‘S02’, ‘9-Sep-2007’, ‘21-Apr-1983’);
(b) Give the output of the following SQL queries:
(i) select count(SGRADE), SGRADE from EMPLOYEE group by SGRADE;
(ii) select min(DOB), max(DOJ) from EMPLOYEE;
(iii) select SGRADE, SALARY+HRA from SALGRADE where SGRADE =’S02’;
Ans. (i) COUNT (SGRADE) SGRADE
2 S03
2 S02
1 S01
12.68
(ii) MAX (DOB) MIN (DOJ)
22-Jul-1987 23-Mar-2003
(iii) SGRADE SALARY+HRA
P003 440000
27. Consider the following tables STOCK and DEALERS and answer (a) and (b) parts of this question:
Table: STOCK
ItemNo Item Dcode Qty UnitPrice StockDate
5005 Ball Pen 0.5 102 100 16 31-Mar-10
5003 Ball Pen 0.25 102 150 20 01-Jan-10
5002 Gel Pen Premium 101 125 14 14-Feb-10
5006 Gel Pen Classic 101 200 22 01-Jan-09
5001 Eraser Small 102 210 5 19-Mar-09
5004 Eraser Big 102 60 10 12-Dec-09
5009 Sharpener Classic 103 160 8 23-Jan-09
Table: DEALERS
Dcode Dname
101 Reliable Stationers
103 Classic Plastics
102 Clear Deals
(a) Write SQL commands for the following statements:
(i) To display details of all Items in the Stock table in ascending order of StockDate.
Ans. select * from STOCK order by StockDate;
(ii) To display ItemNo and Item name of those items from Stock table whose UnitPrice is more than
` 10.
Ans. select ItemNo, Item from STOCK where UnitPrice>10;
(iii) To display the details of those items whose dealer code (Dcode) is 102 or Quantity in Stock (Qty)
is more than 100 from the table Stock.
Ans. select * from STOCK where Dcode=102 or Qty>100;
(iv) To display Maximum UnitPrice of items for each dealer individually as per Dcode from the table
Stock.
Ans. select Dcode, max(UnitPrice) from STOCK group by Dcode;
(b) Give the output of the following SQL queries:
(i) select count(distinct Dcode) from Stock;
Ans.
Count(DISTINCT Dcode)
3
(ii) select Qty*UnitPrice from Stock where ItemNo=5006;
Ans. Qty*UnitPrice
4400
(iii) select min(StockDate) from Stock;
Ans. MIN (StockDate)
01-Jan-09
Relational Database and SQL
28. Write SQL commands for (a) to (f) on the basis of table SPORTS:
Table: SPORTS
StudentNo Class Name Game1 Grade1 Game2 Grade2
10 7 Sameer Cricket B Swimming A
11 8 Sujit Tennis A Skating C
12 7 Kamal Swimming B Football B
13 7 Venna Tennis C Tennis A
14 9 Archana Basketball A Cricket A
15 10 Arpit Cricket A Athletics C
12.69
(a) Display the names of the students who have grade ‘C’ in either Game1 or Game2 or both.
(b) Display the number of students getting grade ‘A’ in Cricket.
(c) Display the names of the students who have the same game for both Game1 and Game2.
(d) Display the game taken up by the students, whose name starts with ‘A’.
(e) Add a new column named ‘Marks’.
(f) Assign a value 200 for marks for all those who are getting grade ‘B’ or grade ‘A’ in both Game1 and
Game2.
Ans. (a) select Name from SPORTS where Grade1=‘C’ or Grade2=‘C’;
(b) select count(*) from SPORTS where (Grade1='A' and Grade2='A') and (Game1='Cricket' or
Game2='Cricket');
(c) select name from SPORTS where Game1 = Game2;
(d) select Game1, Game2 from SPORTS where Name like ‘A%’;
(e) alter table SPORTS add (Marks int(4));
(f) update SPORTS set Marks=200 where (Grade1='A' or Grade2='A') or (Grade1='B' or Grade2='B');
29. (a) Study the following table and write SQL queries for questions (i) to (iv) and output for (v) and (vi).
Table: Orders
Orderid Pname Quantity Rate Sale_date Discount
1001 Pen 10 20 2019-10-05
1002 Pencil 20 10 2019-10-21
1003 Book 10 100 2019-11-02 50
1004 Eraser 100 5 2019-12-05 25
1005 Copy 50 20 2019-12-10
(i) Write SQL query to display Pname, Quantity and Rate for all the orders that are either Pencil or Pen.
(ii) Write SQL query to display the orders which are not getting any Discount.
(iii) Write SQL query to display the Pname, Quantity and Sale_date for all the orders whose total cost
(Quantity * Rate) is greater than 500.
(iv) Write SQL query to display the orders whose Rate is in the range 20 to 100.
(v) select Pname, Quantity from Orders where Pname like(‘_e%’);
(vi) select Pname, Quantity, Rate from Orders order by Quantity desc;
Ans. (i) select Pname, Quantity, Rate from Orders where Pname in (‘Pencil’,’Pen’);
(ii) select * from Orders where Discount is NULL;
(iii) select Pname, Quantity, Sale_date from Orders where Quantity * Rate > 500;
(iv) select * from Orders where Rate between 20 and 100;
(v)
Pname Quantity
Supplement – Computer Science with Python–XII
Pen 10
Pencil 20
(vi)
Pname Quantity Rate
Eraser 100 5
Copy 50 20
Pencil 20 20
Book 10 100
Pen 10 20
(b) Based on the Orders Table given above, write SQL query to display the minimum quantity, maximum
quantity and total quantity of Orders.
Ans. select min(Quantity), max(Quantity), sum(Quantity) from Orders;
(c) What is the difference between COUNT(*) and COUNT(Column Name)?
Ans. COUNT(*) includes the cells in the column containing NULL values.
COUNT(Column name) ignores the cells in the column containing NULL values.
12.70
UNSOLVED QUESTIONS
1. What is an Alternate Key?
2. What are views? How are they useful?
3. Define the following terms:
(a) Relation (b) Tuple
(c) Attribute (d) Domain
4. What do you understand by the terms candidate key and cardinality of a relation in a relational database?
5. What is SQL? What are different categories of commands available in SQL?
6. What is a database system? What is its need?
7. Differentiate between DDL and DML commands.
8. What is a datatype? Name some datatypes available in MySQL.
9. Differentiate between char and varchar datatypes.
10. Which operator concatenates two strings in a query result?
11. How would you calculate 13*15 in SQL?
12. Which keywords eliminate redundant data from a query?
13. What is the significance of GROUP BY clause in an SQL query?
14. What is the difference between WHERE and HAVING clause in SQL select command?
15. Write SQL queries to perform the following based on the table PRODUCT having fields as (prod_id,
prod_name, quantity, unit_rate, price, city)
(i) Display those records from table PRODUCT where prod_id is more than 100.
(ii) List records from table PRODUCT where prod_name is ‘Almirah’.
(iii) List all those records whose price is between 200 and 500.
(iv) Display the product names whose price is less than the average of price.
(v) Show the total number of records in the table PRODUCT.
16. Define the following terms:
(i) Database (ii) Data Inconsistency
(iii) Primary Key (iv) Candidate Key
(v) Indexes
17. Consider the following EMP and DEPT tables:
Table: EMP
EmpNo EmpName City Designation DOJ Sal Comm DeptID
8369 SMITH Mumbai CLERK 1990-12-18 800.00 NULL 20
8499 ANYA Varanasi SALESMAN 1991-02-20 1600.00 300.00 30
8521 SETH Jaipur SALESMAN 1991-02-22 1250.00 500.00 30
8566 MAHADEVAN Delhi MANAGER 1991-04-02 2985.00 NULL 20
... .......... .......... .......... .......... .......... .......... ..........
Table: DEPT
Relational Database and SQL
Table: STUDENT
StdID Name FName Stream TeacherID
Write the SQL commands to get the following:
(a) Show the names of students enrolled in the Science Stream.
(b) Count the number of students in the Commerce Stream.
(c) Count the number of teachers in each designation.
(d) Display the maximum pay of the teacher who is teaching English.
(e) Write a query to find out the number of students in each Stream in STUDENT table.
19. Consider the following tables STORE and SUPPLIERS. Write SQL commands for the statements (i) to (iv)
and give outputs for SQL queries (v) to (viii).
Table: Store
ItemNo Item Scode Qty Rate LastBuy
2005 Sharpener Classic 23 60 8 31-Jun-09
2003 Ball Pen 0.25 22 50 25 01-Feb-10
2002 Gel Pen Premium 21 150 12 24-Feb-10
2006 Gel Pen Classic 21 250 20 11-Mar-09
2001 Eraser Small 22 220 6 19-Jan-09
2004 Eraser Big 22 110 8 02-Dec-09
2009 Ball Pen 0.5 21 180 18 03-Nov-09
Table: SUPPLIERS
Supplement – Computer Science with Python–XII
Scode Sname
21 Premium Stationery
23 Soft Plastics
22 Tetra Supply
(i) To display details of all the items in the Store table in ascending order of LastBuy.
(ii) To display Itemno and item name of those items from Store table whose rate is more than 15 rupees.
(iii) To display the details of those items whose supplier code is 22 or quantity in store is more than 110
from the table Store.
(iv) To display minimum rate of items for each Supplier individually as per Scode from the table Store.
(v) select count(distinct Scode) from STORE;
(vi) select Rate*Qty from STORE where Itemno=2004;
(vii) select Item, Sname from STORE S, SUPPLIER P where S.Scode=P.Scode and ItemNo=2006;
(viii) select max(LastBuy) from STORE;
12.72
20. Write SQL commands for (i) to (vi) on the basis of relations given below:
BOOKS
book_id Book_name author_name Publishers Price Type qty
k0001 Let us C Sanjay Mukharjee EPB 450 Comp 15
p0001 Genuine J. Mukhi FIRST PUBL. 755 Fiction 24
m0001 Mastering C++ Kantkar EPB 165 Comp 60
n0002 VC++ advance P. Purohit TDH 250 Comp 45
k0002 Programming with Python Sanjeev FIRST PUBL. 350 Fiction 30
ISSUED
Book_ID Qty_Issued
L02 13
L04 5
L05 21
(i) To show the books of FIRST PUBL. Publishers written by P. Purohit.
(ii) To display cost of all the books published for FIRST PUBL.
(iii) Depreciate the price of all books of EPB publishers by 5%.
(iv) To display the BOOK_NAME and price of the books, more than 3 copies of which have been issued.
(v) To show total cost of books of each type.
(vi) To show the details of the costliest book.
21. Write SQL commands for (i) to (vi) and write output for (vii) on the basis of PRODUCTS relation given
below:
PRODUCTS TABLE
PCODE PNAME COMPANY PRICE STOCK MANUFACTURE WARRANTY
P001 TV BPL 10000 200 12-JAN-2018 3
P002 TV SONY 12000 150 23-MAR-2017 4
P003 PC LENOVO 39000 100 09-APR-2018 2
P004 PC COMPAQ 38000 120 20-JUN-2019 2
P005 HANDYCAM SONY 18000 250 23-MAR-2017 3
(i) To show details of all PCs with stock more than 110.
(ii) To list the company which gives warranty of more than 2 years.
(iii) To find stock value of the BPL company where stock value is the sum of the products of price and
stock.
(iv) To show number of products from each company.
(v) To count the number of PRODUCTS which shall be out of warranty on 20-NOV-2020.
(vi) To show the PRODUCT name of the products which are within warranty as on date.
(vii) Give the output of the following statements:
(a) select count(distinct COMPANY) from PRODUCT;
(b) select max(PRICE) from PRODUCT where WARRANTY<=3;
Relational Database and SQL
12.73
26. Consider the given table and answer the questions.
Table: SchoolBus
Rtno Area_Covered Capacity Noofstudents Distance Transporter Charges
1 Vasant Kunj 100 120 10 Shivam travels 100000
2 Hauz Khas 80 80 10 Anand travels 85000
3 Pitampura 60 55 30 Anand travels 60000
4 Rohini 100 90 35 Anand travels 100000
5 Yamuna Vihar 50 60 20 Bhalla travels 55000
6 Krishna Nagar 70 80 30 Yadav travels 80000
7 Vasundhara 100 110 20 Yadav travels 100000
8 Paschim Vihar 40 40 20 Speed travels 55000
9 Saket 120 120 10 Speed travels 100000
10 Janakpuri 100 100 20 Kisan Tours 95000
(i)To show all information of students where capacity is more than the no. of students in order of Rtno.
(ii)To show Area_Covered for buses covering more than 20 km., but Charges less than 80000.
(iii)To show transporter-wise total no. of students travelling.
(iv) To show Rtno, Area_Covered and average cost per student for all routes where average cost per
student is—Charges/Noofstudents.
(v) Add a new record with the following data:
(11, “Motibagh”,35,32,10, “Kisan tours”, 35000)
(vi) Give the output considering the original relation as given:
(a) select sum(Distance) from SchoolBus where Transporter=“Yadav travels”;
(b) select min(Noofstudents) from SchoolBus;
(c) select avg(Charges) from SchoolBus where Transporter=“Anand travels”;
(d) select distinct Transporter from SchoolBus;
27. Write SQL Commands for (i) to (v) and write the outputs for (vi) to (viii) on the basis of the following table:
Table: FURNITURE
NO ITEM TYPE DATEOFSTOCK PRICE DISCOUNT
1 WhiteLotus DoubleBed 2002-02-23 3000 25
2 Pinkfeathers BabyCot 2002-01-29 7000 20
3 Dolphin BabyCot 2002-02-19 9500 20
4 Decent OfficeTable 2002-02-01 25000 30
Supplement – Computer Science with Python–XII
Table: PRODUCT
P_ID ProductName Manufacturer Price Discount
TP01 Talcum Powder LAK 40
FW05 Face Wash ABC 45 5
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120 10
FW12 Face Wash XYZ 95
12.75
Table: CLIENT
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi TP01
02 Total Health Mumbai FW05
03 Live Life Delhi BS01
04 Pretty Woman Delhi SH06
05 Dreams Delhi FW12
(i) Write SQL Query to display ProductName and Price for all products whose Price is in the range 50 to
150.
(ii) Write SQL Query to display details of products whose manufacturer is either XYZ or ABC.
(iii) Write SQL query to display ProductName, Manufacturer and Price for all products that are not
giving any discount.
(iv) Write SQL query to display ProductName and price for all products whose ProductName ends with
‘h’.
(v) Write SQL query to display ClientName, City, P_ID and ProductName for all clients whose city is
Delhi.
(vi) Which column is used as Foreign Key and name the table where it has been used as Foreign key.
32. Answer the questions based on the table given below:
Table: HOSPITAL
SNo Name Age Department Dateofadm Charges Sex
1 Arpit 62 Surgery 21-01-98 300 M
2 Zareena 22 ENT 12-12-97 250 F
3 Kareem 32 Orthopaedic 19-02-98 200 M
4 Arun 12 Surgery 11-01-98 300 M
5 Zubin 30 ENT 12-01-98 250 M
6 Ketaki 16 ENT 24-02-98 250 F
7 Ankit 29 Cardiology 20-02-98 800 F
8 Zareen 45 Gynaecology 22-02-98 300 F
9 Kush 19 Cardiology 13-01-98 800 M
10 Shilpa 23 Nuclear Medicine 21-02-98 400 F
(a) To list the names of all the patients admitted after 15/01/98.
Supplement – Computer Science with Python–XII
(b) To list the names of female patients who are in ENT department.
(c) To list the names of all patients with their date of admission in ascending order.
(d) To display Patient’s Name, Charges, Age for only female patients.
(e) Find out the output of the following SQL commands:
(i) select count(distinct Charges) from HOSPITAL;
(ii) select min(Age) from HOSPITAL where Sex=”F”;
12.76
Case-based/Source-based
Integrated Questions
(Chapters 1–12)
Supplement – Computer Science with Python–XII
C.2
2. Hindustan Chemicals Ltd. is a company that deals in manufacturing and exporting of chemicals across
the world and has hundreds of employees on its roll. It wishes to computerize the process of salary
generation. Write a Python program to enter the names of employees and their salaries as input and
store them in a dictionary and also represent the data as a Salary Generation Report.
Ans.
C.3
CHAPTER 2: FUNCTIONS
1. Traffic accidents occur due to various reasons. While problems with roads or inadequate safety facilities
lead to some accidents, majority of the accidents are caused by drivers’ carelessness and their failure to
abide by traffic rules.
ITS Roadwork is a company that deals with manufacturing and installation of traffic lights so as to
minimize the risk of accidents. Keeping in view the requirements, traffic simulation is to be done. Write
a program in Python that simulates a traffic light. The program should perform the following:
(a) A user-defined function trafficLight() that accepts input from the user, displays an error message if
the user enters anything other than RED, YELLOW and GREEN. Function light() is called and
the following is displayed depending upon return value from light():
(i) “STOP, Life is more important than speed” if the value returned by light() is 0.
(ii) “PLEASE GO SLOW.” if the value returned by light() is 1.
(iii) “You may go now.” if the value returned by light() is 2.
(b) A user-defined function light() that accepts a string as input and returns 0 when the input is RED,
1 when the input is YELLOW and 2 when the input is GREEN. The input should be passed as an
argument.
(c) Display “BETTER LATE THAN NEVER” after the function trafficLight() is executed.
Ans.
Supplement – Computer Science with Python–XII
C.4
2. Kids Elementary is a playway school that focuses on ‘Play and learn’ strategy that helps toddlers
understand concepts in a fun way. Being a senior programmer, you have taken responsibility to develop
a program using user-defined functions to help children differentiate between upper case and lower case
letters/English alphabet in a given sentence. Make sure that you perform a careful analysis of the type
of alphabets and sentences that can be included as per age and curriculum.
Write a Python program that accepts a string and calculates the number of upper case letters and lower
case letters.
Ans.
C.5
Ans.
OUTPUT:
2. (a) Gurukul Academy uses “Student Management Information System” (SMIS) to manage student-related
data. This system provides facilities for:
• recording and maintaining personal details of students,
Supplement – Computer Science with Python–XII
School Name
Name: ABC Roll No: 25
Age: 16 Class: XII
Address: Address line1 State: Delhi
Pin Code: 999999
C.6
(b) On the basis of the above scenario, write a user-defined function to:
• Accept the marks of the student in five major subjects in Class XII and display the same.
• Calculate the sum of the marks of all subjects.
• Divide total marks by number of subjects, i.e., 5, and calculate and display the percentage
(percentage = total marks/5).
• Find the grade of the student as per the following criteria:
C.7
library. Write a Python program to add the records of new books in a file so that the records are stored
for future retrieval and can be accessed whenever required.
Ans.
C.8
Contents of the file “book.txt” with records of newly added books
2. Genesis Infotech plans to develop a computerized system for payroll processing of all its employees for
storing salary details and furnishing relevant and required data in terms of total contribution towards
its employees.
Develop a Python program which stores data in “employee.csv”, calculates and displays total salary
remitted to its employees and to display the number of employees who are drawing a salary of more
than ` 5000 per month.
Ans.
C.9
Contents of “employee.csv”
C.10
2. FLYAIR Airlines has grown big and touches more than 140 destinations worldwide, offering excellent
service to its passengers. To provide latest information to its customers at the click of a button, the
company offers computerized processing of passenger details.
Write a Python program comprising methods/functions to add or delete a passenger’s name from the list
of passengers, considering them as insert and delete operations of the Queue data structure.
Ans.
C.11
CHAPTER 8: COMPUTER NETWORKS
1. Perfect Edu. Services Ltd. is an educational organization. It is planning to set up its India campus at Chennai
with its head office at Delhi. The Chennai campus has four main buildings—ADMIN, ENGINEERING,
BUSINESS and MEDIA.
You, as a network expert, have to suggest the best network-related solutions for their problems raised in
(a) to (d), keeping in mind the distances between the buildings and other given parameters.
DELHI CHENNAI
Head Office Campus
ENGINEERING
ADMIN BUSINESS
MEDIA
Shortest distance between various buildings:
ADMIN to ENGINEERING 55 m
ADMIN to BUSINESS 90 m
ADMIN to MEDIA 50 m
ENGINEERING to BUSINESS 55 m
Supplement – Computer Science with Python–XII
ENGINEERING to MEDIA 50 m
BUSINESS to MEDIA 45 m
DELHI Head Office to CHENNAI Campus 2175 m
Number of Computers installed at various buildings is as follows:
ADMIN 110
ENGINEERING 75
BUSINESS 40
MEDIA 12
DELHI Head Office 20
(a) Suggest the most appropriate location for the server inside the Chennai campus (out of the 4
buildings) to get the best connectivity for maximum number of computers. Justify your answer.
(b) Suggest and draw the cable layout to efficiently connect various buildings within the Chennai
campus for connecting the computers.
(c) Which hardware device will you suggest to be procured by the company to be installed to protect
and control the internet use within the campus?
C.12
(d) Which of the following will you suggest to establish online face-to-face communication between
the people in the Admin Office of the Chennai campus and Delhi Head Office?
(i) Cable TV (ii) Email (iii) Video conferencing (iv) Text Chat
Ans. (a) ADMIN (due to maximum number of computers) or MEDIA (due to shorter distance from other
buildings)
(b) Any one of the following:
ENGINEERING ENGINEERING
MEDIA MEDIA
(c) Firewall or Router
(d) (iii) Video conferencing
2. Tech Up Corporation (TUC) is a professional consultancy company. The company is planning to set up
new offices in India with its hub at Hyderabad. As a network adviser, you have to understand their
requirements and suggest to them the best available solutions. [CBSE D 2014]
Conference Human
Block Resource
Block
Finance
Block
Block-to-Block distance (in Mtrs.):
Block (From) Block (To) Distance
Human Resources Conference 60
Human Resources Finance 60
Conference Finance 120
C.13
Ans. (a) Human resources will be the most appropriate block where TUC should plan to install the server.
(b)
Conference Human
Block Resource
Block
Finance
Block
(c) Ethernet Cable
(d) Switch
(e) Linux and Open Solaris
(f) Cost reduction: Unlike on-site hosting, the price of deploying applications in the cloud can be less
due to lower hardware costs from more effective use of physical resources.
Choice of applications: This allows flexibility for cloud users to experiment and choose the best
option for their needs. Cloud computing also allows a business to use, access and pay only for
what they use, with a fast implementation time.
3. Rovenza Communication International (RCI) is an online corporate training provider company for
IT-related courses. The company is setting up their new campus in Kolkata. You, as a network expert,
have to study the physical locations of various blocks and the number of computers to be installed. In
the planning phase, provide the best possible answer for the queries (a) to (d) raised by them.
Block-to-Block distance (in Mtrs.):
From To Distance
Administrative Block Finance Block 60
Administrative Block Faculty Recording Block 120
Finance Block Faculty Recording Block 70
Expected Computers to be installed in each block:
Block Computers
Administrative Block 30
Finance Block 20
Faculty Recording Block 100
(a) Suggest the most appropriate block where RCI should plan to install the server.
Supplement – Computer Science with Python–XII
(b) Suggest the most appropriate block-to-block cable layout to connect all three blocks for efficient
communication.
(c) Which type of network out of the following is formed by connecting the computers of these three
blocks?
(i) LAN (ii) MAN (iii) WAN
(d) Which wireless channel out of the following should be opted by RCI to connect to students from
all over the world?
(i) Infrared (ii) Microwave (iii) Satellite
Ans. (a) Faculty recording block (due to maximum number of computers)
or
Finance (due to shorter distance from the other buildings)
or
Administrative block (due to name or nature of the building)
C.14
(b) The different cable layout can be:
Faculty Administrative
Recording Block
Block
Finance
Block
or
Faculty Finance
Recording Block
Block
Administrative
Block
or
Faculty Administrative
Recording Block
Block
Finance
Block
Law
Admin
School
Centre-to-centre distance between various buildings:
Law School to Business School 60 m
Law School to Technology School 90 m
Law School to Admin Centre 115 m
Business School to Technology School 40 m
Business School to Admin Centre 45 m
Technology School to Admin Centre 25 m
C.15
Number of computers in each of the Schools/Centre:
Law School 25
Technology School 50
Admin Centre 125
Business School 35
(a) Suggest the most suitable place (i.e., schools/centre) to install the server of this university with a
suitable reason.
(b) Suggest an ideal layout for connecting these schools/centre for a wired connectivity.
(c) Which device will you suggest to be placed/installed in each of these schools/centre to efficiently
connect all the computers within these schools/centre?
(d) The university is planning to connect its admission office in the closest big city, which is more than
350 km from the university. Which type of network out of LAN, MAN or WAN will be formed? Justify
your answer.
Ans. (a) Admin Centre because Admin Centre has the maximum number of computers, or Business School
because it is closest to all other centres (minimum cable length required).
(b) BUS topology is the most suitable cable layout.
(c) Switch
(d) WAN is the preferred network for this purpose because 350 km is more than the range of LAN and MAN.
5. University of Correspondence in Allahabad is setting up a network between its different wings. There are
4 wings named Science (S), Journalism (J), Arts (A) and Home Science (H).
Distance between various wings:
Law School to Business School 60 m
Law School to Technology School 90 m
Law School to Admin Centre 115 m
Business School to Technology School 40 m
Business School to Admin Centre 45 m
Technology School to Admin Centre 25 m
Number of computers in each of the Schools/Centre:
Law School 25
Technology School 50
Admin Centre 125
Business School 35
(a) Suggest the most suitable Topology for networking the computers of all wings.
Supplement – Computer Science with Python–XII
(b) Name the wing where the Server is to be installed. Justify your answer.
(c) Suggest the placement of the Hub/Switch in the network.
(d) Mention how economic technology will provide internet accessibility to all wings.
Ans. (a) Star Topology can be used to network the computers of all wings.
(b) The Server should be installed in Wing A as Wing A has the maximum number of computers and
installing the server in this wing will help to reduce the network traffic.
(c) Hub/Switch will be required in all the wings.
(d) The economic way to provide internet accessibility to all the wings is to use the proxy server at
Wing A and connect to the internet through a dial-up network.
6. Sony has set up its Branch at Srinagar for its office and web-based activities. It has four Zones of buildings
as shown in the diagram:
Zone Zone
Z Y
Zone Zone
X U
C.16
Branch-to-branch distance is:
Zone X to Zone Z 40 m
Zone Z to Zone Y 60 m
Zone Y to Zone X 135 m
Zone Y to Zone U 70 m
Zone X to Zone U 165 m
Zone Z to Zone U 80 m
Number of Computers:
Zone X 50
Zone Z 130
Zone Y 40
Zone U 15
(a) Suggest the most suitable cable layout or Networking Topology of connections between the Zones.
(b) Suggest the most suitable place (i.e., Zone) to house the ERP and BI Server of this organization with
a suitable reason, with justification.
(c) Suggest the placement of the following devices with justification:
(i) Repeater (ii) Hub/Switch
(d) Which is the most economic type of cable for the selected topology?
Ans. (a) Bus Topology
(b) The most suitable place (i.e., Zone) to house the ERP and BI Server is Zone Z as it has the most
number of computers; thus, cabling cost will be reduced and most traffic will be local.
(c) Repeater: As per the suggested layout, separate repeaters need not be installed as each building/
zone will be having a hub that acts as a repeater.
Hub/switch should be placed in each zone.
Hub Hub
Zone Zone
X U
(d) An economic type of cable is dial-up or broadband as it can connect two computers at an economic
rate though it provides lesser speed than other expensive methods.
INDIA
New Delhi
Front Back
Supplement – Computer Science with Python–XII
Work
West
South East
Approximate distance between these offices as per network survey team is as follows:
Place From Place To Distance
Back Office Front Office 10 km
Back Office Work Office 70 m
Back Office East Office 1291 km
Back Office West Office 790 km
Back Office South Office 1952 km
C.18
In continuation of the above, the company experts have planned to install the following number of
computers in each of their offices:
Back Office 100
Front Office 20
Work Office 50
East Office 50
West Office 50
South Office 50
(a) Suggest network type (out of LAN, MAN, WAN) for connecting each of the following sets of their
offices:
(i) Back Office and Work Office (ii) Back Office and South Office
(b) Which device out of the following will you suggest to be produced by the company for connecting
all the computers within each of their offices?
(i) Switch/Hub (ii) Modem (iii) Telephone
(c) Which of the following communication mediums will you suggest to be procured by the company
for connecting their local office units in New Delhi for very effective and fast communication?
(i) Telephone Cable (ii) Optical Fibre (iii) Ethernet Cable
(d) Suggest a cable/wiring layout for connecting the company’s local office located in New Delhi. Also,
suggest an effective method/technology for connecting the company’s regional office—“East
Office”, ”West Office“ and ”South Office”—with offices located in New Delhi.
Ans. (a) Back Office and Work Office—MAN
Back Office and South Office—WAN
(b) Switch/Hub
(c) Optical Fibre
(d) Cable/Wiring Layout:
INDIA
New Delhi
Front Back
Work
West East
South
C.19
(a) Program to read and fetch all the records from EMP table having salary more than ` 70000.
Ans.
(b) Program to update the records of employees by increasing salary by ` 1000 of all those employees
who are getting less than ` 80000.
Ans.
Supplement – Computer Science with Python–XII
C.20
(c) Program to delete the record on the basis of inputted salary.
Ans.
(b) M/S Trends Garments also keeps BLAZER of MAROON colour in medium size, priced at ` 900 each.
Insert this record in COST table.
Ans. INSERT INTO COST VALUES(7,’M’,900); This record is not inserted and error gets displayed.
(c) When you used the above query to insert data, you were able to enter the values for BLAZER
without entering its details in the UNIFORM relation. If not, state the reason behind it.
Ans. No, the above record does not get inserted as it is violating the REFFERENTIAL INTEGRITY clause in SQL,
which says that a record in a secondary table is accompanied only if the same record with the same
primary key value exists in its respective base table. So, any value that does not exist in a primary table
can never be taken as a value in the secondary table.
(d) ALTER table to add the constraint that price of an item is always greater than zero.
Ans. ALTER TABLE PRICE
MODIFY COST CHECK COST>0;
C.22