0% found this document useful (0 votes)
47 views

Passing Parameters in Functions: Output: Hello - Python None

Uploaded by

jhony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Passing Parameters in Functions: Output: Hello - Python None

Uploaded by

jhony
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

The above function will output the following.

Output:
hello – Python
None

7.4 Passing Parameters in Functions

Parameters can be declared to functions

Syntax:
def function_name (parameter(s) separated by comma):

Let us see the use of parameters while defining functions. The parameters that you
place in the parenthesis will be used by the function itself. You can pass all sorts of data to the
functions. Here is an example program that defines a function that helps to pass parameters
into the function.
Example: 7.4
# assume w = 3 and h = 5
def area(w,h):
return w * h
print (area (3,5))

The above code assigns the width and height values to the parameters w and h. These
parameters are used in the creation of the function “area”. When you call the above function,
it returns the product of width and height as output.
The value of 3 and 5 are passed to w and h respectively, the function will return 15 as
output.

We often use the terms parameters and arguments interchangeably. However, there
is a slight difference between them. Parameters are the variables used in the function
definition whereas arguments are the values we pass to the function parameters

7.5 Function Arguments

Arguments are used to call a function and there are primarily 4 types of functions that
one can use: Required arguments, Keyword arguments, Default arguments and Variable-length
arguments.

XII Std Computer Science 92

12th Computer Science_EM Chapter 7.indd 92 21-12-2022 15:21:23


Function Arguments

1 Required arguments

2 Keyword arguments

3 Default arguments

4 Variable-length arguments

7.5.1 Required Arguments


“Required Arguments” are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with the
function definition. You need atleast one parameter to prevent syntax errors to get the required
output.
Example :7.5.1
def printstring(str):
print ("Example - Required arguments ")
print (str)
return
# Now you can call printstring() function
printstring()

When the above code is executed, it produces the following error.


Traceback (most recent call last):
File "Req-arg.py", line 10, in <module>
printstring()
TypeError: printstring() missing 1 required positional argument: 'str'

Instead of printstring() in the above code if we use printstring (“Welcome”) then the
output is

Output:
Example - Required arguments
Welcome

93 Python Functions

12th Computer Science_EM Chapter 7.indd 93 21-12-2022 15:21:23


7.5.2 Keyword Arguments
Keyword arguments will invoke the function after the parameters are recognized by
their parameter names. The value of the keyword argument is matched with the parameter
name and so, one can also put arguments in improper order (not in order).
Example: 7.5.2 (a)
def printdata (name):
print (“Example-1 Keyword arguments”)
print (“Name :”,name)
return
# Now you can call printdata() function
printdata(name = “Gshan”)

When the above code is executed, it produces the following output :

Output:
Example-1 Keyword arguments
Name :Gshan

Example: 7.5.2 (b)


def printdata (name):
print (“Example-2 Keyword arguments”)
print (“Name :”, name)
return
# Now you can call printdata() function
printdata (name1 = “Gshan”)

When the above code is executed, it produces the following result :

TypeError: printdata() got an unexpected keyword argument 'name1'

Example: 7.5.2 (c)


def printdata (name, age):
print ("Example-3 Keyword arguments")
print ("Name :",name)
print ("Age :",age)
return
# Now you can call printdata() function
printdata (age=25, name="Gshan")

XII Std Computer Science 94

12th Computer Science_EM Chapter 7.indd 94 21-12-2022 15:21:23


When the above code is executed, it produces the following result:

Output:
Example-3 Keyword arguments
Name : Gshan
Age : 25

Note
In the above program the parameters orders are changed

7.5.3 Default Arguments


In Python the default argument is an argument that takes a default value if no value
is provided in the function call. The following example uses default arguments, that prints
default salary when no argument is passed.

Example: 7.5.3
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)

When the above code is executed, it produces the following output

Output:
Name: Mani
Salary: 3500

When the above code is changed as printinfo(“Ram”,2000) it produces the following


output:

Output:
Name: Ram
Salary: 2000

In the above code, the value 2000 is passed to the argument salary, the default value
already assigned for salary is simply ignored.

95 Python Functions

12th Computer Science_EM Chapter 7.indd 95 21-12-2022 15:21:23


7.5.4 Variable-Length Arguments
In some instances you might need to pass more arguments than have already been
specified. Going back to the function to redefine it can be a tedious process. Variable-Length
arguments can be used instead. These are not specified in the function’s definition and an
asterisk (*) is used to define such arguments.
Lets see what happens when we pass more than 3 arguments in the sum() function.

Example: 7.5.4
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15,20,25)

When the above code is executed, it produces the following result :

TypeError: sum() takes 3 positional arguments but 5 were given

7.5.4.1 Syntax - Variable-Length Arguments


def function_name(*args):
function_body
return_statement

Example: 7.5.4. 1
def printnos (*nos): Output:
for n in nos: Printing two values
print(n) 1
return 2
# now invoking the printnos() function Printing three values
print ('Printing two values') 10
printnos (1,2) 20
print ('Printing three values') 30
printnos (10,20,30)

Evaluate Yourself ?

In the above program change the function name printnos as printnames in all places
wherever it is used and give the appropriate data Ex. printnos (10, 20, 30) as printnames ('mala',
'kala', 'bala') and see output.

XII Std Computer Science 96

12th Computer Science_EM Chapter 7.indd 96 21-12-2022 15:21:24


In Variable Length arguments we can pass the arguments using two methods.
1. Non keyword variable arguments
2. Keyword variable arguments
Non-keyword variable arguments are called tuples. You will learn more about tuples in
the later chapters. The Program given is an illustration for non keyword variable argument.

Note
Keyword variable arguments are beyond the scope of this book.

The Python’s print() function is itself an example of such a function which


supports variable length arguments.

7.6 Anonymous Functions

What is anonymous function?


In Python, anonymous function is a function that is defined without a name. While
normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword. Hence, anonymous functions are also called as lambda
functions.

What is the use of lambda or anonymous function?


• Lambda function is mostly used for creating small and one-time anonymous function.
• Lambda functions are mainly used in combination with the functions like filter(), map()
and reduce().

Note
filter(), map() and reduce() functions are beyond the scope of this book.

Lambda function can take any number of arguments and must return one
value in the form of an expression. Lambda function can only access global variables
and variables in its parameter list.

97 Python Functions

12th Computer Science_EM Chapter 7.indd 97 21-12-2022 15:21:24


7.6.1 Syntax of Anonymous Functions
The syntax for anonymous functions is as follows:

lambda [argument(s)] :expression Example: 7.6.1


sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10

The above lambda function that adds argument arg1 with argument arg2 and stores the
result in the variable sum. The result is displayed using the print().

7.7 The return Statement

• The return statement causes your function to exit and returns a value to its caller. The
point of functions in general is to take inputs and return something.
• The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
• Any number of 'return' statements are allowed in a function definition but only one of
them is executed at run time.
7.7.1 Syntax of return

return [expression list ]

This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.

XII Std Computer Science 98

12th Computer Science_EM Chapter 7.indd 98 21-12-2022 15:21:24


Example : 7.7.1
# return statment
def usr_abs (n):
if n>=0:
return n
else:
return –n
# Now invoking the function
x=int (input(“Enter a number :”)
print (usr_abs (x))
Output 1:
Enter a number : 25
25
Output 2:
Enter a number : -25
25

7.8 Scope of Variables


Scope of variable refers to the part of the program, where it is accessible, 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 scopes - local scope and global scope.

7.8.1 Local Scope


A variable declared inside the function's body is known as local variable.
Rules of local variable
• A variable with local scope can be accessed only within the function that it is created in.
• When a variable is created inside the function the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal parameters are also local to function.

99 Python Functions

12th Computer Science_EM Chapter 7.indd 99 21-12-2022 15:21:24


Example : 7.8.1 (a) Create a Local Variable
def loc():
y=0 # local scope
print(y)
loc()
Output:
0

Example : 7.8.1 (b)Accessing local variable outside the scope


def loc():
y = "local"
loc()
print(y)

When we run the above code, the output shows the following error:
The above error occurs because we are trying to access a local variable ‘y’ in a global
scope.

NameError: name 'y' is not defined

7.8.2 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.
Rules of global Keyword
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
• We use global keyword to modify the value of the global variable inside a function.
• Use of global keyword outside a function has no effect
Use of global Keyword
Example : 7.8.2 (a) Accessing global Variable From Inside a Function
c = 1 # global variable
def add():
print(c)
add()
Output:
1

XII Std Computer Science 100

12th Computer Science_EM Chapter 7.indd 100 21-12-2022 15:21:24


Example : 7.8.2 (b) Modifying Global Variable From Inside the Function
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Output:
UnboundLocal Error: local variable 'c' referenced before assignment

Note
Without using the global keyword we cannot modify the global variable inside
the function but we can only access the global variable.

Example : 7.8.2(c) C hanging Global Variable From Inside a Function


using global keyword
x = 0 # global variable
def add():
global x
x = x + 5 # increment by 5
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5

In the above program, x is defined as a global variable. Inside the add() function, global
keyword is used for x and we increment the variable x by 5. Now We can see the change on the
global variable x outside the function i.e the value of x is 5.

101 Python Functions

12th Computer Science_EM Chapter 7.indd 101 21-12-2022 15:21:24


7.8.3 Global and local variables
Here, we will show how to use global variables and local variables in the same code.
Example : 7.8.3 (a) Using Global and Local variables in same code
x=8 # x is a global variable
def loc():
global x
y = "local"
x=x*2
print(x)
print(y)
loc()
Output:
16
local

In the above program, we declare x as global and y as local variable in the function
loc().
After calling the function loc(), the value of x becomes 16 because we used x=x * 2.
After that, we print the value of local variable y i.e. local.

Example : 7.8.3 (b) Global variable and Local variable with same name

x=5
def loc():
x = 10
print ("local x:", x)
loc()
print ("global x:", x)

Output:
local x: 10
global x: 5

In above code, we used same name ‘x’ for both global variable and local variable. We get
different result when we print same variable because the variable is declared in both scopes, i.e.
the local scope inside the function loc() and global scope outside the function loc().
The output :- local x: 10, is called local scope of variable.
The output:- global x: 5, is called global scope of variable.

XII Std Computer Science 102

12th Computer Science_EM Chapter 7.indd 102 21-12-2022 15:21:24


7.9 Functions using libraries
7.9.1 Built-in and Mathematical functions

Function Description Syntax Example


abs ( ) Returns an x=20
absolute value y=-23.2
of a number. print('x = ', abs(x))
The argument
print('y = ', abs(y))
may be an abs (x)
integer or a Output:
floating point
x = 20
n u m b e r.
y = 23.2
ord ( ) Returns the c= 'a'
ASCII value d= 'A'
for the given print ('c = ',ord (c))
Unicode ord (c) print ('A = ',ord (d))
character.
This function is Output:
inverse of chr() c = 97
function. A = 65
chr ( ) Returns the c=65
Unicode d=43
character for print (chr (c))
the given ASCII chr (i) prin t(chr (d))
value.
This function is Output:
inverse of ord() A
function. +
bin ( ) Returns a x=15
binary string y=101
prefixed with print ('15 in binary : ',bin (x))
“0b” for the print ('101 in binary : ',bin (y))
given integer bin (i)
number. Output:
Note: format 15 in binary : 0b1111
() can also be 101 in binary : 0b1100101
used instead of
this function.

103 Python Functions

12th Computer Science_EM Chapter 7.indd 103 21-12-2022 15:21:24


type ( ) Returns the x= 15.2
type of object y= 'a'
for the given s= True
single object. print (type (x))
Note: This type (object) print (type (y))
function print (type (s))
used with
single object Output:
parameter. <class 'float'>
<class 'str'>
<class 'bool'>
id ( ) id( ) Return x=15
the “identity” of y='a'
an object. i.e. print ('address of x is :',id (x))
the address of id (object) print ('address of y is :',id (y))
the object in
Output:
memory.
Note: the address of x is : 1357486752
address of x address of y is : 13480736
and y may
differ in your
system.
min ( ) Returns the MyList = [21,76,98,23]
minimum value print ('Minimum of MyList :', min(MyList))
in a list. min (list)
Output:
Minimum of MyList : 21
max ( ) Returns the MyList = [21,76,98,23]
maximum print ('Maximum of MyList :', max(MyList))
value in a list.
max (list) Output:
Maximum of MyList : 98
sum ( ) Returns the MyList = [21,76,98,23]
sum of values print ('Sum of MyList :', sum(MyList))
in a list. sum (list)
Output:
Sum of MyList : 218

XII Std Computer Science 104

12th Computer Science_EM Chapter 7.indd 104 21-12-2022 15:21:24


format ( ) Returns the x= 14
output based y= 25
on the given print ('x value in binary :',format(x,'b'))
format print ('y value in octal :',format(y,'o'))
1. Binary print('y value in Fixed-point no ',format(y,'f '))
format.
Outputs the format (value Output:
number in [, format_ x value in binary : 1110
base 2. spec]) y value in octal : 31
2. Octal y value in Fixed-point no : 25.000000
format.
Outputs the
number in
base 8.
3. Fixed-point
notation.
Displays the
number as a
fixed-point
number.
The default
precision
is 6.
round ( ) Returns the x= 17.9
nearest integer y= 22.2
to its input. z= -18.3
1. First print ('x value is rounded to', round (x))
argument round print ('y value is rounded to', round (y))
(number) (number print ('z value is rounded to', round (z))
is used to [,ndigits])
specify the
value to be
rounded.

105 Python Functions

12th Computer Science_EM Chapter 7.indd 105 21-12-2022 15:21:24


2. Second Output:1
argument x value is rounded to 18
(ndigits) y value is rounded to 22
is used to z value is rounded to -18
specify the n1=17.89
number print (round (n1,0))
of decimal print (round (n1,1))
digits print (round (n1,2))
desired after
rounding. Output:2
18.0
17.9
17.89
pow ( ) Returns the a= 5
computation of b= 2
ab i.e. (a**b ) c= 3.0
a raised to the print (pow (a,b))
power of b. print (pow (a,c))
pow (a,b) print (pow (a+b,3))

Output:
25
125.0
343

Mathematical Functions

Note
Specify import math module before using all mathematical
functions in a program

Function Description Syntax Example


floor ( ) Returns the largest integer math.floor (x) import math
less than or equal to x x=26.7
y=-26.7
z=-23.2
print (math.floor (x))
print (math.floor (y))
print (math.floor (z))
Output:
26
-27
-24

XII Std Computer Science 106

12th Computer Science_EM Chapter 7.indd 106 21-12-2022 15:21:24


ceil ( ) Returns the smallest math.ceil (x) import math
integer greater than or x= 26.7
equal to x y= -26.7
z= -23.2
print (math.ceil (x))
print (math.ceil (y))
print (math.ceil (z))
Output:
27
-26
-23
sqrt ( ) Returns the square root math.sqrt (x ) import math
of x a= 30
Note: x must be greater b= 49
than 0 (zero) c= 25.5
print (math.sqrt (a))
print (math.sqrt (b))
print (math.sqrt (c))
Output:
5.477225575051661
7.0
5.049752469181039
7.9.2 Composition in functions
What is Composition in functions?
The value returned by a function may be used as an argument for another function in
a nested manner. This is called composition. For example, if we wish to take a numeric value
or an expression as a input from the user, we take the input string from the user using the
function input() and apply eval() function to evaluate its value, for example:
Example : 7.9. 2
# This program explains composition
>>> n1 = eval (input ("Enter a number: "))
Enter a number: 234
>>> n1
234
>>> n2 = eval (input ("Enter an arithmetic expression: "))
Enter an arithmetic expression: 12.0+13.0 * 2
>>> n2
38.0

7.10 Python recursive functions


When a function calls itself is known as recursion. Recursion works like loop but
sometimes it makes more sense to use recursion than loop. You can convert any loop to

107 Python Functions

12th Computer Science_EM Chapter 7.indd 107 21-12-2022 15:21:24


recursion.
A recursive function calls itself. Imagine a process would iterate indefinitely if not
stopped by some condition! Such a process is known as infinite iteration. The condition that
is applied in any recursive function is known as base condition. A base condition is must in
every recursive function otherwise it will continue to execute like an infinite loop.

Overview of how recursive function works


1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue
recursion.
Here is an example of recursive function used to calculate factorial.

Example : 7.10
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120

print(fact (2000)) will give Recursion Error after maximum recursion depth exceeded
in comparison. This happens because python stops calling recursive function after
1000 calls by default. It also allows you to change the limit using sys.setrecursionlimit
(limit_value).

Example:
import sys
sys.setrecursionlimit(3000)
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (2000))

XII Std Computer Science 108

12th Computer Science_EM Chapter 7.indd 108 21-12-2022 15:21:24


Points to remember:

• Functions are named blocks of code that are designed to do one specific job.
• Types of Functions are User defined, Built-in, lambda and recursion.
• Function blocks begin with the keyword “def ” followed by function name and
parenthesis ().
• A “return” with no arguments is the same as return None. Return statement
is optional in python.
• In Python, statements in a block should begin with indentation.
• A block within a block is called nested block.
• Arguments are used to call a function and there are primarily 4 types of
functions that one can use: Required arguments, Keyword arguments, Default
arguments and Variable-length arguments.
• Required arguments are the arguments passed to a function in correct
positional order.
• Keyword arguments will invoke the function after the parameters are
recognized by their parameter names.
• A Python function allows to give the default values for parameters in the
function definition. We call it as Default argument.
• Variable-Length arguments are not specified in the function’s definition and
an asterisk (*) is used to define such arguments.
• Anonymous Function is a function that is defined without a name.
• Scope of variable refers to the part of the program, where it is accessible, i.e.,
area where you can refer (use) it.
• The value returned by a function may be used as an argument for another
function in a nested manner. This is called composition.
• A function which calls itself is known as recursion. Recursion works like a
loop but sometimes it makes more sense to use recursion than loop.

109 Python Functions

12th Computer Science_EM Chapter 7.indd 109 21-12-2022 15:21:24


