1 Computer Science Python Book Class XI
1 Computer Science Python Book Class XI
ScienceClass XI
CENTRAL BOARD OF
SECONDARY EDUCATION
Shiksha Kendra, 2, Community Centre,
Preet Vihar, Delhi-110 092 India
Computer Science - Class XI
COMPUTER
SCIENCE
Class-XI
PRINTED BY :
H
k
k
jrd
klaf
o/
ku
m
í
sf
'
kdk
g
e
]H
k
k
jrd
sy k
sx
]Hk
k
jrd
k
s,
d^
¹lE
i
w.
k
Zi
zH
k
qR
o&l
ai
U
ule
kto
k n h
iaF
k
f
u j
i
s{
ky
ksdr
a=
k
kR
edx
.k
j
kT
;º
cu
k
u
sdsf
y,
]r
F
k
km
ld
s
l
e
Lr
u
kx
fj
dk
sa dk
s%
l
k
ek
ftd
]vkf
F
kZdv
k
Sj
jk
tu
Sf
r
d U
;k;
]
f
o
pkj
]vf
Hk
O
;fDr
]f
o'
ok
l]/
e Z
v k Sj
mik
luk
dhL
o r
a=
k
rk
]
izf
r "
Bkvk
Sj
vol
j dhler
k
izk
I
rd j
kusdsf
y,
]r
Fk
k m
u l
cesa]
O;
f
Drd
hx f
j
ekv
kSj¹j
k"
V
ªd
2
h
,dr
k
vkSj
v[k
.
M r
k
ºlqf
u
f'prd
ju
s
o
ky
h
ca/
qr
k
c<+k
u
sdsf
y, n
`<
+lad
Yig
k
sd
jv i
uhb
ll
af o
/k
ulH
k
ke
sa v
ktr
k
j h
[k
26u
oE
cj
]19
4
9b
Zñd
ks,
r
n~}
k
j
kbllaf
o
/k
udk
s
v
ax
h
Ñr]v
f
/fu;f
e rvk
Sj
v k
Rek
fi
Zr
dj
r
sg
SaA
1
- l
af
o
/k
u(c
;
k
yh
lo
kal
a'
k
k
s/
u)
v
f/
f
u
;e]
19
76
dh
/k
jk
2}k
j
k(3
-
1-
19
77
)
ls¶
i
zH
k
qR
o&
lai
U
uyk
sd
r
a=k
k
R
edx.
k
jk
T
;¸dsL
F
kk
uij
i
zf
r
LF
kk
f
irA
2
- l
af
o
/k
u(c
;
k
yh
lo
kal
a'
k
k
s/
u)
v
f/
f
u
;e]
19
76
dh
/k
jk
2}k
j
k(3
-
1-
19
77
l
s)
]¶
jk
"V
ªdh,
dr
k¸dsL
Fk
k
uij
i
zf
r
LF
kk
f
irA
H
k
k
x 4
d
e
wy
d
Ùk
ZO
;
5
1
d-
ewy
d
Ùk
ZO
;&
Hk
k
jrd
si
zR
;
sdu
k
xf
jdd
k
;gd
Ù
k
ZO
;g
k
sx
k
fdo
g
&
(
d
) l
af
o/
ku
dk
ik
yud
j
sv
k
Sj
ml
dsv
k
n'
kk
sZa]
laL
F
k
kv
ksa]
jk
"
Vªè
o
tvk
Sj
j
k"
V
ªx
k
udk
vkn
jd
j
s_
(
[
k
) L
o
ra=
k
rk
dsf
y,g
e
k
jsj
k
"
Vªh
;vk
an
k
sy
ud
k
si
zsf
j
rdj
u
so
k
ysm
P
pv
k
n'
kk
sZa d
k
sâ
n;
e
sa l
at
k
s,
j[
k
sv
kSj
mu
dk
ik
yud
j
s_
(
x
) H
k
k
jrd
h
izH
k
qr
k
],
dr
k
vkSj
v[
k
aM
rk
dhj
{
kk
djsv
k
Sj
ml
sv
{
k
q.
.
kj
[k
s_
(
?
k
) n
s'
k
dhj
{
kk
djsv
k
Sj
vk
g~o
k
uf
d,t
k
usi
j
jk
"
Vªd
h
lso
k
djs_
(
Ä
) H
k
k
jr dslH
k
h y
ksx
k sa e
sa l
ej
lrk
vkSjl
ek
u H
k
zk
r`R
odh
Hk
ko
ukd
k f
u
ek
Z.
k
djst
k
s/
eZ]
Hk
k
"k
kvk
Sj
izn
s'
k
;ko
xZi
j
vk
/k
fj
rl
Hk
hH
ksn
H
k
k
ols
i
j
sg
ksa]
, sl
h
izF
k
k
v k
sa d kR
;k
xdj
st k
sf
L
=k
;k
sa dslE
ek
udsf
o#
¼gSa_
(
p
) g
e
k
jh
lk
ek
f
ldl
aL
Ñ
fr
dh
xk
Sj
o
'k
k
yhi
j
ai
j
k
dke
gÙ
ol
e>
sv
k
Sj
ml
dk
ijh
{
k.
kd
js_
(
N
) i
zk
Ñf
rdi
;
k
Zo
j
.k
d h
ft
ld
sv
ar
x
Zr
o
u]
>h
y]
un
h]
vk
Sj
oU
;th
ogSa]
j{
kk
d j
sv
k
Sj
ml
dk
lao
/
Zu
dj
sr
F
k
ki
zk
f
.k
ek
=k
d si
zf
rn;
k
H
kk
o
j
[k
s_
(
t
) o
SK
k
f
udn
`f
"
Vdk
s.
k
]ek
uo
ok
nvk
Sj
Kk
uk
tZu
r
Fk
klq/
k
jdh
Hk
k
ouk
dkf
odk
ldj
s_
(
>
) l
k
oZt
f
u
d l
ai
f
Ù
kdk
sl
qj
f
{
krj
[
ksv
k
Sj
f
gal
k
lsn
wj
j
gs_
(
×
k
) O
;
fD
rx
rv
k
Sj
lk
ewf
g
d x
f
rf
of
/ ;
k
sa d
sl
H
k
h{
ks=
k
k
sa e
sa m
R
d"
k
Zdh
vksj
c<
+u
sd
k
lrr
i
z;
k
ldj
sf
tl
lsj
k
"
Vªf
u
jar
j
c<
+r
sg
q,
i
z;
R
uvk
Sj
m
iy
f
C/
dhu
b
Zm
apk
b;
ksa d
k
sN
wysA
THE CONSTITUTION OF INDIA
PREAMBLE
WE, THE PEOPLE OF INDIA, having solemnly resolved to constitute India into a SOVEREIGN 1
1. Subs, by the Constitution (Forty-Second Amendment) Act. 1976, sec. 2, for "Sovereign Democratic Republic (w.e.f. 3.1.1977)
2. Subs, by the Constitution (Forty-Second Amendment) Act. 1976, sec. 2, for "unity of the Nation (w.e.f. 3.1.1977)
ARTICLE 51A
CBSE ADVISORS
v
Shri Vineet Joshi, Chairman, CBSE
v
Dr. Sadhana Parashar, Director
(Academics, Research, Training & Innovation)
DEVELOPMENT TEAM
v
Ms. Anju Gupta, Rukmini Devi Public School, Pitam Pura, New Delhi.
v
Ms. Mohini Arora, Air Force Golden Jubilee Institute, Subroto Park, New Delhi.
v
Ms. S. Meena, Sachdeva Public School, Pitam Pura, New Delhi.
v
Ms. Shally Arora, Delhi Public School, Gurgaon.
MEMBER COORDINATOR
v
Ms. Kshipra Verma, Education Officer, CBSE, New Delhi.
Content
Acknowledgement
Introduction
Computers are seen everywhere around us, in all spheres of life. May it be the field of
education and research, travel and tourism, weather forecasting, social networking, e-
commerce or any other, computers have now become an indispensable part of our lives.
The manner, in which computers have revolutionised our lives because of their
accuracy and speed of performing a job, is truly remarkable. Today no organization can
function without a computer. In fact various organizations are trying to become paper
free owing to benefits of computers. But the computers of today have evolved over the
years from a simple calculating device to the portable high speed computers that we see
today.
Evolution of Computers
The growth of computer industry started with the need for performing fast calculations.
The manual method of computing was slow and prone to errors. So attempts were
made to develop faster calculating devices. The journey that started from the first
calculating device i.e. Abacus has led us today to extremely high speed calculating
devices. Let us first have a look at some early calculating devices and then we will
explore various generations of computer.
2
Abacus
Abacus was discovered by the Mesopotamians in around 3000 BC. An abacus consisted
of beads on movable rods divided into two parts. (Fig-1) Addition and multiplication of
numbers was done by using the place value of digits of the numbers and position of
beads in an abacus.
Fig: An Abacus
The Chinese further improved on the abacus so that calculations could be done more
easily. Even today abacus is considered as an apt tool for young children to do
calculations. In an abacus, each row is thought of as a ten’s place. From right to left ,
row no-1 represents the one’s column and the second column represents ten’s place.
The third column represents the hundred’s place and so on. The starting position of the
top beads (representing the value of five) is always towards the top wall of the abacus
while the lower beads (representing the value of one) will always be pushed towards
the lower wall as a starting position.
3
side and the bones corresponding to the digits of the multiplicand on the right , the
product of two numbers can be easily obtained.
Pascaline
Blaise Pascal, a French mathematician invented an adding machine in 1642 that was
made up of gears and was used for adding numbers quickly. This machine was also
called Pascaline and was capable of addition and subtraction along with carry-transfer
capability. It worked on clock
Fig: Pascaline
4
Leibnitz’s Calculator
In 1673 Gottfried Leibnitz, a German mathematician extended the capabilities of the
adding machine invented by Pascal to perform multiplication and division as well. The
multiplication was done through repeated addition of numbers using a stepped
cylinder each with nine teeth of varying lengths.
Jacquard’s Loom
In order to make the cotton weaving process automatic, Joseph Jaquard devised punch
cards and used them to control looms in 1801. The entire operation was under a
program’s control. Through this historic invention, the concept of storing and retrieving
information started.
5
Thereafter in 1833, he designed the Analytical Engine which later on proved to be the
basis of modern computer. This machine could perform all the four arithmetic
operations as well as comparison. It included the concept of central processor, memory
storage and input-output devices. Even the stored information could be modified.
Although the analytical engine was never built that time but Babbage established the
basic principles on which today’s modern computers work.
Both these great inventions earned him the title of ‘Father of Modern Computers’.
Mark 1
In 1944 Prof Howard Aiken in collaboration with IBM constructed an electromechanical
computer named Mark 1 which could multiply two 10 digit numbers in 5 seconds. This
machine was based on the concept of Babbage’s Analytical engine and was the first
operational general purpose computer which could execute preprogrammed
instructions automatically without any human intervention.
Fig: Mark 1
In 1945, Dr. John Von Neumann proposed the concept of a stored program computer.
As per this concept the program and data could be stored in the same memory unit. The
basic architecture of the Von Neumann computer is shown in the figure below
6
Program
Communication
+
Data
channel
Processor
Storage (Memory)
Generation of Computers
Growth in the computer industry is determined by the development in technology.
Each phase/generation of computer development is characterized by one or more
hardware/software developments that distinctly improved the performance of the
computers of that generation. Based on various stages of development, computers can
be divided into different generations.
7
thousands of vacuum tubes and were the fastest calculating devices of their time. These
computers were very large in size, consumed lot of electricity and generated lot of heat.
UNIVAC 1 was the first electronic computer of this generation and was used for
business applications.
Note: ENIAC weighed about 27 tons, was of the size 8 feet * 100 feet * 3 feet and
consumed around 150 watts of power.
8
management, inventory control etc. IBM 1401 and IBM 1620 were popular computers of
this generation.
Magnetic core memories and magnetic disks were used as primary and
secondary storage respectively
Programming in assembly language and in the later part high level languages
were used
9
Salient Features of Third Generation computers:
In this generation Large Scale Integration (LSI) and Very Large scale integration (VLSI)
technology was used by which up to 300,000 transistors were used on a single chip.
Thus integration of complete CPU on a single chip was achieved in 1971 and was
named microprocessor which marked the fourth generation of computers. The
computers based on microprocessor technology had faster accessing and processing
speeds. In addition to this the increased memory capacity further made the computers
more powerful and also more efficient operating systems were developed for these
computers. New concepts of microprogramming, application software, databases,
virtual memory etc were developed and used.
The computers that we use today belong to this generation. These portable computers
can be carried from one place to another owing to their compact size. They are much
more accurate. Even memory sizes have become phenomenal. Commercial production
of these computers is easier and they are the least expensive, compared to the earlier
generation computers.
Also computer networks starting coming up during this generation. It is today one of
the most popular means to interact and communicate with people.
Microprocessors developed
10
Different types of secondary memory with high storage capacity and fast access
developed
Parallel Processing
Superconductivity
Artificial Intelligence
Data: It is the term used for raw facts and figures. For example, 134, + 9, ‘Raju’, ‘C’ are
data. Definition of information should start from next line as given in the word file. In
composed file it is starting from the same line immediately after the definition of data.
Information: Data represented in useful and meaningful form is information. In simple
words we can say that data is the raw material that is processed to give meaningful,
11
ordered or structured information. For example Raju is 9 years old. This is information
about Raju and conveys some meaning. This conversion of data to information is called
data processing.
Every task given to a computer follows an Input- Process- Output Cycle (IPO cycle). It
needs certain input, processes that input and produces the desired output. The input
unit takes the input, the central processing unit does the processing of data and the
output unit produces the output. The memory unit holds the data and instructions
during the processing.
Output
unit
CPU
ALU
CU
12
Input Unit
The input unit consists of input devices that are attached to the computer. These devices
take input and convert it into binary language that the computer understands. Some of
the common input devices are keyboard, mouse, joystick, scanner etc.
Control Unit
The Control unit coordinates and controls the data flow in and out of CPU and also
controls all the operations of ALU, memory registers and also input/output units. It is
also responsible for carrying out all the instructions stored in the program. It decodes
the fetched instruction, interprets (understands) it and sends control signals to
input/output devices until the required operation is done properly by ALU and
memory.
Memory Registers
A register is a temporary unit of memory in the CPU. These receive data/information
and then this data/information is held in them as per the requirement. Registers can be
of different sizes(16 bit , 32 bit , 64 bit and so on) and each register inside the CPU has a
13
specific function like storing data, storing an instruction, storing address of a location in
memory etc. The user registers can be used by an assembly language programmer for
storing operands, intermediate results etc. Accumulator (ACC) is the main register in
the ALU and contains one of the operands of an operation to be performed in the ALU.
Memory
Memory attached to the CPU is used for storage of data and instructions and is called
internal memory. During processing, it is the internal memory that holds the data. The
internal memory is divided into many storage locations, each of which can store data or
instructions. Each memory location is of the same size and has an address. With the
help of the address, the computer can find any data easily without having to search the
entire memory. The internal memory is also called the Primary memory or Main
memory. When the task is performed, the CU makes the space available for storing data
and instructions, thereafter the memory is cleared and the memory space is then
available for the next task. The time of access of data is independent of its location in
memory, therefore this memory is also called Random Access memory (RAM). Primary
memory is volatile in nature. That means when the power is switched off, the data
stored in this memory is permanently erased. That is why secondary memory is needed
to store data and information permanently for later use. Some of the examples of
secondary storage devices are hard disk, compact disks, pen drives etc.
Output Unit
The output unit consists of output devices that are attached with the computer. It
converts the binary data coming from CPU to human understandable from. The
common output devices are monitor, printer, plotter etc.
14
of electric signals, is passed from one component to another in a computer. The bus can
be of three types – Address bus, Data bus and Control Bus.
ALU
CU
System bus
Controller Controller
The address bus carries the address location of the data or instruction. The data bus
carries data from one component to another and the control bus carries the control
signals. As shown in the figure above, the system bus is the common communication
path that carries signals to/from CPU, main memory and input/output devices. The
input/output devices communicate with the system bus through the controller circuit.
This controller circuit helps to manage various input/output devices attached to the
computer.
15
Concept of Booting
When the computer is switched on, a copy of boot program is brought from ROM into
the main memory. This process is called booting. The CPU first runs a jump instruction
that transfers to BIOS (Basic Input output System) and it starts executing. The BIOS
conducts a series of self diagnostic tests called POST (Power On Self Test). These tests
include memory tests, configuring and starting video circuitry, configuring the system’s
hardware and checking other devices that help to function the computer properly.
Thereafter the BIOS locates a bootable drive to load the boot sector. The execution is
then transferred to the Boot Strap Loader program on the boot sector which loads and
executes the operating system. If the boot sector is on the hard drive then it will have a
Master Boot record (MBR) which checks the partition table for active partition. If found,
the MBR loads that partition’s boot sector and executes it.
Cold Booting: When the system starts from initial state i.e. it is switched on, we call it
cold booting or Hard Booting. When the user presses the Power button, the instructions
are read from the ROM to initiate the booting process.
Warm Booting: When the system restarts or when Reset button is pressed, we call it
Warm Booting or Soft Booting. The system does not start from initial state and so all
diagnostic tests need not be carried out in this case. There are chances of data loss and
system damage as the data might not have been stored properly.
Classification of Computers
The computers can be classified based on the technology being used as: Digital, Analog
and Hybrid
Digital Computers
These computers are capable of processing information in discrete form. In digital
technology data which can be in the form of letters, symbols or numbers is represented
in binary form i.e. 0s and 1s. Binary digits are easily expressed in a digital computer by
the presence (1) or absence (0) of current or voltage. It computes by counting and
adding operations. The digital computers are used in industrial, business and scientific
applications. They are quite suitable for large volume data processing.
16
Analog Computers
An analog computer works on continuously changeable aspects of physical
phenomenon such as fluid pressure, mechanical motion and electrical quantities. These
computers measure changes in continuous physical quantities say current and voltage.
These computers are used to process data generated by ongoing physical processes. A
thermometer is an example of an analog computer since it measures the change in
mercury level continuously. Although the accuracy of an analog computer is less as
compared to digital computers, yet it is used to process data generated by changing
physical quantities especially when the response to change is fast. Most present day
analog computers are well suited to simulating systems. A simulator helps to conduct
experiments repeatedly in real time environment. Some of the common examples are
simulations in aircrafts, nuclear power plants, hydraulic and electronic networks.
Hybrid Computers
These use both analog and digital technology. It has the speed of analog computer and
the accuracy of a digital computer. It may accept digital or analog signals but an
extensive conversion of data from digital to analog and analog to digital has to be done.
Generally the analog components provide efficient processing of differential equations
while the digital part deals with logical operations of the system. Hence benefits of both
analog and digital computing are readily available. Hybrid Computers are used as a
cost effective means for complex simulations.
Micro Computers
These are also known as Personal Computers. These type of digital computer uses a
microprocessor (a CPU on a single chip) and include both desktops and laptops. These
computers can work on small volume of data, are very versatile and can handle variety
of applications. These computers are being used as work stations, CAD, multimedia
and advertising applications. Small portable computers such as PDAs (Personal Digital
Assistants) and tablets with wireless computing technology are increasingly becoming
popular.
17
Mini Computers
These computers can support multiple users working simultaneously on the same
machine. These are mainly used in an organization where computers installed in
various departments are interconnected. These computers are useful for small business
organizations.
Main Frames
These computers are large and very powerful computers with very high memory
capacity. These can process huge databases such as census at extremely fast rate. They
are suitable for big organizations, banks, industries etc. and can support hundreds of
users simultaneously on the network.
Super Computers
These are fastest and very expensive computers. They can execute billions of
instructions per second. These are multiprocessor, parallel systems suitable for
specialized complex scientific applications involving huge amounts of mathematical
applications such as weather forecasting. The main difference between a supercomputer
and a mainframe is that a supercomputer executes fewer programs as fast as possible
whereas a mainframe executes many programs concurrently.
18
EXERCISE
Answer the following questions
i) Explain the functional components of a computer with the help of a block diagram.
m) Differentiate between :
19
Chapter 2
Software Concepts
Types of Software
Software can be broadly are categorized as: (Fig 1)
System Software
Application Software
Utility Software
20
Software
System Software
System Software is the software that is directly related to coordinating computer
operations and performs tasks associated with controlling and utilizing computer
hardware. These programs assist in running application programs and are designed to
control the operation of a computer system. System software directs the computer what
to do, when to do and how to do. System software can be further categorized into
Operating System
Language Translators
Operating System
An Operating system is the most important system software. It is a set of programs that
control and supervise the hardware of a computer and also provide services to
application software, programmers and users. It manages all hardware and software,
input, output and processing activities within the computer system, the flow of
information to and from the processor, sets priorities for handling different tasks, and
so on. Without operating system a computer cannot do anything useful. When a
computer is switched on, the operating system is the first program that is loaded onto
21
its memory. A user cannot communicate directly with the computer hardware, so the
operating system acts as an interface between the user and the computer hardware.
Some of the popular operating systems used in personal computers are DOS, Windows,
Unix, Linux, Solaris, etc.
Our choice of operating system, therefore, depends to a great extent on the CPU and the
other attached devices and the applications we want to run. The operating system
controls the various system hardware and software resources and allocates them to the
users or programs as per their requirement.
Priority Scheduling: Each task is given CPU time according to the priority
assigned to that task. The program with higher priority will be given CPU
time before a program with lower priority. The CPU executes the task till it
is completed or there is some interrupt request i.e. till the time operating
22
system has to stop (interrupt) the current task due to an unavoidable job
request. The major drawback of Priority scheduling is that even a small job
has to wait for a long time when a long duration job with higher priority is
being executed.
Buffering: In this technique the temporary storage of input and output data
is done in Input Buffer and Output Buffer. Once the signal for input or
output is sent to or from the CPU respectively, the operating system
through the device controller moves the data from the input device to the
input buffer and for the output device to the output buffer. When the signal
is sent to/from the operating system to the respective device controllers, the
program doesn’t wait rather it returns to its processing. In case of input, if
the buffer is full, the operating system sends a signal to the program which
processes the data stored in the buffer. When the buffer becomes empty, the
program informs the operating system which reloads the buffer and the
input operation continues. Similarly for output when the program being
executed has to display some output, it fills the buffer and then informs the
operating system. Thereafter the operating system empties the buffer by
sending data to the output device and in the meantime the program fills
23
another buffer. This technique is called overlapped processing. This is
because while the operating system reloads one buffer, the executing
program doesn’t stop as it is able to retrieve/fill data from/in another
buffer.
Memory management: In a computer, both the CPU and the I/O devices interact
with the memory. When a program needs to be executed it is loaded onto the main
memory till the execution is complete. Thereafter that memory space is freed and
is available for other programs. The common memory management techniques
used by the operating system are Partitioning and Virtual Memory.
24
the help of Page Map Tables (PMT), the operating system keeps track
which page of main memory is storing which block of secondary memory.
A virtual address (which is not the real physical address) is mapped either
to the main memory or the secondary memory. Hence virtual memory
allows more programs and even larger programs to be executed in the main
memory leading to efficient memory utilization.
File Management: The operating System manages the files, folders and directory
systems on a computer. Any data on a computer is stored in the form of files and
the operating system keeps information about all of them using File Allocation
Table (FAT). The FAT stores general information about files like filename, type
(text or binary), size, starting address and access mode (sequential/indexed
sequential/direct/relative). The file manager of the operating system helps to
create, edit, copy, allocate memory to the files and also updates the FAT. The
operating system also takes care that files are opened with proper access rights to
read or edit them.
OS are classified into the following types depending on their capability of processing
Single User and Single Task OS: It is used on a standalone single computer for
performing a single task. Operating systems for Personal Computers (PC) are
single-user OS. Single user OS are simple operating system designed to manage
one task at a time. MS-DOS is an example of single user OS.
Multiuser OS is used in mini computers or mainframes that allow same data and
applications to be accessed by multiple users at the same time. The users can also
communicate with each other. Linux and UNIX are examples of multiuser OS.
25
Time sharing Operating System: It allows execution of more than one tasks or
processes concurrently. For this, the processor time is divided amongst different
tasks. This division of time is also called time sharing. The processor switches
rapidly between various processes. After the stipulated time is over, the CPU shifts
to next task in waiting, So this type of operating system employs round robin
scheduling technique. The system switches rapidly from one user to another but
still each user feels that it is getting a dedicated CPU time. Virtual Memory
techniques are used in this type of operating system. For example, the user can
listen to music on the computer while writing an article using a word processing
software. The user can switch between the applications and also transfer data
between them. Time sharing operating system can be both single user and
multiuser. Windows 95 and all later versions of Windows are examples of
multitasking OS.
26
Commonly Used Operating Systems
1. Windows: Microsoft launched Windows 1.0 operating system in 1985 and since
then Windows has ruled the world’s software market. It is a GUI (Graphic User
Interface) and various versions of Windows have been launched like Windows
95, Windows 98, Win NT, Windows XP, Windows 7 and the latest being
Windows 8.
2. Linux: Linux is a free and open software which means it is freely available for
use and since its source code is also available so anybody can use it, modify it
and redistribute it. It can be downloaded from www.linux.org. It is a very
popular operating system used and supported by many companies. The defining
component of this operating system is the Linux kernel.
It is the operating system that operates on digital mobile devices like smart phones and
tablets. It extends the features of a normal operating system for personal computers so
as to include touch screen, Bluetooth, WiFi, GPS mobile navigation, camera, music
27
player and many more. The most commonly used mobile operating systems are –
Android and Symbian
Android: It is a Linux derived Mobile OS released on 5th November 2007 and by 2011 it
had more than 50% of the global Smartphone market share. It is Google’s open and free
software that includes an operating system, middleware and some key applications for
use on mobile devices. Android applications are quiet user friendly and even one can
easily customize the Smartphone with Android OS. Various versions of Android OS
have been released like 1.0, 1.5, 1.6, 2. x, 3.0 etc. Most Android phones use the 2.x release
while Android 3.0 is available only for tablets. The latest Android version released is
4.2.2. The Android releases have dessert inspired codenames like Cupcake, Honeycomb, Ice
Cream sandwich and Jelly Bean.
Language Processors
We know that computer understands instructions in machine code, i.e. in the form of 0s
and 1s. It is difficult for us to write computer program directly in machine code. The
programs are written mostly in high-level languages, i.e. BASIC, C++, Python etc. A
program written in any high-level programming language (or written in assembly
language) is called the Source Program or Source Code.
The source code cannot be executed directly by the computer. The source code must be
converted into machine language to be executed. The program translated into machine
code is known as Object Program or Object code.
The special translator system software that is used to translate the program written in
high-level language (or Assembly language) into machine code is called language
processor or translator program.
The language processors can be any of the following three types- Assembler, Compiler
and Interpreter.
28
Assembler
The Assembler is used to translate the program written in Assembly language into
machine code. The input of Assembler is a source program that contains assembly
language instructions. The output generated by assembler is the object code or machine
code understandable by the computer.
Compiler
The language processor that translates the complete source program as a whole in one
go into machine code is called compiler. Some of the examples are C and C++
compilers.
The program translated into machine code is called the object program. The source code
is translated to object code successfully if it is free of errors. If there are any errors in the
source code, the compiler specifies the errors at the end of compilation with line
numbers. The errors must be removed before the compiler can successfully recompile
the source code again.
Interpreter
The language processor that translates a single statement of source program into
machine code and executes it immediately before moving on to the next line is called an
Interpreter. If there is an error in the statement the interpreter terminates its translating
process at that statement and displays an error message.
Only after removal of the error, the interpreter moves on to the next line for execution.
Utilities
A utility software is one which provides certain tasks that help in proper maintenance
of the computer. The job of utility programs is to keep the computer system running
smoothly. Nowadays many utility softwares are part of the operating system itself.
Even if there is no utility software on your computer, the computer works but with the
right kind of utility software loaded, the computer becomes more reliable and even its
processing speed increases. Some of the commonly use utility softwares are antivirus,
Disk defragmenter, backup, compression etc.
29
Antivirus
An antivirus is utility software which detects and removes computer viruses. If the
software is not able to remove the virus, it is neutralized. The antivirus keeps a
watch on the functioning of the computer system. If a virus is found it may alert
the user, flag the infected program or kill the virus. Some of the common types of
viruses are:
Boot Sector Virus: A boot sector virus displaces the boot record and copies
itself to the boot sector i.e. where the program to boot the machine is stored.
So first the virus is loaded on to the main memory and then the operating
system. Whenever a new disk is inserted the virus copies itself to the new
disk. The antivirus overwrites the correct boot record on the infected boot
sector and also cleans the bad sectors.
File Virus: A file virus generally attacks executable files. They can attach to
various locations of the original file, replace code, fill in open spaces in the
code, or create companion files to work with an executable file. Most of the
file viruses are memory resident and wait in the memory until the user runs
another program. While another program is running, the virus replicates.
30
Disk Defragmenter
The memory is used in small chunks randomly. Sometimes when a memory chunk
of appropriate size is not available, the operating system breaks or fragments the
files resulting in slower access to files. A disk defragmenter scans the hard disk for
fragmented files and brings all the fragments together.
Backup Utility
This utility is used to create the copy of the complete or partial data stored in a
disk or CD on any other disk. In case the hard disk crashes or some other system
failure occurs, the files can be restored using backup software.
Compression Utility
This utility is used to compress large files. Compression is useful because it helps
reduce resources usage and the file transmission on the network becomes easier.
Disk Cleaner
This utility scans for file that have not been accessed/used since long. Such files
might be occupying huge amount of memory space. In that case the Disk Cleaner
utility prompts the user to delete such files so as to create more space on the disk.
If the files are important, the user might take a backup before deleting them.
Application Software
An application software is bought by the user to perform specific applications or tasks,
say for example making a document or making a presentation or handling inventory or
managing the employee database. An application software can be of two types –
General Purpose Application Software and Customized Application software.
31
General Purpose Application Software
Some of the application software is made for the common users for day to day
applications and uses. These are also referred as Office Tools. The users may use them
in the manner they want. Some of the popular types of general purpose application
software are discussed below:
We use word processing software for various uses like writing a simple document
to designing special art effects. Since we can attach images and different shapes,
can use different colors, even a poster can be designed using word processing
software. Features like Mail Merge, Macro has further enhanced the word
processing software and made it very useful.
32
creation, maintenance, and the use of database for an organization and its end
users. We can not only store data but can also manage data in a database. We can
also import and export the data to many formats including Excel, Outlook, ASCII,
dBase, FoxPro, Oracle, SQL Server, ODBC, etc. Popular examples of Database
Management System are Base (Open Office) and Microsoft Access.
Customized Software
Customized Software is one which is tailor made as per the user’s requirement. Such
type of software is customer specific. It is made keeping in mind the individual needs of
the user and so are also referred as Domain Specific Tools. Such software cannot be
installed and used by any other user/customer since the requirements may differ. Some
examples of customized software are discussed below:
33
Financial Accounting: Financial accounting System is used to prepare accounting
information, maintain different accounts ledger, and account books. It also helps
an organization to make budget.
1. Proprietary
2. Shareware
3. Freeware
4. Open source
5. Free Software
Proprietary
We pay a supplier for a copy of the software which these days may be supplied on
physical media (disks) or downloaded from the Internet. We get the permission to
34
use the software on one or sometimes more than one machines. Examples of this
type of software include Microsoft Office and Microsoft Windows.
Shareware
Shareware is basically a software for trial purpose that the user is allowed to try
for free, for a specified period of time. It is usually downloaded from the Internet.
When the trial period ends, the software must be purchased or uninstalled.
Freeware
Freeware software is free of cost and is usually bundled up with some operating
system or any other software. Examples of freeware include Microsoft Internet
Explorer which comes bundled up with any Microsoft operating system. The
author of the freeware software is the owner of the software, though people may
use it for free. The source code is not available, so no modifications can be done.
Freeware should not be mistaken with Open Source Software or Free Software.
Open source
Open Source Software (OSS) is the software which gives the users freedom to
run/use the software for any purpose and in any manner. They can be used,
modified and even redistributed. In simple terms it can be freely used but it may
not be free of charge. The source code is freely available to the customer. Python,
Tux Paint etc are examples of Open Source Software.
Free Software
This type of software is freely accessible and can be freely used, modified, copied
or distributed by anyone. And no licence fee or any other form of payment need to
be made for a free software. The source code is also accessible in case of free
softwares.
35
EXERCISE
b) How can the software be classified? Name at least one software in each of the
categories.
g) Differentiate between:
j) What is the difference between an Open source Software and a Freeware. Write 2
examples of each.
36
Chapter 3
Data Representation in Computers
Numbering Systems
Each number system has a base also called a Radix. A decimal number system is a
system of base 10; binary is a system of base 2; octal is a system of base 8; and
hexadecimal is a system of base 16. What are these varying bases? The answer lies in
what happens when we count up to the maximum number that the numbering system
allows. In base 10, we can count from 0 to 9, that is,10 digits.
Binary 2 0,1
Octal 8 0,1,2,3,4,5,6,7
Decimal 10 0,1,2,3,4,5,6,7,8,9
Hexadecimal 16 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
37
Converting a number from one Base to another:
Binary to Decimal
2. Take that bit and multiply by 2n where n is the current position beginning at 0 and
increasing by 1 each time. This represents a power of two.
3. Sum each terms of product until all bits have been used.
Example
1 * 25 + 0 * 24 + 1 * 23 + 0 * 22 + 1 * 21 + 1 * 20
32 + 0 + 8 + 0 +2 + 1 = (43)10
Example
1 * 23 + 0 * 22 + 0 * 21 + 1 * 20
8 + 0 + 0 + 1 = (9)10
Example
= 16+8+0+2+1+0.5+0+0.125
= (27.625)10
Decimal to Binary
38
1. Divide the decimal number by 2.
5. Record the remainders in reverse order and you get the resultant binary number.
Example
125 / 2 = 62 1
62 / 2 = 31 0
31 / 2 = 15 1
15 / 2 = 7 1
7/2=3 1
3/2=1 1
1/2=0 1
Answer: (1111101)2
Example
Multiply the given fraction by 2. Keep the integer in the product as it is and multiply
the new fraction in the product by 2. Continue the process till the required number of
decimal places or till you get zero in the fraction part. Record the integers in the
products from top to bottom.
Reading the integers from top to bottom 0.75 in decimal number system is 0.11 in binary
number system.
39
Example
(105)10 = (1101001)2
Decimal to Octal
5. Record the remainders in reverse order and you get the resultant binary
Example
125 / 8 = 15 5
15/ 8 = 1 7
1/8 =0 1
40
Answer: (175)8
Example
Multiply the given fraction by 8. Keep the integer in the product as it is and multiply
the new fraction in the product by 8. Continue the process and read the integers in the
products from top to bottom.
Reading the integers from top to bottom 0.75 in decimal number system is 0.6 in octal
number system.
Octal to Decimal
2. Take that bit and multiply by 8n where n is the current position beginning at 0 and
increasing by 1 each time. This represents the power of 8.
3. Sum each of the product terms until all bits have been used.
Example
3 * 82 + 2 * 81 + 1 * 80
192+16+ 1 = (209)10
Example
81 80 . 8-1 8-2
2 3 2 5
41
= (2 x 81)+ (3 x 80)+ (2 x 8-1)+ (5 x 8-2)
= 16+3+0.25+0.07812
= (19.32812)10
Decimal to Hexadecimal
4. Record the remainders in reverse order and you get the equivalent hexadecimal
number.
Example
300 / 16 = 18 12-(C)
18 / 16 = 1 2
1 / 16 = 0 1
Answer: (12C)16
Example
Multiply the given fraction by 16. Keep the integer in the product as it is and multiply
the new fraction in the product by 16. Continue the process and read the integers in the
products from top to bottom.
Reading the integers from top to bottom 0.75 in decimal number system is 0C in
Hexadecimal number system.
42
Hexadecimal to Decimal
2. Take that bit and multiply by 16n where n is the current position beginning at 0
and increasing by 1 each time. This represents a power of 16.
3. Sum each terms of product until all bits have been used.
Example
=A * 161 + B * 160
=160+11 = (171)16
Example
= 16+14+0.5+0.04688
= (30.54688)10
Binary to Hexadecimal
We take a binary number in groups of 4 and use the appropriate hexadecimal digit in
it’s place. We begin at the rightmost 4 bits. If we are not able to form a group of four,
insert 0s to the left until we get all groups of 4 bits each. Write the hexadecimal
equivalent of each group. Repeat the steps until all groups have been converted.
43
Example
Answer: (45)16
In case of a fractional binary number form groups of four bits on each side of decimal
point. Then replace each group by its corresponding hexadecimal number.
Example
Answer : (1C.A)16
Hexadecimal to Binary
Convert each digit of Hexadecimal Number to it’s binary equivalent and write them in
4 bits. Then, combine each 4 bit binary number and that is the resulting answer.
Example
1 0 A F
0001 | 0000 | 1010 | 1111
Answer: (0001000010101111)2
Example
A 2 F
44
Binary to Octal and Octal to Binary
To convert Binary to Octal, as the octal system is a power of two (2 3), we can take the
bits into groups of 3 and represent each group as an octal digit. The steps are the same
for the binary to hexadecimal conversions except we are dealing with the octal base
now.
To convert from octal to binary, we simply represent each octal digit in it’s three bit
binary form.
Example
7 | 4 | 2
Answer: (111100010)2
Example
A|4|2
Answer: (5102)8
To convert Octal to hexadecimal, convert each digit of Octal Number to it’s binary
equivalent and write them in 3 bits. Then, combine each 4 bit binary number and that is
converted into hexadecimal.
Example
45
7|6|2
Answer: (172)16
The following table summarizes the number representation in decimal, binary, octal
and hexadecimal number system:
0 0 0 0
1 1 1 1
2 10 2 2
3 11 3 3
4 100 4 4
5 101 5 5
6 110 6 6
7 111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
46
Binary Representation of Integers
Binary number can be represented only by using 0’s and 1’s, but can not use the sign (-)
to denote the negative number or sign (+) to denote the positive number. So it must be
either 0 or 1. There are three methods to represent binary number. They are
In this method, first bit is considered as a sign bit. Here positive number starts with 0
and negative number starts with 1.
Example
25
25/2 = 12 1
12/2 = 6 0
6/2 = 3 0
3/2 = 1 1
1/2 = 0 1
So the binary number is (11001)2. If we take the size of the word is 1 byte, then the
number 25 will be represented as
00011001
10011001
47
Example
86/2 =43 0
43/2 =21 1
21/2 =10 1
10/2 =5 0
5/2 =2 1
2/2 =1 0
1/2 =0 1
55/2 =27 1
27/2 =13 1
13/2 =6 1
6/2 =3 0
3/2 =1 1
1/2 =0 1
48
Two’s Complement method
In this method, the positive number is represented as the binary number. If the number
is negative, then we need to calculate two’s complement of a binary number. The two’s
complement of a binary number is calculated by adding 1 to its one’s complement.
Example
87/2 =43 1
43/2 =21 1
21/2 =10 1
10/2 =5 0
5/2 =2 1
2/2 =1 0
1/2 =0 1
54/2 =27 0
27/2 =13 1
13/2 =6 1
6/2 =3 0
3/2 =1 1
1/2 =0 1
49
Add 1 to one’s complement
1
11001001 (1+1=2, binary equivalent =11)
+1
11001010
77/2 =38 1
38/2 =19 0
19/2 =9 1
9/2 =4 1
4/2 =2 0
2/2 =1 0
1/2 =0 1
10110010
+1
10110011
Representing Characters
A computer can handle numeric and non numeric data like letters, punctuation marks
and other special characters. Some predefined codes are used to represent numeric and
non numeric characters. Some of the standards are discussed below:
50
ASCII
ASCII stands for American Standard Code for Information Interchange. ASCII-7 can
represent 128 characters. Out of 7 bits, 3 are zone bits and 4 are numeric bits. ASCII-8
can represent 256 characters. It is an extended form of ASCII-7.
51
L 100 1100 1010 1100
M 100 1101 1010 1101
N 100 1110 1010 1110
O 100 1111 1010 1111
P 101 0000 1011 0000
Q 101 0001 1011 0000
R 101 0010 1011 0010
S 101 0011 1011 0011
T 101 0100 1011 0100
U 101 0101 1011 0101
V 101 0110 1011 0110
W 101 0111 1011 0111
X 101 1000 1011 1000
Y 101 1001 1011 1001
Z 101 1010 1011 1010
Unicode
Unicode is a new universal coding standard adopted by all new platforms. It is
promoted by Unicode Consortium which is a non profit organization. Unicode provides
a unique number for every character irrespective of the platform, program and the
language. It is a character coding system designed to support the worldwide
interchange, processing, and display of the written texts of the diverse languages.
52
EXERCISE
c) What is the base of Decimal, Binary, Octal and Hexadecimal number systems?
h) Do as directed :
53
Chapter 4
Microprocessors and Memory Concepts
Microprocessor
We studied that the Central processing unit processes data inside the computer. It
interprets all the instructions given to it and carries out these instructions. A
microprocessor is a Central Processing Unit (CPU) on a single chip. It is a multipurpose
programmable device constructed using Metal Oxide Semiconductor (MOS)
technology. In 1971 Intel Corporation fabricated the first microprocessor- 4004. It could
do only add and subtract operations and that too it could process only 4 bits at a time.
But Intel 4004 powered one of the first portable electronic calculators and since then the
microprocessor technology has come a long way. Today we have processors with which
can process upto 128 bits at a time at the speed of billion instructions per second.
Word Length: The number of bits processed in a single instruction is called word
length or word size. The word size is directly proportional to the processing power
of the CPU. During the processing, the internal general purpose registers hold
data. So if internal registers can hold data upto 8 bits, the word length is 8 bits. If it
can process 16 bits at a time, then the internal registers can hold upto 16 bits at a
time and so on. Hence a 32 bit processor is about 4 times faster than an 8 bit
processor. Examples of word lengths are 16 bit, 32 bit, 64 bit. The terms 16-bit
CPU, 32-bit CPU, 64-bit CPU are used very often while talking about CPUs. Now
54
we know that these terms mean the maximum number of bits a given CPU can
handle at a time.
Classification of Microprocessors
Apart from the width of data (word length) that the microprocessors can process at a
time, the classification is also based on the architecture i.e. Instruction Set of the
microprocessor. While studying about CPUs, we come across two abbreviations CISC
and RISC.
CISC: It stands for Complex Instruction Set Computer. A CISC chip such as Intel
Pentium provides programmers with hundreds of instructions of variable sizes,
and the processing circuitry includes many special purpose circuits that carry out
these instructions at high speeds. These instructions interface with memory in
multiple mechanisms with complex addressing modes. In this case the program
size is reduced and hence lesser number of memory cycles are required to execute
55
the instruction. So fewer general purpose registers(8-12) are present in CISC
processors. Also less number of memory cycles result in faster execution of the
program.
Memory Concepts
Memory is one of the most important components of a computer system as it stores
data and instructions. Every memory chip contains thousands of memory locations. In
the computer, the data is stored in the form of bits and bytes. A bit is the smallest
storage unit of memory. A nibble is a collection of 4 bits. Eight bits combined together
to form a single byte, which in turn represents a single character. Other units of
memory are KB (Kilobyte), MB (Megabyte), GB (Gigabyte) ,TB(Terabytes), PB
(Petabyte), EB (Exabytes), ZB (Zettabytes) and YB (Yottabytes). Every higher unit is
equal to 210 of the previous unit. The following table shows various units of computer
memory:
Kilo Byte (KB) 1 Kilo Byte = 1024 Bytes(or 210 Bytes) 1024
Mega Byte (MB) 1 Mega Byte = 1024 Kilo Byte(or 210 KB) 1024x1024
Giga Byte (GB) 1 Giga Byte = 1024 Mega Byte(or 210 MB) 1024x1024x1024
Tera Byte (TB) 1 Tera Byte = 1024 Giga Byte(or 210 GB) 1024x1024x1024x1024
Peta Byte (PB) 1 Peta Byte = 1024 Tera Byte(or 210 TB) 1024x1024x1024x1024x
1024
Exa Byte(EB) 1 Exa Byte = 1024 Peta Byte(or 210 PB) 1024x1024x1024x1024x
1024x1024
56
Zetta Byte(ZB) 1 Zetta Byte = 1024 Exa Byte(or 210 EB) 1024x1024x1024x1024x
1024x1024x 1024
Yotta Byte(YB) 1 Yotta Byte = 1024 Zetta Byte(or 210 ZB) 1024x1024x1024x1024x
1024x1024x 1024x1024
Primary Memory
Secondary memory
Cache Memory
Primary Memory
0 ......
1 ......
2 ......
.
.
.
. N words
.
.
.
N–2 ...... All words have
N–1 ...... same Length
The figure above shows a high speed main memory that is organised into words of
fixed lengths. A given memory is divided into N words where each word is assigned an
address in the memory. A word is generally more than 8 bits in length and the number
of bits in a word is termed as word length. Computers with 8, 16, 24 and 32 and 64 bit
word length are available. The higher the word length, the more powerful a computer
57
is. Each word is assigned an address starting from 0 to the largest number that the
computer can support. Each address uniquely specifies the memory location of a
particular word. The total number of memory cells that can be uniquely addressed by
CPU depends on the total number of address lines in an address bus. If there are n lines
in the address bus then there are 2n addressable locations in the memory.
Memories can be both read from and written to are called read/write memories. On the
other hand memories that have data or program permanently stored onto them and
hence can be only read from are called Read Only memories. Broadly primary memory
can be of two types – RAM (Random Access Memory) and ROM (Read only memory).
In case of RAM, the memory can be accessed from any desired location randomly. That
means without searching the entire memory, any location can be accessed in the same
amount of time. The instructions and data that we input into the computer are stored in
the RAM of the Computer. It is a read/write memory, so data can be both read from
and written to the RAM. It is a volatile memory and loses its contents when the power
is switched off or interrupted. Nowadays RAMs are available in gigabytes. The normal
memory access time of a RAM is 20-80 ns. RAM can be broadly classified into two
categories: Dynamic RAM (DRAM) and Static RAM (SRAM).
Dynamic RAM (DRAM): It consists of a transistor and a capacitor that stores electric
charge. The DRAMs are physically smaller, cheaper and slower memories. They are
slower because the data stored in them needs to continuously refreshed and this
consumes lot of processor time. Each refresh operation takes several CPU cycles to
complete. This is because a capacitor tends to loose charge over a period of time which
needs to be refreshed again and again. DRAM is used in primary storage areas and is
available in various forms as EDORAM (Extended Data Output RAM), SDRAM
(Synchronous DRAM) and DDR SDRAM.
Static RAM: This type of RAM is large in physical size but is an expensive and faster
memory. It is faster because it is made up of flip flops to store data and these flip flops
do not require any refreshing. Static RAM is also volatile and is easier to use as
compared to dynamic RAM. These are used in specialized applications.
58
Read only memory (ROM)
As the name suggests, a ROM is a type of memory that can perform read operation
only. The contents of ROM are written by the manufacturer and come along with the
computer. We cannot change its contents or write something else on it. Data is written
on to the ROM at the time of its manufacture and it cannot be changed thereafter. It is a
non-volatile memory, which means that contents stored in it are not lost even when the
power to the computer is switched off. ROMs are used in applications where the
information once written, need not be altered. They hold certain essential instructions
such as interrupt service routines or a monitor program controlling the machine.
Instructions that are needed to start the computer are also stored in the ROM. ROMs are
slower as compared to RAMs and are available in various types –
Erasable Programmable Read Only Memory (EPROM): In this type of ROM, the
contents can be erased and the memory can be reprogrammed. To erase the data,
an EPROM is exposed to ultraviolet light and then it can be reprogrammed using a
PROM programmer circuit. When the EPROM is in use, then it behaves like a
ROM, that means the information can only be read.
Cache Memory
Cache memory is a special high speed memory made up of high speed static RAMs. It is
used to hold frequently accessed data and instructions. We know that the processing
speed of CPU is much more than the main memory access time of the computer. This
means the CPU has to wait for a substantial amount of time. Alternatively we have the
cache memory which is a small, expensive but fast memory that is placed between the
CPU and the main memory. Whenever some data is required, the CPU first looks into
59
cache. If data is found, we call it a cache hit and the information is transferred to the
CPU. In case of a miss, the main memory is accessed. Memory caching proves to be
efficient because most programs repeatedly access the same data and instructions, so
access of frequently used data becomes very fast with cache memory. There are two
types of cache memory:
L1 cache: It is small and is built inside the CPU. It is fast as compared to L2 cache
Secondary Memory
The major limitation of primary memory is that it has limited storage capacity and is
volatile. To overcome this limitation we have secondary memory storage devices. This
type of memory is also called external memory. It refers to the various storage media on
which a computer can store data and programs. It is an additional storage, not part of
the main computer.
The Secondary storage media can be fixed or removable. Fixed Storage media is an
internal storage medium like hard disk that is fixed inside the computer. Removable
storage media is a data storage medium that is portable and can be taken outside the
computer.
a. For permanence: As the RAM is volatile, i.e. it loses all information when the
electricity is turned off, something is needed for permanence. Secondary storage
devices serve this purpose. They do not lose data when electricity is turned off.
b. For portability: Secondary storage, like the CDs, flash drives can be used to
transport data from one computer to another.
60
Magnetic storage media: Examples of magnetic storage media are hard disks, floppy
disks and magnetic tapes. Magnetic media is coated with a magnetic sensitive layer and
this layer is magnetized in clockwise or anticlockwise directions, which then are
interpreted as binary 1s and 0s at reading.
Floppy Disk (Diskette): A floppy disk is a flexible disk made up of mylar with a
magnetic coating on it. It is packaged inside a protective plastic envelope. These were
one of the oldest type of portable storage devices that could store up to 1.44 MB of data
but now they are no longer in use.
Hard disk: A hard disk consists of one or more circular disks called platters which are
mounted on a common spindle. Each surface of a platter is coated with a magnetic
material. Both surfaces of each disk are capable of storing data except the top and
bottom disk where only the inner surface is used. The information is recorded on the
surface of the rotating disk by magnetic read/write heads. These heads are joined to a
common arm known as access arm. This arm moves over the surface of the rotating disk
as shown in the figure below.
61
Information is recorded on each of these disks in the form of concentric circles called
tracks which are further divided into sectors. Hard drives however, are not very
portable and are primarily used internally in a computer system. But external hard
disks are also available as a substitute for portable storage. Today the hard disks have
the storage capacity of several gigabytes to terabytes.
On an optical storage media information is stored and read using a laser beam. The data
is stored as a spiral pattern of pits and ridges denoting binary 0 and binary 1.
Compact Disk: A compact disk or CD can store approximately 650 to 700 megabytes
(MB) of data. We must have a CD drive in our computer to read them.
The bits ( 0 and 1) are encoded as transitions between raised ridges and etched pits,
which are lined up in a spiral like pattern. This pattern is then stamped into a 1.2-mm
clear polycarbonate disc (a CD), which is then covered with a super thin coating of
reflective metal (usually aluminum or gold) and a label.
To read the data, an infrared laser is beamed through the CD's polycarbonate substrate.
The wavelength of light that bounces off the mirror-like reflective backing is then
measured. A pit scatters the light and the ridge reflects the light. Since pits and ridges
pass different amounts of light, the fluctuations in the reflected beam are then
translated back into the original ones and zeros.
CD- ROM: It stands for Compact Disk - Read Only Memory and data is written on
these disks at the time of manufacture. Thereafter this data cannot be changed but can
62
only be read by a laser beam in the form of a continuous spiral. CD- ROMs are used for
text, audio and video distribution like games, encyclopedias and application softwares.
CD-R: It stands for Compact Disk- Recordable. Data can be recorded on these disks but
only once. So we can write data on these disks through a read/write CD drive but after
that the disk cannot be erased/modified.
DVD: It stands for Digital Versatile Disk or Digital Video Disk. It looks just like a CD
and use a similar technology as that of the CDs discussed above but employ a shorter-
wavelength red laser that permits a narrower beam. This allows tracks to be spaced
closely enough to store data that is more than six times the CD's 700MB capacity. It is a
significant advancement in portable storage technology. DVDs consist of two half-
thickness (0.6-mm) CD-like discs glued back-to-back. This protects the delicate
reflective coating as it is on the inside of the disc. Also it makes possible to have double-
sided DVDs—where data can be stored on each half disc.
A DVD holds 4.7 GB to 17 GB of data. That means a complete movie can be stored on
one side of a DVD. Like CDs DVDs also come in three varieties –
DVD- ROM
DVD- R
DVD-RW
Blue Ray Disk: This is the latest optical storage media to store high definition audio
and video. It looks like a CD or DVD but can store up to 27 GB of data on a single layer
disk and up to 54 GB of data on a dual layer disk. Where CDs or DVDs use red laser
beam, the blue ray disk uses a blue laser to read/write data on a disk.
63
As the wavelength of the blue ray is shorter, more data per unit area can be stored on
the disk. This is because due to shorter wavelength, it is possible to focus the laser spot
with greater precision. Hence data can be packed more tightly. Blue-ray Disc (BD) was
developed to enable recording, rewriting and playback of high-definition video (HD),
as well as storing large amounts of data.
The term ‘solid-state’ essentially means ‘no moving parts’. Hence Solid-state storage
devices are based on electronic circuits with no moving parts (no reels of tape, no
spinning discs, no laser beams, etc.) Solid-state storage devices store data using a
special type of memory called flash memory. SSD, Solid-state drive (or flash memory) is
used mainly in digital cameras, pen drives or USB flash drives.
Pen Drives: Pen Drives or Thumb drives or Flash drives are the recently emerged
portable storage media. It is an EEPROM based flash memory which can be repeatedly
erased and written using electric signals. This memory is coupled with a USB connector
through which it can be plugged into the computer. They have a capacity smaller than a
hard disk but greater than a CD.
64
Fig: Ports at the back of CPU
A port’s main function is to act as a point of attachment where the cable from the
peripheral device plugs into the system unit, allowing data to flow from the peripheral
device. Some of the common sockets/ports are power socket for connecting power
cable, PS2 ports for connecting Mouse & Keyboard, USB Port for connecting USB
devices such as mouse, keyboard, printer, pen drive etc. and VGA port for connecting
Monitor/Screen.
Serial Port
Through a serial port data is transmitted travels one bit at a time through a single wire.
The data transmission speed is quite slow. Serial ports are commonly known as
communication (COM) ports or RS232C ports and connect devices like mouse and
modem. These ports are rarely used these days.
65
Fig: Serial Port
Parallel port
These ports were earlier used to connect printers to the computer system. A parallel
port can send 8 bits (1 byte) at a time simultaneously (in parallel). Hence data
transmission is faster through these ports. Parallel ports are used to connect printers,
scanners, CD writers etc.
66
PS/2 Port
This is a round port for plugging in keyboard or mouse. It has a PS/2 cable with a mini
DIN connector. These ports are becoming obsolete now. In fact some systems these days
do not have PS/2 ports.
USB Port
A USB (Universal Serial Bus) port is a standard cable connection interface available on
personal computers and some other electronic devices for data communication. It is a
single, low cost, plug n play connector. The operating system automatically detects the
device connected through the USB port. USB ports have become very popular these
days as they connect many different devices to the computer these days. Most
computers have USB ports on front, back and/or sides of system unit. Flash drives,
digital cameras, printers, scanners are some of the devices that often connect through
the USB port.
Infrared Port
In this type of port, data is transmitted through Infrared waves. For infrared
transmission the device and the computer both must have infrared ports. These allow
67
computers and peripherals to communicate serially over an Infrared link rather than
over cables. The remote control of our TV sets uses the same technology. For wireless
data communication between computers and various peripheral devices we use
infrared ports.
Bluetooth Port
Bluetooth is used to connect mobile phones, computers and PDAs using a short range
wireless connection. This technology uses radio waves to transmit data between any
two devices. The devices that are Bluetooth enabled contain a small transceiver chip
that allows them to communicate with other Bluetooth enabled computer or device.
Data can be exchanged at the rate of about 2 megabit per second.
FireWire® ports are forms of a serial port that make use of FireWire® technology to
transfer data rapidly from one electronic device to another. The FireWire® port has the
ability to interact with a number of different devices since it provides a single plug and
socket connection for all devices. A FireWire® port can provide an ideal way to connect
a scanner and digital camera/camcorder to a computer system as the data transfer is
relatively faster than on USB and also results in excellent quality.
68
EXCERCISE
e) Why do we use secondary storage? Name any two secondary storage devices.
69
UNIT 2
Chapter 1
Algorithms and Flowcharts
Introduction
Algorithm is a step-by-step process of solving a well-defined computational problem. In
practice, in order to solve any complex real life problems, first we have to define the
problem and then, design algorithm to solve it. Writing and executing a simple
program may be easy; however, for executing a bigger one, each part of the program
must be well organized. In short, algorithms are used to simplify the program
implementation. The next step is making the flowchart. It is a type of diagram that
represents an algorithm or process, showing the steps as „boxes‟ of various kinds and
their order by connecting them with arrows. Then, the flowchart will be converted into
program code.
Algorithm
An algorithm is an effective method expressed as a finite list of well defined
instructions for calculating a function, starting from an initial state and initial input. The
instructions describe a computation, which will eventually produce output, when
executed. We can use algorithm to solve any kind of problems. However, before writing
a program, we need to write the steps to solve the problem in simple English language.
This step-by-step procedure to solve the problem is called algorithm.
Example
Let us take one simple day-to-day example by writing algorithm for making „Maggi
Noodles‟ as a food.
71
Step 1: Start
Further, the way of execution of the program shall be categorized into three ways: (i)
sequence statements; (ii) selection statements; and (iii) iteration or looping statements.
This is also called as „control structure‟.
Sequence statements: In this program, all the instructions are executed one after
another.
Example
Step 1: Start
Step 3: Stop
Example
Step 1: Start
72
Step 4: Print area
Step 5: Stop
In the above mentioned two examples (Example II and III), all the instructions are
executed one after another. These examples are executed under sequential statement.
Selective Statements: In this program, some portion of the program is executed based
upon the conditional test. If the conditional test is true, compiler will execute some part
of the program, otherwise it will execute the other part of the program.
Example
Step 1: Start
Step 3: Check age value, if age >= 18 then go to step 4 else step 5
Step 6: Stop
Example
Step 1: Start
73
Step 7: Print “Given number is zero”
Step 8: Stop
In the above mentioned examples IV and V, all the statements are not executed, but
based upon the input, some portions of the algorithm are executed, because we have
„true‟ or „false‟ situation in the program.
Iterative statements: In some programs, certain set of statements are executed again
and again based upon conditional test. i.e. executed more than one time. This type of
execution is called „looping or iteration‟.
Example
Step 1: Start
Step 3: Store 1 in I
Step 5: Print I
Step 5: Go to step 4
Step 8: Stop
In the above example, steps 4, 5, 6 and 7 are executed more than one time.
Flowchart
In the previous section of this chapter, we have learnt to write algorithms, i.e. step-by-
step process of solving a problem. We can also show these steps in graphical form by
using some symbols. This is called flowcharting.
Flowchart Symbols
Some of the standard symbols along with respective function(s) that are used for
making flowchart are as follows:
74
Symbols Functions
1. Start/stop
2. Input/output
3. Processing
4. Decision Box
5. Flow of control
6. Connector
Example
75
Solution:
Start
Input P,R,T
SI=P*R*T/100
Print SI
Stop
Example
Solution:
Start
Input A, B
No Yes
IS
A>B
Stop
76
The following are the examples (VIII & IX) of an iterative execution.
Example
Solution:
Start
Input N
I=1
F=1
Is I<=N
No Yes
Print F F=F*I
I=I+1
Stop
Example
77
Solution:
Start
Input n
Input A
I=1
Big =A
Big=A
No I=I+1
Is
I<=n Yes
Input A
Print Big
Is Big<A
Yes
Stop No
I=I+1
78
Example
Solution:
Start
Input N
I=1
No Yes
Is I<=N
Stop Print I
In the above example “I” value is not at all incremented, so it will create endless loop.
This is also called infinite loop.
Note: Set of statements is executed again and again without any end is called infinite
loop.
79
EXERCISE
3. Set of statements is executed again and again based upon conditional test.
1. Define Algorithm.
2. Define Flowchart.
80
5. Write an algorithm to find whether given number is odd or even.
6. Write an algorithm to find the sum of all even number up to given number.
10. Draw a flowchart to find the sum of all multiples of 5 up to given number.
11. Mona is confused about finite loop and infinite loop, explain her with the help of
example.
81
Chapter 2
Programming Methodology
Introduction
Learning to write computer program is very much like learning any skill. First, we
should understand the problems well and then try to solve it in a logical manner. For
example: We have read many books available in the market for describing the car
driving methods. However, we can learn driving once we actually get into the car and
start driving it. The same logic is applied in computer programming also. Computer
programming is the process of writing, testing, troubleshooting, debugging and
maintaining of a computer program.
An effective program is that which gives result of all different inputs, including wrong
input also. While creating program, we need to follow certain systematic approach. This
systematic approach comprises two steps/things, viz., program structure and program
representation. The program structure is implemented by using top-down or bottom-up
approach and is known as „popular approach‟, while the program representation plays
an important role in making the program more readable and understandable.
82
Clarity and Simplicity of Expression
Expressions are used to implement a particular task. It is a combination of Operators,
Operands and Constants. Any expression used in the program should be understood by
the user. The followings are some of the points to be kept in mind while using
expressions in a program.
Example
To find output = x6
Output = X *X * X * X * X * X
Example
X = A+B – U +VY
A-B X+Y
X1 = (A+B) / (A-B)
X2 = (U+V*Y) / (X +Y)
X = X1 –X2
(iii) Avoid program tricks usage, whose meaning is difficult to understand by the
user.
83
(i) Give meaningful name for variable (data – object) and function.
Example
Example
¶ = 3.14
Give Pi = 3.14
(iii) Do not use same name like custom, customer or account, accountant.
Comments
A comment is a programming language construct, which is used to embed
programmer-readable annotations in the source code of a computer program. Those
annotations are potentially significant to programmers but typically ignorable to
compilers and interpreters. Comments are usually added with the purpose of making
the source code easy to understand. Hence, add comments to your code in simple
English language that describes the function of the code and the reason for your
decision to do it in a particular way as well. They are generally categorized as either
„block comment‟ or „line comment‟. Block comment is implemented in python by “””
and “”” and line comment is implemented by #.
Example
"Write a program to print all numbers from 1 to 100 using while loop in python"
A=1
print a
a = a+1
84
Indentation
Leading white space (spaces and taps) at the beginning of each statement, which is used
to determine the group of statement, is known as „indentation‟.
Example
If A > B :
else:
In the above example, if statements are a type of code block. If the „if‟ expression
evaluates to true, then Block1 is executed, otherwise, it executes Block2. Obviously,
blocks can have multiple lines. As long as they are all indented with the same amount
of spaces, they constitute one block.
Flexibility
A program should be flexible enough to handle most of the changes without having to
rewrite the entire program. A flexible program is used to serve many purposes. For
example, CAD (Computer Aided Design) software is used for different purposes such
as; engineering drafting, printing circuit board layout and design, architectural design,
technical drawing, industrial art, etc. Most of the programs are being developed for
certain period and they need updation during the course of time.
85
User Friendly
A program that can be easily understood by a beginner is called „user friendly‟. It must
interact with user through understandable messages. In addition, the proper message
for the user to input data and to display the result, besides making the program easily
understandable and modifiable.
Portability
Portability refers to the ability of an application to run on different platforms (operating
systems) with or without minimal changes. Since the change of platform is a common
phenomenon nowadays, due to the developments in hardware and the software,
portability has to be taken care of it. In case, a program is developed for a particular
platform, it would become obsolete after a certain period of time. At the same time, if a
program that is developed does have the ability to work on different platforms, it
makes software more useable. High language programs are often more portable than
assembly language programs.
Reliability
It is the ability of a program to do its intended function accurately even if there are even
small changes in the computer system. Moreover, the program must be able to handle
unexpected situation like wrong input or no input. The programs, which save such
ability are known as „reliable‟. For example, if the user does/gives wrong information to
input, it should display a proper error message.
Self-Documenting Code
The source code, which uses suitable name for the identifiers (variables and methods),
is called self-documenting code. Also, giving proper name for variables and methods
would tell the reader of your code clearly -what is it doing? Hence, a good program
must have a self-documenting code.
86
(i) Understanding the problem;
(iv) Evaluation
Devising a plan
It means drawing an action plan to solve the problem, once understood. A plan is
devised from data processing to the result according to the relationship that links both
of them. If the problem is trivial, this step will not require much thinking.
Evaluation
Finally, the result should be examined in order to make sure that it is valid and that the
problem has been solved completely.
87
of a program), that can be adapted by each person to solve the problem in their own
style. They are given as under:
1. Problem Definition
2. Problem Analysis
4. Coding
6. Documentation
7. Program Maintenance
Posing such questions compels you to define the problem very precisely. Once you are
sure of what the problem entails, you must write down a list of specifications.
Specifications are precise definitions of what the program must do. It must include the
following at least:
Output: what data must the program produce and in which form? (in order to
solve the problem)
Note: At the end of the problem definition step, you should have a list of
specifications.
88
Problem Analysis
In this step, the problem has to be fragmented into smaller and manageable parts. The
original problem has to be analyzed and divided into a number of sub-problems as
these sub-problems are easier to solve and their solutions would become the
components of the final program. Each sub-problem is divided into further smaller ones
and this fragmentation has to be continued to achieve simple solutions. The use of
modular programming is to get proper solution.
Top-Down design: The principles of top-down design dictate that a program should be
divided into a main module and its related module. Each module should also be
divided into sub modules according to software engineering and programming style.
The division continues till the module consists only of an elementary process that is
intrinsically understood and cannot be further sub-divided.
Bottom-up design: Bottom-up design is just the opposite of top-down design. It refers
to a style of programming, in which, an application is constructed with existing
primitives of the programming language and then gradually more and more
complicated features are added till applications are written. In other words, initiating
the design with simple modules and then build them into more complex structures
ending at the top is bottom-up design.
Algorithm
Flowchart
89
Flowchart: The algorithm is represented in the form of a diagram with action boxes
linked by lines showing the order in which they are executed. This is known as „the
flow of control‟. It is the diagrammatic representation of an algorithm.
Coding
The process of translating the algorithm into syntax of a given language is known as
„Coding‟. Since algorithm cannot be executed directly by the computer, it has to be
translated into a programming language.
Type of errors: There are three types of errors generally occur during compilation and
running a program. They are (i) Syntax error; (ii) Logical error; and (iii) Runtime error.
Syntax error: Every programming language has its own rules and regulations (syntax).
If we overcome the particular language rules and regulations, the syntax error will
appear (i.e. an error of language resulting from code that does not conform to the syntax
of the programming language). It can be recognized during compilation time.
Example
a=0
while a < 10
a=a+1
print a
In the above statement, the second line is not correct. Since the while statement does not
end with „:‟. This will flash a syntax error.
Logical error: Programmer makes errors while writing program that is called „logical
error‟. It is an error in a program's source code that results in incorrect or unexpected
result. It is a type of runtime error that may simply produce the wrong output or may
cause a program to crash while running. The logical error might only be noticed during
runtime, because it is often hidden in the source code and are typically harder to find
and debug.
90
a = 100
a=a+1
print a
In the above example, the while loop will not execute even a single time, because the
initial value of „a‟ is 100.
Example
(a) A=10
B=0
print A/B
(b) During running time, if we try to open a file that does not exist in the hard disk,
then it will create runtime error.
Documentation
The documentation includes the problem definition, design documents, a description of
the test perform, a history of the program development and its different versions and a
user‟s manual. Such a manual is designed for a naive user and illustrates the
preparation of input data, running the program and obtaining & interpreting the
results.
Program maintenance
It is not directly part of the original implementation process, but needs special
emphasis. All activities that occur after a program operation are part of the program
maintenance. Many large programs have long life span that often exceed the lifetime of
91
the hardware they run on. Usually, the expenditure for the program maintenance will
be more than the developmental cost of the program. The program maintenance
includes the following:
92
EXERCISE
6. The program must be able to handle unexpected situation like wrong input or no
input.
93
8. It refers to the ability of an application to run on different platforms with or
without minimal changes.
10. Each module should also be divided into sub modules according to software
engineering and programming style.
2. What is an identifier?
7. Define documentation.
94
13. Write all steps of program methodology?
95
UNIT 3
Chapter 1
Getting Started
Introduction
In order to tell the computer „what you want to do‟, we write a program in a language
which computer can understand. Though there are many different programming
languages such as BASIC, Pascal, C, C++, Java, Haskell, Ruby, Python, etc. but we will
study Python in this course.
Before learning the technicalities of Python, let‟s get familiar with it.
Python was created by Guido Van Rossum when he was working at CWI (Centrum
Wiskunde & Informatica) which is a National Research Institute for Mathematics and
Computer Science in Netherlands. The language was released in I991. Python got its
name from a BBC comedy series from seventies- “Monty Python‟s Flying Circus”.
Python can be used to follow both Procedural approach and Object Oriented approach
of programming. It is free to use.
97
It is a very simple high level language with vast library of add-on modules.
The language is used by companies in real revenue generating products, such as:
Intel, Cisco, HP, IBM, etc use Python for hardware testing.
NASA and others use Python for their scientific programming task.
To write and run Python program, we need to have Python interpreter installed in our
computer. IDLE (GUI integrated) is the standard, most popular Python development
environment. IDLE is an acronym of Integrated Development Environment. It lets edit,
run, browse and debug Python Programs from a single interface. This environment
makes it easy to write programs.
We will be using version 2.7 of Python IDLE to develop and run Python code, in this
course. It can be downloaded from www.python.org
Python shell can be used in two ways, viz., interactive mode and script mode. Where
Interactive Mode, as the name suggests, allows us to interact with OS; script mode let us
98
create and edit python source file. Now, we will first start with interactive mode. Here,
we type a Python statement and the interpreter displays the result(s) immediately.
Interactive Mode
For working in the interactive mode, we will start Python on our computer. You can
take the help of your Teacher.
What we see is a welcome message of Python interpreter with revision details and the
Python prompt, i.e., „>>>‟. This is a primary prompt indicating that the interpreter is
expecting a python command. There is secondary prompt also which is „…‟ indicating
that interpreter is waiting for additional input to complete the current statement.
Interpreter uses prompt to indicate that it is ready for instruction. Therefore, we can
say, if there is prompt on screen, it means IDLE is working in interactive mode.
We type Python expression / statement / command after the prompt and Python
immediately responds with the output of it. Let‟s start with typing print “How are you”
after the prompt.
What we get is Python‟s response. We may try the following and check the response:
i) print 5+7
99
ii) 5+7
iii) 6*250/9
Example 1 Example 2
#result is tuple of 2 values, is a comment statement. We will talk about it in the later
part of chapter.
Now we are good to write a small code on our own in Python. While writing in Python,
remember Python is case sensitive. That means x & X are different in Python.
Note: If we want to repeat prior command in interactive window, you can use „ ‟ key
to scroll backward through commands history and „ ‟ key to scroll forward. Use Enter
key to select it. Using these keys, your prior commands will be recalled and displayed,
and we may edit or rerun them also.
Help of IDLE can be explored to know about the various menu options available for
Programmer.
Apart from writing simple commands, let‟s explore the interpreter more.
100
Type Credits after the prompt and what we get is information about the organization
involved in Python development. Similarly, Copyright and Licenses command can be
used to know more about Python. Help command provides help on Python. It can be
used as….. help() with nothing in parenthesis will allow us to enter an interactive help
mode. And with a name (predefined) in bracket will give us details of the referred
word.
To leave the help mode and return back to interactive mode, quit command can be
used.
Script Mode
In script mode, we type Python program in a file and then use the interpreter to execute
the content from the file. Working in interactive mode is convenient for beginners and
for testing small pieces of code, as we can test them immediately. But for coding more
than few lines, we should always save our code so that we may modify and reuse the
code.
Note: Result produced by Interpreter in both the modes, viz., Interactive and script
mode is exactly same.
Python, in interactive mode, is good enough to learn, experiment or explore, but its only
drawback is that we cannot save the statements for further use and we have to retype
all the statements to re-run them.
To create and run a Python script, we will use following steps in IDLE, if the script
mode is not made available by default with IDLE environment.
1. File>Open OR File>New Window (for creating a new script file)
2. Write the Python code as function i.e. script
3. Save it (^S)
4. Execute it in interactive mode- by using RUN option (^F5)
Note: For every updation of script file, we need to repeat step 3 & step 4
101
If we write Example 1 in script mode, it will be written in the following way:
Step 2:
def test():
x=2
y=6
z = x+y
print z
Step 3:
Use File > Save or File > Save As - option for saving the file
(By convention all Python program files have names which end with .py)
Step 4:
For execution, press ^F5, and we will go to Python prompt (in other window)
>>> test()
Alternatively we can execute the script directly by choosing the RUN option.
Note: While working in script mode, we add „print‟ statement in our program to see
the results which otherwise were displayed on screen in interactive mode without
typing such statements.
102
B. A type – can be checked using type (object) and
C. A value
A. Identity of the object: It is the object's address in memory and does not change
once it has been created.
B. Type (i.e data type): It is a set of values, and the allowable operations on those
values. It can be one of the following:
1. Number
Number data type stores Numerical Values. This data type is immutable i.e. value
of its object cannot be changed (we will talk about this aspect later). These are of
three different types:
b) Float/floating point
c) Complex
1.1 Integers are the whole numbers consisting of + or – sign with decimal digits
like 100000, -99, 0, 17. While writing a large integer value, don‟t use commas
to separate digits. Also integers should not have leading zeros.
103
When we are working with integers, we need not to worry about the size of
integer as a very big integer value is automatically handled by Python. When
we want a value to be treated as very long integer value append L to the
value. Such values are treated as long integers by python.
>>> a = 10
>>> c= 4298114
<type 'int'>
>>> c = c * 5669
>>> type(c)
<type 'long'>
We can know the largest integer in our version of Python by following the
given set of commands:
>>> import sys
>>> print sys.maxint
Integers contain Boolean Type which is a unique data type, consisting of two
constants, True & False. A Boolean True value is Non-Zero, Non-Null and
Non-empty.
Example
>>> type(flag)
<type 'bool'>
1.2 Floating Point: Numbers with fractions or decimal point are called floating
point numbers.
104
A floating point number will consist of sign (+,-) sequence of decimals digits
and a dot such as 0.0, -21.9, 0.98333328, 15.2963. These numbers can also be
used to represent a number in engineering/ scientific notation.
Example
y= 12.36
Example
>>> x = 1+0j
1.0 0.0
Example
>>> y = 9-5j
9.0 -5.0
2. None
This is special data type with single value. It is used to signify the absence of
value/false in a situation. It is represented by None.
105
3. Sequence
Example
>>> a = 'Ram'
If we are not sure, what is the data type of a value, Python interpreter can tell
us:
>>> type („Good Morning‟)
<type „str‟>
>>> type („3.2‟)
<type „str‟>
int ()
float ()
str ()
bool ()
106
Example
>>> a= 12.34
>>> b= int(a)
>>> print b
12
Example
>>>a=25
>>>y=float(a)
>>>print y
25.0
3.2 Lists: List is also a sequence of values of any type. Values in the list are called
elements / items. These are mutable and indexed/ordered. List is enclosed in
square brackets.
Example
l = [„spam‟, 20.5,5]
3.3 Tuples: Tuples are a sequence of values of any type, and are indexed by
integers. They are immutable. Tuples are enclosed in (). We have already seen
a tuple, in Example 2 (4, 2).
4. Sets
Set is an unordered collection of values, of any type, with no duplicate entry. Sets
are immutable.
Example
s = set ([1,2,34])
5. Mapping
This data type is unordered and mutable. Dictionaries fall under Mappings.
107
5.1 Dictionaries: Can store any number of python objects. What they store is a
key – value pairs, which are accessed using key. Dictionary is enclosed in
curly brackets.
Example
d = {1:'a',2:'b',3:'c'}
Example
>>> pi = 31415
Example
>>>x=5
x 5
>>>y=x
>>> x=x+y
In the statement, expression on RHS will result into value 10 and when this is assigned
to LHS (x), x will rebuild to 10. So now
108
x 10 and
y 5
After learning about what a variable can incorporate, let‟s move on with naming them.
Programmers choose the names of the variable that are meaningful. A variable name:
2. Have allowed characters, which are a-z, A-Z, 0-9 and underscore (_)
Keywords
They are the words used by Python interpreter to recognize the structure of program.
As these words have specific meaning for interpreter, they cannot be used for any other
purpose.
109
Remember:
Variables are created when they are first assigned a value.
Variables must be assigned a value before using them in expression,
Variables refer to an object and are never declared ahead of time.
Mathematical/Arithmetic Operators
110
% Remainder/ >>>17%5 >>> 23%2
Modulo 2 1
Relational Operators
False
111
True False
>>> 7<=4
>>>'Goodbye' <= 'Hello'
False
True
Note: Two values that are of different data type will never be equal to each other.
Logical Operators
Symbol Description
or If any one of the operand is true, then the condition becomes true.
and If both the operands are true, then the condition becomes true.
112
Assignment Operators
Assignment Operator combines the effect of arithmetic and assignment operator
The operand/
expression/
added and assign back the result constant written on
+= >>>x+=2
to left operand RHS of operator is
will change the
value of x to 14
113
Note:
1. Same operator may perform a different function depending on the data type of
the value to which it is applied.
2. Division operator „/‟ behaves differently on integer and float values.
Example
Value/ Operands
2 + 2
Operator
The expression is solved by Computer and gets it value. In the above example, it will be
4, and we say the expression is evaluated.
Note: Expression values in turn can act as, Operands for Operators
We have seen many such expressions (with list of operator as example). 10+5 and 9+4+2
are two expressions which will result into value 15. Taking another example, 5.0/4+ (6-
3.0) is an expression in which values of different data types are used. These type of
expressions are also known as mixed type expressions.
When mixed type expressions are evaluated, Python promotes the result of lower data
type to higher data type, i.e. to float in the above example. This is known as implicit
type casting. So the result of above expression will be 4.25. Expression can also contain
another expression. As we have already seen in 9+4+2. When we have an expression
consisting of sub expression(s), how does Python decide the order of operations?
114
It is done based on precedence of operator. Higher precedence operator is worked on
before lower precedence operator. Operator associativity determines the order of
evaluation when they are of same precedence, and are not grouped by parenthesis. An
operator may be Left-associative or Right –associative. In left associative, the operator
falling on left side will be evaluated first, while in right assosiative operator falling on
right will be evaluated first.
Operator Description
% =, / =, // = , - Assignment operators
=, + =, * =
Using the above table, we know that 9+4 itself is an expression which evaluates to 13
and then 13+2 is evaluated to 15 by computer. Similarly, 5.0/4 + (6-3.0) will be
evaluated as 5.0/4+3.0 and then to 1.25 + 3.0, and then 4.25.
If we just type 10+, we will get an error message. This happens because 10+ is not a
complete expression. A complete expression will always have appropriate number of
value (Operands) with each operator. „+‟ needs two operands and we have given just
one.
115
Note: Remember precedence of operators is applied to find out which sub expression
should be evaluated first.
Expression can be combined together to form large expressions but no matter how big
the expression is, it always evaluate into a single value.
A Python statement is a unit of code that the Python interpreter can execute.
Note: To print multiple items in same line, separate them with comma.
What we have seen as an example till now were simple statements, i.e. they do not
contain a nested block. In Python, there are compound/ group statements also. They
are sometimes called nested block. Statement belonging to a block are indented (usually
by 4 spaces). Leading whitespace at the beginning of logical line is used to determine
the indentation level of line. That means statement(s) which go together must have
same indentation level.
116
Example
if i<0:
print “i is negative”
else:
print “i is non-negative”
Example
if i>0:
print “i is positive”
else:
print “i is equal to 0”
1. Write one python statement per line (Physical Line). Although it is possible to
write two statements in a line separated by semicolon.
2. Comment starts with „#‟ outside a quoted string and ends at the end of a line.
Comments are not part of statement. They may occur on the line by themselves or
at the end of the statement. They are not executed by interpreter.
3. For a long statement, spanning multiple physical lines, we can use „/‟ at the end of
physical line to logically join it with next physical line. Use of the „/‟ for joining
lines is not required with expression consists of ( ), [ ], { }
117
Note:
raw_input()
raw_input ([prompt])
Optional
If prompt is present, it is displayed on the monitor after which user can provide the
data from keyboard. The function takes exactly what is typed from keyboard, convert it
to string and then return it to the variable on LHS of „=‟.
x is a variable which will get the string (ABC), typed by user during the execution of
program. Typing of data for the raw_input function is terminated by „enter‟ key.
We can use raw_input() to enter numeric data also. In that case we typecast, i.e., change
the datatype using function, the string data accepted from user to appropriate Numeric
type.
118
Example
y=int(raw_input(“enter your roll no”))
will convert the accepted string i.e. 5 to integer before assigning it to „y‟.
input()
Syntax for input() is:
Input ([prompt])
Optional
If prompt is present, it is displayed on monitor, after which the user can provide data
from keyboard. Input takes whatever is typed from the keyboard and evaluates it. As
the input provided is evaluated, it expects valid python expression. If the input
provided is not correct then either syntax error or exception is raised by python.
Example
Output is what program produces. In algorithm, it was represented by print. For output
in Python we use print. We have already seen its usage in previous examples. Let‟s
learn more about it.
Print Statement
Syntax:
print expression/constant/variable
119
Print evaluates the expression before printing it on the monitor. Print statement outputs
an entire (complete) line and then goes to next line for subsequent output (s). To print
more than one item on a single line, comma (,) may be used.
Example
Hello
5.5
10
>>>print “I‟m”,
Comments
As the program gets bigger, it becomes difficult to read it, and to make out what it is
doing by just looking at it. So it is good to add notes to the code, while writing it. These
notes are known as comments. In Python, comment start with „#‟ symbol. Anything
written after # in a line is ignored by interpreter, i.e. it will not have any effect on the
program.
A comment can appear on a line by itself or they can also be at the end of line.
Example
120
or
ii) Use triple quoted string. They will only work as comment, when they are not
being used as docstring. (A docstring is the first thing in a class/function /module,
and will be taken up in details when we study functions).
The comment line “#calculating area of a rectangle” can also be written as following
using triple quote:
of a rectangle “””
*important details or decisions made in the program. This will make program more
readable. We already know the importance of comments (documented in the program).
121
EXERCISE
i) 2*(3+4)
ii) 2*3+4
iii) 2+3*4
i) 1+2.0+3
i) global
ii) 99flag
iii) sum
iv) an$wer
5. True or False
i) Character Data type values should be delimited by using the single quote.
iii) The += operator is used to add the right hand side value to the left hand side
variable.
iv) The data type double is not a valid python data type.
122
6. Check all syntactically correct statements
i) a = raw_input ( )
iv) print 9
i) a = 1*2
ii) 2 = 1+1
iii) 5+6=y
iv) Seven = 3 * 4
i) int (7.0+0.1)
iv) str ( 9 / 0 )
i) 65 // 8
ii) 17 % 9
iii) 2**4
iv) 64 * * 0.5
123
f) Which lines are commented?
i) “””This is a comment”””
i) 1023 boolean
v) 17.54 str
7. MCQ
ii) If the value of a = 20 and b = 20, then a+=b will assign ________ to a
a) 40 b) 30 c) 20 d) 10
iii) The ____________ operator is used to find out if division of two number
yields any remainder
a) / b) + c) % d) //
>>> B+4
124
11. What does „immutable‟ mean; which data type in python are immutable.
12. Name four of Python‟s Basic data types? Why are they called so?
13. What are relational operators? Explain with the help of examples.
18. How can you convert a string to integer and when can it be used?
LAB EXERCISE
1. Record what happens when following statements are executed:
a) print n=7
b) print 5+7
a) 6+4*10
b) (6+4)*10
a) 2**500
b) 1/0
a = 3 - 4 + 10
b=5*6
125
c = 7.0/8.0
6. Write a code that prints your full name and your Birthday as separate strings.
7. Write a program that asks two people for their names; stores the names in
variables called name1 and name2; says hello to both of them.
b) 2x 2 - x -3 = 0
126
Chapter 2
Functions
Introduction
Remember, we earlier talked about working in script mode in chapter-1 of this unit to
retain our work for future usage. For working in script mode, we need to write a function
in the Python and save it in the file having .py extension.
i. Modules
ii. Built in
Module
A module is a file containing Python definitions (i.e. functions) and statements.
Standard library of Python is extended as module(s) to a programmer. Definitions from
the module can be used within the code of a program. To use these modules in the
127
program, a programmer needs to import the module. Once you import a module, you
can reference (use), any of its functions or variables in your code. There are many ways
to import a module in your program, the one‟s which you should know are:
i. import
ii. from
Import
It is simplest and most common way to use modules in our code. Its syntax is:
Example
(ii) Create space where modules definition & variable will be created,
Now the definitions of the module will become part of the code in which the module
was imported.
To use/ access/invoke a function, you will specify the module name and name of the
function- separated by dot (.). This format is also known as dot notation.
Example
The example uses sqrt( ) function of module math to calculate square root of the value
provided in parenthesis, and returns the result which is inserted in the value. The
expression (variable) written in parenthesis is known as argument (actual argument). It
is common to say that the function takes arguments and return the result.
This statement invokes the sqrt ( ) function. We have already seen many function
invoke statement(s), such as
128
>>> type ( )
From Statement
It is used to get a specific function in the code instead of the complete module file. If we
know beforehand which function(s), we will be needing, then we may use from. For
modules having large no. of functions, it is recommended to use from instead of import.
Its syntax is
Example
Here, we are importing sqrt function only, instead of the complete math module. Now
sqrt( ) function will be directly referenced to. These two statements are equivalent to
previous example.
Note: You normally put all import statement(s) at the beginning of the Python file but
technically they can be anywhere in program.
129
floor( x ) It returns the largest math.floor(-45.17)
integer not greater than x, -46.0
where x is a numeric
math.floor(100.12)
expression.
100.0
math.floor(100.72)
100.0
130
0.0001
math.pow(2, 4)
16.0
math.pow(3, 0)
1.0
131
degrees (x) It converts angle x from math.degrees(3)
radians to degrees, where x 171.887338539
must be a numeric value.
math.degrees(-3)
-171.887338539
math.degrees(0)
0.0
132
randrange It returns a random item >>>random.randrange(100
([start,] stop [,step]) from the given range ,1000,3)
150
Some of the other modules, which you can explore, are: string, time, date
Built in Function
Built in functions are the function(s) that are built into Python and can be accessed by a
programmer. These are always available and for using them, we don‟t have to import
any module (file). Python has a small set of built-in functions as most of the functions
have been partitioned to modules. This was done to keep core language precise.
min( x, y, z, .... ) It returns the smallest of its >>> min(80, 100, 1000)
arguments; where x, y, and 80
z are numeric
>>> min(-80, -20, -10)
variable/expression.
-80
133
divmod (x,y ) Returns both quotient and >>> divmod (14,5)
remainder by division (2,4)
through a tuple, when x is
>>> divmod (2.7, 1.5)
divided by y; where x & y
are variable/expression. (1.0, 1.20000)
134
round( x [, n] ) It returns float x rounded >>>round(80.23456, 2)
to n digits from the 80.23
decimal point, where x and
>>>round(-100.000056, 3)
n are numeric expressions.
-100.0
If n is not provided then x
is rounded to 0 decimal >>> round (80.23456)
digits. 80.0
Apart from these functions, you have already seen the use of the following functions:
Composition
Composition is an art of combining simple function(s) to build more complicated ones,
i.e., result of one function is used as the input to another.
Example
Suppose we have two functions fn1 & fn2, such that
a= fn2 (x)
b= fn1 (a)
Example
Example
degrees=270
135
Composition is used to package the code into modules, which may be used in many
different unrelated places and situations. Also it is easy to maintain the code.
Note: Python also allow us to take elements of program and compose them.
To define a function keyword def is used. After the keyword comes an identifier i.e.
name of the function, followed by parenthesized list of parameters and the colon which
ends up the line. Next follows the block of statement(s) that are the part of function.
Before learning about Function header & its body, lets explore block of statements,
which become part of function body.
Block of statements
A block is one or more lines of code, grouped together so that they are treated as one
big sequence of statements while executing. In Python, statements in a block are written
with indentation. Usually, a block begins when a line is indented (by four spaces) and
all the statements of the block should be at same indent level. A block within block
begins when its first statement is indented by four space, i.e., in total eight spaces. To
end a block, write the next statement with the same indentation before the block started.
136
The first line of function definition, i.e., Line No. 1 is called header and the rest, i.e. Line
No. 2 in our example, is known as body. Name of the function is sayHello, and empty
parenthesis indicates no parameters. Body of the function contains one Python
statement, which displays a string constant on screen. So the general structure of any
function is
Function Header
It begins with the keyword def and ends with colon and contains the function
identification details. As it ends with colon, we can say that what follows next is, block
of statements.
Function Body
Consisting of sequence of indented (4 space) Python statement(s), to perform a task.
Defining a function will create a variable with same name, but does not generate any
result. The body of the function gets executed only when the function is
called/invoked. Function call contains the name of the function (being executed)
followed by the list of values (i.e. arguments) in parenthesis. These arguments are
assigned to parameters from LHS.
Hello World!
Apart from this, you have already seen many examples of invoking of functions in
Modules & Built-in Functions.
Let‟s know more about def. It is an executable statement. At the time of execution a
function is created and a name (name of the function) is assigned to it. Because it is a
statement, def can appear anywhere in the program. It can even be nested.
Example
if condition:
def fun ( ): # function definition one way
.
137
.
.
else:
def fun ( ): # function definition other way
.
.
.
fun ( ) # calls the function selected.
This way we can provide an alternative definition to the function. This is possible
because def is evaluated when it is reached and executed.
def fun (a):
What function does (without How it does) i.e. summary of its purpose
DocString is an important tool to document the program better, and makes it easier to
understand. We can actually access docstring of a function using __ doc__ (function
name). Also, when you used help(), then Python will provide you with docstring of that
function on screen. So it is strongly recommended to use docstring … when you write
functions.
Example
138
a=radius**2
return a
Function is pretty simple and its objective is pretty much clear from the docString
added to the body.
The last statement of the function, i.e. return statement returns a value from the
function. Return statement may contain a constant/literal, variable, expression or
function, if return is used without anything, it will return None. In our example value
of a variable area is returned.
a = radius **2
return a
Here the function will first calculate and then return the value of the expression.
It is possible that a function might not return a value, as sayHello( ) was not returning a
value. sayHello( ) prints a message on screen and does not contain a return statement,
such functions are called void functions.
Void functions might display something on the screen or have some other effect, but
they don‟t have a return value. If you try to assign the result of such function to a
variable, you get a special value called None.
Example
def check (num):
if (num%2==0):
print “True”
else:
print “False”
139
False
None
DocString Conventions:
The first line of a docstring starts with capital letter and ends with a period (.)
Second line is left blank (it visually separates summary from other description).
Other details of docstring start from 3rd line.
If there is more than one value required by the function to work on, then, all of them
will be listed in parameter list separated by comma.
Example
Scope of Variables
Scope of variable refers to the part of the program, where it is visible, i.e., area where
you can refer (use) it. We can say that scope holds the current set of variables and their
values. We will study two types of scope of variables- global scope or local scope.
140
Global Scope
A variable, with global scope can be used anywhere in the program. It can be created by
defining a variable outside the scope of any function/block.
Example
x=50
def test ( ):
Inside test x is 50
Value of x is 50
Any modification to global is permanent and visible to all the functions written in the
file.
Example
x=50
def test ( ):
x+= 10
will produce
Inside test x is 60
Value of x is 60
Local Scope
A variable with local scope can be accessed only within the function/block that it is
created in. When a variable is created inside the function/block, the variable becomes
local to it. A local variable only exists while the function is executing.
141
Example
X=50
def test ( ):
y = 20
print „Value of x is ‟, X, „; y is ‟ , y
print „Value of x is ‟, X, „ y is „ , y
Value of x is 50; y is 20
The next print statement will produce an error, because the variable y is not accessible
outside the function body.
A global variable remains global, till it is not recreated inside the function/block.
Example
x=50
def test ( ):
x=5
y=2
If we want to refer to global variable inside the function then keyword global will be
prefixed with it.
Example
x=50
142
def test ( ):
global x
x =2
y=2
Example
Default value to parameter
def greet (message,
times=1):
>>> greet („Hello‟, 2) # calling function with both the argument values.
Welcome
HelloHello
The function greet () is used to print a message (string) given number of times. If the
second argument value, is not specified, then parameter times work with the default
value provided to it. In the first call to greet ( ), only one argument value is provided,
which is passed on to the first parameter from LHS and the string is printed only once
143
as the variable times take default value 1. In the second call to greet ( ), we supply both
the argument values a string and 2, saying that we want to print the message twice. So
now, parameter times get the value 2 instead of default 1 and the message is printed
twice.
As we have seen functions with default argument values, they can be called in with
fewer arguments, then it is designed to allow.
Note:
The default value assigned to the parameter should be a constant only.
Only those parameters which are at the end of the list can be given default value.
You cannot have a parameter on left with default argument value, without
assigning default values to parameters lying on its right side.
The default value is evaluated only once, at the point of function definition.
If there is a function with many parameters and we want to specify only some of them
in function call, then value for such parameters can be provided by using their name,
instead of the position (order)- this is called keyword arguments.
print „a is ‟, a, „b is ‟, b, „c is ‟, c
1. >>>fun (3)
a is 3 b is 1 c is 5
a is 3 b is 7 c is 10
a is 25 b is 1 c is 20
a is 10 b is 1 c is 20
144
1st and 2nd call to function is based on default argument value, and the 3rd and 4th call
are using keyword arguments.
In the first usage, value 3 is passed on to a, b & c works with default values. In second
call, all the three parameters get values in function call statement. In third usage,
variable a gets the first value 25, due to the position of the argument. And parameter c
gets the value 20 due to naming, i.e., keyword arguments. The parameter b uses the
default value.
In the fourth usage, we use keyword argument for all specified value, as we have
specified the value for c before a; although a is defined before c in parameter list.
Note: The function named fun ( ) have three parameters out of which first one is
without default value and other two have default values. So any call to the function
should have at least one argument.
fun (5, a=5, 6) # non keyword argument (6) following keyword argument
145
Advantages of writing functions with keyword arguments are:
Using the function is easier as we do not need to remember about the order of the
arguments.
We can specify values of only those parameters to which we want to, as - other
parameters have default argument values.
Example
def x ( ):
print 20
>>> y=x
>>>x ( )
>>>y ( )
20
Example
def x ( ):
print 20
fn( )
20
20
146
20
20
Execution always begins at the first statement of the program. Statements are executed
one at a time, in order from top to bottom. Function definition does not alter the flow of
execution of program, as the statement inside the function is not executed until the
function is called.
On a function call, instead of going to the next statement of program, the control jumps
to the body of the function; executes all statements of the function in the order from top
to bottom and then comes back to the point where it left off. This remains simple, till a
function does not call another function. Simillarly, in the middle of a function, program
might have to execute statements of the other function and so on.
Don‟t worry; Python is good at keeping track of execution, so each time a function
completes, the program picks up from the place it left last, until it gets to end of
program, where it terminates.
Note:
Python does not allow you to call a function before the function is declared.
When you write the name of a function without parenthesis, it is interpreted as
the reference, when you write the function name with parenthesis, the
interpreter invoke the function (object).
147
EXERCISE
a) area b) block
c) function d) Scope
2. True or False
ii. ! (p or q) is same as !p or !q
def f1 ( ):
n = 44
def f2( ):
n=77
4. For each of the following functions. Specify the type of its output. You can assume
each function is called with an appropriate argument, as specified by its
docstrings.
a) def a (x):
„‟‟
x: int or float.
„‟‟
return x+1
b) def b (x):
„‟‟
x: int or float.
„‟‟
148
return x+1.0
„‟‟
x: int or float.
y: int or float.
„‟‟
return x+y
„‟‟
„‟‟
e) def d (x,y):
„‟‟
„‟‟
return x > y
5. Below is a transcript of a session with the Python shell. Assume the functions in
previous question (Q 4) have been defined. Provide the type and value of the
expressions being evaluated.
v) d („apple‟, 11.1)
149
6. Define a function get Bigger Number (x,y) to take in two numbers and return the
bigger of them.
7. What is the difference between methods, functions & user defined functions.
ii. Describe how square root of a value may be calculated without using a math
module
iii. What are the two data constants available in math module.
i. 0≤n<6
LAB EXERCISE
Month? March
Day? 10
Year? 1992
“””
150
a: a positive integer argument
“””
while x>=a:
count +=1
x = x-a
return count
when we call
We get an error message. Modify the code so that error does not occur.
3. Write a script that asks a user for a number. Then adds 3 to that number, and then
multiplies the result by 2, subtracts twice the original number, then prints the
result.
4. In analogy to the example, write a script that asks users for the temperature in F
and prints the temperature in C. (Conversion: Celsius = (F - 32) * 5/9).
5. Write a Python function, odd, that takes in one number and returns True when the
number is odd and False otherwise. You should use the % (mod) operator, not if.
7. Write a Python function, fourthPower( ), that takes in one number and returns that
value raised to the fourth power.
8. Write a program that takes a number and calculate and display the log, square, sin
and cosine of it.
151
10. Write a function roll_D ( ), that takes 2 parameters- the no. of sides (with default
value 6) of a dice, and the number of dice to roll-and generate random roll values
for each dice rolled. Print out each roll and then return one string “That‟s all”.
That‟s all
152
Chapter 3
Conditional and Looping Construct
if x > 0:
print „x is positive‟
Here, the Boolean expression written after if is known as condition, and if Condition is
True, then the statement written after, is executed. Let‟s see the syntax of if statement
Option 1 Option 2
if condition: if condition-1:
153
STATEMENTs- BLOCK 2] STATEMENTs- BLOCK 2
else:
STATEMENTs- BLOCK N]
Let us understand the syntax, in Option 1- if the condition is True (i.e. satisfied), the
statement(s) written after if (i.e. STATEMENT-BLOCK 1) is executed, otherwise
statement(s) written after else (i.e. STATEMENT-BLOCK 2) is executed. Remember else
clause is optional. If provided, in any situation, one of the two blocks get executed not
both.
We can say that, „if‟ with „else‟ provides an alternative execution, as there are two
possibilities and the condition determines which one gets executed. If there are more
than two possibilities, such as based on percentage print grade of the student.
> 85 A
> 70 to <=85 B
> 60 to <=70 C
> 45 to <=60 D
Then we need to chain the if statement(s). This is done using the 2nd option of if
statement. Here, we have used ‘elif’ clause instead of „else‟. elif combines if else- if else
statements to one if elif …else. You may consider elif to be an abbreviation of else if.
There is no limit to the number of „elif‟ clause used, but if there is an „else‟ clause also it
has to be at the end.
print „A‟
154
print „B‟
print „C‟
print „D‟
In the chained conditions, each condition is checked in order if previous is False then
next is checked, and so on. If one of them is True then corresponding block of
statement(s) are executed and the statement ends i.e., control moves out of „if
statement‟. If none is true, then else block gets executed if provided. If more than one
condition is true, then only the first true option block gets executed.
If you look at the conditional construct, you will find that it has same structure as
function definition, terminated by a colon. Statements like this are called compound
statements. In any compound statement, there is no limit on how many statements can
appear inside the body, but there has to be at least one. Indentation level is used to tell
Python which statement (s) belongs to which block.
There is another way of writing a simple if else statement in Python. The complete
simple if, can be written as:
Example
>>> a =5
>>> b=10
>>> x = True
>>> y = False
155
Sometimes, it is useful to have a body with no statements, in that case you can use pass
statement. Pass statement does nothing.
Example
if condition:
pass
It is possible to have a condition within another condition. Such conditions are known
as Nested Condition.
Example
if x==y:
else:
if x<y:
else:
Here a complete if… else statement belongs to else part of outer if statement.
Note: The condition can be any Python expression (i.e. something that returns a
value). Following values, when returned through expression are considered to be
False:
None, Number Zero, A string of length zero, an empty collection
Looping Constructs
We know that computers are often used to automate the repetitive tasks. One of the
advantages of using computer to repeatedly perform an identical task is that it is done
without making any mistake. Loops are used to repeatedly execute the same code in a
program. Python provides two types of looping constructs:
156
1) While statement
2) For statement
While Statements
STATEMENTs BLOCK 1
STATEMENTs BLOCK 2]
We can see that while looks like if statement. The statement bExampleins with keyword
while followed by boolean condition followed by colon (:). What follows next is block
of statement(s).
The statement(s) in BLOCK 1 keeps on executing till condition in while remains True;
once the condition becomes False and if the else clause is written in while, then else will
get executed. While loop may not execute even once, if the condition evaluates to false,
initially, as the condition is tested before entering the loop.
Example
i=1
while (i <=10):
print i,
You can almost read the statement like English sentence. The first statement initialized
the variable (controlling loop) and then while evaluates the condition, which is True so
the block of statements written next will be executed.
Last statement in the block ensures that, with every execution of loop, loop control
variable moves near to the termination point. If this does not happen then the loop will
keep on executing infinitely.
157
As soon as i becomes 11, condition in while will evaluate to False and this will
terminate the loop. Result produced by the loop will be:
1 2 3 4 5 6 7 8 9 10
As there is „,‟ after print i all the values will be printed in the same line
Example
i=1
while (i <=10):
print i,
i+ =1
else:
1 2 3 4 5 6 7 8 9 10
Nested loops
Block of statement belonging to while can have another while statement, i.e. a while can
contain another while.
Example
i=1
while i<=3:
j=1
while j<=i:
j=j+1
158
print
i=i+1
12
123
For Statement
Its Syntax is
STATEMENT BLOCK 1
STATEMENT BLOCK 2]
Example
print i,
1 2 3 4 5 6 7 8 9 10
range( ) generates a list of values starting from start till stop-1. Step if given is added to
the value generated, to get next value in the list. You have already learnt about it in built-in
functions.
Let‟s move back to the for statement: i is the variable, which keeps on getting a value
generated by range ( ) function, and the block of statement (s) are worked on for each
159
value of i. As the last value is assigned to i, the loop block is executed last time and
control is returned to next statement. If else is specified in for statement, then next
statement executed will be else. Now we can easily understand the result of for
statement. range( ) generates a list from 1, 2, 3, 4, 5, …., 10 as the step mentioned is 1, i
keeps on getting a value at a time, which is then printed on screen.
Apart from range( ) i (loop control variable) can take values from string, list, dictionary, etc.
Example
else:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
A for statement can contain another for statement or while statement. We know such
statement form nested loop.
Example
n=2
j=1
160
print “Table to “, i, “is as follows”
while j <6:
j = j+1
Table to 1 is as follows
1*1=1
1*2=2
1*3=3
1*4=4
1*5=5
Table to 2 is as follows
2*1=2
2*2=4
2*3=6
2*4=8
2 * 5 = 10
Nesting a for loop within while loop can be seen in following example :
Example
i=6
while i >= 0:
print j,
161
i=i-1
12345
1234
123
12
By now, you must have realized that, Syntax of for statement is also same as if
statement or while statement.
While For
statement(s)
i+=step
Break Statement
Break can be used to unconditionally jump out of the loop. It terminates the execution
of the loop. Break can be used in while loop and for loop. Break is mostly required,
when because of some external condition, we need to exit from a loop.
Example
if letter = = „h‟:
break
print letter
162
P
Continue Statement
This statement is used to tell Python to skip the rest of the statements of the current
loop block and to move to next iteration, of the loop. Continue will return back the
control to the bExampleinning of the loop. This can also be used with both while and
for statement.
Example
if letter == „h‟:
continue
print letter
163
EXERCISE
1) Mark True/False:
(vi) Checking condition in python can be done by using the if-else statement
(i) if n>2:
if n <6 :
print „OK‟
else:
print „NG‟
(ii) if n>2:
if n<6:
print „OK‟
else:
print „NG‟
164
(ii) A loop that never ends is called a:
a) loop b) back
c) start d) continue
LAB EXERCISE
if answer == "yes":
else:
165
Modify the program so that it answers "That is great!" if the answer was "yes",
"That is disappointing" if the answer was "no" and "That is not an answer to my
question." otherwise.
3) Print all multiples of 13 that are smaller than 100. Use the range function in the
following manner: range (start, end, step) where "start" is the starting value of the
counter, "end" is the end value and "step" is the amount by which the counter is
increased each time.
4) Write a program using while loop that asks the user for a number, and prints a
countdown from that number to zero. Note: Decide on what your program will
do, if user enters a nExampleative number.
5) Using for loop, write program that prints out the decimal equivalent of ½, , ¼, --
----,
8) Write a program using a for loop, that calculates exponentials. Your program
should ask for base and exp. value form user. Note: Do not use ** operator and
math module.
9) Write a program using loop that asks the user to enter an even number. If the
number entered is not even then display an appropriate message and ask them to
enter a number again. Do not stop until an even number is entered. Print a
Congratulatory message at end.
10) Using random module, Simulate tossing a coin N times. Hint: you can use zero for
head and 1 for tails.
166
UNIT 4
Chapter 1
Strings
Introduction
In python, consecutive sequence of characters is known as a string. An individual
character in a string is accessed using a subscript (index). The subscript should always
be an integer (positive or negative). A subscript starts from 0.
Example
>>>myfirst=“Save Earth”
>>>print myfirst
Save Earth
>>>print myfirst[0]
168
To access the fourth character of the string
>>>print myfirst[3]
>>>print myfirst[-1]
>>h
>>>print myfirst[-3]
String A H E L L O
Positive Index 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
Subscript 0 or –ve n(where n is length of the string) displays the first element.
Note: Python does not support character data type. A string of size 1 can be treated as
characters.
169
Creating and initializing strings
A literal/constant value to a string can be assigned using a single quotes, double quotes
or triple quotes.
Example
As shown in example 2, to include the single quote within the string it should be
preceded by a backslash.
170
In the above example, backslash (\) is used as an escape sequence. An escape
sequences is nothing but a special character that has a specific function. As shown
above, backslash (\) is used to escape the double quote.
Example
>>>raw_input()
Right to education
„Right to education‟
As soon as the interpreter encounters raw_input method, it waits for the user to
key in the input from a standard input device (keyboard) and press Enter key. The
input is converted to a string and displayed on the screen.
Note: raw_input( ) method has been already discussed in previous chapter in detail.
Example
171
Python interpreter was not able associate appropriate data type with the entered
data. So a NameError is shown. The error can be rectified by enclosing the given
input i.e. hello in quotes as shown below
Example
>>>str='honesty'
>>>str[2]='p'
Traversing a string
Traversing a string means accessing all the elements of the string one after the other by
using the subscript. A string can be traversed using: for loop or while loop.
String traversal using for loop String traversal using while loop
A=‟Welcome‟ A=‟Welcome‟
>>>for i in A: >>>i=0
print i >>>while i<len(A)
W print A[i]
172
e i=i+1
l W
c e
o l
m c
e o
m
e
Strings Operations
173
string on the left hand side „Save Earth Save Earth Save Earth
times the value on right ‟
hand side.
174
More on string Slicing
Consider the given figure
String A S A V E E A R T H
Positive Index 0 1 2 3 4 5 6 7 8 9
Example
>>>A=‟Save Earth‟
av
The print statement prints the substring starting from subscript 1 and ending at
subscript 3 .
Example
>>>print A[3:]
„e Earth‟
Omitting the second index, directs the python interpreter to extract the substring till the
end of the string
Example
>>>print A[:3]
Sav
Omitting the first index, directs the python interpreter to extract the substring before
the second index starting from the beginning.
175
Example
>>>print A[:]
„Save Earth‟
Omitting both the indices, directs the python interpreter to extract the entire string
starting from 0 till the last index
Example
>>>print A[-2:]
„th‟
For negative indices the python interpreter counts from the right side (also shown
above). So the last two letters are printed.
Example
>>>Print A[:-2]
„Save Ear‟
Omitting the first index, directs the python interpreter to start extracting the substring
form the beginning. Since the negative index indicates slicing from the end of the string.
So the entire string except the last two letters is printed.
Note: Comparing strings using relational operators has already been discussed in the
previous chapter
176
upper case >>>print str.capitalize()
Welcome
177
contains only numbers. false
Otherwise it returns False.
178
right of the string. Teach India Movement
179
LOWER
Note: In the table given above, len( ) is a built in function and so we don‟t need
import the string module. For all other functions import string statement is required
for their successful execution.
180
Let‟s discuss some interesting strings constants defined in string module:
string.ascii_uppercase
Example
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase
Example
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.ascii_letters
The command displays a string containing both uppercase and lowercase characters.
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits
>>> string.digits
'0123456789'
string.hexdigits
>>> string.hexdigits
'0123456789abcdefABCDEF'
181
string.octdigits
>>> string.octdigits
'01234567'
string.punctuations
>>> string.punctuations
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}-'
string.whitespace
The command displays a string containing all ASCII characters that are considered
whitespace. This includes the characters space, tab, linefeed, return, formfeed, and
vertical tab.
>>> string.whitespace
'\t\n\x0b\x0c\r '
string.printable
The command displays a string containing all characters which are considered printable
like letters, digits, punctuations and whitespaces.
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!
"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}- \t\n\r\x0b\x0c'
Note: Import string module to get the desired results with the commands mentioned
above.
182
Programs using string functions and operators
defpalin():
l=len(str)
p=l-1
index=0
while (index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
break
else:
def lettercount():
word = 'pineapple'
count = 0
if letter == 'p':
count = count + 1
print(count)
183
Regular expressions and Pattern matching
A regular expression is a sequence of letters and some special characters (also called
meta characters). These special characters have symbolic meaning. The sequence
formed by using meta characters and letters can be used to represent a group of
patterns.
For example
str= “Ram$”
The pattern “Ram$” is known as a regular expression. The expression has the meta
character „$‟. Meta character „$‟ is used to match the given regular expression at the end
of the string. So the regular expression would match the string „SitaRam‟ or „HeyRam‟
but will not match the string „Raman‟.
string1='SitaRam' string1='SitaRam'
if if re.search('Sita$',string1):
re.search('Ram$',string1): print "String Found"
print "String Found" else :
else : print" No Match"
print" No Match" Output
Output: No Match
String Found
As shown in the above examples, Regular expressions can be used in python for
matching a particular pattern by importing the re module.
184
Now let‟s learn how the meta characters are used to form regular expressions.
185
6 ? Used to specify that the previous wate?r
character can be matched either The regular expression
once or zero times would only match strings
like watr or water
re.compile()
The re.compile( ) function will compile the pattern into pattern objects. After the
compilation the pattern objects will be able to access methods for various operations
like searching and subsitutions
Example
import re
p=re.compile(„hell*o‟)
re.match()
The match function is used to determine if the regular expression (RE) matches at the
beginning of the string.
re.group()
Example
>>>P=re.compile(„hell*o‟)
>>>m.group()
„hello‟
186
re.start()
re.end()
re.span()
The span function returns the tuple containing the (start, end) positions of the match
Example
>>> import re
>>> P=re.compile('hell*o')
>>> m.start()
>>> m.end()
>>> m.span()
(0, 5)
re.search()
The search function traverses through the string and determines the position where the
RE matches the string
Example
>>> m.start()
15
>>> m.end()
187
20
>>> m.group()
'hello'
>>> m.span()
(15, 20)
Re.findall()
The function determines all substrings where the RE matches, and returns them as a list.
Example
>>> m
['hello', 'hello']
re.finditer()
The function determines all substrings where the RE matches, and returns them as an
iterator.
Example
>>> m
print match.span()
(0, 5)
(24, 29)
188
Script 1: Write a script to determine if the given substring is present in the string.
def search_string():
import re
substring='water'
search1=re.search(substring,'Water water everywhere but not a drop to drink')
if search1:
position=search1.start()
print "matched", substring, "at position", position
else:
print "No match found"
Script 2: Write a script to determine if the given substring (defined using meta
characters) is present in the given string
def metasearch():
import re
p=re.compile('sing+')
search1=re.search(p,'Some singers sing well')
if search1:
match=search1.group()
index=search1.start()
lindex=search1.end()
print "matched", match, "at index", index ,"ending at" ,lindex
else:
print "No match found"
189
EXERCISE
1. Input a string “Green Revolution”. Write a script to print the string in reverse.
2. Input the string “Success”. Write a script of check if the string is a palindrome or
not
3. Input the string “Successor”. Write a script to split the string at every occurrence of
the letter s.
4. Input the string “Successor”. Write a script to partition the string at the occurrence
of the letter s. Also Explain the difference between the function split( ) and
partition().
22
333
4444
55555
6. What will be the output of the following statement? Also justify for answer.
>>> str.replace('o','*')
>>>str.istiltle()
190
10. Write a program to print alternate characters in a string. Input a string of your own
choice.
11. Input a string „Python‟. Write a program to print all the letters except the letter‟y‟.
i) To replace all the occurrences of letter „a‟ in the string with „*‟
def metasearch():
import re
p=re.compile('sing+')
if search1:
match=search1.group()
index=search1.start()
lindex=search1.end()
else:
191
print "No match found"
What will be the output of the above script if search() from the re module is
replaced by match () of the re module. Justify your answer
14. What will be the output of the script mentioned below? Justify your answer.
def find():
import re
p=re.compile('sing+')
print search1
>>> str[5]='p'
192
Chapter 2
Lists
Introduction
Like a String, list also is sequence data type. It is an ordered set of values enclosed in
square brackets []. Values in the list can be modified, i.e. it is mutable. As it is set of
values, we can use index in square brackets [] to identify a value belonging to it. The
values that make up a list are called its elements, and they can be of any type.
We can also say that list data type is a container that holds a number of elements in a
given order. For accessing an element of the list, indexing is used.
It will provide the value at „index+1‟ in the list. Index here, has to be an integer value-
which can be positive or negative. Positive value of index means counting forward from
beginning of the list and negative value means counting backward from end of the list.
Remember the result of indexing a list is the value of type accessed from the list.
0, -size 1st
1, -size +1 2nd
193
2, -size +2 3rd
.
.
.
Please note that in the above example size is the total number of elements in the list.
iv) >>>L4 = [“abc”, 10, 20] # list with different types of elements
You will study about Nested lists in later parts of the chapter.
To change the value of element of list, we access the element & assign the new value.
Example
>>> L1 [2] = 5
[1, 2, 5, 4]
Here, 3rd element of the list (accessed using index value 2) is given a new value, so
instead of 3 it will be 5.
194
L1 0 1 L2 0 Delhi L3
1 2 1 Chennai
2 3 2 Mumbai
3 4
Note: List index works the same way as String index, which is:
An integer value/expression can be used as index.
An Index Error appears, if you try and access element that does not exist in the
list.
An index can have a negative value, in that case counting happens from the end
of the list.
Creating a list
List can be created in many ways:
Example
L5=L1 [:]
>>>print L5
L6 = L1 [0:2]
>>>print L6
Example
>>>n = 5
195
>>>l = range(n)
>>>print l
[0, 1, 2, 3, 4]
Example
>>> print S
In mathematical terms, S can be defined as S = {x2 for: x in (0.....9)}. So, we can say
that list comprehension is short-hand for creating list.
Example
>>> A = [3, 4, 5]
Here B will be created with the help of A and its each element will be thrice of
element of A.
>>> print B
>>>B = [ ]
>>>for i in A
B. append (i*3)
Example
>>> print B
>>>C = [i for i in S if i % 2 = = 0]
196
>>>print C
Example
>>>l = list ( )
>>>print l
[ ] # empty list
Or
L = list (sequence)
Example
>>>print L
[1, 2, 3, 4]
A single new list is created every time, you execute [ ]. We have created many
different lists each using [ ]. But if a list is assigned to another variable, a new list
is not created.
i) A=B=[ ]
Example
>>> print A, B
ii) A=[]
B=A
197
Example
>>> A = [1, 2, 3]
>>> B = A
>>> print A, B
[1, 2, 3] [1, 2, 3]
List Slices
Slice operator works on list also. We know that a slice of a list is its sub-list. For creating
a list slice, we use
[n:m] operator.
>>>print L5 [0]
>>>print L5 [2]
[6, 7, 8]
as the 3rd element of this list is a list. To access a value from this sub-list, we will use
This will return the part of the list from nth element to mth element, including the first
element but excluding the last element. So the resultant list will have m-n elements in it.
>>> L1 [1:2]
will give
[2]
198
Slices are treated as boundaries, and the result will contain all the elements between
boundaries.
Where start, stop & step- all three are optional. If you omit first index, slice starts from
„0‟ and omitting of stop will take it to end. Default value of step is 1.
Example
>>>L2 [0:2]
[“Delhi”, “Chennai”]
Example
>>>list [4:] # will produce a list containing all the elements from 5th position
till end
[50, 60]
Example
>>>list [:3]
>>>list [:]
Example
60
199
Note: Since lists are mutable, it is often recommended to make a copy of it before
performing operation that change a list.
Traversing a List
Let us visit each element (traverse the list) of the list to display them on screen. This can
be done in many ways:
(i) i=0
while i < 4:
print L1 [i],
i+=1
1254
print i,
(iii) i=0
print L1 [i],
i+=1
OR
i= 0
L = len (L1)
while i < L :
print L1 [i],
i+=1
200
Here len( ) function is used to get the length of list L1. As length of L1 is 4, i will take
value from 0 to 3.
print L1 [i],
Using 2nd way for transversal will only allow us to print the list, but other ways can also
be used to write or update the element of the list.
In 4th way, range ( ) function is used to generate, indices from 0 to len -1; with each
iteration i gets the index of next element and values of list are printed.
Example
for i in [ ]:
print i
i=1
print L1 [-i],
i += 1
In this case, Python will add the length of the list to index and then return the
index value and accesses the desired element. In this loop execution for a positive
value of „i‟ L1 [-i] will result into L1 [len (L1)-i] for i=1, L1 [4-1] will be printed. So
resultant of the loop will be 4 5 2.
201
L1. append (70)
This will add 70 to the list at the end, so now 70 will be the 5th element of the list, as it
already have 4 elements.
>>> print L1
[1, 2, 5, 4, 70]
Example
>>>print L4
Using append ( ), only one element at a time can be added. For adding more than one
element, extend ( ) method can be used, this can also be used to add elements of another
list to the existing one.
Example
>>> print L1
will add all the elements of list „A‟ at the end of the list „L1‟.
>>>print A
Example
>>>B.extend (c)
>>>print B
202
[2009, 2011, „abc‟, „xyz‟, „pqr‟, „mn‟]
Example
>>> print L1
will produce
Example
>>>print A
will produce
[10, 100]
As lists are sequences, they support many operations of strings. For example, operator +
& * results in concatenation & repetition of lists. Use of these operators generate a new
list.
Example
>>> a= L1+L2
will produce a 3rd list a containing elements from L1 & then L2. a will contain
[1, 10, 20, 4, 70, 100, 90, 80, 50, “Delhi”, “Chennai”, “Mumbai”]
203
Example
[1, 2, 3, 4, 5, 6]
Example
>>> b = L1*2
>>> print b
[[1, 10, 20, 4, 70, 100, 90, 80, 50, 1, 10, 20, 4, 70, 100, 90, 80, 50]
Example
>>> [„Hi!‟]* 3
It is important to know that ‘+’ operator in lists expects the same type of sequence on
both the sides otherwise you get a type error.
If you want to concatenate a list and string, either you have to convert the list to string
or string to list.
Example
Deleting Elements
It is possible to delete/remove element(s) from the list. There are many ways of doing
so:
(ii) If the element is known, not the index, remove ( ) can be used.
(iii) To remove more than one element, del ( ) with list slice can be used.
204
Let us study all the above methods in details:
Pop ( )
It removes the element from the specified index, and also return the element which was
removed.
List.pop ([index])
Example
>>> a= L1.pop (1) # here the element deleted will be returned to ‘a’
>>> print L1
>>> print a
>>>L1.pop ( )
50
del removes the specified element from the list, but does not return the deleted
value.
>>> print L1
remove ( )
In case, we know the element to be deleted not the index, of the element, then remove (
) can be used.
205
>>> print L1
Examples
>>>print L1
[1, 5, 80]
will remove 2nd and 3rd element from the list. As we know that slice selects all the
elements up to 2nd index but not the 2nd index element. So 4th element will remain in the
list.
>>> L5 [1:2] = [ ]
>>>print L5
Note:
(i) All the methods, modify the list, after deletions.
(ii) If an out of range index is provided with del ( ) and pop ( ), the code will result
in to run-time error.
(iii) del can be used with negative index value also.
206
Its syntax is
Index specifies the position (starting from 0) where the element is to be inserted. Item is
the element to be inserted in the list. Length of list changes after insert operation.
Example
>>>print L1
will produce
Note: If the index specified is greater then len (list) the object is inserted in the last
and if index is less than zero, the object is inserted at the beginning.
>>>print L1
will produce
reverse ( )
This method can be used to reverse the elements of the list in place
list.reverse ( )
Method does not return anything as the reversed list is stored in the same variable.
Example
>>> L1.reverse ( )
207
>>> print L1
will produce
>>>L1 [: : -1]
As this slices the whole sequence with the step of -1 i.e. in reverse order.
sort ( )
For arranging elements in an order Python provides a method sort ( ) and a function
sorted ( ). sort ( ) modifies the list in place and sorted ( ) returns a new sorted list.
Parameters mentioned in [ ] are optional in both the cases. These parameters allow us to
customize the function/method.
cmp, argument allow us to override the default way of comparing elements of list. By
default, sort determines the order of elements by comparing the elements in the list
against each other. To overside this, we can use a user defined function which should
take two values and return -1 for ‘less than’, 0 for ‘equal to’ and 1 for „greater than‟.
Example
The parameter ‘key’ is for specifying a function that transforms each element of list
before comparison. We can use predefined functions or a user defined function here. If
its user defined then, the function should take a single argument and return a key
which can be used for sorting purpose.
Reverse parameter can have a boolean value which is used to specify the order of
arranging the elements of list. Value ‘True’ for reverse will arrange the elements of list
in descending order and value ‘False’ for reverse will arrange the elements in ascending
order. Default value of this parameter is False.
208
sorted ( ) function also behaves in similar manner except for it produce a new sorted
list, so original is not changed. This function can also be used to sort any iterable
collection. As sort ( ) method does not create a new list so it can be little faster.
Example
>>> L1.sort ( )
>>> print L1
will produce
>>> L2.sort ( )
>>> print L2
will produce
will produce
Here we have specified len ( ) built in function, as key for sorting. So the list will get
sorted by the length of the strings, i.e., from shorted to longest.
sort will call len ( ) function for each element of list and then these lengths will be used
for arranging elements.
>>> L4.sort ( )
>>> print L4
will produce
209
[10, 20, 30, „abc‟]
>>>L4.sort (reverse = True)
[„abc‟, 30, 20, 10]
>>> def compare (str):
... return len (str)
>>> L2.sort (key=compare)
>>> L2
[„Delhi‟, „Mumbai‟, „Chennai‟]
List as arguments
When a list is passed to the function, the function gets a reference to the list. So if the
function makes any changes in the list, they will be reflected back in the list.
Example
L [i] += 10
>>> X = [1, 2, 3, 4, 5]
>>> print X
Here parameter „L‟ and argument „X‟ are alias for same object. Its state diagram will
look like
210
Note: Here, it becomes important to distinguish between the operations which
modifies a list and operation which creates a new list. Operations which create a new
list will not affect the original (argument) list.
Let‟s look at some examples to see when we have different lists and when an alias is
created.
>>> a = [2, 4, 6]
>>> b = a
will map b to a. To check whether two variables refer to same object (i.e. having same
value), we can use „is‟ operator. So in our example:
>>> a is b
>>> a = [2, 4, 6]
>>> b = [2, 4, 6]
>>> a is b
False
In first example, Python created one list, reference by a & b. So there are two references
to the same object b. We can say that object [2, 4, 6] is aliased as it has more than one
name, and since lists are mutable. So changes made using „a‟ will affect „b‟.
>>> a [1] = 10
>>> print b
will print
[2, 10, 6]
211
Matrix implementation using list
We can implement matrix operation using list. Matrix operation can be implemented
using nested list. List inside another list is called nested list.
Example
Write a program to input any matrix with mXn, and print the number on the output
screen in matrix format.
Matrix creation
Program 1
212
Output
>>>
output is
10 20 30
40 50 60
70 80 90
>>>
Program 2
import random
for i in range(m):
213
for j in range(n):
a[i][j]=input()
for i in range(m):
for j in range(n):
print a[i][j],'\t',
Output
>>>
output is
1 2 3
4 5 6
7 8 9
>>>
214
Matrix Addition
Write a program to input any two matrices and print sum of matrices.
import random
for i in range(m1):
for j in range(n1):
a[i][j]=input()
for i in range(2):
for j in range(2):
b[i][j]=input()
for i in range(m1):
for j in range(n1):
c[i][j]=a[i][j]+b[i][j]
print c[i][j],'\t',
else
215
Output
>>>
output is
3 3
3 3
Example
Write a program to input any two matrices and print product of matrices.
import random
for i in range(m1):
for j in range(n1):
a[i][j]=input()
216
m2=input ("Enter total number of rows in the second matrix")
for i in range(m2):
for j in range(n2):
b[i][j]=input()
if (n1==m2):
for i in range(m1):
for j in range(n2):
c[i][j]=0
for k in range(n1):
c[i][j]+=a[i][k]*b[k][j]
print c[i][j],'\t',
else:
Output
>>>
217
Enter total number of columns in the second matrix2
4 4
4 4
>>>
Example
Write a program to input any matrix and print both diagonal values of the matrix.
import random
if (m==n):
for i in range(m):
for j in range(n):
a[i][j]=input()
for i in range(m):
print a[i][i],'\t',
k=m-1
for j in range(m):
print a[j][k],'\t',
218
k-=1
else:
Output
>>>
First diagonal
1 5 9
Second diagonal
3 5 7
>>>
Example
Write a program to pass any list and to arrange all numbers in descending order.
219
def arrange (l,n):
for i in range(n-1):
for j in range(n-i-1):
if l[j]>l[j+1]:
temp=l[j]
l[j]=l[j+1]
l[j+1]=temp
Output
>>>
>>> l=[7,5,8,2,9,10,3]
>>> print l
[10, 9, 8, 7, 5, 3, 2]
>>>
Example
Write a program to input nXm matrix and find sum of all numbers using function.
Function:
def summat(a,m,n):
s=0
for i in range(m):
for j in range(n):
s+=a[i][j]
return s
220
Function call
import random
import mataddition
for i in range(m):
for j in range(n):
a[i][j]=input()
s=mataddition.summat(a,m,n)
print s
Output
>>>
10
>>>
Example
count = -1
for list in a:
221
count + = 1
print item,
123
45
678
222
EXERCISE
1. Define list
b) a= [1, 2, 3, None, ( ), [ ]}
print len(a)
(iii) 5 (iv) 6
(v) 7
A=[2,4,6,8,10]
L=len(L)
S=0
for I in range(1,L,2):
S+=A[I]
print “Sum=”,S
l=range(n)
print l
for i in (n);
l[i]=input("enter element")
223
print "All elements in the list on the output screen"
for i on range(n):
print l[i]
5. Write a function group of list (list, size) that takes a list and splits into smaller list
of given size.
7. For each of the expression below, specify its type and value. If it generates error,
write error.
(i) x[0]
(ii) x[2]
(iii) x[-1]
(iv) x[0:1]
(v) 2 in x
(vi) x[0]=8
8. For each of the expression below, specify its type and value. If it generates error,
write error:
List A= [1, 4, 3, 0]
(ii) List A
224
(vii) List B.pop ( )
LAB EXERCISE
2. Write a function that takes a list of numbers and returns the cumulative sum; that
is, a new list where the its element is the sum of the first i+1 elements from the
original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].
3. Write a function called chop that takes a list and modifies it, removing the first and
last elements, and returns None. Then write a function called middle that takes a list
and returns a new list that contains all but the first and last elements.
4. Write a function called is_sorted that takes a list as a parameter and returns True if
the list is sorted in ascending order and False otherwise. You can assume (as a
precondition) that the elements of the list can be compared with the relational
operators <, >, etc.
For example, is_sorted ([1, 2, 2]) should return True and is_sorted ([‘b’, ‘a’]) should
return False.
5. Write a function called remove_duplicates that takes a list and returns a new list
with only the unique elements from the original. Hint: they don‟t have to be in the
same order.
6. Write a function that takes in two sorted lists and merges them. The lists may not
be of same length and one or both may be empty. Don‟t use any Python built-in
methods or functions.
225
7. Create a list that contains the names of 5 students of your class. (Do not ask for
input to do so)
(ii) Ask the user to input one name and append it to the list
(iv) Ask user to input a number. Print the name that has the number as index
(Generate error message if the number provided is more than last index
value).
(v) Add “Kamal” and “Sanjana” at the beginning of the list by using „+‟.
(vii) Ask the user to type a name. Check whether that name is in the list. If exist,
delete the name, otherwise append it at the end of the list.
8. Use the list of student names from the previous exercise. Create a for loop that asks
the user for every name whether they would like to keep the name or delete it.
Delete the names which the user no longer wants. Hint: you cannot go through a
list using a for loop and delete elements from the same list simultaneously because
in that way the for loop will not reach all elements. You can either use a second
copy of the list for the loop condition or you can use a second empty list to which
you append the elements that the user does not want to delete.
9. Write a function to find product of the element of a list. What happens when the
function is called with list of strings?
10. Write a program to input NXM matrix and find sum of all even numbers in the
matrix.
13. Write a program to find sum of rows and columns of the matrix.
226
Chapter 3
Dictionaries
What is dictionary?
A dictionary is like a list, but more in general. In a list, index value is an integer, while
in a dictionary index value can be any other data type and are called keys. The key will
be used as a string as it is easy to recall. A dictionary is an extremely useful data storage
construct for storing and retrieving all key value pairs, where each element is accessed
(or indexed) by a unique key. However, dictionary keys are not in sequences and hence
maintain no left-to right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps a value. The association of a key and a value is
called a key-value pair.
Syntax:
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
227
In the above example, we have created a list that maps from numbers to English words,
so the keys values are in numbers and values are in strings.
1 one
A =
2 two
3 three
>>>computer={'input':'keybord','output':'mouse','language':'python','os':'windows-
8',}
>>>
In the above example, we have created a list that maps from computer related things
with example, so here the keys and values are in strings. The order of the key-value
pairs is not in same order (ie. input and output orders are not same). We can get
different order of items in different computers. Thus, the order of items in a dictionary
is unpredictable.
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> print D
228
>>> D=dict()
>>> print D
{}
{} represents empty string. To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
>>>
Traversing a dictionary
Let us visit each element of the dictionary to display its values on screen. This can be
done by using ‘for-loop’.
Example
Code
for i in H:
Output
>>>
>>>
229
OR
Code
for i in H:
Output
Four scanner
one keyboard
three printer
two Mouse
Example
Write a program to input total number of sections and class teachers’ name in 11 th class
and display all information on the output screen.
Code
classxi=dict()
i=1
while i<=n:
a=raw_input("enter section")
230
b=raw_input ("enter class teacher name")
classxi[a]=b
i=i+1
for i in classxi:
print "XI","\t",i,"\t",classxi[i]
Output
>>>
enter sectionA
enter sectionB
enter sectionC
XI A Leena
XI C Surpreeth
XI B Madhu
>>>
Syntax:
231
Example
>>> a={"mon":"monday","tue":"tuesday","wed":"wednesday"}
>>> a["thu"]="thursday"
>>> print a
>>>
Syntax:
Dic_name1.update (dic_name2)
Example
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
Example
{1: 10, 2: 30, 3: 30, 5: 40, 6: 60} # k>>> d1={1:10,2:20,3:30} # key 2 value is 20
>>> d1.update(d2)
>>> print d1
232
Removing an item from dictionary
We can remove item from the existing dictionary by using del key word.
Syntax:
del dicname[key]
Example
>>> A={"mon":"monday","tue":"tuesday","wed":"wednesday","thu":"thursday"}
>>> print A
>>>
Syntax:
returns 0 or 1 or -1
Example
>>>
D1={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursd
ay','fri':'Friday','sat':'Saturday'}
>>>
D2={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursd
ay','fri':'Friday','sat':'Saturday'}
>>> D3={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
233
1
>>> cmp(D3,D1)
-1
len( )
This method returns number of key-value pairs in the given dictionary.
Syntax:
len(d) #d dictionary
Example
>>> len(H)
clear ( )
It removes all items from the particular dictionary.
Syntax:
d.clear( ) #d dictionary
Example
>>> D={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
>>> print D
>>> D.clear( )
>>> print D
{}
234
get(k, x )
There are two arguments (k, x) passed in ‘get( )’ method. The first argument is key
value, while the second argument is corresponding value. If a dictionary has a given
key (k), which is equal to given value (x), it returns the corresponding value (x) of given
key (k). However, if the dictionary has no key-value pair for given key (k), this method
returns the default values same as given key value. The second argument is optional. If
omitted and the dictionary has no key equal to the given key value, then it returns
None.
Syntax:
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.get('wed',"wednesday") # corresponding value wed
'Wednesday'
>>> D.get("fri","monday") # default value of fri
'Friday'
>>> D.get("mon") # default value of mon
'Monday'
>>> D.get("ttu") # None
>>>
has_key( )
This function returns ‘True’, if dictionary has a key, otherwise it returns ‘False’.
Syntax:
Example
>>>
235
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.has_key("fri")
True
>>> D.has_key("aaa")
False
>>>
items( )
It returns the content of dictionary as a list of key and value. The key and value pair
will be in the form of a tuple, which is not in any particular order.
Syntax:
D.items() # D dictionary
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.items()
Note: items () is different from print command because, in print command dictionary
values are written in {}
keys()
It returns a list of the key values in a dictionary, , which is not in any particular order.
Syntax:
D.keys( ) #D dictionary
Example
>>>
236
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.keys()
>>>
values()
It returns a list of values from key-value pairs in a dictionary, which is not in any
particular order. However, if we call both the items () and values() method without
changing the dictionary's contents between these two (items() and values()), Python
guarantees that the order of the two results will be the same.
Syntax:
D.values() #D values
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> D.values()
>>> D.items()
Solved Examples
1. Write a python program to input ‘n’ names and phone numbers to store it in a
dictionary and to input any name and to print the phone number of that particular
name.
Code
phonebook=dict()
237
n=input("Enter total number of friends")
i=1
while i<=n:
a=raw_input("enter name")
phonebook[a]=b
i=i+1
name=raw_input("enter name")
f=0
l=phonebook.keys()
for i in l:
if (cmp(i,name)==0):
f=1
if (f==0):
Output
>>>
enter nameMona
enter nameSonu
enter nameRohan
enter nameSonu
238
Phone number= 45678956
>>>
2. Write a program to input ‘n’ employee number and name and to display all
employee’s information in ascending order based upon their number.
Code
empinfo=dict()
i=1
while i<=n:
a=raw_input("enter number")
b=raw_input("enter name")
empinfo[a]=b
i=i+1
l=empinfo.keys()
l.sort()
for i in l:
print i,'\t',empinfo[i]
Output
>>>
enter number555
enter nameArpit
enter number333
239
enter nameShilpa
enter number777
enter nameKush
enter number222
enter nameAnkita
enter number666
enter nameArun
Employee Information
222 Ankita
333 Shilpa
555 Arpit
666 Arun
777 Kush
>>>
A={1:100,2:200,3:300,4:400,5:500}
print A.items()
print A.keys()
print A.values()
Output
[(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)]
[1, 2, 3, 4, 5]
240
4. Write a program to create a phone book and delete particular phone number using
name.
Code
phonebook=dict()
i=1
while i<=n:
a=raw_input("enter name")
phonebook[a]=b
i=i+1
name=raw_input("enter name")
del phonebook[name]
l=phonebook.keys()
for i in l:
print i,'\t',phonebook[i]
Output
>>>
enter nameLeena
enter nameMadhu
enter nameSurpreeth
241
enter phone number 9678543245
enter nameDeepak
enter nameAnuj
enter nameDeepak
Phonebook Information
Leena 9868734523
Surpreeth 9678543245
Madhu 9934567890
Anuj 9655442345
>>>
242
EXERCISE
1. Write the code to input any 5 years and the population of any city and print it on
the screen.
2. Write a code to input ‘n’ number of subject and head of the department and also
display all information on the output screen.
A={10:1000,20:2000,30:3000,40:4000,50:5000}
print A.items()
print A.keys()
print A.values()
4. Write a code to create customer’s list with their number & name and delete any
particular customer using his /her number.
5. Write a Python program to input ‘n’ names and phone numbers to store it in a
dictionary and print the phone number of a particular name.
c=dict()
n=input(Enter total number )
i=1
while i<=n
a=raw_input("enter place")
b=raw_input("enter number")
c(a)=b
i=i+1
print "place","\t","number"
for i in c:
print i,"\t",cla[i]
243
Chapter 4
Tuples
What is a Tuple?
A tuple is a sequence of values, which can be of any type and they are indexed by
integer. Tuples are just like list, but we can’t change values of tuples in place. Thus
tuples are immutable. The index value of tuple starts from 0.
>>> print T
But in the result, same tuple is printed using parentheses. To create a tuple with single
element, we have to use final comma. A value with in the parenthesis is not tuple.
Example
>>> T=(10)
>>> type(T)
<type 'int'>
Example
>>> t=10,
>>> print t
(10,)
244
Example
>>> T=(10,20)
>>> type(T)
<type 'tuple'>
Example
>>> T=('sun','mon','tue')
>>> print T
Example
>>> T=('P','Y','T','H','O','N')
>>> print T
Tuple Creation
If we need to create a tuple with a single element, we need to include a final comma.
Example
>>> t=10,
>>> print t
(10,)
Syntax:
T = tuple()
Example
>>> T=tuple()
245
>>> print T
()
Example
>>> t=(10,20,30,40)
>>> print t
>>> print t
Example
Code
t=tuple()
for i in range(n):
a=input("enter number")
t=t+(a,)
print t
246
Output
>>>
enter number10
enter number20
enter number30
output is
>>>
Code
t=tuple()
for i in range(n):
a=input("enter number")
t=t+(a,)
for i in range(n):
print t[i]
Output
>>>
enter number10
247
enter number20
enter number30
output is
10
20
30
>>>
We can also add new element to tuple by using list. For that we have to convert the
tuple into a list first and then use append() function to add new elements to the list.
After completing the addition, convert the list into tuple. Following example illustrates
how to add new elements to tuple using a list.
>>> print T
()
>>> l.append(20)
>>> print T
(10, 20)
>>> T=(0,)*10
>>> print T
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
Tuple Assignment
If we want to interchange (swap) any two variable values, we have to use temporary
variable. For example;
248
>>> A=10
>>> B=20
10 20
>>> T=A
>>> A=B
>>> B=T
20 10
Example
>>> T1=(10,20,30)
>>> T2=(100,200,300,400)
>>> print T1
>>> print T2
>>> print T1
>>> print T2
The left side is a tuple of variables, while the right side is a tuple of expressions. Each
value is assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments.
249
The number of variables on the left and the number of values on the right have to be the
same:
Example
>>> T1=(10,20,30)
>>> T2=(100,200,300)
>>> t3=(1000,2000,3000)
>>> T1,T2=T2,T1,t3
T1,T2=T2,T1,t3
Here, two tuples are in the left side and three tuples are in right side. That is why, we
get errors. Thus, it is required to have same number of tuples in both sides to get the
correct result.
Example
>>> T1,T2,t3=t3,T1,T2
>>> print T1
>>> print T2
>>> print t3
Tuple Slices
Slice operator works on Tuple also. This is used to display more than one selected value
on the output screen. Slices are treated as boundaries and the result will contain all the
elements between boundaries.
250
Syntax is:
Where start, stop & step all three are optional. If we omit first index, slice starts from ‘0’.
On omitting stop, slice will take it to end. Default value of step is 1.
Example
>>> T=(10,20,30,40,50)
>>> T1=T[2:4]
>>> print T1
(30, 40)
In the above example, starting position is 2 and ending position is 3(4-1), so the selected
elements are 30 & 40.
>>> T[:]
>>> T[::2]
>>> T[:3]
>>> T[2:]
251
Tuple Functions
cmp( )
This is used to check whether the given tuples are same or not. If both are same, it will
return ‘zero’, otherwise return 1 or -1. If the first tuple is big, then it will return 1,
otherwise return -1.
Syntax:
cmp(t1,t2) #t1and t2 are tuples.
returns 0 or 1 or -1
Example
>>> T1=(10,20,30)
>>> T2=(100,200,300)
>>> T3=(10,20,30)
>>> cmp(T1,T2)
-1
>>> cmp(T1,T3)
0
>>> cmp(T2,T1)
1
len( )
It returns the number of items in a tuple.
Syntax:
len(t) #t tuples
Example
>>> T2=(100,200,300,400,500)
>>> len(T2)
5
252
max( )
It returns its largest item in the tuple.
Syntax:
max(t) #t tuples
returns maximum value among the given tuple.
Example
>>> T=(100,200,300,400,500)
>>> max(T)
500
min( )
It returns its smallest item in the tuple.
Syntax:
min(t) #t tuples
returns minimum value among the given tuple.
Example
>>> T=(100,200,300,400,500)
>>> min(T)
100
tuple( )
It is used to create empty tuple.
Syntax:
T=tuple() #t tuples
Create empty tuple.
Example
>>> t=tuple()
>>> print t
()
253
Solved Examples
1. Write a program to input 5 subject names and put it in tuple and display that tuple
information on the output screen.
Code
t=tuple()
for i in range(5):
a=raw_input("enter subject")
t=t+(a,)
print t
Output
>>>
enter subjectEnglish
enter subjectHindi
enter subjectMaths
enter subjectScience
output is
>>>
2. Write a program to input any two tuples and interchange the tuple values.
Code
t1=tuple()
254
for i in range(n):
a=input("enter elements")
t1=t1+(a,)
t2=tuple()
for i in range(m):
a=input("enter elements")
t2=t2+(a,)
print t1
print t2
t1,t2=t2,t1
print t1
print t2
Output
>>>
enter elements100
enter elements200
enter elements300
enter elements10
255
enter elements20
enter elements30
enter elements40
First Tuple
Second Tuple
AFTER SWAPPING
First Tuple
Second Tuple
>>>
3. Write a program to input ‘n’ numbers and store it in a tuple and find maximum &
minimum values in the tuple.
Code
t=tuple()
for i in range(n):
a=input("enter elements")
t=t+(a,)
Output
>>>
256
enter elements40
enter elements50
enter elements10
maximum value= 50
minimum value= 10
>>>
T=(10,30,2,50,5,6,100,65)
print max(T)
print min(T)
Output
100
t=tuple()
t = t +(PYTHON,)
print t
print len(t)
t1=(10,20,30)
print len(t1)
Output
('PYTHON',)
257
EXERCISE
(i) t=(10,20,30,40,50)
print len(t)
(ii) t=('a','b','c','A','B')
max(t)
min(t)
(iii) T1=(10,20,30,40,50)
T2 =(10,20,30,40,50)
T3 =(100,200,300)
cmp(T1,T2)
cmp(T2,T3)
cmp(T3,T1)
(iv) t=tuple()
Len(t)
(v) T1=(10,20,30,40,50)
T2=(100,200,300)
T3=T1+T2
print T3
2. Write a program to input two set values and store it in tuples and also do the
comparison.
3. Write a program to input ‘n’ employees’ salary and find minimum & maximum
salary among ‘n’ employees.
t=tuple{}
258
n=input(Total number of values in tuple)
for i in range(n)
a=input("enter elements")
t=t+(a)
5. Write a program to input ‘n’ customers’ name and store it in tuple and display all
customers’ names on the output screen.
6. Write a program to input ‘n’ numbers and separate the tuple in the following
manner.
Example
T=(10,20,30,40,50,60)
T1 =(10,30,50)
T2=(20,40,60)
259
Computer Science - Class XI
CENTRAL BOARD OF SECONDARY EDUCATION
Shiksha Kendra, 2, Community Centre, Preet Vihar, Delhi-110 092 India