Hands on Experience
1. Try the following code in the above program

Slno code Result


1 printinfo(“3500”)
2 printinfo(“3500”,”Sri”)
3 printinfo(name=”balu”)
4 printinfo(“Jose”,1234)
5 printinfo(“ ”,salary=1234)

2. Evaluate the following functions and write the output

Slno Function Output

1 eval(‘25*2-5*4')

2 math.sqrt(abs(-81))

3 math.ceil(3.5+4.6)

4 math.floor(3.5+4.6)

3. Evaluate the following functions and write the output


Slno function Output
1 1) abs(-25+12.0))
2) abs(-3.2)
2 1) ord('2')
2) ord('$')
3 type('s')
4 bin(16)
5 1) chr(13)
2) print(chr(13))
6 1) round(18.2,1)
2) round(18.2,0)
3) round(0.5100,3)
4) round(0.5120,3)

XII Std Computer Science 110

12th Computer Science_EM Chapter 7.indd 110 21-12-2022 15:21:24


7 1) format(66, 'c')
2) format(10, 'x')
3) format(10, 'X')
4) format(0b110, 'd')
5) format(0xa, 'd')
8 1) pow(2,-3)
2) pow(2,3.0)
3) pow(2,0)
4) pow((1+2),2)
5) pow(-3,2)
6) pow(2*2,2)

Evaluation

Part - I
Choose the best answer: (1 Mark)
1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching
(c) Function (d) Block
2. A Function which calls itself is called as
(a) Built-in (b) Recursion
(c) Lambda (d) return
3. Which function is called anonymous un-named function
(a) Lambda (b) Recursion
(c) Function (d) define
4. Which of the following keyword is used to begin the function block?
(a) define (b) for
(c) finally (d) def
5. Which of the following keyword is used to exit a function block?
(a) define (b) return
(c) finally (d) def
6. While defining a function which of the following symbol is used.
(a) ; (semicolon) (b) . (dot)
(c) : (colon) (d) $ (dollar)

111 Python Functions

12th Computer Science_EM Chapter 7.indd 111 21-12-2022 15:21:24


7. In which arguments the correct positional order is passed to a function?
(a) Required (b) Keyword
(c) Default (d) Variable-length
8. Read the following statement and choose the correct statement(s).
(I) In Python, you don’t have to mention the specific data types while defining
function.
(II) Python keywords can be used as function name.
(a) I is correct and II is wrong
(b) Both are correct
(c) I is wrong and II is correct
(d) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if ____ : print(x, " is a leap year")
(a) x%2=0 (b) x%4==0
(c) x/4=0 (d) x%4=0
10. Which of the following keyword is used to define the function testpython(): ?
(a) define (b) pass
(c) def (d) while

Part - II

Answer the following questions: (2 Marks)


1. What is function?
2. Write the different types of function.
3. What are the main advantages of function?
4. What is meant by scope of variable? Mention its types.
5. Define global scope.
6. What is base condition in recursive function
7. How to set the limit for recursive function? Give an example.

XII Std Computer Science 112

12th Computer Science_EM Chapter 7.indd 112 21-12-2022 15:21:24


Part - III

Answer the following questions: (3 Marks)


1. Write the rules of local variable.
2. Write the basic rules for global keyword in python.
3. What happens when we modify global variable inside the function?
4. Differentiate ceil() and floor() function?
5. Write a Python code to check whether a given year is leap year or not.
6. What is composition in functions?
7. How recursive function works?
8. What are the points to be noted while defining a function?

Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
2. Explain the scope of variables with an example.
3. Explain the following built-in functions.
(a) id()
(b) chr()
(c) round()
(d) type()
(e) pow()
4. Write a Python code to find the L.C.M. of two numbers.
5. Explain recursive function with an example.
Reference Books
1. Python Tutorial book from tutorialspoint.com
2. Python Programming: A modular approach by Pearson – Sheetal, Taneja
3. Fundamentals of Python –First Programs by Kenneth A. Lambert

113 Python Functions

12th Computer Science_EM Chapter 7.indd 113 21-12-2022 15:21:24


CHAPTER 8
Unit II
STRINGS AND STRING MANIPULATION

Learning Objectives

After completion of this chapter, the student will be able to


• Know how to process text.
• Understanding various string functions in Python.
• Know how to format Strings.
• Know about String Slicing.
• Know about Strings application in real world.

8.1 Introduction

String is a data type in python, which is used to handle array of characters. String is
a sequence of Unicode characters that may be a combination of letters, numbers, or special
symbols enclosed within single, double or even triple quotes.

Example

‘Welcome to learning Python’


“Welcome to learning Python”
‘‘‘ “Welcome to learning Python” ’’’

In python, strings are immutable, it means, once you define a string, it cannot be
changed during execution.
8.2 Creating Strings
As we learnt already, a string in Python can be created using single or double or even
triple quotes. String in single quotes cannot hold any other single quoted string in it, because
the interpreter will not recognize where to start and end the string. To overcome this problem,
you have to use double quotes. Strings which contains double quotes should be define within
triple quotes. Defining strings within triple quotes also allows creation of multiline strings.

XII Std Computer Science 114

12th Computer Science_EM Chapter 8.indd 114 21-12-2022 15:28:38


Example
#A string defined within single quotes
>>> print (‘Greater Chennai Corporation’)
Greater Chennai Corporation
#single quoted string defined within single quotes
>>> print ('Greater Chennai Corporation's student')
SyntaxError: invalid syntax

#A string defined within double quotes


>>>print (“Computer Science”)
Computer Science
#double quoted string defined within double quotes
>>> print (''' "Computer Science" ''')
"Computer Science"
#single and double quoted multiline string defined within triple quotes
>>> print (''' "Strings are immutable in 'Python',
which means you can't make any changes
once you declared" ''')
"Strings are immutable in 'Python',
which means you can't make any changes once you declared"

8.3 Accessing characters in a String


Once you define a string, python allocate an index value for its each character. These
index values are otherwise called as subscript which are used to access and manipulate the
strings. The subscript can be positive or negative integer numbers.

The positive subscript 0 is assigned to the first character and n-1 to the last character,
where n is the number of characters in the string. The negative index assigned from the last
character to the first character in reverse order begins with -1.

Example
String S C H O O L
Positive subscript 0 1 2 3 4 5
Negative subscript -6 -5 -4 -3 -2 -1

115 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 115 21-12-2022 15:28:38


Example 1 : Program to access each character with its positive subscript of
a giving string
str1 = input ("Enter a string: ")
index=0
for i in str1:
print ("Subscript[",index,"] : ", i)
index + = 1
Output
Enter a string: welcome
Subscript [ 0 ] : w
Subscript [ 1 ] : e
Subscript [ 2 ] : l
Subscript [ 3 ] : c
Subscript [ 4 ] : o
Subscript [ 5 ] : m
Subscript [ 6 ] : e

Example 2 : Program to access each character with its negative subscript of


a giving string
str1 = input ("Enter a string: ")
index=-1
while index >= -(len(str1)):
print ("Subscript[",index,"] : " + str1[index])
index += -1
Output
Enter a string: welcome
Subscript [ -1 ] : e
Subscript [ -2 ] : m
Subscript [ -3 ] : o
Subscript [ -4 ] : c
Subscript [ -5 ] : l
Subscript [ -6 ] : e
Subscript [ -7 ] : w

8.4 Modifying and Deleting Strings


As you already learnt, strings in python are immutable. That means, once you define
a string modifications or deletion is not allowed. However, we can replace the existing string
entirely with the new string.

XII Std Computer Science 116

12th Computer Science_EM Chapter 8.indd 116 21-12-2022 15:28:38


Example
>>> str1="How are you"
>>> str1[0]="A"
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
str1[0]="A"
TypeError: 'str' object does not support item assignment

In the above example, string variable str1 has been assigned with the string “How are
you” in statement 1. In the next statement, we try to update the first character of the string with
character ‘A’. But python will not allow the update and it shows a TypeError.
To overcome this problem, you can define a new string value to the existing string
variable. Python completely overwrite new string on the existing string.
Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> str1="How about you"
>>> print (str1)
How about you

Usually python does not support any modification in its strings. But, it provides a
function replace() to temporarily change all occurrences of a particular character in a string.
The changes done through replace () does not affect the original string.
General formate of replace function:

replace(“char1”, “char2”)
The replace function replaces all occurrences of char1 with char2.

Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> print (str1.replace("o", "e"))
Hew are yeu

Similar as modification, python will not allow deleting a particular character in a string.
Whereas you can remove entire string variable using del command.

117 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 117 21-12-2022 15:28:38


Example 3: Code lines to delete a particular character in a string:

>>> str1="How are you"


>>> del str1[2]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
del str1[2]
TypeError: 'str' object doesn't support item deletion

Example 4: Code lines to delete a string variable

>>> str1="How about you"


>>> print (str1)
How about you
>>> del str1
>>> print (str1)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
print (str1)
NameError: name 'str1' is not defined

8.5 String Operators


Python provides the following operators for string operations. These operators are
useful to manipulate string.
(i) Concatenation (+)
Joining of two or more strings is called as Concatenation. The plus (+) operator is used
to concatenate strings in python.
Example
>>> "welcome" + "Python"
'welcomePython'

(ii) Append (+ =)
Adding more strings at the end of an existing string is known as append. The operator
+= is used to append a new string with an existing string.

Example
>>> str1="Welcome to "

XII Std Computer Science 118

12th Computer Science_EM Chapter 8.indd 118 21-12-2022 15:28:38


>>> str1+="Learn Python"
>>> print (str1)
Welcome to Learn Python
(iii) Repeating (*)
The multiplication operator (*) is used to display a string in multiple number of times.
Example
>>> str1="Welcome "
>>> print (str1*4)
Welcome Welcome Welcome Welcome
(iv) String slicing
Slice is a substring of a main string. A substring can be taken from the original string
by using [ ] operator and index or subscript values. Thus, [ ] is also known as slicing operator.
Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
Where start is the beginning index and end is the last index value of a character in the
string. Python takes the end value less than one from the actual index specified. For example,
if you want to slice first 4 characters from a string, you have to specify it as 0 to 5. Because,
python consider only the end value as n-1.
Example I : slice a single character from a string
>>> str1="THIRUKKURAL"

>>> print (str1[0])


T
Example II : slice a substring from index 0 to 4
>>> print (str1[0:5])
THIRU
Example III : slice a substring using index 0 to 4 but without specifying the beginning
index.
>>> print (str1[:5])
THIRU
Example IV : slice a substring using the start index alone without specifying the end index.
>>> print (str1[6:])
KURAL

119 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 119 21-12-2022 15:28:38


Example V : Program to slice substrings using for loop

str1="COMPUTER"
index=0
for i in str1:
print (str1[:index+1])
index+=1
Output
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
COMPUTER

(v) Stride when slicing string


When the slicing operation, you can specify a third argument as the stride, which refers
to the number of characters to move forward after the first character is retrieved from the
string. The default value of stride is 1.

Example
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[10:16:4])
r
>>> print (str1[10:16:2])
er
>>> print (str1[::3])
Wceoenyo

Note: Remember that, python takes the last value as n-1


You can also use negative value as stride (third argument). If you specify a negative
value, it prints in reverse order.

XII Std Computer Science 120

12th Computer Science_EM Chapter 8.indd 120 21-12-2022 15:28:38


Example
>>> str1 = "Welcome to learn Python"
>>> print(str1[::-2])
nhy re teolW

8.6 String Formatting Operators


The string formatting operator is one of the most exciting feature of python. The
formatting operator % is used to construct strings, replacing parts of the strings with the data
stored in variables.

Syntax:
(“String to be display with %val1 and %val2” %(val1, val2))

Example

name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name,mark))

Output
Name: Rajarajan and Marks: 98

8.7 Formatting characters


Format characters USAGE
%c Character
%d (or) %i Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer (lower case x refers a-f; upper case X refers
A-F)
%e or %E Exponential notation
%f Floating point numbers
%g or %G Short numbers in floating point or exponential notation.

121 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 121 21-12-2022 15:28:39


Escape sequence in python
Escape sequences starts with a backslash and it can be interpreted differently. When
you have use single quote to represent a string, all the single quotes inside the string must be
escaped. Similar is the case with double quotes.

Example
# String within triple quotes to display a string with single quote
>>> print ('''They said, "What's there?"''')
They said, "What's there?"
# String within single quotes to display a string with single quote using escape sequence
>>> print ('They said, "What\'s there?"')
They said, "What's there?"
# String within double quotes to display a string with single quote using escape sequence
>>> print ("They said, \"What's there?\"")
He said, "What's there?"

Escape sequences supported by python


Escape Sequence DESCRIPTION
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Form feed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH

8.8 The format( ) function


The format( ) function used with strings is very versatile and powerful function used
for formatting strings. The curly braces { } are used as placeholders or replacement fields which
get replaced along with format( ) function.

XII Std Computer Science 122

12th Computer Science_EM Chapter 8.indd 122 21-12-2022 15:28:39


Example
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of { } and { } is { }".format(num1, num2,(num1+num2)))
Out Put
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

8.9 Built-in String functions


Python supports the following built-in functions to manipulate string.

Syntax Description Example


len(str) Returns the length (no of >>> A="Corporation"
characters) of the string. >>> print(len(A))
11
capitalize( ) Used to capitalize the first >>> city="chennai"
character of the string >>> print(city.capitalize())
Chennai
center(width, fillchar) Returns a string with the >>> str1="Welcome"
original string centered to >>> print(str1.center(15,'*') )
a total of width columns ****Welcome****
and filled with fillchar in
columns that do not have
characters
find(sub[, start[, end]]) The function is used to >>>str1=’mammals’
search the first occurrence >>>str1.find(‘ma’)
of the sub string in the 0
given string. It returns On omitting the start parameters,
the index at which the the function starts the search
substring starts. It returns from the beginning.
-1 if the substring does >>>str1.find(‘ma’,2)
not occur in the string. 3
>>>str1.find(‘ma’,2,4)
-1
Displays -1 because the substring
could not be found between the
index 2 and 4-1.
>>>str1.find(‘ma’,2,5)
3

123 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 123 21-12-2022 15:28:39


Syntax Description Example
isalnum( ) Returns True if the string >>>str1=’Save Earth’
contains only letters and >>>str1.isalnum()
digit. It returns False. If False
the string contains any The function returns False as space
special character like _, @, is an alphanumeric character.
#, *, etc. >>>’Save1Earth’.isalnum()
True
isalpha( ) Returns True if the string >>>’Click123’.isalpha()
contains only letters. False
Otherwise return False. >>>’python’.isalpha( )
True
isdigit( ) Returns True if the string >>> str1=’Save Earth’
contains only numbers. >>>print(str1.isdigit( ))
Otherwise it returns False. False
lower( ) Returns the exact copy >>>str1=’SAVE EARTH’
of the string with all the >>>print(str1.lower())
letters in lowercase. save earth
islower( ) Returns True if the string >>> str1=’welcome’
is in lowercase. >>>print (str1.islower( ))
True
isupper( ) Returns True if the string >>> str1=’welcome’
is in uppercase. >>>print (str1.isupper( ))
False
upper( ) Returns the exact copy of >>> str1=’welcome’
the string with all letters >>>print (str.upper( ))
in uppercase. WELCOME
title( ) Returns a string in title >>> str1='education department'
case >>> print(str1.title())
Education Department
swapcase( ) It will change case of >>> str1="tAmiL NaDu"
every character to its >>> print(str1.swapcase())
opposite case vice-versa. TaMIl nAdU

XII Std Computer Science 124

12th Computer Science_EM Chapter 8.indd 124 21-12-2022 15:28:39


Syntax Description Example
count(str, beg, end) Returns the number >>> str1="Raja Raja Chozhan"
of substrings occurs >>> print(str1.count('Raja'))
within the given range. 2
Remember that substring >>> print(str1.count('r'))
may be a single character. 0
Range (beg and end) >>> print(str1.count('R'))
arguments are optional. 2
If it is not given, python >>> print(str1.count('a'))
searched in whole string. 5
Search is case sensitive. >>> print(str1.count('a',0,5))
2
>>> print(str1.count('a',11))
1
ord(char ) Returns the ASCII code >>> ch = 'A'
of the character. >>> print(ord(ch))
65
>>> print(ord('B'))
66
chr(ASII) Returns the character >>> ch=97
represented by a ASCII. >>> print(chr(ch))
a
>>> print(chr(87))
W
8.10 Membership Operators
The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string is
present in another string. Therefore, these operators are called as Membership Operators.

Example
str1=input ("Enter a string: ")
str2="chennai"
if str2 in str1:
print ("Found")
else:
print ("Not Found")
Output : 1
Enter a string: Chennai G HSS, Saidapet
Found
Output : 2
Enter a string: Govt G HSS, Ashok Nagar
Not Found

125 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 125 21-12-2022 15:28:39


Example 8.11 Programs using Strings :
Example 8.11.1 : Program to check whether the given string is palindrome
or not
str1 = input ("Enter a string: ")
str2 = ' '
index=-1
for i in str1:
str2 += str1[index]
index -= 1
print ("The given string = { } \n The Reversed string = { }".format(str1, str2))
if (str1==str2):
print ("Hence, the given string is Palindrome")
else:
print ("Hence, the given is not a palindrome")
Output : 1
Enter a string: malayalam
The given string = malayalam
The Reversed string = malayalam
Hence, the given string is Palindrome
Output : 2
Enter a string: welcome
The given string = welcome
The Reversed string = emoclew
Hence, the given string is not a palindrome

Example 8.11.2 : Program to display the following pattern

*
* *
* * *
* * * *
* * * * *
str1=' * '
i=1
while i<=5:
print (str1*i)
i+=1
Output
*
* *
* * *
* * * *
* * * * *

XII Std Computer Science 126

12th Computer Science_EM Chapter 8.indd 126 21-12-2022 15:28:39


Example 8.11.3 : Program to display the number of vowels and consonants
in the given string
str1=input ("Enter a string: ")
str2="aAeEiIoOuU"
v,c=0,0
for i in str1:
if i in str2:
v+=1
elif i.isalpha():
c+=1
print ("The given string contains { } vowels and { } consonants".format(v,c))

Output
Enter a string: Tamilnadu School Education
The given string contains 11 vowels and 13 consonants

Example 8.11.4 : Program to create an Abecedarian series. (Abecedarian


refers list of elements appear in alphabetical order)
str1="ABCDEFGH"
str2="ate"
for i in str1:
print ((i+str2),end='\t')
Output
Aate Bate Cate Date Eate Fate Gate Hate

Example 8.11.5 : Program that accept a string from the user and display
the same after removing vowels from it
def rem_vowels(s):
temp_str=''
for i in s:
if i in "aAeEiIoOuU":
pass
else:
temp_str+=i
print ("The string without vowels: ", temp_str)
str1= input ("Enter a String: ")
rem_vowels (str1)
Output
Enter a String: Mathematical fundations of Computer Science
The string without vowels: Mthmtcl fndtns f Cmptr Scnc

127 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 127 21-12-2022 15:28:39


Example 8.11.6 : Program that count the occurrences of a character in a
string
def count(s, c):
c1=0
for i in s:
if i == c:
c1+=1
return c1
str1=input ("Enter a String: ")
ch=input ("Enter a character to be searched: ")
cnt=count (str1, ch)
print ("The given character {} is occurs {} times in the given string".format(ch,cnt))
Out Put
Enter a String: Software Engineering
Enter a character to be searched: e
The given character e is occurs 3 times in the given string

Points to remember:
• String is a data type in python.
• Strings are immutable, that means once you define string, it cannot be changed during
execution.
• Defining strings within triple quotes also allows creation of multiline strings.
• In a String, python allocate an index value for its each character which is known as
subscript.
• The subscript can be positive or negative integer numbers.
• Slice is a substring of a main string.
• Stride is a third argument in slicing operation.
• Escape sequences starts with a backslash and it can be interpreted differently.
• The format( ) function used with strings is very versatile and powerful function used
for formatting strings.
• The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string
is present in another string.

Hands on Experience

1. Write a python program to find the length of a string.

2. Write a program to count the occurrences of each word in a given string.

XII Std Computer Science 128

12th Computer Science_EM Chapter 8.indd 128 21-12-2022 15:28:39


3. Write a program to add a prefix text to all the lines in a string.

4. Write a program to print integers with ‘*’ on the right of specified width.

5. Write a program to create a mirror image of the given string. For example, “wel” = “lew“.

6. Write a program to removes all the occurrences of a give character in a string.

7. Write a program to append a string to another string without using += operator.

8. Write a program to swap two strings.

9. Write a program to replace a string with another string without using replace().

10. Write a program to count the number of characters, words and lines in a given string.

Evaluation
Part - I

Choose the best answer (1 Mark)


1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau
(c) udanlimaT d) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School
(c) Type error (D) Chennai
3. Which of the following operator is used for concatenation?
(a) + (b) & (c) * d) =
4. Defining strings within triple quotes allows creating:
(a) Single line Strings (b) Multiline Strings
(c) Double line Strings (d) Multiple Strings
5. Strings in python:
(a) Changeable (b) Mutable
(c) Immutable (d) flexible

129 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 129 21-12-2022 15:28:39


6. Which of the following is the slicing operator?
(a) { } (b) [ ] (c) < > (d) ( )
7. What is stride?
(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in
upper case?
(a) %f (b) %E (c) %g (d) %n
9. Which of the following is used as placeholders or replacement fields which get replaced
along with format( ) function?
(a) { } (b) < > (c) ++ (d) ^^
10. The subscript of a string may be:
(a) Positive (b) Negative
(c) Both (a) and (b) (d) Either (a) or (b)

Part -II

Answer the following questions (2 Marks)


1. What is String?
2. Do you modify a string in Python?
3. How will you delete a string in Python?
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
5. What is slicing?
Part -III

Answer the following questions (3 Marks)


1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C

XII Std Computer Science 130

12th Computer Science_EM Chapter 8.indd 130 21-12-2022 15:28:39


2. Write a short about the followings with suitable example:
(a) capitalize( ) (b) swapcase( )
3. What will be the output of the given python program?
str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
4. What is the use of format( )? Give an example.
5. Write a note about count( ) function in python.

Part -IV

Answer the following questions (5 Marks)


1. Explain about string operators in python with suitable example.

Reference Books
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.

131 Strings and String Manipulation

12th Computer Science_EM Chapter 8.indd 131 21-12-2022 15:28:39


CHAPTER 9
Unit III
LISTS, TUPLES, SETS AND DICTIONARY

Learning Objectives

After studying this chapter, students will be able to:


• Understand the basic concepts of various collection data types in python such as List,
Tuples, sets and Dictionary.
• Work with List, Tuples, sets and Dictionaries using variety of functions.
• Writting Python programs using List, Tuples, sets and Dictionaries.
• Understand the relationship between List, Tuples and Dictionaries.

9.1 Introduction to List

Python programming language has four collections of data types such as List, Tuples,
Set and Dictionary. A list in Python is known as a “sequence data type” like strings. It is an
ordered collection of values enclosed within square brackets [ ]. Each value of a list is called
as element. It can be of any type such as numbers, characters, strings and even the nested lists
as well. The elements can be modified or mutable which means the elements can be replaced,
added or removed. Every element rests at some position in the list. The position of an element
is indexed with numbers beginning with zero which is used to locate and access a particular
element. Thus, lists are similar to arrays, what you learnt in XI std.
9.1.1 Create a List in Python
In python, a list is simply created by using square bracket. The elements of list should
be specified within square brackets. The following syntax explains the creation of list.

Syntax:
Variable = [element-1, element-2, element-3 …… element-n]

XII Std Computer Science 132

12th Computer Science_EM Chapter 9.indd 132 21-12-2022 15:37:02


Example
Marks = [10, 23, 41, 75]
Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
MyList = [ ]

In the above example, the list Marks has four integer elements; second list Fruits has
four string elements; third is an empty list. The elements of a list need not be homogenous type
of data. The following list contains multiple type elements.

Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ]

In the above example, Mylist contains another list as an element. This type of list is
known as “Nested List”.

Nested list is a list containing another list as an element.

9.1.2 Accessing List elements


Python assigns an automatic index value for each element of a list begins with zero.
Index value can be used to access an element in a list. In python, index value is an integer
number which can be positive or negative.

Example
Marks = [10, 23, 41, 75]
Marks 10 23 41 75
Index (Positive) 0 1 2 3
IndexNegative) -4 -3 -2 -1

Positive value of index counts from the beginning of the list and negative value means
counting backward from end of the list (i.e. in reverse order).

To access an element from a list, write the name of the list, followed by the index of the
element enclosed within square brackets.

Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])

133 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 133 21-12-2022 15:37:02


Example (Accessing single element):
>>> Marks = [10, 23, 41, 75]
>>> print (Marks[0])
10

In the above example, print command prints 10 as output, as the index of 10 is zero.

Example: Accessing elements in revevrse order


>>> Marks = [10, 23, 41, 75]
>>> print (Marks[-1])
75

Note
A negative index can be used to access an element in reverse order.

(i) Accessing all elements of a list


Loops are used to access all elements from a list. The initial value of the loop must be
zero. Zero is the beginning index value of a list.

Example
Marks = [10, 23, 41, 75]
i=0
while i < 4:
print (Marks[i])
i=i+1
Output
10
23
41
75

In the above example, Marks list contains four integer elements i.e., 10, 23, 41, 75. Each
element has an index value from 0. The index value of the elements are 0, 1, 2, 3 respectively.
Here, the while loop is used to read all the elements. The initial value of the loop is zero, and
the test condition is i < 4, as long as the test condition is true, the loop executes and prints the
corresponding output.

XII Std Computer Science 134

12th Computer Science_EM Chapter 9.indd 134 21-12-2022 15:37:02


During the first iteration, the value of i is 0, where the condition is true. Now, the
following statement print (Marks [i]) gets executed and prints the value of Marks [0] element
ie. 10.

The next statement i = i + 1 increments the value of i from 0 to 1. Now, the flow of
control shifts to the while statement for checking the test condition. The process repeats to
print the remaining elements of Marks list until the test condition of while loop becomes false.

The following table shows that the execution of loop and the value to be print.

print
Iteration i while i < 4 i=i+1
(Marks[i])

1 0 0 < 4 True Marks [0] = 10 0+1=1

2 1 1 < 4 True Marks [1] = 23 1+1=2

3 2 2 < 4 True Marks [2] = 41 2+1=3

4 3 3 < 4 True Marks [3] = 75 3+1=4

5 4 4 < 4 False -- --

(ii) Reverse Indexing


Python enables reverse or negative indexing for the list elements. Thus, python lists
index in opposite order. The python sets -1 as the index value for the last element in list and -2
for the preceding element and so on. This is called as Reverse Indexing.

Example
Marks = [10, 23, 41, 75]
i = -1
while i >= -4:
print (Marks[i])
i = i + -1
Output
75
41
23
10

The following table shows the working process of the above python coding

135 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 135 21-12-2022 15:37:02


Iteration i while i >= -4 print ( Marks[i] ) i = i + -1
1 -1 -1 >= -4 True Marks[-1] = 75 -1 + (-1) = -2
2 -2 -2 >= -4 True Marks[-2] = 41 -2 + (-1) = -3
3 -3 -3 >= -4 True Marks[-3] = 23 -3 + (-1) = -4
4 -4 -4 >= -4 True Marks[-4] = 10 -4 + (-1) = -5
5 -5 -5 >= -4 False -- --

9.1.3 List Length


The len() function in Python is used to find the length of a list. (i.e., the number of
elements in a list). Usually, the len() function is used to set the upper limit in a loop to read all
the elements of a list. If a list contains another list as an element, len() returns that inner list as
a single element.

Example :Accessing single element


>>> MySubject = [“Tamil”, “English”, “Comp. Science”, “Maths”]
>>> len(MySubject)
4

Example : Program to display elements in a list using loop


MySubject = ["Tamil", "English", "Comp. Science", "Maths"]
i=0
while i < len(MySubject):
print (MySubject[i])
i=i+1
Output
Tamil
English
Comp. Science
Maths

9.1.4 Accessing elements using for loop


In Python, the for loop is used to access all the elements in a list one by one. This is just
like the for keyword in other programming language such as C++.

Syntax:
for index_var in list:
print (index_var)

XII Std Computer Science 136

12th Computer Science_EM Chapter 9.indd 136 21-12-2022 15:37:02


Here, index_var represents the index value of each element in the list. Python reads
this “for” statement like English: “For (every) element in (the list of) list and print (the name of
the) list items”

Example

Marks=[23, 45, 67, 78, 98]


for x in Marks:
print( x )
Output
23
45
67
78
98

In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The
Python reads the for loop and print statements like English: “For (every) element (represented
as x) in (the list of) Marks and print (the values of the) elements”.

9.1.5 Changing list elements


In Python, the lists are mutable, which means they can be changed. A list element or
range of elements can be changed or altered by using simple assignment operator =.

Syntax:
List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed

Where, index from is the beginning index of the range; index to is the upper limit of
the range which is excluded in the range. For example, if you set the range [0:5] means, Python
takes only 0 to 4 as element index. Thus, if you want to update the range of elements from 1 to
4, it should be specified as [1:5].

137 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 137 21-12-2022 15:37:02


Example 9.1: Python program to update/change single value
MyList = [2, 4, 5, 8, 10]
print ("MyList elements before update... ")
for x in MyList:
print (x)
MyList[2] = 6
print ("MyList elements after updation... ")
for y in MyList:
print (y)
Output:
MyList elements before update...
2
4
5
8
10
MyList elements after updation...
2
4
6
8
10
Example 9.2: Python program to update/change range of values
MyList = [1, 3, 5, 7, 9]
print ("List Odd numbers... ")
for x in MyList:
print (x)
MyList[0:5] = 2,4,6,8,10
print ("List Even numbers... ")
for y in MyList:
print (y)
Output
List Odd numbers...
1
3
5
7
9
List Even numbers...
2
4
6
8
10

XII Std Computer Science 138

12th Computer Science_EM Chapter 9.indd 138 21-12-2022 15:37:02


9.1.6 Adding more elements in a list Example
In Python, append() function is >>> Mylist.extend([71, 32, 29])
used to add a single element and extend()
>>> print(Mylist)
function is used to add more than one
element to an existing list. [34, 45, 48, 90, 71, 32, 29]

Syntax: In the above code, extend() function


List.append (element to be added) is used to include multiple elements, the
List.extend ( [elements to be added]) print statement shows all the elements of
the list after the inclusion of additional
In extend() function, multiple elements.
elements should be specified within square 9.1.7 Inserting elements in a list
bracket as arguments of the function.
As you learnt already, append()
Example function in Python is used to add more
>>> Mylist=[34, 45, 48] elements in a list. But, it includes elements
>>> Mylist.append(90) at the end of a list. If you want to include
>>> print(Mylist) an element at your desired position, you can
[34, 45, 48, 90] use insert () function. The insert() function
is used to insert an element at any position
In the above example, Mylist is of a list.
created with three elements. Through >>>
Syntax:
Mylist.append(90) statement, an additional
value 90 is included with the existing list List.insert (position index, element)
as last element, following print statement
shows all the elements within the list MyList.

Example
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
>>> print(MyList)
[34, 98, 47, 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
>>> MyList.insert(3, 'Ramakrishnan')
>>> print(MyList)
[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']

In the above example, insert() function inserts a new element ‘Ramakrishnan’ at the
index value 3, ie. at the 4th position. While inserting a new element in between the existing
elements, at a particular location, the existing elements shifts one position to the right.

139 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 139 21-12-2022 15:37:02


9.1.8 Deleting elements from a list
There are two ways to delete an element from a list viz. del statement and remove()
function. del statement is used to delete elements whose index is known whereas remove()
function is used to delete elements of a list if its index is unknown. The del statement can also
be used to delete entire list.

Syntax:
del List [index of an element]
# to delete a particular element
del List [index from : index to]
# to delete multiple elements
del List
# to delete entire list

Example
>>> MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> print (MySubjects)
['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> del MySubjects[1]
>>> print (MySubjects)
['Tamil', 'Telugu', 'Maths']

In the above example, the list MySubjects has been created with four elements. print
statement shows all the elements of the list. In >>> del MySubjects[1] statement, deletes an
element whose index value is 1 and the following print shows the remaining elements of the
list.
Example
>>> del MySubjects[1:3]
>>> print(MySubjects)
['Tamil']

In the above codes, >>> del MySubjects[1:3] deletes the second and third elements
from the list. The upper limit of index is specified within square brackets, will be taken as -1 by
the python.

XII Std Computer Science 140

12th Computer Science_EM Chapter 9.indd 140 21-12-2022 15:37:02


Example
>>> del MySubjects
>>> print(MySubjects)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(MySubjects)
NameError: name 'MySubjects' is not defined

Here, >>> del MySubjects, deletes the list MySubjects entirely. When you try to print the
elements, Python shows an error as the list is not defined. Which means, the list MySubjects
has been completely deleted.

As already stated, the remove() function can also be used to delete one or more elements
if the index value is not known. Apart from remove() function, pop() function can also be
used to delete an element using the given index value. pop() function deletes and returns the
last element of a list if the index is not given.

The function clear() is used to delete all the elements in list, it deletes only the elements
and retains the list. Remember that, the del statement deletes entire list.

Syntax:
List.remove(element) # to delete a particular element
List.pop(index of an element)
List.clear( )

Example
>>> MyList=[12,89,34,'Kannan', 'Gowrisankar', 'Lenin']
>>> print(MyList)
[12, 89, 34, 'Kannan', 'Gowrisankar', 'Lenin']
>>> MyList.remove(89)
>>> print(MyList)
[12, 34, 'Kannan', 'Gowrisankar', 'Lenin']

In the above example, MyList has been created with three integer and three string
elements, the following print statement shows all the elements available in the list. In the
statement >>> MyList.remove(89), deletes the element 89 from the list and the print statement
shows the remaining elements.

141 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 141 21-12-2022 15:37:02


Example
>>> MyList.pop(1)
34
>>> print(MyList)
[12, 'Kannan', 'Gowrisankar', 'Lenin']

In the above code, pop() function is used to delete a particular element using its index
value, as soon as the element is deleted, the pop() function shows the element which is deleted.
pop() function is used to delete only one element from a list. Remember that, del statement
deletes multiple elements.

Example
>>> MyList.clear( )
>>> print(MyList)
[ ]

In the above code, clear() function removes only the elements and retains the list. When
you try to print the list which is already cleared, an empty square bracket is displayed without
any elements, which means the list is empty.

9.1.9 List and range ( ) function


The range() is a function used to generate a series of values in Python. Using range()
function, you can create list with series of values. The range() function has three arguments.

Syntax of range ( ) function:


range (start value, end value, step value)

where,

• start value – beginning value of series. Zero is the default beginning value.
• end value – upper limit of series. Python takes the ending value as upper limit – 1.
• step value – It is an optional argument, which is used to generate different interval of
values.

XII Std Computer Science 142

12th Computer Science_EM Chapter 9.indd 142 21-12-2022 15:37:02


Example : Generating whole numbers upto 10
for x in range (1, 11):
print(x)
Output
1
2
3
4
5
6
7
8
9
10

Example : Generating first 10 even numbers


for x in range (2, 11, 2):
print(x)
Output
2
4
6
8
10

(i) Creating a list with series of values


Using the range() function, you can create a list with series of values. To convert the
result of range() function into list, we need one more function called list(). The list()

function makes the result of range() as a list.

Syntax:
List_Varibale = list ( range ( ) )

Note

The list ( ) function is also used to create list in python.

143 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 143 21-12-2022 15:37:02


Example
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
[2, 4, 6, 8, 10]

In the above code, list() function takes the result of range() as Even_List elements. Thus,
Even_List list has the elements of first five even numbers.

Similarly, we can create any series of values using range() function. The following example
explains how to create a list with squares of first 10 natural numbers.

Example : Generating squares of first 10 natural numbers


squares = [ ]
for x in range(1,11):
s = x ** 2
squares.append(s)
print (squares)

In the above program, an empty list is created named “squares”. Then, the for loop
generates natural numbers from 1 to 10 using range() function. Inside the loop, the current
value of x is raised to the power 2 and stored in the variables. Each new value of square is
appended to the list “squares”. Finally, the program shows the following values as output.
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

9.1.10 List comprehensions


List comprehension is a simplest way of creating sequence of elements that satisfy a
certain condition.

Syntax:
List = [ expression for variable in range ]

Example : Generating squares of first 10 natural numbers using the


concept of List comprehension

>>> squares = [ x ** 2 for x in range(1,11) ]


>>> print (squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

XII Std Computer Science 144

12th Computer Science_EM Chapter 9.indd 144 21-12-2022 15:37:02


In the above example, x ** 2 in the expression is evaluated each time it is iterated. This
is the shortcut method of generating series of values.

9.1.11 Other important list funcion

Function Description Syntax Example

MyList=[12, 12, 36]


x = MyList.copy()
Returns a copy of the print(x)
copy ( ) List.copy( )
list
Output:
[12, 12, 36]
MyList=[36 ,12 ,12]
Returns the number x = MyList.count(12)
count ( ) of similar elements List.count(value) print(x)
present in the last. Output:
2
MyList=[36 ,12 ,12]
Returns the index value x = MyList.index(12)
index ( ) of the first recurring List.index(element) print(x)
element Output:
1
MyList=[36 ,23 ,12]
MyList.reverse()
Reverses the order of print(MyList)
reverse ( ) List.reverse( )
the element in the list.
Output:
[12 ,23 ,36]

sort ( ) Sorts the element in list List.sort(reverse=True|False, key=myFunc)

MyList=['Thilothamma', 'Tharani', 'Anitha',


Both arguments are optional 'SaiSree', 'Lavanya']
• If reverse is set as True, list sorting MyList.sort( )
is in descending order. print(MyList)
• Ascending is default. MyList.sort(reverse=True)
• Key=myFunc; “myFunc” - the name print(MyList)
of the user defined function that
specifies the sorting criteria. Output:
['Anitha', 'Lavanya', 'SaiSree', 'Tharani',
Note: sort( ) will affect the original list. 'Thilothamma']
['Thilothamma', 'Tharani', 'SaiSree', 'Lavanya',
'Anitha']

145 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 145 21-12-2022 15:37:02


MyList=[21,76,98,23]
Returns the maximum print(max(MyList))
max( ) max(list)
value in a list. Output:
98
MyList=[21,76,98,23]
Returns the minimum print(min(MyList))
min( ) min(list)
value in a list. Output:
21
MyList=[21,76,98,23]
Returns the sum of print(sum(MyList))
sum( ) sum(list)
values in a list. Output:
218
9.1.12 Programs using List

Program 1: write a program that creates a list of numbers from 1 to 20


that are divisible by 4
divBy4=[ ]
for i in range(21):
if (i%4==0):
divBy4.append(i)
print(divBy4)
Output
[0, 4, 8, 12, 16, 20]

Program 2: Write a program to define a list of countries that are a member of


BRICS. Check whether a county is member of BRICS or not
country=["India", "Russia", "Srilanka", "China", "Brazil"]
is_member = input("Enter the name of the country: ")
if is_member in country:
print(is_member, " is the member of BRICS")
else:
print(is_member, " is not a member of BRICS")
Output
Enter the name of the country: India
India is the member of BRICS
Output
Enter the name of the country: Japan
Japan is not a member of BRICS

XII Std Computer Science 146

12th Computer Science_EM Chapter 9.indd 146 21-12-2022 15:37:02


Program 3: Python program to read marks of six subjects and to print the
marks scored in each subject and show the total marks
marks=[]
subjects=['Tamil', 'English', 'Physics', 'Chemistry', 'Comp. Science', 'Maths']
for i in range(6):
m=int(input("Enter Mark = "))
marks.append(m)
for j in range(len(marks)):
print("{ }. { } Mark = { } ".format(j+1,subjects[j],marks[j]))
print("Total Marks = ", sum(marks))
Output
Enter Mark = 45
Enter Mark = 98
Enter Mark = 76
Enter Mark = 28
Enter Mark = 46
Enter Mark = 15
1. Tamil Mark = 45
2. English Mark = 98
3. Physics Mark = 76
4. Chemistry Mark = 28
5. Comp. Science Mark = 46
6. Maths Mark = 15
Total Marks = 308

Program 4: Python program to read prices of 5 items in a list and then


display sum of all the prices, product of all the prices and find the average

items=[]
prod=1
for i in range(5):
print ("Enter price for item { } : ".format(i+1))
p=int(input())
items.append(p)
for j in range(len(items)):
print("Price for item { } = Rs. { }".format(j+1,items[j]))
prod = prod * items[j]
print("Sum of all prices = Rs.", sum(items))
print("Product of all prices = Rs.", prod)
print("Average of all prices = Rs.",sum(items)/len(items))

147 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 147 21-12-2022 15:37:02


Output:
Enter price for item 1 :
5
Enter price for item 2 :
10
Enter price for item 3 :
15
Enter price for item 4 :
20
Enter price for item 5 :
25
Price for item 1 = Rs. 5
Price for item 2 = Rs. 10
Price for item 3 = Rs. 15
Price for item 4 = Rs. 20
Price for item 5 = Rs. 25
Sum of all prices = Rs. 75
Product of all prices = Rs. 375000
Average of all prices = Rs. 15.0

Program 5: Python program to count the number of employees earning


more than 1 lakh per annum. The monthly salaries of n number of
employees are given

count=0
n=int(input("Enter no. of employees: "))
print("No. of Employees",n)
salary=[]
for i in range(n):
print("Enter Monthly Salary of Employee { } Rs.: ".format(i+1))
s=int(input())
salary.append(s)
for j in range(len(salary)):
annual_salary = salary[j] * 12
print ("Annual Salary of Employee { } is:Rs. { }".format(j+1,annual_salary))
if annual_salary >= 100000:
count = count + 1
print("{ } Employees out of { } employees are earning more than Rs. 1 Lakh per annum".
format(count, n))

XII Std Computer Science 148

12th Computer Science_EM Chapter 9.indd 148 21-12-2022 15:37:02


Output:
Enter no. of employees: 5
No. of Employees 5
Enter Monthly Salary of Employee 1 Rs.:
3000
Enter Monthly Salary of Employee 2 Rs.:
9500
Enter Monthly Salary of Employee 3 Rs.:
12500
Enter Monthly Salary of Employee 4 Rs.:
5750
Enter Monthly Salary of Employee 5 Rs.:
8000
Annual Salary of Employee 1 is:Rs. 36000
Annual Salary of Employee 2 is:Rs. 114000
Annual Salary of Employee 3 is:Rs. 150000
Annual Salary of Employee 4 is:Rs. 69000
Annual Salary of Employee 5 is:Rs. 96000
2 Employees out of 5 employees are earning more than Rs. 1 Lakh per annum

Program 6: Write a program to create a list of numbers in the range 1 to 10.


Then delete all the even numbers from the list and print the final list.
Num = []
for x in range(1,11):
Num.append(x)
print("The list of numbers from 1 to 10 = ", Num)

for index, i in enumerate(Num):


if(i%2==0):
del Num[index]
print("The list after deleting even numbers = ", Num)

Output
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The list after deleting even numbers = [1, 3, 5, 7, 9]

149 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 149 21-12-2022 15:37:02


Program 7: Write a program to generate in the Fibonacci series and store it
in a list. Then find the sum of all values.
a=-1
b=1
n=int(input("Enter no. of terms: "))
i=0
sum=0
Fibo=[]
while i<n:
s=a+b
Fibo.append(s)
sum+=s
a=b
b=s
i+=1
print("Fibonacci series upto "+ str(n) +" terms is : " + str(Fibo))
print("The sum of Fibonacci series: ",sum)
Output
Enter no. of terms: 10
Fibonacci series upto 10 terms is : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The sum of Fibonacci series: 88

9.2 Tuples

Introduction to Tuples
Tuples consists of a number of values separated by comma and enclosed within
parentheses. Tuple is similar to list, values in a list can be changed but not in a tuple.

The term Tuple is originated from the Latin word represents an abstraction of the
sequence of numbers:
single(1), double(2), triple(3), quadruple(4), quintuple(5), sextuple(6), septuple(7),
octuple(8), ..., n‑tuple, ...,

9.2.1 Comparison of Tuples and list


1. The elements of a list are changeable (mutable) whereas the elements of a tuple are
unchangeable (immutable), this is the key difference between tuples and list.

2. The elements of a list are enclosed within square brackets. But, the elements of a tuple are
enclosed by paranthesis.

3. Iterating tuples is faster than list.

XII Std Computer Science 150

12th Computer Science_EM Chapter 9.indd 150 21-12-2022 15:37:02


9.2.2 Creating Tuples
Creating tuples is similar to list. In a list, elements are defined within square brackets,
whereas in tuples, they may be enclosed by parenthesis. The elements of a tuple can be even
defined without parenthesis. Whether the elements defined within parenthesis or without
parenthesis, there is no differente in it's function.

Syntax:
# Empty tuple
Tuple_Name = ( )

# Tuple with n number elements


Tuple_Name = (E1, E2, E2 ……. En)

# Elements of a tuple without parenthesis


Tuple_Name = E1, E2, E3 ….. En

Example
>>> MyTup1 = (23, 56, 89, 'A', 'E', 'I', "Tamil")
>>> print(MyTup1)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')

>>> MyTup2 = 23, 56, 89, 'A', 'E', 'I', "Tamil"


>>> print (MyTup2)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')

(i) Creating tuples using tuple( ) function


The tuple() function is used to create Tuples from a list. When you create a tuple, from a
list, the elements should be enclosed within square brackets.

Syntax:
Tuple_Name = tuple( [list elements] )

Example
>>> MyTup3 = tuple( [23, 45, 90] )
>>> print(MyTup3)
(23, 45, 90)
>>> type (MyTup3)
<class ‘tuple’>

151 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 151 21-12-2022 15:37:02


Note
Type ( ) function is used to know the data type of a python object.

(ii) Creating Single element tuple


While creating a tuple with a single element, add a comma at the end of the element.
In the absence of a comma, Python will consider the element as an ordinary data type; not a
tuple. Creating a Tuple with one element is called “Singleton” tuple.

Example
>>> MyTup4 = (10)
>>> type(MyTup4)
<class 'int'>
>>> MyTup5 = (10,)
>>> type(MyTup5)
<class 'tuple'>

9.2.3 Accessing values in a Tuple


Like list, each element of tuple has an index number starting from zero. The elements of
a tuple can be easily accessed by using index number.

Example
>>> Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48)
# to access all the elements of a tuple
>>> print(Tup1)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
#accessing selected elements using indices
>>> print(Tup1[2:5])
(91, 'Tamil', 'Telugu')
#accessing from the first element up to the specified index value
>>> print(Tup1[:5])
(12, 78, 91, 'Tamil', 'Telugu')
# accessing from the specified element up to the last element.
>>> print(Tup1[4:])
('Telugu', 3.14, 69.48)
# accessing from the first element to the last element
>>> print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)

XII Std Computer Science 152

12th Computer Science_EM Chapter 9.indd 152 21-12-2022 15:37:02


9.2.4 Update and Delete Tuple
As you know a tuple is immutable, the elements in a tuple cannot be changed. Instead of
altering values in a tuple, joining two tuples or deleting the entire tuple is possible.

Example
# Program to join two tuples
Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)

Output
(2, 4, 6, 8, 10, 1, 3, 5, 7, 9)

To delete an entire tuple, the del command can be used.

Syntax:
del tuple_name

Example
Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ", Tup1)
del Tup1
print (Tup1)

Output:
The elements of Tup1 is (2, 4, 6, 8, 10)
Traceback (most recent call last):
File "D:/Python/Tuple Examp 1.py", line 4, in <module>
print (Tup1)
NameError: name 'Tup1' is not defined

Note that, the print statement in the above code prints the elements. Then, the del statement
deletes the entire tuple. When you try to print the deleted tuple, Python shows the error.

9.2.5 Tuple Assignment


Tuple assignment is a powerful feature in Python. It allows a tuple variable on the left
of the assignment operator to be assigned to the values on the right side of the assignment

153 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 153 21-12-2022 15:37:02


operator. Each value is assigned to its respective variable.

a b c
= 34 90 76

Example
>>> (a, b, c) = (34, 90, 76)
>>> print(a,b,c)
34 90 76
# expression are evaluated before assignment
>>> (x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
>>> print(x,y,z,p)
4 5.666666666666667 1 False

Note that, when you assign values to a tuple, ensure that the number of values on both sides of
the assignment operator are same; otherwise, an error is generated by Python.

9.2.6 Returning multiple values in Tuples


A function can return only one value at a time, but Python returns more than one value
from a function. Python groups multiple values and returns them together.

Example : Program to return the maximum as well as minimum values in


a list
def Min_Max(n):
a = max(n)
b = min(n)
return(a, b)
Num = (12, 65, 84, 1, 18, 85, 99)
(Max_Num, Min_Num) = Min_Max(Num)
print("Maximum value = ", Max_Num)
print("Minimum value = ", Min_Num)

Output:
Maximum value = 99
Minimum value = 1

XII Std Computer Science 154

12th Computer Science_EM Chapter 9.indd 154 21-12-2022 15:37:02


9.2.7 Nested Tuples
In Python, a tuple can be defined inside another tuple; called Nested tuple. In a nested
tuple, each tuple is considered as an element. The for loop will be useful to access all the
elements in a nested tuple.

Example

Toppers = (("Vinodini", "XII-F", 98.7), ("Soundarya", "XII-H", 97.5),


("Tharani", "XII-F", 95.3), ("Saisri", "XII-G", 93.8))
for i in Toppers:
print(i)

Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)

Note
Some of the functions used in List can be applicable even for tuples.

9.2.8 Programs using Tuples

Program 1: Write a program to swap two values using tuple assignment

a = int(input("Enter value of A: "))


b = int(input("Enter value of B: "))
print("Value of A = ", a, "\n Value of B = ", b)
(a, b) = (b, a)
print("Value of A = ", a, "\n Value of B = ", b)

Output:
Enter value of A: 54
Enter value of B: 38
Value of A = 54
Value of B = 38
Value of A = 38
Value of B = 54

155 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 155 21-12-2022 15:37:02


Program 2: Write a program using a function that returns the area and
circumference of a circle whose radius is passed as an argument.two values
using tuple assignment
pi = 3.14
def Circle(r):
return (pi*r*r, 2*pi*r)
radius = float(input("Enter the Radius: "))
(area, circum) = Circle(radius)
print ("Area of the circle = ", area)
print ("Circumference of the circle = ", circum)

Output:
Enter the Radius: 5
Area of the circle = 78.5
Circumference of the circle = 31.400000000000002

Program 3: Write a program that has a list of positive and negative numbers.
Create a new tuple that has only positive numbers from the list

Numbers = (5, -8, 6, 8, -4, 3, 1)


Positive = ( )
for i in Numbers:
if i > 0:
Positive += (i, )
print("Positive Numbers: ", Positive)

Output:
Positive Numbers: (5, 6, 8, 3, 1)

9.3 Sets

Introduction
In python, a set is another type of collection data type. A Set is a mutable and an unordered
collection of elements without duplicates. That means the elements within a set cannot be
repeated. This feature used to include membership testing and eliminating duplicate elements.

XII Std Computer Science 156

12th Computer Science_EM Chapter 9.indd 156 21-12-2022 15:37:02


9.3.1 Creating a Set
A set is created by placing all the elements separated by comma within a pair of curly
brackets. The set() function can also used to create sets in Python.

Syntax:
Set_Variable = {E1, E2, E3 …….. En}

Example
>>> S1={1,2,3,'A',3.14}
>>> print(S1)
{1, 2, 3, 3.14, 'A'}

>>> S2={1,2,2,'A',3.14}
>>> print(S2)
{1, 2, 'A', 3.14}

In the above examples, the set S1 is created with different types of elements without
duplicate values. Whereas in the set S2 is created with duplicate values, but python accepts
only one element among the duplications. Which means python removed the duplicate value,
because a set in python cannot have duplicate elements.

Note
When you print the elements from a set, python shows the values in different order.

9.3.2 Creating Set using List or Tuple


A list or Tuple can be converted as set by using set() function. This is very simple
procedure. First you have to create a list or Tuple then, substitute its variable within set()
function as argument.

Example

MyList=[2,4,6,8,10]
MySet=set(MyList)
print(MySet)

Output:
{2, 4, 6, 8, 10}

157 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 157 21-12-2022 15:37:02


9.3.3 Set Operations
As you learnt in mathematics, the python is also supports the set operations such as
Union, Intersection, difference and Symmetric difference.

(i) Union: It includes all elements from two or more sets

Set A Set B

In python, the operator | is used to union of two sets. The function union() is also used
to join two sets in python.

Example: Program to Join (Union) two sets using union operator

set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}

Example: Program to Join (Union) two sets using union function

set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
set_U=set_A.union(set_B)
print(set_U)
Output:
{'D', 2, 4, 6, 8, 'B', 'C', 'A'}

XII Std Computer Science 158

12th Computer Science_EM Chapter 9.indd 158 21-12-2022 15:37:02


(ii) Intersection: It includes the common elements in two sets

Set A Set B

The operator & is used to intersect two sets in python. The function intersection() is also
used to intersect two sets in python.

Example: Program to insect two sets using intersection operator

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)

Output:
{'A', 'D'}

Example: Program to insect two sets using intersection function

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.intersection(set_B))

Output:
{'A', 'D'}

159 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 159 21-12-2022 15:37:02


(iii) Difference
It includes all elements that are in first set (say set A) but not in the second set (say set B)

Set A Set B

The minus (-) operator is used to difference set operation in python. The function
difference() is also used to difference operation.

Example: Program to difference of two sets using minus operator

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)

Output:
{2, 4}

Example: Program to difference of two sets using difference function

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.difference(set_B))

Output:
{2, 4}

XII Std Computer Science 160

12th Computer Science_EM Chapter 9.indd 160 21-12-2022 15:37:03


(iv) Symmetric difference
It includes all the elements that are in two sets (say sets A and B) but not the one that are
common to two sets.

Set A Set B

The caret (^) operator is used to symmetric difference set operation in python. The
function symmetric_difference() is also used to do the same operation.

Example: Program to symmetric difference of two sets using caret operator

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)

Output:
{2, 4, 'B', 'C'}

Example: Program to difference of two sets using symmetric difference


function

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.symmetric_difference(set_B))

Output:
{2, 4, 'B', 'C'}

161 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 161 21-12-2022 15:37:03


9.3.4 Programs using Sets
Program 1: Program that generate a set of prime numbers and another set of even
numbers. Demonstrate the result of union, intersection, difference and symmetirc
difference operations.

Example

even=set([x*2 for x in range(1,11)])


primes=set()
for i in range(2,20):
j=2
f=0
while j<=i/2:
if i%j==0:
f=1
j+=1
if f==0:
primes.add(i)
print("Even Numbers: ", even)
print("Prime Numbers: ", primes)
print("Union: ", even.union(primes))
print("Intersection: ", even.intersection(primes))
print("Difference: ", even.difference(primes))
print("Symmetric Difference: ", even.symmetric_difference(primes))
Output:
Even Numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
Prime Numbers: {2, 3, 5, 7, 11, 13, 17, 19}
Union: {2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}
Intersection: {2}
Difference: {4, 6, 8, 10, 12, 14, 16, 18, 20}
Symmetric Difference: {3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}

9.4 Dictionaries

Introduction
In python, a dictionary is a mixed collection of elements. Unlike other collection data
types such as a list or tuple, the dictionary type stores a key along with its element. The keys in
a Python dictionary is separated by a colon ( : ) while the commas work as a separator for the
elements. The key value pairs are enclosed with curly braces { }.

XII Std Computer Science 162

12th Computer Science_EM Chapter 9.indd 162 21-12-2022 15:37:03


Syntax of defining a dictionary:
Dictionary_Name = { Key_1: Value_1,
Key_2:Value_2,
……..
Key_n:Value_n
}

Key in the dictionary must be unique case sensitive and can be of any valid Python type.

9.4.1 Creating a Dictionary


# Empty dictionary
Dict1 = { }

# Dictionary with Key


Dict_Stud = { 'RollNo': '1234', 'Name':'Murali', 'Class':'XII', 'Marks':'451'}

9.4.2 Dictionary Comprehensions


In Python, comprehension is another way of creating dictionary. The following is the
syntax of creating such dictionary.

Syntax
Dict = { expression for variable in sequence [if condition] }

The if condition is optional and if specified, only those values in the sequence are evaluated
using the expression which satisfy the condition.

Example

Dict = { x : 2 * x for x in range(1,10)}


Output of the above code is
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

9.4.3 Accessing, Adding, Modifying and Deleting elements from a Dictionary


Accessing all elements from a dictionary is very similar as Lists and Tuples. Simple print
function is used to access all the elements. If you want to access a particular element, square
brackets can be used along with key.

163 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 163 21-12-2022 15:37:03


Example : Program to access all the values stored in a dictionary
MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',
'School' : 'CGHSS',
'Address' : 'Rotler St., Chennai 112' }
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
Output:
{'Reg_No': '1221', 'Name': 'Tamilselvi', 'School': 'CGHSS', 'Address': 'Rotler St., Chennai 112'}
Register Number: 1221
Name of the Student: Tamilselvi
School: CGHSS
Address: Rotler St., Chennai 112

Note that, the first print statement prints all the values of the dictionary. Other statements
are printing only the specified values which is given within square brackets.
In an existing dictionary, you can add more values by simply assigning the value along
with key. The following syntax is used to understand adding more elements in a dictionary.
dictionary_name [key] = value/element

Example : Program to add a new value in the dictionary


MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',
'School' : 'CGHSS', 'Address' : '
Rotler St., Chennai 112'}
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
MyDict['Class'] = 'XII - A' # Adding new value
print("Class: ", MyDict['Class']) # Printing newly added value
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])

Modification of a value in dictionary is very similar as adding elements. When you assign
a value to a key, it will simply overwrite the old value.
In Python dictionary, del keyword is used to delete a particular element. The clear()
function is used to delete all the elements in a dictionary. To remove the dictionary, you can
use del keyword with dictionary name.
XII Std Computer Science 164

12th Computer Science_EM Chapter 9.indd 164 21-12-2022 15:37:03


Syntax:
# To delete a particular element.
del dictionary_name[key]
# To delete all the elements
dictionary_name.clear( )
# To delete an entire dictionary
del dictionary_name

Example : Program to delete elements from a dictionary and finally deletes


the dictionary.

Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary

Output:
Dictionary elements before deletion:
{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{ }
Traceback (most recent call last):
File "E:/Python/Dict_Test_02.py", line 8, in <module>
print(Dict)
NameError: name 'Dict' is not defined

9.4.4 Difference between List and Dictionary


(1) List is an ordered set of elements. But, a dictionary is a data structure that is used for
matching one element (Key) with another (Value).

(2) The index values can be used to access a particular element. But, in dictionary key
represents index. Remember that, key may be a number of a string.

(3) Lists are used to look up a value whereas a dictionary is used to take one value and look
up another value.

165 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 165 21-12-2022 15:37:03


Points to remember:
• Python programming language has four collections of data types such as List, Tuple,
Set and Dictionary.
• A list is known as a “sequence data type”. Each value of a list is called as element.
• The elements of list should be specified within square brackets.
• Each element has a unique value called index number begins with zero.
• Python allows positive and negative values as index.
• Loops are used access all elements from a list.
• The “for” loop is a suitable loop to access all the elements one by one.
• The append ( ), extend ( ) and insert ( ) functions are used to include more elements
in a List.
• The del, remove ( ) and pop ( ) are used to delete elements from a list.
• The range ( ) function is used to generate a series of values.
• Tuples consists of a number of values separated by comma and enclosed within
parentheses.
• Iterating tuples is faster than list.
• The tuple ( ) function is also used to create Tuples from a list.
• Creating a Tuple with one element is called “Singleton” tuple.
• A Set is a mutable and an unordered collection of elements without duplicates.
• A set is created by placing all the elements separated by comma within a pair of curly
brackets.
• A dictionary is a mixed collection of elements.

Hands on Experience

1. Write a program to remove duplicates from a list.

2. Write a program that prints the maximum value in a Tuple.

3. Write a program that finds the sum of all the numbers in a Tuples using while loop.

4. Write a program that finds sum of all even numbers in a list.

XII Std Computer Science 166

12th Computer Science_EM Chapter 9.indd 166 21-12-2022 15:37:03


5. Write a program that reverse a list using a loop.

6. Write a program to insert a value in a list at the specified location.

7. Write a program that creates a list of numbers from 1 to 50 that are either divisible by 3 or
divisible by 6.

8. Write a program to create a list of numbers in the range 1 to 20. Then delete all the numbers
from the list that are divisible by 3.

9. Write a program that counts the number of times a value appears in the list. Use a loop to
do the same.

10. Write a program that prints the maximum and minimum value in a dictionary.

Evaluation

Part - I

Choose the best answer (1 Marks)


1. Pick odd one in connection with collection data type
(a) List (b) Tuple (c) Dictionary (d) Loop
2. Let list1=[2,4,6,8,10], then print(List1[-2]) will result in
(a) 10 (b) 8 (c) 4 (d) 6
3. Which of the following function is used to count the number of elements in a list?
(a) count() (b) find() (c) len() (d) index()
4. If List=[10,20,30,40,50] then List[2]=35 will result
(a) [35,10,20,30,40,50] (b) [10,20,30,40,50,35]
(c) [10,20,35,40,50] (d) [10,35,30,40,50]
5. If List=[17,23,41,10] then List.append(32) will result
(a) [32,17,23,41,10] (b) [17,23,41,10,32]
(c) [10,17,23,32,41] (d) [41,32,23,17,10]
6. Which of the following Python function can be used to add more than one element
within an existing list?
(a) append()  (b) append_more()  (c) extend()  (d) more()

167 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 167 21-12-2022 15:37:03


7. What will be the result of the following Python code?
S=[x**2 for x in range(5)]
print(S)
(a) [0,1,2,4,5]   (b) [0,1,4,9,16] (c) [0,1,4,9,16,25] (d) [1,4,9,16,25]
8. What is the use of type() function in python?
(a) To create a Tuple
(b) To know the type of an element in tuple.
(c) To know the data type of python object.
(d) To create a list.
9. Which of the following statement is not correct?
(a) A list is mutable
(b) A tuple is immutable.
(c) The append() function is used to add an element.
(d) The extend() function is used in tuple to add elements in a list.
10. Let setA = {3,6,9}, setB = {1,3,9}. What will be the result of the following snippet?
print(setA|setB)
(a) {3,6,9,1,3,9} (b) {3,9} (c) {1} (d) {1,3,6,9}
11. Which of the following set operation includes all the elements that are in two sets but not
the one that are common to two sets?
(a) Symmetric difference (b) Difference
(c) Intersection (d) Union
12. The keys in Python, dictionary is specified by
(a) = (b) ; (c) + (d) :

Part - II

Answer the following questions (2 Marks)


1. What is List in Python?
2. How will you access the list elements in reverse order?
3. What will be the value of x in following python code?
List1=[2,4,6[1,3,5]]
x=len(List1)
XII Std Computer Science 168

12th Computer Science_EM Chapter 9.indd 168 21-12-2022 15:37:03


4. Differentiate del with remove() function of List.
5. Write the syntax of creating a Tuple with n number of elements.
6. What is set in Python?

Part - III

Answer the following questions (3 Marks)


1. What are the difference between list and Tuples?
2. Write a shot note about sort().
3. What will be the output of the following code?
list = [2**x for x in range(5)]
print(list)
4. Explain the difference between del and clear() in dictionary with an example.
5. List out the set operations supported by python.
6. What are the difference between List and Dictionary?

Part - IV

Answer the following questions (5 Marks)


1. What the different ways to insert an element in a list. Explain with suitable example.
2. What is the purpose of range()? Explain with an example.
3. What is nested tuple? Explain with an example.
4. Explain the different set operations supported by python with suitable example.

References
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford
University press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.

169 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter 9.indd 169 21-12-2022 15:37:03


CHAPTER 10
Unit III
PYTHON CLASSES AND OBJECTS

Learning Objectives

After the completion of this chapter, the student is able to

• Understand the fundamental concepts of Object Oriented Programming like: Classes,


Objects, Constructor and Destructor.

• Gain the knowledge of creating classes and objects in Python.

• Create classes with Constructors.

• Write complex programs in Python using classes.

10.1 Introduction

Python is an Object Oriented Programming language. Classes and Objects are the key
features of Object Oriented Programming. Theoretical concepts of classes and objects are very
similar to that of C++. But, creation and implementation of classes and objects is very simple
in Python compared to C++.
Class is the main building block in Python. Object is a collection of data and function
that act on those data. Class is a template for the object. According to the concept of Object
Oriented Programming, objects are also called as instances of a class. In Python, everything is
an object. For example, all integer variables that we use in our program is an object of class int.
Similarly all string variables are also object of class string.
10.2 Defining classes
In Python, a class is defined by using the keyword class. Every class has a unique name
followed by a colon ( : ).
Syntax:
class class_name:
statement_1
statement_2
…………..
…………..
statement_n

XII Std Computer Science 170

12th Computer Science_EM Chapter 10.indd 170 26-12-2022 16:45:44


Where, statement in a class definition may be a variable declaration, decision control,
loop or even a function definition. Variables defined inside a class are called as “Class Variable”
and functions are called as “Methods”. Class variable and methods are together known as
members of the class. The class members should be accessed through objects or instance of
class. A class can be defined anywhere in a Python program.
Example: Program to define a class
class Sample:
x, y = 10, 20 # class variables
In the above code, name of the class is Sample and it has two variables x and y having
the initial value 10 and 20 respectively. To access the values defined inside the class, you need
an object or instance of the class.

10.3 Creating Objects


Once a class is created, next you should create an object or instance
of that class. The process of creating object is called as “Class Instantiation”.

Syntax:
Object_name = class_name( )

Note that the class instantiation uses function notation ie. class_name with ()

10.4 Accessing Class Members


Any class member ie. class variable or method (function) can be accessed by using
object with a dot ( . ) operator.
Syntax:
Object_name . class_member

Example : Program to define a class and access its member variables


class Sample:
x, y = 10, 20 #class variables
S=Sample( ) # class instantiation
print("Value of x = ", S.x)
print("Value of y = ", S.y)
print("Value of x and y = ", S.x+S.y)
Output :
Value of x = 10
Value of y = 20
Value of x and y = 30

171 Python Classes and Objects

12th Computer Science_EM Chapter 10.indd 171 26-12-2022 16:45:44


In the above code, the name of the class is Sample. Inside the class, we have assigned
the variables x and y with initial value 10 and 20 respectively. These two variables are called as
class variables or member variables of the class. In class instantiation process, we have created
an object S to access the members of the class. The first two print statements simply print the
value of class variable x and y and the last print statement add the two values and print the
result.

10.5 Class Methods


Python class function or Method is very similar to ordinary function with a small
difference that, the class method must have the first parameter named as self. No need to pass
a value for this parameter when we call the method. Python provides its value automatically.
Even if a method takes no arguments, it should be defined with the first parameter called self.
If a method is defined to accept only one parameter it will take it as two arguments ie. self and
the defined parameter.
When you access class variable within class, methods must be prefixed by the class
name and dot operator.

Note
• The statements defined inside the class must be properly indented.
• Parameters are the variables in the function definition.
• Arguments are the values passed to the function definition.

Example: Program to find total and average marks using class

class Student:
mark1, mark2, mark3 = 45, 91, 71 #class variable

def process(self): #class method


sum = Student.mark1 + Student.mark2 + Student.mark3
avg = sum/3
print("Total Marks = ", sum)
print("Average Marks = ", avg)
return

S=Student()
S.process()

In the above program, after defining the class, an object S is created. The statement
S.process( ), calls the function to get the required output.
XII Std Computer Science 172

12th Computer Science_EM Chapter 10.indd 172 26-12-2022 16:45:44


Note that, we have declared three variables mark1, mark2 and mark3 with the values
45, 91, 71 respectively. We have defined a method named process with self argument, which
means, we are not going to pass any value to that method. First, the process method adds the
values of the class variables, stores the result in the variable sum, finds the average and displays
the result.
Thus the above code will show the following output.
Output
Total Marks = 207
Average Marks = 69.0
Example : program to check and print if the given number is odd or
even using class
class Odd_Even:
def check(self, num):
if num%2==0:
print(num," is Even number")
else:
print(num," is Odd number")
n=Odd_Even()
x = int(input("Enter a value: "))
n.check(x)
When you execute this program, Python accepts the value entered by the user
and passes it to the method check through object.
Output 1
Enter a value: 4
4 is Even number
Output 2
Enter a value: 5
5 is Odd number

10.6 Constructor and Destructor in Python


Constructor is the special function that is automatically executed when an object of a
class is created. In Python, there is a special function called “init” which act as a Constructor.
It must begin and end with double underscore. This function will act as an ordinary function;
but only difference is, it is executed automatically when the object is created. This constructor
function can be defined with or without arguments. This method is used to initialize the class
variables.
General format of _ _init_ _ method (Constructor function)
def _ _init_ _(self, [args ……..]):
<statements>

173 Python Classes and Objects

12th Computer Science_EM Chapter 10.indd 173 26-12-2022 16:45:44


Example : Program to illustrate Constructor
class name
class Sample: Parameter
def __init__(self, num):
print("Constructor of class Sample...")
self.num=num Instance variable
print("The value is :", num)
S=Sample(10)
The above class “Sample”, has only a constructor with one parameter named as num.
When the constructor gets executed, first the print statement, prints the “Constructor of
class Sample….”, then, the passing value to the constructor is assigned to instance variable
self.num = num and finally it prints the value passed along with the given string.
The above constructor gets executed automatically, when an object S is created with
actual parameter 10. Thus, the Python display the following output.
Constructor of class Sample...
The value is : 10
Class variable defined within constructor keep count of number of objects created with
the class.

Note

Instance variables are the variables whose value varies from object to object.
For every object, a separate copy of the instance variable will be created.
Instance variables are declared inside a method using the self keyword. In
the above example, we use constructor to define instance variable.

Example : Program to illustrate class variable to keep count of number


of objects created.
class Sample:
num=0 class variable
def __init__(self, var):
Sample.num+=1
self.var=var instance variable
print("The object value is = ", self.var)
print("The count of object created = ", Sample.num)

S1=Sample(15)
S2=Sample(35)
S3=Sample(45)

XII Std Computer Science 174

12th Computer Science_EM Chapter 10.indd 174 26-12-2022 16:45:44


In the above program, class variable num is shared by all three objects of the class
Sample. It is initialized to zero and each time an object is created, the num is incremented by
1. Since, the variable shared by all objects, change made to num by one object is reflected in
other objects as well. Thus the above program produces the output given below.

Output
The object value is = 15
The count of object created = 1
The object value is = 35
The count of object created = 2
The object value is = 45
The count of object created = 3
Destructor is also a special method to destroy the objects. In Python, _ _del_ _( )
method is used as destructor. It is just opposite to constructor.
Example : Program to illustrate about the __del__( ) method
class Sample:
num=0
def __init__(self, var):
Sample.num+=1
self.var=var
print("The object value is = ", self.var)
print("The value of class variable is= ", Sample.num)
def __del__(self):
Sample.num-=1
print("Object with value %d is exit from the scope"%self.var)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
del S1, S2, S3

Note
The __del__ method gets called automatically when we deleted the object
reference using the del.

10.7 Public and Private Data Members

The variables which are defined inside the class is public by default. These variables can
be accessed anywhere in the program using dot operator.
A variable prefixed with double underscore becomes private in nature. These variables
can be accessed only within the class.

175 Python Classes and Objects

12th Computer Science_EM Chapter 10.indd 175 26-12-2022 16:45:44


Example : Program to illustrate private and public variables
class Sample:
n1 = 12
__n2 = 14
def display(self):
print("Class variable 1 = ", self.n1)
print("Class variable 2 = ", self.__n2)
S=Sample()
S.display()
print("Value 1 = ", S.n1)
print("Value 2 = ", S.__n2)

In the above program, there are two class variables n1 and n2 are declared. The variable
n1 is a public variable and n2 is a private variable. The display( ) member method is defined to
show the values passed to these two variables.

The print statements defined within class will successfully display the values of n1 and
n2, even though the class variable n2 is private. Because, in this case, n2 is called by a method
defined inside the class. But, when we try to access the value of n2 from outside the class
Python throws an error. Because, private variable cannot be accessed from outside the class.

Output
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12

Traceback (most recent call last):


File "D:/Python/Class-Test-04.py", line 12, in <module>
print("Value 2 = ", S.__n2)
AttributeError: 'Sample' object has no attribute '__n2'

XII Std Computer Science 176

12th Computer Science_EM Chapter 10.indd 176 26-12-2022 16:45:45


10.8 Sample Programs to illustrate classes and objects

Program 1: Write a program to calculate area and circumference of a circle


class Circle:
pi=3.14
def __init__(self,radius):
self.radius=radius
def area(self):
return Circle.pi*(self.radius**2)
def circumference(self):
return 2*Circle.pi*self.radius
r=int(input("Enter Radius: "))
C=Circle(r)
print("The Area =",C.area())
print("The Circumference =", C.circumference())

Output:
Enter Radius: 5
The Area = 78.5
The Circumference = 31.400000000000002

Program 2: Write a program to accept a string and print the number of


uppercase, lowercase, vowels, consonants and spaces in the given string
class String:
def __init__(self):
self.upper=0
self.lower=0
self.vowel=0
self.consonant=0
self.space=0
self.string=""
def getstr(self):
self.string=str(input("Enter a String: "))
def count (self):
for ch in self.string:
if (ch.isupper()):
self.upper+=1
if (ch.islower()):
self.lower+=1
if (ch in ('AEIOUaeiou'):
self.vowel+=1

177 Python Classes and Objects

12th Computer Science_EM Chapter 10.indd 177 26-12-2022 16:45:45


if (ch.isspace()):
self.space+=1
self.consonant = self.upper+self.lower - self.
vowel
def display(self):
print("The given string contains...")
print("%d Uppercase letters"%self.upper)
print("%d Lowercase letters"%self.lower)
print("%d Vowels"%self.vowel)
print("%d Consonants"%self.consonant)
print("%d Spaces"%self.space)
S = String()
S.getstr()
S.count()
S.display()
Output:
Enter a String:Welcome To Learn Computer Science
The given string contains...
4 Uppercase letters
25 Lowercase letters
12 Vowels
13 Consonants
4 Spaces

Points to remember

• Python is an Object Oriented Programming language.


• Classes and Objects are the key features of Object Oriented Programming.
• In Python, a class is defined by using the keyword class.
• Variables defined inside a class is called as “Class Variable” and function are
called as “Methods”.
• The process of creating object is called as “Class Instantiation”.
• Constructor is the special function that is automatically executed when an
object of a class is created.
• In Python, there is a special function called “init” is used as Constructor.
• Destructor is also a special method gets execution automatically when an
object exits from the scope.
• In Python, __del__( ) method is used as destructor.
• A variable prefixed with double underscore is becomes private in nature.

XII Std Computer Science 178

12th Computer Science_EM Chapter 10.indd 178 26-12-2022 16:45:45


Hands on Experience

1. Write a program using class to store name and marks of students in list and print total
marks.

2. Write a program using class to accept three sides of a triangle and print its area.

3. Write a menu driven program to read, display, add and subtract two distances.

Evaluation

Part - I

Choose the best answer (1 Mark)


1. Which of the following are the key features of an Object Oriented Programming language?
(a) Constructor and Classes (b) Constructor and Object
(c) Classes and Objects (d) Constructor and Destructor
2. Functions defined inside a class:
(a) Functions (b) Module
(c) Methods (d) section
3. Class members are accessed through which operator?
(a) & (b) .
(c) # (d) %
4. Which of the following method is automatically executed when an object is created?
(a) __object__( ) (b) __del__( )
(c) __func__( ) (d) __init__( )
5. A private class variable is prefixed with
(a) __ (b) &&
(c) ## (d) **
6. Which of the following method is used as destructor?
(a) __init__( ) (b) __dest__( )
(c) __rem__( ) (d) __del__( )

179 Python Classes and Objects

12th Computer Science_EM Chapter 10.indd 179 26-12-2022 16:45:45


7. Which of the following class declaration is correct?
(a) class class_name (b) class class_name<>
(c) class class_name: (d) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:
def __init__(self, name):
self.name=name
print (self.name)
S=Student(“Tamil”)
(a) Error (b) Tamil
(c) name (d) self
9. Which of the following is the private class variable?
(a) __num (b) ##num
(c) $$num (d) &&num
10. The process of creating an object is called as:
(a) Constructor (b) Destructor
(c) Initialize (d) Instantiation

Part -II

Answer the following questions (2 Marks)

1. What is class?
2. What is instantiation?
3. What is the output of the following program?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
4. How will you create constructor in Python?
5. What is the purpose of Destructor?

XII Std Computer Science 180

12th Computer Science_EM Chapter 10.indd 180 26-12-2022 16:45:45


Part -III

Answer the following questions (3 Marks)


1. What are class members? How do you define it?
2. Write a class with two private class variables and print the sum using a method.
3. Find the error in the following program to get the given output?
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple', 'Mango')
del F.display
F.display()
Output
Fruit 1 = Apple, Fruit 2 = Mango
4. What is the output of the following program?
class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan')
obj.display()
5. How to define constructor and destructor in Python?
Part -IV

Answer the following questions (5 Marks)


1. Explain about constructor and destructor with suitable example.

References
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.

181 Python Classes and Objects

12th Computer Science_EM Chapter 10.indd 181 26-12-2022 16:45:45


CHAPTER 11
Unit IV
DATABASE CONCEPTS

11.2 Information
Learning Objectives
Information is processed data, which
At the completion of this chapter, the student allows to be utilized in a significant way.
will be able to know Example
• the concept of a database and relational SCERT
database. College Road
• different components of the database. DPI Campus
Chennai 600006
• types of database models.
As you can see
• types of relationship.
from the example above,
• the concepts of relational algebra. data appears as a set of
Introduction words and numbers. However, when the
data is processed, organized and formatted,
A database is an organized collection it gives a meaningful information about the
of data, generally stored and accessed SCERT institution contact address.
electronically from a computer system. The
11.3 Database
term "database" is also used to refer to any
Database is a repository collection of
of the DBMS, the database system or an
related data organized in a way that data can
application associated with the database.
be easily accessed, managed and updated.
Because of the close relationship between
Database can be a software or hardware
them, the term "database" is often used
based, with one sole purpose of storing data.
casually to refer to both a database and
the DBMS used to manipulate it. A school 11.4 DataBase Management
class register is a database where names are System (DBMS)
arranged alphabetically. Databases have A DBMS is a software that allows us
been around since people started recording to create, define and manipulate database,
things. Here we tend to focus on electronic allowing users to store, process and analyze
ones. data easily. DBMS provides us with an
interface or a tool, to perform various
11.1 Data operations to create a database, storing of
Data are raw facts stored in a data and for updating data, etc. DBMS also
computer. A data may contain any character, provides protection and security to the
text, word or a number. databases. It also maintains data consistency
Example : 600006, DPI Campus, SCERT, in case of multiple users.
Chennai, College Road Examples of DBMS softwares : Foxpro, dbase.
182
182

12th Computer Science_EM Chapter 11.indd 182 26-12-2022 16:46:12


11.4.1 Relational Database Management System (RDBMS)
RDBMS is more advanced version of DBMS, that allows to data in a more efficient way.
It is used to store and manupulate the data that are in the form of tables.
Examaple of RDBMS: MySQL,Oracle, MS-Access etc.,
11.4.2 Characteristics of Relational Database Management System
1. 
Ability to manipulate RDBMS provides the facility to manipulate data (store, modify
data and delete)in a data base.

2. Reduced Redundancy In the modern world hard drives are very cheap, but earlier
when hard drives were too expensive, unnecessary repetition
of data in database was a big problem But RDBMS follows
Normalisation which divides the data in such a way that
repetition is minimum.

3.Data Consistency On live data, it is being continuously updated and added,


maintaining the consistency of data can become a challenge.
But RDBMS handles it by itself.

4. Support Multiple user RDBMS allows multiple users to work on it(update, insert,
and Concurrent Access delete data) at the same time and still manages to maintain the
data consistency.

5.Query Language RDBMS provides users with a simple query language, using
which data can be easily fetched, inserted, deleted and updated
in a database.

6. Security The RDBMS also takes care of the security of data, protecting
the data from unauthorized access. In a typical RDBMS, we can
create user accounts with different access permissions, using
which we can easily secure our data by restricting user access.

7. DBMS Supports It allows us to better handle and manage data integrity in real
Transactions world applications where multi-threading is extensively used.

11.4.3 Advantages of RDBMS


• Segregation of application program
• Minimal data duplication or Data Redundancy
• Easy retrieval of data using the Query Language
• Reduced development time and maintenance

183

12th Computer Science_EM Chapter 11.indd 183 26-12-2022 16:46:12


11.4.4 Components of DBMS 3. Data: It is the resource for which DBMS
The Database Management System is designed. DBMS creation is to store and
can be divided into five major components utilize data.
as follows: 4. Procedures/Methods: They are general
1.Hardware 2.Software instructions to use a database management
system such as installation of DBMS,
3.Data 4.Procedures/Methods
manage databases to take backups, report
5.Database Access Languages generation, etc.
5. DataBase Access Languages: They are
the languages used to write commands to
access, insert, update and delete data stored
Hardware in any database.
Examples of popular DBMS: Dbase,
FoxPro
Software
11.5 Database Structure
Data Base Procedures
/ Methods Table is the entire collection of
Access
related data in one table, referred to as a File
DATA

Languages
or Table where the data is organized as row
USER and column.
Components of DBMS
Each row in a table represents a
Figure 11.1 record, which is a set of data for each
database entry.
1. Hardware: The computer, hard disk, I/O
channels for data, and any other physical Each table column represents a Field,
component involved in storage of data which groups each piece or item of data
2. Software: This main component is among the records into specific categories or
a program that controls everything. The types of data. Eg. StuNo., StuName, StuAge,
DBMS software is capable of understanding StuClass, StuSec.
the Database Access Languages and A Table is known as a RELATION
interprets into database commands for
execution. A Row is known as a TUPLE
A column is known as an ATTRIBUTE

XII Std Computer Science 184

12th Computer Science_EM Chapter 11.indd 184 26-12-2022 16:46:12


Attribute / Column Tuple / Row

StuNo StuName StuAge StuClass StuSec


1101 Kannan 14 9 A
1102 Ramakrishnan 14 9 A
1103 Vidhya 14 10 B
1104 Britto 15 9 A
1105 Padmaja 14 10 B

Table / Relation
DataBase Structure
Fig 11.2
11.6 Data Model
• A data model describes how the data can be represented and accessed from a software after
complete implementation
• It is a simple abstraction of complex real world data gathering environment.
• The main purpose of data model is to give an idea as how the final system or software will
look like after development is completed.

11.6.1 Types of Data Model


Following are the different types of a Data Model

• Hierarchical Model
• Relational Model
• Network Database Model
• Entity Relationship Model
• Object Model
1. Hierarchical Model
Hierarchical model was developed by IBM as Information Management System.

In Hierarchical model, data is represented as a simple tree like structure form. This
model represents a one-to-many relationship i.e parent-child relationship. One child can have
only one parent but one parent can have many children. This model is mainly used in IBM
Main Frame computers.

185 Database Concepts

12th Computer Science_EM Chapter 11.indd 185 26-12-2022 16:46:12


School

Course Resources

Theory Lab

Hierarchical Model Fig. 11.3

2. Relational Model
The Relational Database model was first proposed by E.F. Codd in 1970 . Nowadays, it
is the most widespread data model used for database applications around the world.
The basic structure of data in relational model is tables (relations). All the information’s
related to a particular type is stored in rows of that table. Hence tables are also known as
relations in a relational model. A relation key is an attribute which uniquely identifies a
particular tuple (row in a relation (table)).

Stu_id Name Age Subj_id Name Teacher


1 Malar 17 1 C++ Kannan
2 Suncar 16 2 Php Ramakrishnan
3 Velu 16 3 Python Vidhya

Stu_id Subj_id Marks


1 1 92
1 2 89
3 2 96
Relational Model
Fig. 11.4

3. Network Model
Network database model is an extended form of hierarchical data model. The difference
between hierarchical and Network data model is :
• In hierarchical model, a child record has only one parent node,

XII Std Computer Science 186

12th Computer Science_EM Chapter 11.indd 186 26-12-2022 16:46:12


• In a Network model, a child may have many parent nodes. It represents the data in many-
to-many relationships.
• This model is easier and faster to access the data.

School

Library Office Staff Room This child has one parent node

Student Student has 3 parent node

Network Model
Fig. 11.5

School represents the parent node


Library, Office and Staff room is a child to school
Student is a child to library, office and staff room (one to many relationship)
4. Entity Relationship Model. (ER model)
In this database model, relationship are created by dividing the object into entity and its
characteristics into attributes.
It was developed by Chen in 1976. This model is useful in developing a conceptual
design for the database. It is very simple and easy to design logical view of data. The developer
can easily understand the system by looking at ER model constructed.
Rectangle represents the entities. E.g. Doctor and Patient
Ellipse represents the attributes E.g. D-id, D-name, P-id, P-name. Attributes describes
the characteristics and each entity becomes a major part of the data stored in the database.

Diamond represents the relationship in ER diagrams

E.g. Doctor diagnosis the Patient

187 Database Concepts

12th Computer Science_EM Chapter 11.indd 187 26-12-2022 16:46:12


Doctor Diagnosis Patient

D-id D-Name P-id P-Name


ER model
Fig. 11.6

5. Object Model
Object model stores the data in the form of objects, attributes and methods, classes and
Inheritance. This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing. It is used in file
Management System. It represents real world objects, attributes and behaviors. It provides a
clear modular structure. It is easy to maintain and modify the existing code.

Shape
get_area()
get_perimeter()

Circle Rectangle Triangle


Radius Length Base
breath Height
Object Model
Fig. 11.7

An example of the Object model is Shape, Circle, Rectangle and Triangle are all objects
in this model.
• Circle has the attribute radius.
• Rectangle has the attributes length and breadth.
• Triangle has the attributes base and height .
• The objects Circle, Rectangle and Triangle inherit from the object Shape.

11.6.2 Types of DBMS Users


Database Administrators
Database Administrator or DBA is the one who manages the complete database
management system. DBA takes care of the security of the DBMS, managing the license keys,
managing user accounts and access etc.

XII Std Computer Science 188

12th Computer Science_EM Chapter 11.indd 188 26-12-2022 16:46:12


Application Programmers or Software Developers
This user group is involved in developing and designing the parts of DBMS.
End User
All modern applications, web or mobile, store user data. Applications are programmed
in such a way that they collect user data and store the data on DBMS systems running on their
server. End users are the one who store, retrieve, update and delete data.
Database designers: are responsible for identifying the data to be stored in the database for
choosing appropriate structures to represent and store the data.

11.7 Difference between DBMS and RDBMS

Basis of Comparison DBMS RDBMS

Expansion Database Management System Relational DataBase


Management System

Data storage Navigational model Relational model (in tables).


ie data by linked records ie data in tables as row and
column

Data redundancy Present Not Present

Normalization Not performed RDBMS uses normalization


to reduce redundancy

Data access Consumes more time Faster, compared to DBMS.

Keys and indexes Does not use. used to establish


relationship. Keys are used in
RDBMS.

Transaction Inefficient, Efficient and secure.


management Error prone and insecure.

Distributed Databases Not supported Supported by RDBMS.

Example Dbase, FoxPro. SQL server, Oracle, mysql,


MariaDB, SQLite, MS Access.

Database normalization was first proposed by Dr. Edgar F Codd as an integral part
of RDBMS in order to reduce data redundancy and improve data integrity. These rules are
known as E F Codd Rules.

189 Database Concepts

12th Computer Science_EM Chapter 11.indd 189 26-12-2022 16:46:12


11.8 Types of Relationships staff members.

Following are the types of relationships used Staff


in a database. Department

1. One-to-One Relationship Gajalakshmi

2. One-to-Many Relationship
Computer Bindhu
3. Many-to-One Relationship
4. Many-to-Many Relationship Tamil Radha
1. One-to-One Relationship
In One-to-One Relationship, one Maths Ramesh
entity is related with only one other entity.
One row in a table is linked with only one
row in another table and vice versa. Malaiarasu

For example: A student can have only


one exam number One to Many Mapping
Fig 11.9
Student Exam No
3. Many-to-One Relationship
In Many-to-One Relationship, many
entities can be related with only one in the
Tamilselvi 1001 other entity.
For example: A number of staff
Jayapandiyan 1002 members working in one Department.
Multiple rows in staff members table
Sarojini 1003 is related with only one row in Department
table.
Staff Department

One to one Relationships


Fig 11.8
Suganya
Computer
2. One-to-Many Relationship
Bala
In One-to-Many relationship, one Maths
entity is related to many other entities. Valarmathi
One row in a table A is linked to
many rows in a table B, but one row in a
table B is linked to only one row in table A. Many to one Relationship
For example: One Department has many Fig 11.10

XII Std Computer Science 190

12th Computer Science_EM Chapter 11.indd 190 26-12-2022 16:46:13


4. Many-to-Many Relationship 11.9 Relational Algebra in DBMS
A many-to-many relationship
occurs when multiple records in a table are What is Relational Algebra?
associated with multiple records in another Relational Algebra, was first created
table. by Edgar F Codd while at IBM. It was used
for modeling the data stored in relational
Example 1: Customers and Product
databases and defining queries on it.
Customers can purchase various
products and Products can be purchased by Relational Algebra is a procedural
many customers query language used to query the database
tables using SQL.
Example 2: Students and Courses
Relational algebra operations are
A student can register for many
performed recursively on a relation (table)
Courses and a Course may include many
to yield an output. The output of these
stu d e nt s
operations is a new relation, which might be
Example 3: Books and Student. formed by one or more input relations.
Many Books in a Library are issued
Relational Algebra is divided into various
to many students.
groups
Book Student
Unary Relational Operations
SELECT ( symbol : σ)
C++ Kalaivani
PROJECT ( symbol : ∏)

SQL Manjula Relational Algebra Operations from Set


Theor y
Sridevi
python • UNION (∪)
• INTERSECTION (∩)
Many to Many Relationship • DIFFERENCE (−)
Fig 11.11
• CARTESIAN PRODUCT (X)
SELECT (symbol : σ)
The relational model
was invented by Edgar General form σ ( R ) with a relation
c
Frank Codd (Father of R and a condition C on the attributes of R.
Relational DataBase) as The SELECT operation is used for
a general model of data, and selecting a subset with tuples according to a
subsequently promoted by Chris Date given condition.
and Hugh Darwen among others.
Select filters out all tuples that do not
satisfy C.
191 Database Concepts

12th Computer Science_EM Chapter 11.indd 191 26-12-2022 16:46:13


STUDENT

Studno Name Course Year

cs1 Kannan Big Data II

cs2 Gowri Shankar R language I

cs3 Lenin Big Data I

cs4 Padmaja Python Programming I

Table 11.1

σcourse = “Big Data” (STUDENT )

Studno Name Course Year

cs1 Kannan Big Data II

cs3 Lenin Big Data I

PROJECT (symbol : Π)
The projection eliminates all attributes of the input relation but those mentioned in
the projection list. The projection method defines a relation that contains a vertical subset of
Relation.

Example 1 using Table 11.1


Πcourse (STUDENT)
Result

Course

Big Data

R language

Python Programming

Note
duplicate row is removed in the result

XII Std Computer Science 192

12th Computer Science_EM Chapter 11.indd 192 26-12-2022 16:46:13


Example 2 (using Table 11.1)
Πstudno, course (STUDENT)
Result
Studno Course
cs1 Big Data
cs2 R language
cs3 Big Data
cs4 Python Programming

UNION (Symbol :∪)


It includes all tuples that are in tables A or in B. It also eliminates duplicates. Set A
Union Set B would be expressed as A ∪ B
Example 3
Consider the following tables

Table A Table B

Studno Name Studno Name

cs1 Kannan cs1 Kannan

cs3 Lenin cs2 GowriShankarn

cs4 Padmaja cs3 Lenin


Table 11.2
Result
Table A ∪ B
Studno Name
cs1 Kannan
cs2 GowriShankar
cs3 Lenin
cs4 Padmaja

SET DIFFERENCE ( Symbol : - )


The result of A – B, is a relation which includes all tuples that are in A but not in B.
The attribute name of A has to match with the attribute name in B.
Example 4 ( using Table 11.2)

193 Database Concepts

12th Computer Science_EM Chapter 11.indd 193 26-12-2022 16:46:13


Result
Table A - B
cs4 Padmaja

INTERSECTION (symbol : ∩) A ∩ B
Defines a relation consisting of a set of all tuple that are in both in A and B. However, A
and B must be union-compatible.

Example 5 (using Table 11.2)

A∩B
cs1 Kannan
cs3 Lenin

PRODUCT OR CARTESIAN PRODUCT (Symbol : X )


Cross product is a way of combining two relations. The resulting relation contains, both
relations being combined.

A x B means A times B, where the relation A and B have different attributes.


This type of operation is helpful to merge columns from two relations.
Table A Table B Table A x Table B

1 S 1 S
2 1 R
R
3 2 S
2 R
Table A = 3
Table B = 2 3 S
Table A x B = 3 x 2 = 6
3 R
Cartesian Product
Fig. 11.12

Table A Table B
studno name course subject
cs1 Kannan cs28 Big Data
cs2 Gowri Shankar cs62 R language
cs4 Padmaja cs25 python programming
Table 11.3

XII Std Computer Science 194

12th Computer Science_EM Chapter 11.indd 194 26-12-2022 16:46:13


Cartesian product : Table A x Table B
studno name course subject
cs1 Kannan cs28 Big Data
cs1 Kannan cs62 R language
cs1 Kannan cs25 python rogramming
cs2 Gowri Shankar cs28 Big Data
cs2 Gowri Shankar cs62 R language
cs2 Gowri Shankar cs25 python programming
cs4 Padmaja cs28 Big Data
cs4 Padmaja cs62 R language
cs4 Padmaja cs25 python programming

Points to remember:
• DBMS is a computer based record keeping system
• Data is unprocessed data which contains any character, text, word or number
has no meaning
• Information is processed data, organized and formatted.
• Examples of RDBMS are mysql, oracle, sql server, ibm db2
• Redundancy means duplication of data in a database.
• Data Consistency means that data values are the same at all instances of a
database
• Data Integrity is security from unauthorized users
• Table is known a relation
• A row is called a tuple
• A column is known as an attribute
• Types of data model are Hierarchical, Relational, Network, ER and Object
model.
• Hierarchical model is a simple tree like structure form with one-to-many
relationship called parent-child relationship
• Relational Model represents data as relations or tables
• Network model is similar to Hierarchical model but it allows a record to have
more than one parent
• ER model consists of entities, attributes and relationships

195 Database Concepts

12th Computer Science_EM Chapter 11.indd 195 26-12-2022 16:46:13


Points to remember:
• Object model stores data as objects, attributes, methods, classes and inheritance
• Normalization reduces data redundancy and improves data integrity
• Different types of Relationship are one-to-one, one-to-many, many-to-one and
many-to-many relationships
• Database Normalization was proposed by Dr.Edgar F Codd
• Relational Algebra is used for modeling data stored in relational databases and
for defining queries on it.

Evaluation

Part - I

Choose the best answer (1 Mark)


1. What is the acronym of DBMS?
a) DataBase Management Symbol b) Database Managing System
c) DataBase Management System d) DataBasic Management System
2 A table is known as
a) tuple b) attribute
c) relation d) entity
3 Which database model represents parent-child relationship?
a) Relational b) Network
c) Hierarchical d) Object
4 Relational database model was first proposed by
a) E F Codd b) E E Codd
c) E F Cadd d) E F Codder
5 What type of relationship does hierarchical model represents?
a) one-to-one b) one-to-many
c) many-to-one d) many-to-many
6. Who is called Father of Relational Database from the following?
a) Chris Date b) Hugh Darween
c) Edgar Frank Codd d) Edgar Frank Cadd

XII Std Computer Science 196

12th Computer Science_EM Chapter 11.indd 196 26-12-2022 16:46:13


7. Which of the following is an RDBMS?
a) Dbase b) Foxpro
c) Microsoft Access d) Microsoft Excel
8 What symbol is used for SELECT statement?
a) σ b) Π c) X d) Ω
9 A tuple is also known as
a) table b) row
c) attribute d) field
10. Who developed ER model?
a) Chen b) EF Codd
c) Chend d) Chand

Part -II

Answer the following questions (2 Marks)


1. Mention few examples of a DBMS.
2. List some examples of RDBMS.
3. What is data consistency?
4. What is the difference between Hierarchical and Network data model?
5. What is normalization?
Part -III

Answer the following questions (3 Marks)


1. What is the difference between Select and Project command?
2. What is the role of DBA?
3. Explain Cartesian Product with a suitable example.
4. Explain Object Model with example.
5. Write a note on different types of DBMS users.
Part -IV
Answer the following questions (5 Marks)
1. Explain the different types of data model.
2. Explain the different types of relationship mapping.
3. Differentiate DBMS and RDBMS.
4. Explain the different operators in Relational algebra with suitable examples.
5. Explain the characteristics of RDBMS.

197 Database Concepts

12th Computer Science_EM Chapter 11.indd 197 26-12-2022 16:46:13


CHAPTER 12
Unit IV
STRUCTURED QUERY LANGUAGE (SQL)

Learning Objectives

After studying this lesson, students will be able to:


• The processing skills of SQL.
• The components of SQL.
• To create a table by specifying the fields and records.
• To apply various manipulations like inserting, updating and deleting records in a table.
• To learn about various constraints and to apply it on tables.
• To generate queries in the table by applying various clauses.
• To modify the structure of an existing table.
• The commands to delete records, table and revoke the commands.

12.1 Introduction to SQL

The Structured Query Language (SQL) is a standard programming language to access


and manipulate databases. SQL allows the user to create, retrieve, alter, and transfer information
among databases. It is a language designed for managing and accessing data in a Relational
Data Base Management System (RDBMS).
There are many versions of SQL. The original version was developed at IBM’s Research
centre and originally called as Sequel in early 1970’s. Later the language was changed to SQL.
In 1986, ANSI (American National Standard Institute) published an SQL standard that was
updated again in 1992, the latest SQL was released in 2008 and named as SQL 2008.

Note
Latest SQL standard as of now is SQL 2008, released in 2008.

12.2 Role of SQL in RDBMS

RDBMS stands for Relational DataBase Management System. Oracle, MySQL, MS SQL
Server, IBM DB2 and Microsoft Access are RDBMS packages. SQL is a language used to access
data in such databases.

XII Std Computer Science 198

12th Computer Science_EM Chapter 12.indd 198 22-12-2022 11:54:46


In general, Database is a collection of tables that store sets of data that can be queried
for use in other applications. A database management system supports the development,
administration and use of database platforms. RDBMS is a type of DBMS with a row-based
table structure that connects related data elements and includes functions related to Create,
Read, Update and Delete operations, collectively known as CRUD.
The data in RDBMS, is stored in database objects, called Tables. A table is a collection
of related data entries and it consist of rows and columns.
A field is a column in a table that is designed to maintain specific related information
about every record in the table. It is a vertical entity that contains all information associated
with a specific field in a table. The fields in a student table may be of the type AdmnNo,
StudName, StudAge, StudClass, Place etc.
A Record is a row, which is a collection of related fields or columns that exist in a table.
A record is a horizontal entity in a table which represents the details of a particular student in
a student table.

12.3 Processing Skills of SQL


The various processing skills of SQL are :
1. Data Definition Language (DDL) : The SQL DDL provides commands for defining
relation schemas (structure), deleting relations, creating indexes and modifying relation
schemas.
2. Data Manipulation Language (DML) : The SQL DML includes commands to insert,
delete, and modify tuples in the database.
3. Embedded Data Manipulation Language : The embedded form of SQL is used in high
level programming languages.
4. View Definition : The SQL also includes commands for defining views of tables.
5. Authorization : The SQL includes commands for access rights to relations and views of
tables.
6. Integrity : The SQL provides forms for integrity checking using condition.
7. Transaction control : The SQL includes commands for file transactions and control over
transaction processing.

SQL-Structured Query Language is a language used for accessing databases while


MySQL is a database management system, like SQL Server, Oracle, Informix,
Postgres, etc. MySQL is a RDBMS.

Refer installing MYSQL in Annexure -1

199 Structured Query Language

12th Computer Science_EM Chapter 12.indd 199 22-12-2022 11:54:46


12.4 Creating Database

1. To create a database, type the following command in the prompt:


CREATE DATABASE database_name;
Example:
CREATE DATABASE stud;
2. To work with the database, type the following command.
USE DATABASE;
For example to use the stud database created, give the command
USE stud;

12.5 Components of SQL

SQL commands are divided into five categories:

DML - Data Manipulation Language

DDL - Data Definition Language

DCL - Data Control Language

TCL - Transaction Control Language

DQL - Data Query Language

12.5.1 DATA DEFINITION LANGUAGE

The Data Definition Language (DDL) consist of SQL statements used to define the
database structure or schema. It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in databases.

The DDL provides a set of definitions to specify the storage structure and access
methods used by the database system.

A DDL performs the following functions :

1. It should identify the type of data division such as data item, segment, record and database
file.
2. It gives a unique name to each data item type, record type, file type and data base.

XII Std Computer Science 200

12th Computer Science_EM Chapter 12.indd 200 22-12-2022 11:54:46


3. It should specify the proper data type.
4. It should define the size of the data item.
5. It may define the range of values that a data item may use.
6. It may specify privacy locks for preventing unauthorized data entry.
SQL commands which comes under Data Definition Language are:
Create To create tables in the database.

Alter Alters the structure of the database.

Drop Delete tables from database.

Truncate Remove all records from a table, also release the space occupied by those records.

12.5.2 DATA MANIPULATION LANGUAGE


A Data Manipulation Language (DML) is a query language used for adding
(inserting), removing (deleting), and modifying (updating) data in a database. In SQL, the
data manipulation language comprises the SQL-data change statements, which modify stored
data but not the schema of the database table.
After the database schema has been specified and the database has been created, the
data can be manipulated using a set of procedures which are expressed by DML.

By Data Manipulation we mean,


• Insertion of new information into the database
• Retrieval of information stored in a database.
• Deletion of information from the database.
• Modification of data stored in the database.

The DML is basically of two types:


Procedural DML – Requires a user to specify what data is needed and how to get it.

Non-Procedural DML - Requires a user to specify what data is needed without


specifying how to get it.
SQL commands which comes under Data Manipulation Language are :

Insert Inserts data into a table

Update Updates the existing data within a table.

Delete Deletes all records from a table, but not the space occupied by them.

201 Structured Query Language

12th Computer Science_EM Chapter 12.indd 201 22-12-2022 11:54:46


12.5.3 DATA CONTROL LANGUAGE
A Data Control Language (DCL) is a programming language used to control
the access of data stored in a database. It is used for controlling privileges in the database
(Authorization). The privileges are required for performing all the database operations such as
creating sequences, views of tables etc.

SQL commands which come under Data Control Language are:

Grant Grants permission to one or more users to perform specific tasks.

Revoke Withdraws the access permission given by the GRANT statement.

12.5.4 TRANSACTIONAL CONTROL LANGUAGE


Transactional control language (TCL) commands are used to manage transactions
in the database. These are used to manage the changes made to the data in a table by DML
statements.

SQL command which come under Transfer Control Language are:

Commit Saves any transaction into the database permanently.

Roll back Restores the database to last commit state.

Save point Temporarily save a transaction so that you can rollback.

12.5.5 DATA QUERY LANGUAGE


The Data Query Language consist of commands used to query or retrieve data from a
database. One such SQL command in Data Query Language is

Select : It displays the records from the table.

12.6 Data Types

The data in a database is stored based on the kind of value stored in it. This is identified
as the data type of the data or by assigning each field a data type. All the values in a given field
must be of same type.
The ANSI SQL standard recognizes only Text and Number data type, while some
commercial programs use other datatypes like Date and Time etc. The ANSI data types are
listed in the following Table 12.1

XII Std Computer Science 202

12th Computer Science_EM Chapter 12.indd 202 22-12-2022 11:54:46


Data Type Description
char Fixed width string value. Values of this type is enclosed in single quotes.
(Character) For ex. Anu’s will be written as ‘Anu’ ‘s’.

Variable width character string. This is similar to char except the size of the
varchar
data entry vary considerably.

It represents a fractional number such as 15.12, 0.123 etc. Here the size
argument consist of two parts : precision and scale. The precision indicates
dec (Decimal) how many digits the number may have and the scale indicates the maximum
number of digits to the right of the decimal point. The size (5, 2) indicates
precision as 5 and scale as 2. The scale cannot exceed the precision.

It is same as decimal except that the maximum number of digits may not
numeric
exceed the precision argument.
int It represents a number without a decimal point. Here the size argument is
(Integer) not used.

smallint It is same as integer but the default size may be smaller than Integer.

It represents a floating point number in base 10 exponential notation and


float
may define a precision up to a maximum of 64.

It is same as float, except the size argument is not used and may define a
real
precision up to a maximum of 64.

double Same as real except the precision may exceed 64.


Table 12.1

12.7 SQL Commands and their Functions

Tables are the only way to store data, therefore all the information has to be arranged in
the form of tables. The SQL provides a predetermined set of commands to work on databases.

Keywords They have a special meaning in SQL. They are understood as instructions.

They are instructions given by the user to the database also known as
Commands
statements.

Clauses They begin with a keyword and consist of keyword and argument.

Arguments They are the values given to make the clause complete.

203 Structured Query Language

12th Computer Science_EM Chapter 12.indd 203 22-12-2022 11:54:46


12.7.1 DDL Commands
CREATE TABLE Command
You can create a table by using the CREATE TABLE command. When a table is created,
its columns are named, data types and sizes are to be specified. Each table must have at least
one column. The syntax of CREATE TABLE command is :

CREATE TABLE <table-name>


(<column name><data type>[<size>]
(<column name><data type>[<size>]……
);

Now let us use the above syntax to store some information about the students of a class
in a database, for this you first need to create table. To create a student table, let us take some
information related to students like admission number which we can use it in short form as
(admno), name of student (name), gender, age etc. of the student. Let us create a table having
the field names Admno, Name, Gender, Age and Place.
The SQL command will be as follows:

CREATE TABLE Student


(Admno integer,
Name char(20),
Gender char(1),
Age integer,
Place char(10),
);

The above one is a simple table structure without any restrictions. You can also set
constraints to limit the type of data that can go into the fields of the table. Constraints are used
to limit the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the database. Constraints could be either on a column level or a table level.

Note
Constraint is a condition applicable on a field or set of fields.

Column constraint: Column constraint apply only to individual column.

Table constraint : Table constraint apply to a group of one or more columns.

XII Std Computer Science 204

12th Computer Science_EM Chapter 12.indd 204 22-12-2022 11:54:46


The syntax for a table created with constraint is given as below:

CREATE TABLE <table-name>


(<column name><data type>[<size>]<column constraint>,
<column name><data type>[<size>]<column constraint>……
<table constraint>(<column name>,[<column name>….]…..
);

Following is an example for student table with “NOT NULL” column constraint. This
constraint enforces a field to always contain a value.
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Name char(20) NOT NULL,
Gender char(1),
Age integer,
Place char(10),
);

The above command creates a table “student” in which the field Admno of integer type
is defined NOT NULL, Name of char type is defined as NOT NULL which means these two
fields must have values. The fields Gender, Age and Place do not have any constraints.
12.7.2 Type of Constraints
Constraints ensure database integrity, therefore known as database integrity constraints.
The different types of constraints are :
Unique Constraint
Primary Key Constraint
Constraint
Default Constraint
Check Constraint

12.7.2.1 Unique Constraint


This constraint ensures that no two rows have the same value in the specified columns.
For example UNIQUE constraint applied on Admno of student table ensures that no two
students have the same admission number and the constraint can be used as:

205 Structured Query Language

12th Computer Science_EM Chapter 12.indd 205 22-12-2022 11:54:47


CREATE TABLE Student
(
Admno integer NOT NULL UNIQUE, → Unique constraint
Name char (20) NOT NULL,
Gender char (1),
Age integer,
Place char (10),
);

The UNIQUE constraint can be applied only to fields that have also been declared as
NOT NULL.
When two constraints are applied on a single field, it is known as multiple constraints. In
the above Multiple constraints NOT NULL and UNIQUE are applied on a single field Admno,
the constraints are separated by a space and at the end of the field definition a comma(,) is
added. By adding these two constraints the field Admno must take some value ie. will not be
NULL and should not be duplicated.

12.7.2.2 Primary Key Constraint


This constraint declares a field as a Primary key which helps to uniquely identify a
record. It is similar to unique constraint except that only one field of a table can be set as
primary key. The primary key does not allow NULL values.
Example showing Primary Key Constraint in the student table:

CREATE TABLE Student


(
Admno integer PRIMARY KEY, → Primary Key constraint
Name char(20) NOT NULL,
Gender char(1),
Age integer,
Place char(10),
);

In the above example the Admno field has been set as primary key and therefore will
help us to uniquely identify a record, it is also set NOT NULL, therefore this field value cannot
be empty.
12.7.2.3 DEFAULT Constraint
The DEFAULT constraint is used to assign a default value for the field. When no value
is given for the specified field having DEFAULT constraint, automatically the default value will
be assigned to the field.

XII Std Computer Science 206

12th Computer Science_EM Chapter 12.indd 206 22-12-2022 11:54:47


Example showing DEFAULT Constraint in the student table:

CREATE TABLE Student


(
Admno integer PRIMARY KEY,
Name char(20)NOT NULL,
Gender char(1),
Age integer DEFAULT 17, → Default Constraint
Place char(10)
);

In the above example the “Age” field is assigned a default value of 17, therefore when no
value is entered in age by the user, it automatically assigns 17 to Age.
12.7.2.4 Check Constraint
This constraint helps to set a limit value placed for a field. When we define a check
constraint on a single column, it allows only the restricted values on that field. Example
showing check constraint in the student table:
CREATE TABLE Student
(
Admno integer PRIMARY KEY
Name char(20)NOT NULL,
Gender char(1),
Age integer CHECK (Age <=19), → Check Constraint
Place char(10),
);

In the above example the check constraint is set to Age field where the value of Age
must be less than or equal to 19.

Note
The check constraint may use relational and logical operators for condition.

12.7.2.5 TABLE CONSTRAINT


When the constraint is applied to a group of fields of the table, it is known as Table
constraint. The table constraint is normally given at the end of the table definition. Let us take
a new table namely Student1 with the following fields Admno, Firstname, Lastname, Gender,
Age, Place:

207 Structured Query Language

12th Computer Science_EM Chapter 12.indd 207 22-12-2022 11:54:47


CREATE TABLE Student 1
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname) → Table constraint
);
In the above example, the two fields, Firstname and Lastname are defined as Primary
key which is a Table constraint.
12.7.3 DML COMMANDS
Once the schema or structure of the table is created, values can be added to the table.
The DML commands consist of inserting, deleting and updating rows into the table.

12.7.3.1 INSERT command


The INSERT command helps to add new data to the database or add new records to the
table. The command is used as follows:
INSERT INTO <table-name> [column-list] VALUES (values);

INSERT INTO Student (Admno, Name, Gender, Age, Place)


VALUES (100, ‘Ashish’, ‘M’, 17, ‘Chennai’);
INSERT INTO Student (Admno, Name, Gender, Age, Place)
VALUES (101, ‘Adarsh’, ‘M’, 18, ‘Delhi’);
Two new records are added to the table as shown below:
Admno Name Gender Age Placee
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi

The order of values must match the order of columns in the CREATE TABLE command.
Specifying the column names is optional if data is to be added for all columns. The command
to add values into the student table can also be used in the following way:
INSERT INTO Student VALUES ( 102, ‘Akshith’, ‘M’, 17, ‘Bangalore’);
102 Akshith M 17 Bangalore
The above command inserts the record into the student table.
To add data to only some columns in a record by specifying the column name and their data,
it can be done by:

XII Std Computer Science 208

12th Computer Science_EM Chapter 12.indd 208 22-12-2022 11:54:47


INSERT INTO Student(Admno, Name, Place) VALUES (103, ‘Ayush’, ‘Delhi’);
103 Ayush M 18 Delhi
The above command adds the following record with default values of ‘M’ for Gender and Age
as 18.
INSERT INTO Student (Admno, Name, Place) VALUES (104, ‘Abinandh’, ‘Chennai’);
104 Abinandh M 18 Chennai
The student table will have the following data:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
The fields that are not given in the INSERT command will take default values, if it is defined
for them, otherwise NULL value will be stored.

In the INSERT command the fields that are omitted will have either default value
defined or NULL value.

12.7.3.2 DELETE COMMAND


The DELETE command permanently removes one or more records from the table. It
removes the entire row, not individual fields of the row, so no field argument is needed. The
DELETE command is used as follows :

DELETE FROM table-name WHERE condition;


For example to delete the record whose admission number is 104 the command is given
as follows:
DELETE FROM Student WHERE Admno=104;
104 Abinandh M 18 Chennai

The following record is deleted from the Student table.


To delete all the rows of the table, the command is used as :
DELETE FROM Student;
The table will be empty now and could be destroyed using the DROP command
(Discussed in section 12.7.4.3).

209 Structured Query Language

12th Computer Science_EM Chapter 12.indd 209 22-12-2022 11:54:47


12.7.3.3 UPDATE COMMAND
The UPDATE command updates some or all data values in a database. It can update
one or more records in a table. The UPDATE command specifies the rows to be changed using
the WHERE clause and the new data using the SET keyword. The command is used as follows:

UPDATE <table-name> SET column-name = value, column-name = value,…


WHERE condition;
For example to update the following fields:
UPDATE Student SET Age = 20 WHERE Place = ῾Bangalore᾿;
The above command will change the age to 20 for those students whose place is “Bangalore”.
The table will be as updated as below:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 20 Bangalore
103 Ayush M 18 Delhi
To update multiple fields, multiple field assignment can be specified with the SET clause
separated by comma. For example to update multiple fields in the Student table, the command
is given as:
UPDATE Student SET Age=18, Place = ‘Chennai’ WHERE Admno = 102;
102 Akshith M 18 Chennai
The above command modifies the record in the following way.

Admno Name Gender Age Place


100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 18 Chennai
103 Ayush M 18 Delhi

12.7.4 Some Additional DDL Commands:

12.7.4.1 ALTER COMMAND


The ALTER command is used to alter the table structure like adding a column, renaming
the existing column, change the data type of any column or size of the column or delete the
column from the table. It is used in the following way :

ALTER TABLE <table-name> ADD <column-name><data type><size>;

XII Std Computer Science 210

12th Computer Science_EM Chapter 12.indd 210 22-12-2022 11:54:47


To add a new column “Address” of type ‘char’ to the Student table, the command is used as
ALTER TABLE Student ADD Address char;
To modify existing column of table, the ALTER TABLE command can be used with MODIFY
clause like wise:
ALTER TABLE <table-name> MODIFY<column-name><data type><size>;

ALTER TABLE Student MODIFY Address char (25);


The above command will modify the address column of the Student table to now hold 25
characters.
The ALTER command can be used to rename an existing column in the following way :
ALTER TABLE <table-name> CHANGE old-column-name new-column-name new column definition;

For example to rename the column Address to City, the command is used as :
ALTER TABLE Student CHANGE Address City char(20);
The ALTER command can also be used to remove a column or all columns, for example
to remove a particular column, the DROP COLUMN is used with the ALTER TABLE to
remove a particular field. The command can be used as:
ALTER TABLE <table-name> DROP COLUMN <column-name>;

To remove the column City from the Student table, the command is used as :

ALTER TABLE Student DROP COLUMN City;

12.7.4.2 TRUNCATE command


The TRUNCATE command is used to delete all the rows from the table, the structure
remains and the space is freed from the table. The syntax for TRUNCATE command is:
TRUNCATE TABLE table-name;

For example to delete all the records of the student table and delete the table the SQL statement
is given as follows:
TRUNCATE TABLE Student;
The table Student is removed and the space is freed.

12.7.4.3 DROP TABLE command


The DROP TABLE command is used to remove a table from the database. If you
drop a table, all the rows in the table is deleted and the table structure is removed from the
database. Once a table is dropped we cannot get it back, so be careful while using DROP
TABLE command.

211 Structured Query Language

12th Computer Science_EM Chapter 12.indd 211 22-12-2022 11:54:47


The table can be deleted by DROP TABLE command in the following way:

DROP TABLE table-name;

For example to delete the Student table:

DROP TABLE Student;


DELETE, TRUNCATE AND DROP statement:

The DELETE command deletes only the rows from the table based on
the condition given in the where clause or deletes all the rows from the
DELETE
table if no condition is specified. But it does not free the space containing
the table.

The TRUNCATE command is used to delete all the rows, the structure
TRUNCATE
remains in the table and free the space containing the table.

The DROP command is used to remove an object from the database. If you
DROP drop a table, all the rows in the table is deleted and the table structure is
removed from the database. Once a table is dropped we cannot get it back.

12.7.5 DQL COMMAND– SELECT command


One of the most important tasks when working with SQL is to generate Queries and
retrieve data. A Query is a command given to get a desired result from the database table. The
SELECT command is used to query or retrieve data from a table in the database. It is used to
retrieve a subset of records from one or more tables. The SELECT command can be used in
various forms:
Syntax of SELECT command :

SELECT <column-list>FROM<table-name>;

• Table-name is the name of the table from which the information is retrieved.

• Column-list includes one or more columns from which data is retrieved.

For example to view only admission number and name of students from the Student table the
command is given as follows:
If the Student table has the following data:

XII Std Computer Science 212

12th Computer Science_EM Chapter 12.indd 212 22-12-2022 11:54:47


Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
SELECT Admno, Name FROM Student;
The above SELECT command will display the following data:
Admno Name
100 Ashish
101 Adarsh
102 Akshith
103 Ayush
104 Abinandh
105 Revathi
106 Devika
107 Hema
To view all the fields and rows of the table the SELECT command can be given as
SELECT * FROM STUDENT;
12.7.5.1 DISTINCT Keyword
The DISTINCT keyword is used along with the SELECT command to eliminate
duplicate rows in the table. This helps to eliminate redundant data. For Example:
SELECT DISTINCT Place FROM Student;
Will display the following data as follows :

Place
Chennai
Bangalore
Delhi
In the above output you can see, there would be no duplicate rows in the place field.
When the keyword DISTINCT is used, only one NULL value is returned, even if more NULL
values occur.

213 Structured Query Language

12th Computer Science_EM Chapter 12.indd 213 22-12-2022 11:54:47


12.7.5.2 ALL Keyword
The ALL keyword retains duplicate rows. It will display every row of the table without
considering duplicate entries.
SELECT ALL Place FROM Student;
The above command will display all values of place field from every row of the table
without eliminating the duplicate entries.
Place
Chennai
Delhi
Bangalore
Delhi
Chennai
Chennai
Bangalore
Chennai
The WHERE clause in the SELECT command specifies the criteria for getting the
desired result. The general form of SELECT command with WHERE Clause is:
SELECT <column-name>[,<column-name>,….] FROM <table-name>WHERE condition>;

For example to display the students admission number and name of only those students who
belong to Chennai, the SELECT command is used in the following way :
SELECT Admno, Name, Place FROM Student WHERE Place = ῾Chennai᾿;

Admno Name Place


100 Ashish Chennai
104 Abinandh Chennai
105 Revathi Chennai
107 Hema Chennai
SELECT Admno, Name, Age FROM Student WHERE Age >= 18;
Admno Name Age
101 Adarsh 18
103 Ayush 18
104 Abinandh 18
105 Revathi 19
106 Devika 19
The relational operators like =, <, <=, >, >=, <> can be used to compare two values in
the SELECT command used with WHERE clause. The logical operaors OR, AND and NOT

XII Std Computer Science 214

12th Computer Science_EM Chapter 12.indd 214 22-12-2022 11:54:47


can also be used to connect search conditions in the WHERE clause. For example :
SELECT Admno, Name, Age, Place FROM Student WHERE (Age>=18 AND Place = ῾Delhi᾿);

Admno Name Age Place


101 Adarsh 18 Delhi
103 Ayush 18 Delhi
The SELECT command can also be used in the following ways:
SELECT Admno, Name, Age, Place FROM Student WHERE (Age>=18 OR Place =῾Delhi᾿);
SELECT Admno, Name, Place FROM Student WHERE (NOT Place =῾Delhi᾿);

12.7.5.3 BETWEEN and NOT BETWEEN Keywords


The BETWEEN keyword defines a range of values the record must fall into to make the
condition true. The range may include an upper value and a lower value between which the
criteria must fall into.
SELECT Admno, Name, Age, Gender FROM Student WHERE Age BETWEEN 18 AND 19;

Admno Name Age Gender


101 Adarsh 18 M
103 Ayush 18 M
104 Abinandh 18 M
105 Revathi 19 F
106 Devika 19 F

The NOT BETWEEN is reverse of the BETWEEN operator where the records not satisfying
the condition are displayed.
SELECT Admno, Name, Age FROM Student WHERE Age NOT BETWEEN 18 AND 19;

Admno Name Age


100 Ashish 17
102 Akshith 17
107 Hema 17

12.7.5.4 IN Keyword
The IN keyword is used to specify a list of values which must be matched with the
record values. In other words it is used to compare a column with more than one value. It is
similar to an OR condition.
For example :
SELECT Admno, Name, Place FROM Student WHERE Place IN (῾Chennai᾿, ῾Delhi᾿);

215 Structured Query Language

12th Computer Science_EM Chapter 12.indd 215 22-12-2022 11:54:47


Admno Name Place
100 Ashish Chennai
101 Adarsh Delhi
103 Ayush Delhi
104 Abinandh Chennai
105 Revathi Chennai
107 Hema Chennai
The NOT IN keyword displays only those records that do not match in the list.

For example:
SELECT Admno, Name, Place FROM Student WHERE Place NOT IN (῾Chennai᾿, ῾Delhi᾿);
will display students only from places other than “Chennai” and “Delhi”.
Admno Name Place
102 Akshith Bangalore
106 Devika Bangalore
NULL Value :
The NULL value in a field can be searched in a table using the IS NULL in the WHERE
clause. For example to list all the students whose Age contains no value, the command is used
as:
SELECT * FROM Student WHERE Age IS NULL;

Note
Non NULL values in a table can be listed using IS NOT NULL.

12.7.5.5 ORDER BY clause


The ORDER BY clause in SQL is used to sort the data in either ascending or descending
based on one or more columns.
1. By default ORDER BY sorts the data in ascending order.
2. We can use the keyword DESC to sort the data in descending order and the keyword ASC
to sort in ascending order.
The ORDER BY clause is used as :

SELECT <column-name>[,<column-name>,….] FROM <table-name>ORDER


BY <column1>,<column2>,…ASC| DESC ;

XII Std Computer Science 216

12th Computer Science_EM Chapter 12.indd 216 22-12-2022 11:54:47


For example :
To display the students in alphabetical order of their names, the command is used as

SELECT * FROM Student ORDER BY Name;

The above student table is arranged as follows :

Admno Name Gender Age Place


104 Abinandh M 18 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
100 Ashish M 17 Chennai
103 Ayush M 18 Delhi
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
105 Revathi F 19 Chennai

Note
The ORDER BY clause does not affect the original table.

12.7.5.6 WHERE clause


The WHERE clause is used to filter the records. It helps to extract only those records
which satisfy a given condition. For example in the student table, to display the list of students
of age18 and above in alphabetical order of their names, the command is given as below:
SELECT * FROM Student WHERE Age>=18 ORDER BY Name;

Admno Name Gender Age Place

104 Abinandh M 18 Chennai


101 Adarsh M 18 Delhi
103 Ayush M 18 Delhi
106 Devika F 19 Bangalore
105 Revathi F 19 Chennai
To display the list of students in the descending order of names of those students of age
18 and above the command is given as :
SELECT * FROM Student WHERE Age>=18 ORDER BY Name DESC;

217 Structured Query Language

12th Computer Science_EM Chapter 12.indd 217 22-12-2022 11:54:47

You might also like