GR 12 - CS - Quick Revision Notes and Important Questions
GR 12 - CS - Quick Revision Notes and Important Questions
GR 12 - CS - Quick Revision Notes and Important Questions
UNIT I
1. REVISION OF PYTHON
2. WORKING WITH FUNCTIONS
3. FILE HANDLING [TEXT FILES, BINARY FILES, CSV FILES]
4. DATA STRUCTURES – STACK OPERATION
UNIT 2
5. COMPUTER NETWORKS
UNIT 3
6. DATABASE MANAGEMENT
| Page : 1|
HARIKRISHNAN A S | PGT | CS
REVISION OF
BASICS OF PYTHON
Python (a computer language) :
Python is a powerful and high level language and it is an interpreted language.
It is widely used general purpose, high level programming language developed by Guido
van Rossum in 1991.
Python has two basic modes: interactive and script.
In interactive mode (python.exe/py.exe), the result is returned immediately after pressing
the enter key.
In script mode (IDLE), a file must be created and saved before executing the code to get
results.
Python’s Features:
Easy to use Object oriented language
Expressive language
Interpreted Language
Its completeness
Cross-platform Language
Fee and Open source
Variety of Usage / Applications
| Page : 2|
HARIKRISHNAN A S | PGT | CS
Basics of Python: Input
Tokens in Python
In a passage of text, individual words and punctuation marks are called tokens or lexical units or lexical
elements. The smallest individual unit in a program is known as Tokens. Python has following tokens
Keywords
Identifiers(Name)
Literals
Operators
Punctuators
Keywords in Python
There are 33 keywords in Python 3.7. This number can vary slightly in the course of time. All the
keywords except True, False and None are in lowercase and they must be written as it is. The list of
all the keywords is given below.
Operators in Python
Python language supports the following types of operators-
• Arithmetic Operators
• Relational Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
| Page : 3|
HARIKRISHNAN A S | PGT | CS
Operators in Python: Arithmetic
Assume a=10 and b=20
| Page : 4|
HARIKRISHNAN A S | PGT | CS
Operators in Python: Assignment
| Page : 5|
HARIKRISHNAN A S | PGT | CS
list=[1, 2, 3, 4, 5] Output
Control statements are used to control the flow of execution depending upon the specified
condition/logic. There are three types of control statements-
1. Decision Making Statements (if, elif, else)
2. Iteration Statements (while and for Loops)
3. Jump Statements (break, continue, pass)
| Page : 6|
HARIKRISHNAN A S | PGT | CS
Decision Making Program Output
Statements (if, elif, else) a=int(input("Enter any integer Enter any integer
Syntax: number :")) number :5
if(logic): if(a==0): Number is Positive
Statement/s print("Number is Zero")
elif(logic): elif(a>0):
Statemet/s print("Number is Positive")
else: else:
Statement/s print("Number is negative")
Iteration Statements (while Program: Output
loop) n=1 Govind Govind Govind
Syntax: while(n<4):
while(condition): print("Govind ", end=“ “)
Statement/s n=n+1
Iteration Statements (for Program Output
loop) for i in range(1,6): 12345
Syntax: print(i, end=' ')
for value in sequence:
Statements
Jump Statements (break, Program Output
continue, pass) for i in range(1,11): 1 2 hello 4 6 7
Syntax: if(i==3):
for val in sequence: print("hello", end=' ')
if (val== i): continue
break if(i==8):
if (val== j): break
continue if(i==5):
if (val== k): pass
pass else:
print(i, end=' ');
List in Python
Tuple in Python
It is a sequence of immutable objects. It is just like a list. Difference between a tuple and a list
is that the tuple cannot be changed like a list. List uses square bracket whereas tuple use
parentheses.
L=[1,2,3,4,5] Mutable Elements of list can be changed
T=(1,2,3,4,5) Immutable Elements of tuple can not be changed
Creating a tuple and accessing its elements Output
a=(10,20,'abc',30,3.14,40,50) (10, 20, 'abc', 30, 3.14, 40, 50)
print(a) 10 20 abc 30 3.14 40 50
for i in range(0,len(a)): 50 40 3.14 30 abc 20 10
print(a[i], end=' ') 50 40 3.14 30 abc 20 10
print('\n') 50 40 3.14 30 abc 20 10
for i in range(len(a)-1,-1,-1):
print(a[i], end=' ')
print('\n')
for i in a[::-1]:
print(i, end=' ')
print('\n')
for i in reversed(a):
print(i, end=' ')
Function Description
Dictionary in Python
Dictionary in Python is an unordered collection of data values, used to store data values along with the
keys. Dictionary holds key: value pair. Key value is provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a colon:, whereas each key is separated by a ‘comma’.
dict={ “a": “alpha", “o": “omega", “g": ”gamma” }
| Page : 8|
HARIKRISHNAN A S | PGT | CS
# Creating an empty Dictionary Output
Dict = {} Empty Dictionary:
print("Empty Dictionary: ") {}
print(Dict) Dictionary with the use of Integer Keys:
{1: ‘AAA', 2: ‘BBB', 3: ‘CCC'}
# Creating a Dictionary with Integer Keys Dictionary with the use of Mixed Keys:
Dict = {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'} {'Name': 'Govind', 1: [10, 11, 12, 13]}
print("\nDictionary with the use of Integer Keys: ") Dictionary with the use of dict():
print(Dict) {1: 'AAA', 2: 'BBB', 3: 'CCC'}
Dictionary with each item as a pair:
# Creating a Dictionary with Mixed keys
Dict = {'Name': ‘Govind', 1: [10, 11, 12, 13]} {1: 'AAA', 2: 'BBB'}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
| Page : 9|
HARIKRISHNAN A S | PGT | CS
# Creating a Dictionary Output
D = {1: ‘Prasad', 'name': ‘Govind', 3: ‘Arya'} Accessing a element using key: Govind
Accessing a element using key: Prasad
# accessing a element using key Accessing a element using get: Arya
print("Accessing a element using key:")
print(D['name'])
| Page : 13|
HARIKRISHNAN A S | PGT | CS
FUNCTIONS IN PYTHON
Learning Outcomes: Understand the concept of functions in Python.
Definition: It is simply a group of statements under any name i.e. function name and can be
invoked (call) from other part of program. Functions are the subprograms that perform specific task.
Functions are the small modules.
Types of Functions:
There are three types of functions in python:
Built in
functions
Types of Functions defined in
functions modules
User defined
functions
Library Functions: These functions are already built in the python library.
Functions defined in modules: These functions defined in particular modules. When you want to use
these functions in program, you have to import the corresponding module of that function.
User Defined Functions: The functions those are defined by the user are called user defined functions.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668
| Page : 14|
HARIKRISHNAN A S | PGT | CS
User defined functions:
Function Parameters:
functions has two types of parameters:
Formal Parameter: Formal parameters are written in the function prototype and function header of
the definition. Formal parameters are local variables which are assigned values from the arguments
when the function is called.
Actual Parameter: When a function is called, the values that are passed in the call are called actual
parameters. At the time of the call each actual parameter is assigned to the corresponding formal
parameter in the function definition.
Formal
Parameter
Actual
Parameter
| Page : 15|
HARIKRISHNAN A S | PGT | CS
Types of Arguments:
There are 4 types of Actual Arguments allowed in Python:
1. Positional arguments: are arguments passed to a function in correct positional order
2. Default arguments: we can provide default values for our positional arguments. In this case
if we are not passing any value then default values will be considered.
3. Keyword arguments: allows to call function with arguments in any order using name of the
arguments.
4. Variable length arguments: allow to call function with any number of arguments.
b. Function not returning any value : The function that performs some operations but does not return
any value, called void function.
def message():
print("Hello")
m=message()
print(m)
Output: Hello
None
| Page : 16|
HARIKRISHNAN A S | PGT | CS
Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function is not visible from outside. Hence, they have a local scope.
There are two types of scope for variables:
i) Local Scope
ii) Global Scope
Local Scope: Variable used inside the function. It cannot be accessed outside the function. In this
scope, the lifetime of variables inside a function is as long as the function executes. They are
destroyed once we return from the function. Hence, a function does not remember the value of a
variable from its previous calls.
Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a variable is
the period throughout which the variable exits in the memory.
Example 1:
Example 2:
def func2():
A=2
print("Value inside function:",A)
A=5
func2()
print("Value outside function:",A)
OUTPUT:
Value inside function: 2
Value outside function: 5
Here, we can see that the value of A is 5 initially. Even though the function func2() changed the
value of A to 2, it did not affect the value outside the function.
This is because the variable A inside the function is different (local to the function) from the one
outside. Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables using
the keyword global.
Example: Output:
| Page : 17|
HARIKRISHNAN A S | PGT | CS
Very Short
Answer Type Questions (1-Mark)
1. Name the built-in mathematical function / method that is used to return an absolute value of a
number.
Ans: abs()
2. Find and write the output of the following python code:
def myfunc(a):
a=a+2
a=a*2
return a
print(myfunc(2))
Ans:8
3. What is the default return value for a function that does not return any value explicitly?
Ans: None
4. Name the keyword use to define function in Python.
Ans: def
5. Predict the output of following code snippet:
def function1(a):
a=a+’1’
a=a*2
function1(‘Hello’)
Ans: Hello1Hello1
6. Variable defined in function referred to _________variable.
Ans: local
7. Name the argument type that can be skipped from a function call.
Ans: default arguments
8. Positional arguments can be passed in any order in a function call. (True/False)
Ans: False
9. Which of the following is function header statement is correct.
a. def fun(x=1,y) b. def fun(x=1,y,c=2) c. def fun(a,y=3)
Ans: c. def fun(a,y=3)
10. Predict the output of following code snippet.
def printDouble(A):
print(2*A)
print(3)
Ans: 3
Short Answer Type Questions (2-Marks)
1. What is the difference between a Local Scope and Global Scope ? Also, give a suitable Python code to
illustrate both.
Ans: A name declared in top level segment ( main ) of a program is said to have global scope and can
be used in entire program.
A name declare in a function body is said to have local scope i.e. it can be used only within this function
and the other block inside the function.
Global=5
def printDouble(A):
Local=10
| Page : 18|
HARIKRISHNAN A S | PGT | CS
print(Local)
print(Global)
3. Observe the following Python code very carefully and rewrite it after removing all syntactical errors
with each correction underlined.
DEF result_even( ):
x = input(“Enter a number”)
if (x % 2 = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
even ( )
Ans:
def result_even( ):
x = int(input(“Enter a number”))
if (x % 2 == 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
result_even( )
4. Differentiate between Positional Argument and Default Argument of function in python with
suitable example
Ans: Positional Arguments: Arguments that are required to be passed to the function according to their
position in the function header. If the sequence is changed, the result will be changes and if number of
arguments are mismatched, error message will be shown.
Example:
def divi(a, b):
print (a / b)
>>> divi(10, 2)
5.0
>>> divi (10)
Error
Default Argument: An argument that is assigned a value in the function header itself during the
function definition. When such function is called without such argument, this assigned value is used as
default value and function does its processing with this value.
def divi(a, b = 1):
print (a / b)
>>> divi(10, 2)
>>> 5.0
| Page : 19|
HARIKRISHNAN A S | PGT | CS
5. Ravi a python programmer is working on a project, for some requirement, he has to define a
function with name CalculateInterest(), he defined it as:
def CalculateInterest (Principal, Rate=.06,Time): # code
But this code is not working, Can you help Ravi to identify the error in the above function and
what is the solution.
Ans: In the function CalculateInterest (Principal, Rate=.06,Time) parameters should be default
parameters from right to left hence either Time should be provided with some default value or default
value of Rate should be removed.
6. Predict the output of the following python code:
def guess(s):
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'#'
print(m)
guess("welcome2kv")
Ans: vELCcME#Kk
7. What is the meaning of return value of a function? Give an example to illustrate its meaning.
Ans: Return value of a function is the value which is being given back to the main
program after the execution of function.
e.g.
def Check():
return 100
8. Differentiate between call by value and call by reference with a suitable example for each.
Ans: In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is
like call-by-value because you can not change the value of the immutable objects being passed to the
function. Whereas passing mutable objects can be considered as call by reference because when their values
are changed inside the function, then it will also be reflected outside the function.
9. Find and write the output of the following Python code:
def Show(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
| Page : 20|
HARIKRISHNAN A S | PGT | CS
Show('HappyBirthday')
Ans: hAPPYbIRTHDAY
10. Rewrite the following code in python after removing all syntax errors. Underline each correction
done in the code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
elseif i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
Ans:
def func(a): #def
s=m=n=0 #local variable
for i in range(0,a): #range function missing
if i%2==0:
s=s+i
elif i%5==0: #elif and colon
m=m+i
else:
n=n+i
print(s,m,n) #indentation
func(15)
1. Write a function listchange(Arr)in Python, which accepts a list Arr of numbers , the function will
replace the even number by value 10 and multiply odd number by 5 .
Sample Input Data of the list is:
a=[10,20,23,45]
listchange(a,4)
output : [10, 10, 115, 225]
Ans:
def listchange(arr,n):
l=len(arr)
for a in range(l):
if(arr[a]%2==0):
arr[a]=10
else:
arr[a]=arr[a]*5
a=[10,20,23,45]
listchange(a)
print(a)
2. Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers
and n is a numeric value by which all elements of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
| Page : 21|
HARIKRISHNAN A S | PGT | CS
Output
Arr = [30,40,12,11,10,20]
Ans:
def LShift(Arr,n):
L=Arr[n::]
R=Arr[:n:]
Arr=L+R
print(Arr)
3. Write a function REP which accepts a list of integers and size of list and replaces elements having
even values with its half and elements having odd values with twice its value. eg: if the list contains
3, 4, 5, 16, 9
then the function should rearranged list as
6, 2,10,8, 18
Ans:
def REP (L, n):
for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)
4. Write a function which accept the two lists, and returns a list having only those elements that are
common between both the lists (without duplicates) in ascending order.
Make sure your program works on two lists of different sizes. e.g.
L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
The output should be:
[1,2,3,5,8,13]
Ans: L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
L3=[]
temp_L1=list(set(L1))
temp_L2=list(set(L2))
for i in temp_L1:
for j in temp_L2:
if i==j:
L3.append(i)
L3.sort()
print(L3)
5. Write a user defined function countwords() to accept a sentence from console and display the total
number of words present in that sentence.
For example if the sentence entered by user is:
“Living a life you can be proud of doing your best.” then the countwords() function should display
the output as:
Total number of words : 11
Ans:
def countwords():
sen = input(“Enter a line : ”)
z = sen.split ()
print ("Total number of words:", len(z))
| Page : 22|
HARIKRISHNAN A S | PGT | CS
INTRODUCTION TO FILES
A file is an essential data item stored in one’s computer. Each file can be characterized with its
filename & file extension.
TYPES OF FILES
Computers store every file as a collection of 0s and 1s i.e., in binary form. Therefore, every file
is basically just a series of bytes stored one after the other. There are mainly two types of data
files — text file and binary file.
Text file
A text file consists of human readable characters, which can be opened by any text editor and
can be understood as a sequence of characters consisting of alphabets, numbers and other special
symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files. Each line
of a text file is terminated by a special character, called the End of Line (EOL). The default EOL
character in Python is the newline (\n).
CSV files
A CSV (comma-separated values) file is a text file that has a specific format which allows data
to be saved in a table structured format. CSV file is a delimited text file that uses a comma to
separate values. Each line of the file is a data record.
Binary File
Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these bytes do not
represent the ASCII values of characters. Rather, they represent the actual content such as image,
audio, video, compressed versions of other files, executable files, etc. These files are not human
readable. hence require specific programs to access its contents.
Absolute Path-name
An absolute path is defined as the specifying the location of a file or directory from the root
directory(/).To write an absolute path-name:
Start at the root directory ( / ) and work down.
Write a slash ( / ) after every directory name (last one is optional)
An absolute path is a complete path from start of actual file system from / directory.
Relative path
Relative path is defined as the path related to the present working directly(pwd). It starts at your
current directory and never starts with a /.
.(a single dot) - this represents the current directory.
..(two dots) - this represents the parent directory.
Example –
| Page : 23|
HARIKRISHNAN A S | PGT | CS
If we are presently in Directory roger, and want to change the directory to sean, then
command for –
Absolute path is – cd /Users/sean
Relative path is – cd ../../sean
TEXT FILE
1. Opening a text file - It is done using the open() function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, the full address of
the file should be written in place of the filename.
2. Text File open modes –
Modes Description
r Open text file for reading. The handle is positioned at the
beginning of the file. If the file does not exists, raises the
I/O error. This is also the default mode in which a file is
opened.
r+ Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if
the file does not exist.
w Open the file for writing. For the existing files, the data is
truncated and over-written. The handle is positioned at the
beginning of the file. Creates the file if the file does not
exist.
w+ Open the file for reading and writing. For an existing file,
data is truncated and over-written. The handle is positioned
at the beginning of the file.
a Open the file for writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The
data being written will be inserted at the end, after the
existing data.
a+ Open the file for reading and writing. The file is created if
it does not exist. The handle is positioned at the end of the
file. The data being written will be inserted at the end, after
the existing data.
3. Closing a text file – This is done by using close( ) function.
File_object.close( )
| Page : 24|
HARIKRISHNAN A S | PGT | CS
Here - file_path is the path to the file to open, and
Mode is the mode of operation on the file. Eg. read, write etc.
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means
use the current position as the reference position and if it is set to 2 then the end of the file
would be taken as the reference position.
EXAMPLE - Program to show various ways to read and write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
| Page : 25|
HARIKRISHNAN A S | PGT | CS
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth bite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
5 – Write a Python program that takes a text file as input and returns the number of words
of a given text file
number_of_words = 0
with open(r'SampleFile.txt','r') as file:
data = file.read()
| Page : 27|
HARIKRISHNAN A S | PGT | CS
# Splitting the data into separate lines using the split() function
lines = data.split()
BINARY FILE
1. Basic operations on a binary file –
a) Open using file open modes – The open() function opens a file in text format by default.
To open a file in binary format, add 'b' to the mode parameter.
b) Close a binary file – The close() method of a file object flushes any unwritten information
and closes the file object, after which no more writing can be done. Python automatically
closes a file when the reference object of a file is reassigned to another file. It is a good
practice to use the close() method to close a file.
Syntax – fileObject.close()
c) Import pickle module – Python pickle module is used for serializing and de-serializing a
Python object structure. Any object in Python can be pickled so that it can be saved on disk.
What pickle does is that it “serializes” the object first before writing it to file. Pickling is a
| Page : 28|
HARIKRISHNAN A S | PGT | CS
way to convert a python object (list, dict, etc.) into a character stream. The idea is that this
character stream contains all the information necessary to reconstruct the object in another
python script. Unpickling is a process by which original Python objects are retrieved from
the stored string representation i.e., from the pickle file. It converts the byte stream into a
Python object.
d) Dump and load method – We use dump() method to perform pickling operation on our
Binary Files. It returns the object representation in byte mode. The dump() method belongs
to pickle module. The reverse conversion of byte stream back to the structure (lists,
dictionary, tuples etc.) refers to unpickling. Basically it is the reverse operation of pickling.
This is also called de-serialization. We use load() method for unpickling.
e) Read, write/create a binary file – Use “rb” mode to open a binary file for reading contents
and “wb” mode for writing contents to a binary file.
For example – Writing in a binary file and then reading the contents and displaying it.
import pickle
file = open("binary.dat",'wb')
x = [1,2,3,4,5] #data we wrote in file
pickle.dump(x,file)
file.close()
file = open("binary.dat",'rb')
data = pickle.load(file)
file.close()
print(data)
f) Searching in a binary file – Searching in binary files involves reading of the binary file and
then comparing each record with our given value using linear search method.
| Page : 29|
HARIKRISHNAN A S | PGT | CS
g) Appending in a binary file – To append data to a binary file, open the file in “ab” mode. A
file opened in append mode will retain the previous records and append the new records at
the end of the file.
h) Updating a record in a binary file – In order to update a binary file, first the record to be
updated must be searched and the position of file pointer must be known. To check out the
position of the file pointer, we use two file pointer location functions – tell() and seek()
For example – A program to update record of a player in the binary file sports.dat
import pickle
import os # for remove() and rename()
f = open("Sports.dat","rb")
f1=open("temp.dat","wb")
pc = int(input("Player to code to update records:"))
f.seek(0)
while True:
current_pos = f.tell()
data= pickle.load(f)
for record in data:
if record[0]==pc:
record[1]=input("Enter Player Name to update:")
record[2]=input("Enter Individual Score to update:")
record[3]= input("Enter score to update:")
f.seek(current_pos)
pickle.dump(data,f1)
break
f.close()
os.remove("Sports.dat") # deletes the file passed
os.rename("temp.dat","Sports.dat") #renames first file name, with second filevname
| Page : 30|
HARIKRISHNAN A S | PGT | CS
2. Basic operations on csv files –
a) Open/ close csv file – The csv file is opened as a text filewith Python’s built-in function
open(). Closing a csv file is same as closing a text/binary file using function close().
b) Write into a csv file using csv.writer(), writerow() and writerows() – The csv.writer()
function returns a writer object that converts the user's data into a delimited string.
csv.writer class provides two methods for writing to CSV. They are –
writerow(): This method writes a single row at a time. Field row can be written using this
method.
writerows(): This method is used to write multiple rows at a time. This can be used to write
rows list.
For example –
import csv
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
c) Reading from a csv file using csv.reader() - At first, the CSV file is opened using the
open() method in ‘r’ mode(specifies read mode while opening a file) which returns the file
object then it is read by using the reader() method of CSV module that returns the reader
object that iterates throughout the lines in the specified CSV document.
For example –
import csv
# opening the CSV file
2. If the file is opened in write mode and already exists, it truncates the existing content and
places the filehandle at the beginning of the file.
a) True
b) False
7. Select the correct mode to open a file for appending as well as reading
a) a+
b) ar
c) rw
d) ar+
8. Select true statement when a file is opened using the with statement
a) The with statement makes exception handling complex
b) The file is automatically closed after leaving the block, and all the resources that are tied up
with the file are released.
c) File reading and writing are faster using the with statement.
d) None of these
| Page : 32|
HARIKRISHNAN A S | PGT | CS
9. Processing of a text file is faster than binary files
a) True
b) False
10. Which mode creates new file if the file does not exist?
a) Write
b) Append
c) Both a and b
d) None of the above
13. If the file pointer is at the end of 5th line in the file “Summary.txt”, then which of the
following options can be used to read the remaining lines?
a) f.read()
b) f.readlines()
c) f.read(all)
d) f.readline()
14. ______ module is used for serializing and de-serializing any Python object structure
a) csv
b) math
c) pickle
d) pandas
| Page : 33|
HARIKRISHNAN A S | PGT | CS
17. Almost all the files in our computer is stored as ________ file
a) Text
b) Binary
c) CSV
d) None
19. __________ function returns the current position of the file pointer.
a) seek()
b) tell()
c) cur()
d) get()
20. Which statement will move file pointer 10 bytes backward from the current position?
a) f.seek(-10,0)
b) f.seek(10,1)
c) f.seek(-10,1)
d) f.seek(-10,2)
Answer Key –
1. Madhur, a student of class 12th, is learning CSV File Module in Python. During
examination, he has been assigned an incomplete python code (shown below) to create
a CSV File ‘Student.csv’ (content shown below). Help him in completing the code
which creates the desired CSV File.
Incomplete Code
import_____ #Statement-1
fh = open(_____, _____, newline=”) #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’]
data.append(header)
| Page : 34|
HARIKRISHNAN A S | PGT | CS
for i in range(5):
roll_no = int(input(“Enter Roll Number : “))
name = input(“Enter Name : “)
Class = input(“Enter Class : “)
section = input(“Enter Section : “)
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
fh.close()
(i) Identify the suitable code for blank space in line marked as Statement-1.
a) csv file
b) CSV
c) csv
d) Csv
Correct Answer : c) csv
(ii) Identify the missing code for blank space in line marked as Statement-2?
a) “School.csv”,”w”
b) “Student.csv”,”w”
c) “Student.csv”,”r”
d) “School.csv”,”r”
Correct Answer : b) “Student.csv”,”w”
(iii) Choose the function name (with argument) that should be used in the blank space of line
marked as Statement-3
a) reader(fh)
b) reader(MyFile)
c) writer(fh)
d) writer(MyFile)
Correct Answer : c) writer(fh)
(iv) Identify the suitable code for blank space in line marked as Statement-4.
a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’
b) ROLL_NO, NAME, CLASS, SECTION
c) ‘roll_no’,’name’,’Class’,’section’
d) roll_no,name,Class,sectionc) co.connect()
Correct Answer : d) roll_no,name,Class,section
(v) Choose the function name that should be used in the blank space of line marked as
Statement-5 to create the desired CSV File?
a) dump()
b) load()
c) writerows()
d) writerow()
Correct Answer : c) writerows()
| Page : 35|
HARIKRISHNAN A S | PGT | CS
2. Amaira’s teacher asked her to count the no. of times words ‘he’ and ‘she’ comes in a
text file “poem.txt”. She wrote the code, but got confused in few statements. Help her
complete the following code.
(i) Which of the following modes to be used in Statement-1while opening the file?
a) w
b) r
c) a
d) w+
Answer – (b) r
(ii) What should come in statement-2 to read all the contents of the file as a single string?
a) read()
b) readline()
c) readlines()
d) load()
Answer – (a) read()
(iii) Which function should come in Statement-3 to get a list of words?
a) getlist()
b) splitstr()
c) split()
d) getword()
Answer – (c) split()
(iv) Which function should be used in Statement-4 to convert the string in uppercase?
a) toupper()
b) ToUpper()
c) uppercase()
d) upper()
Answer – (d) upper()
(v)What should be written in Statement-5 to close the file?
a) close(‘poem.txt’)
b) close()
c) end()
d) close(f)
Answer – (b) close()
| Page : 36|
HARIKRISHNAN A S | PGT | CS
3. Amit Kumar of class 12 is writing a program to store roman numbers and find their
equivalents using a dictionary. He has written the following code. As a programmer,
help him to successfully execute the given task.
| Page : 37|
HARIKRISHNAN A S | PGT | CS
(v) Fill in the blank in Line 4 to close the file.
a) close(file2)
b) close()
c) end()
d) close(“Roman.log”)
Answer – (b) close()
4. Manisha has been asked to write a code to count and display the no. of lines that starts
with ‘S’ in a text file MyFile.txt. She is not confident with few statements and left it
blank. Help her complete the code.
Answers:
1. File
2. File Handling
3. I/O Operations
4. Data file
5. Text File
6. open(“data.txt”,”r”)
7. open(“data.txt”,”w”)
8. File handle or File Object
9. close
10. read(15)
11. read()
12. readlines()
13. write()
14. writelines()
15. append
16. flush()
17. ASCII, UNICODE
18. CSV
19. open()
20. +
| Page : 39|
HARIKRISHNAN A S | PGT | CS
SHORT ANSWER QUESTIONS(2/3 marks)
2. Write a statement in Python to open a binary file named “First.dat” and add contents to it
without losing its contents.
Ans - F=open(“First.dat,”ab”)
3. What is the advantage of using ‘with’ clause in file handling for opening a file?
Ans - With keyword reduces the overheads involve in file handling operations like closing
the file after operation or handling the file closing with exceptions. When file is opened
using “with” it will manage these things i.e. file will be automatically closed after
operations. It ensures the closing of file even if exceptions arises.
4. Read the following Python code carefully and answers the question given after the code.
import pickle
infile = open('phonebook.dat', '_____') #Line 1
phonebook = __________(infile) #Line 2
print(phonebook)
infile.close()
a. Fill in the blank in line 1 to open file in binary mode for reading.
b. Fill in the blank in line 2 to read object from file.
Ans - (a) rb
(b) pickle.load
7. Write a Python program to find the number of lines in a text file ‘diary.txt’.
Ans - with open("diary.txt", 'r') as fp:
lines = len(fp.readlines())
print('Total Number of lines:', lines)
| Page : 40|
HARIKRISHNAN A S | PGT | CS
8. Write a function that counts and display the number of 5 letter words in a text file
“Sample.txt”
Ans - def count_words( ):
c=0
f = open("Sample.txt")
line = f.read()
word = line.split()
for w in word:
if len(w) == 5:
c += 1
print(c)
10. Write a python program to create and read the city.txt file in one go and print the
contents on
the output screen.
Answer:
# Creating file with open() function
f=open("city.txt","w")
f.write("My city is very clean city.")
f.close()
# Reading contents from city.txt file
f=open("city.txt","r")
dt = f.read()
print(dt)
f.close()
11. Consider following lines for the file friends.txt and predict the output:
f = open("friends.txt")
l = f.readline()
l2 = f.readline(18)
ch3=f.read(10)
print(l2)
print(ch3)
print(f.readline())
f.close()
| Page : 41|
HARIKRISHNAN A S | PGT | CS
Answer - Friends are honest
, Friends
are best !
12. Write a function display_oddLines() to display odd number lines from the text file.
Consider the
file – friends.txt.
Answer -
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
13. Write a function cust_data() to ask user to enter their names and age to store data in
customer.txt file.
Answer -
def cust_data():
name = input("Enter customer name:")
age=int(input("Enter customer age:"))
data = str([name,age])
f = open("customer.txt","w")
f.write(data)
f.close()
14. Write a function VowelCount() in Python, which should read each character of a text
file
Story.txt, should count and display the occurrence of alphabets vowels.
Example: If the file content is as follows:
Updated information As simplified by official websites.
The VowelCount() function should display the output as:
A or a:4
E or e :4
I or i :8
O or o : 0
U or u: 1
Answer –
def VowelCount():
count_a=count_e=count_i=count_o=count_u=0
f= open('MY_TEXT_FILE.TXT', 'r')
d=f.read()
for i in d:
if i.upper()=='A':
count_a+=1
elif letter.upper()=='E':
count_e+=1
elif letter.upper()=='I':
| Page : 42|
HARIKRISHNAN A S | PGT | CS
count_i+=1
elif letter.upper()=='O':
count_o+=1
elif letter.upper()=='U':
count_u+=1
print("A or a:", count_a)
print("E or e:", count_e)
print("I or i:", count_i)
print("O or o:", count_o)
print("U or u:", count_u)
| Page : 43|
HARIKRISHNAN A S | PGT | CS
DATA STRUCTURE
Basic concepts of Data Structure
Definition: The logical or mathematical model of a particular organization of data is
called data structure. It is a way of storing, accessing, manipulating data.
The last item inserted in a stack is the first one to be deleted. Therefore, a stack is called a Last-
In-First-Out (LIFO) data structure.
PUSH means inserting new item at top and POP means deleting item from top.
| Page : 44|
HARIKRISHNAN A S | PGT | CS
Terms related to stack:
Peek: getting the most recent value of stack i.e., value at TOP
Overflow: a situation when we are pushing item in stack that is full.
Underflow: a situation when we are popping item from empty stack.
def pop(stk):
if stk==[]:
return "underflow"
else:
x=stk.pop()
if stk==[]:
top=None
else:
top=len(stk)-1
return x
def peek(stk):
if stk==[]:
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if stk==[]:
print("Underflow")
else:
print ("Top === >",end= " ")
for item in stk[::-1]:
print(item)
while True:
print("============Stack Implementation============\n\n")
print("Enter 1 for Push : ")
print("Enter 2 for Pop : ")
print("Enter 3 for peek : ")
print("Enter 4 for dispaly : ")
print("Enter 5 for exit : ")
ch=int(input("Enter your choice : "))
| Page : 45|
HARIKRISHNAN A S | PGT | CS
if ch==1:
item= int(input("Enter your item for PUSH : "))
push(stk,item)
elif ch==2:
val=pop(stk)
print(val)
elif ch==3:
val=peek(stk)
print(val)
elif ch==4:
display(stk)
elif ch==5:
break
else:
print("Your choice is incorrect : ")
| Page : 46|
HARIKRISHNAN A S | PGT | CS
Short Answer Type Questions (2-marks)
1. Predict the output with respect to the Stack implemented using list:
stk=[11,22,25,40,60,45]
(a) print(stk) Ans: [11,22,25,40,60,45]
(b) print(len(stk)) Ans: 6
(c) stk.pop() ; print(stk) Ans:45
[11,22,25,40,60]
(d) stk.append(30); print(stk) Ans: [11,22,25,40,60,30]
| Page : 47|
HARIKRISHNAN A S | PGT | CS
2. Predict the output of following print statement with respect to the Stack , if push() is used to
append the element in Stack and Top holding the greatest index value of Stack :
Record=[[11,"Rohit"],[12,"John"],[13,"Sonal"]]
a) print(len(Record)) Ans: 3
b) print(Record[Top]) Ans: [13,"Sonal"]
c) pop(); pop(); push([15,"Ronit"]); print(Record) [[11,"Rohit"],[15,"Ronit"]
d) print(Record[Top][1]) Ans: ’Ronit’
Ans: a) [7,2,5] b) 5
| Page : 48|
HARIKRISHNAN A S | PGT | CS
3 Marks (Application Based Questions)
1. Write a function in Python PUSH(Num), where Num is a list of integer numbers. From this list push
all positive even numbers into a stack implemented by using a list. Display the stack if it has at least
one element, otherwise display appropriate error message.
Ans:
def PUSH(Num):
s=[]
for x in Num:
if x%2==0 and x>0:
s.append(x)
if len(s)==0:
print("STACK EMPTY")
else:
print(s)
2. Write a function in Python POP(cities), where cities is a stack implemented by a list of city names for
eg. cities=[‘Delhi’, ’Jaipur’, ‘Mumbai’, ‘Nagpur’]. The function returns the value deleted from the
stack.
Ans:
def POP(cities):
#For empty stack
if (len(cities)==0):
print("Under flow")
else:
P=cities.pop()
if len(cities)==0:
Top=None
else:
Top=len(cities)-1
return P
3. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers
divisible by 5 into a stack implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.
Ans:
def PUSH(Arr,value):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
| Page : 49|
HARIKRISHNAN A S | PGT | CS
4. Write a function in python, PushEl(e) to add a new element and PopEl(e) to delete a element from a
List , considering them to act as push and pop operations of the Stack data structure .
Ans:
def PushEl(element):
a=int(input("enter package title : "))
element.append(a)
def PopEl(element):
if (element==[]):
print( "Stack empty")
else:
print ("Deleted element:", element.pop())
5. Write a function POP(Book) in Python to delete a Book from a list of Book titles, considering it to act
as a pop operation of the Stack data structure.
Ans:
def POP(Book):
if (Book ==[]):
print(“Stack empty”)
else:
print(“Deleted element :”, Book.pop())
6. Write a function in Python PushBook(Book) to add a new book entry as book_no and book_title in the
list of Books , considering it to act as push operations of the Stack data structure.
Ans:
def PushBook(Book):
bno = input("enter book no : ")
btitle = input(“enter book title:”)
rec = [bno, btitle]
Book.append(rec)
print(Book)
7. Write a function AddCustomer(Name) in Python to add a new Customer information NAME into
the List of CStack and display the information.
Ans:
def AddCustomer(Name):
CStake.append(Customer)
if len(CStack)==0:
print (“Empty Stack”)
else:
print (CStack)
8. Write a function DeleteCustomer() to delete a Customer information from a listof CStack. The
function delete the name of customer from the stack
def DeleteCustomer():
if (CStack ==[]):
print(“There is no Customer!”)
else:
print(“Record deleted:”,CStack.pop())
| Page : 50|
HARIKRISHNAN A S | PGT | CS
COMPUTER NETWORKS
INFRARED - High frequencies, allow high speed data transmission, Line-of-sight transmission and can’t
penetrate through walls, trees etc. , Used in remotes of TV,AC etc.
RADIOWAVE – Used for short distance communication eg- Used for transmitting signals from mobile
towers to our mobile phones , No need of line of sight, Can penetrate through walls, trees etc. , Cheaper to
use than wired network, Used in AM and FM radio, television, cordless phones
MICROWAVE – Used for long distance telephonic communications. Eg- From tower to tower, Repeaters
are used at regular intervals (25-30 kms). The data signals are received, amplified and then retransmitted,
Can penetrate through walls, trees etc. but needs line of sight, hence Mobile towers are placed on top of the
buildings.
BLUETOOTH - Used for exchanging data over a short distance wirelessly. Approx range 10 meter, Data
transfer rate is slower than wired and wifi.
SATELLITE COMMUNICATION – Expensive and used for long distance communication such as
between countries and continents, TV Signals, Especially used for remote locations, difficult to reach with
general wired and wireless infrastructure, Also used to provide secure connection to military and VVIP
persons such President, PM etc.
WIFI – Stands for Wireless Fidelity, aka Wireless LAN or 802.11, Range around 100 meter, Used to
provide wireless internet, Uses Radio Waves
WIMAX – Stands for Worldwide Interoperability for Microwave Access , Similar to wifi but uses
Microwaves and large range of around 50 km, Expensive than Wifi
| Page : 52|
HARIKRISHNAN A S | PGT | CS
NETWORK DEVICES - Modem, RJ45 connector, Repeater, Ethernet Card, Hub, Router, Switch,
Gateway
MODEM - Stands for MODulator DEModulator , Used to covert analog to digital signals and vice versa.
RJ45 CONNECTOR – Stands for Registered Jack – 45 , Eight-pin connector used exclusively with
Ethernet cables for networking.
REPEATER - Repeater is an analog device that regenerates/boost weak signals, Required after every 100
meter in Ethernet / LAN Cables.
ETHERNET CARD – aka Network Interface Card ( NIC ), It is a network adapter installed in your
computer and acts as an interface between computer and the network. Each NIC has a MAC address, which
helps in uniquely identifying the computer on the network.
HUB - a network device used to connect different devices through wires, Cheaper and less Intelligent than
Switch , Broadcast signals i.e send signal to all connected computers.
SWITCH - A network device used to connect different devices through wires, Costly and Intelligent than
Hub, Unicast signals i.e send signal to only the destination node, Uses MAC Address to find out the
destination node.
ROUTER - A network device used to connect different devices through wires, Intelligent and costly than
Hub and Switch, Unicast signal and that too through shortest path possible, Uses IP Adresses to create a
routing table and decide shortest path on basis of it, Capable of connecting different networks also such as
wired lan and wireless wifi, Converting big data packets of one network to small packets supported by
destination different network.
GATEWAY - Gateway serves as the entry and exit point of a network, Maintain information about the
routing paths of data packets, the host network's internal connection paths and the identified paths of other
remote networks. Gateway can be software, hardware or both. Gateway consists of firewall which provide
functionalities such as access controls, security, virus protection , admin controls etc., In our homes our
Internet Service Provider (ISP) such as Jio act as gateway, In school, office 1st router acts as gateway.
| Page : 53|
HARIKRISHNAN A S | PGT | CS
STAR TOPOLOGY – Computers and the peripheral devices are
connected through a central device such as Hub / Switch .
Advantages –Simple and Easy to install and maintain, Fault detection easy, Failure of single system
will not bring down the entire network.
Disadvantages – Difficult to expand, If central device fails then whole network goes down,
Expensive than BUS as uses more cable length.
NETWORK TYPES – On the basis of coverage of area - PAN, LAN, MAN, WAN
PAN – Stands for Personal Area Network. Area Range around 10 meter. Small Network Organised
around an individual. It can be wired or wireless. Eg of PAN are Bluetooth, USB, Mouse, Wireless
Keyboard etc.
LAN – Stands for Local Area Network. Area Range around 1 km. Network inside an Office,School,
Hospital, Company etc. It can be wired or wireless.
MAN – Stands for Metropolitan Area Network. Area Range around 30-40 kms. Network inside a
city, big village, district etc.
WAN - Stands for Wide Area Network. Area Range > 40 kms. Network inside a state, country and
the whole world. Internet is an example of WAN.
NETWORK PROTOCOLS –
| Page : 54|
HARIKRISHNAN A S | PGT | CS
Protocol Definition - : Set of rules for communication among networked devices. These include
how and when a device can send and receive data, how it is packaged, how it reaches its destination
etc.Commonly used Protocols mentioned in our syllabus are –
TCP – stands for Transmission Control Protocol. Divides the data into packets for transmitting and
re-assemble received packets at the destination.
IP - stands for Internet Protocol. Responsible for routing the data packets to correct destination,
Provide unique IP Address for every device connected to internet.
PPP- stands for Point-to-Point Protocol. PPP is used with dial-up Internet connections including
ISDN. Used for transmitting the IP data packets over usual telephone lines.
FTP- stands for File Transfer Protocol -Used for transfer of files (upload/download) to or from a
remote server.
HTTP - stands for Hyper Text Transfer Protocol- Transfer data from one device to another on the
world wide web.
HTTPS - stands for Hypertext Transfer Protocol Secure. Advanced and secure version of HTTP.
GSM - stands for Global System for Mobile Communication. GSM technology is used for
transmitting voice and data using SIM (Subscriber Identification Module) cards in our mobiles.
GPRS – stands for General Packet Radio Service. Transmission of IP packets over existing cellular
networks. Multi-media Message Service (MMS), Internet Access via Mobiles and Data
Communication.
WLL – stands for Wireless Local Loop. It is a generic term for an access system that uses wireless
links rather than conventional copper wires to connect subscribers to the local telephone company’s
switch.
TELNET – aka Remote Login.Used for creating a connection with a remote
Computer.
Email Protocols – SMTP , POP3 - Simple Mail Transfer Protocol (SMTP) is used for sending E-
mail over the Internet.Your E-mail client uses SMTP to send a
message to the mail server and the mail server uses SMTP to relay/further send that message to the
correct receiving mail server.
POP3 - Post Office Protocol version 3 - Used to retrieve/download E-mail from a remote server to a
local email client. Once Retrieved emails can be read offline later.
VoIP – stands for Voice over Internet Protocol. Enables voice communications
over the Internet through the compression of voice into data packets. Eg- Whatsapp/Google Duo
voice / video call uses VoIP in background.
VoLTE – stands for Voice over Long Term Evolution.Enables high speed voice and data
communications over the 4G / LTE Networks.
| Page : 55|
HARIKRISHNAN A S | PGT | CS
MOBILE TELECOMMUNICATION TECHNOLOGIES:
MOBILE PROCESSOR -
Like CPU in a computer system, mobile processor receives and executes every command,
performing billions of calculations per second.
Components of Mobile Processors - Mainly the following three -
1. Application Processing Unit = Has the Control Unit of the mobile’s CPU ( Central Processing
Unit)
2. Graphics Processing Unit = Assists the CPU for handling the graphics.
3. Communications Processing Unit = for calling and call receiving via the phone’s middleware
A few more components in smartphone’s processors -
a. Camera ISP ( Image Signal Processing) b. Radio and 3G / 4G Modem
c. Memory Controller d. Audio / Video Engine
COMPUTER THREATS -
Viruses – Vital Information Resource Under Siege; Viruses are small programs that are written
intentionally to damage the data and files on a system; computer slows down; programs malfunction;
files destroyed. . Some well-known viruses include CryptoLocker, ILOVEYOU, MyDoom, Sasser
and Netsky etc.
Worms - a self-replicating program that runs independently. Unlike a virus, a worm does not need a
host program or software to insert its code into. Worms are standalone programs that are capable of
working on its own. Worms cause more damage. Examples of worms include Storm Worm, Sobig,
MSBlast, Code Red, Nimda etc.
Trojan horse - a kind of virus that looks safe but has hidden effects. It looks like a legitimate
software and once it tricks a user into installing it, it acts pretty much like a virus or worm.
| Page : 56|
HARIKRISHNAN A S | PGT | CS
Ransomware - Type of malware that targets user data. It either blocks the user from accessing their
own data or threatens to publish the personal data online and demands ransom payment against the
same. Popular example- WannaCry , in 2017, infected almost 200,000 computers across 150
countries.
Spyware - It records/collects the user/company data and sends the collected information to an
external entity without consent or knowledge of the user.
Adware - is a malware that is created to generate revenue for its developer. An adware displays
online advertisements using pop-ups, web pages, or installation screens. usually annoying, but
harmless.
Spam - Unwanted bulk mail which is sent by an unauthorized or unidentified person in order to eat
the entire disk space.
Keyloggers - record the keys pressed by a user on the keyboard and send it to external entity in
background. Using it very sensitive and personal information like passwords, emails, private
conversations, etc. can be revealed to an external entity without the knowledge of the user.
HACKING - Accessing a computer without authorization by engaging in harmless technical
experiments and fun learning activities, using computer programming skills etc.
CRACKING - A method by which a person gains unauthorized access to a computer with the
intention of causing damage.
THREAT PREVENTION – PREVENTIVE MEASURES AGAINST THREATS - 1.Using
antivirus, anti-malware, and other related software and updating them on a regular basis. 2. Always
check for https and a green padlock in the address bar while making payments online. 3. Never use
pirated on unlicensed software. Instead go for Free and Open Source Software (FOSS). 4. Applying
software updates and patches released by its manufacturers. 5. Taking a regular backup of important
data. 6. Enforcing firewall protection in the network. 7. Avoid entering sensitive (passwords, pins) or
personal information on unknown or public computers.8. Avoid clicking on links or downloading
attachments from unsolicited emails. 9. Scan any removable storage device with an antivirus
software before transferring data to and from it. 9. Remove all the programs that you don’t recognise.
10. Set strong passwords having atleast leangth of 8 characters and consisting of lower, upper,
special chars and numbers.
Firewall - A hardware or software or both that is used to prevent unauthorized access to or from a
computer network. Gateway in a network are preloaded with firewall. Also, Antivirus provides
personal firewall to your computer.
HTTPS - stands for Hypertext Transfer Protocol Secure. Advanced and secure version of HTTP.
CYBER LAW - Legal system of laws and regulatory aspects of issues of the internet. It can be local
or international.
CYBERCRIME - aka Computer-oriented crime, is a crime in which a computer and internet is
used. Cybercrimes can be against persons or against organisations or against the government
INDIAN IT ACT - "INFORMATION TECHNOLOGY ACT, 2000" [ITA- 2000] – Govt of India
enacted to Indian IT act in 2000 to define penalties and punishments related to Cyber Crimes.
The above Act was further amended/updated in 2008.
IPR - INTELLECTUAL PROPERTY RIGHTS –
Intellectual property rights are the rights given to persons over the creations of their minds.
Examples of IPR - Patents, Trademarks, Plant Varieties, Copyrights, Trade secrets, Industrial Design
rights etc.
Patent – Issued for new research and innovation. Eg- Covid Vaccine, 3D Printer
| Page : 57|
HARIKRISHNAN A S | PGT | CS
Trademark – Issued for unique logo, slogan, tagline, product design etc. eg- Apple,Nike logo
trademarks
Copyright – Issued automatically without applying for audio, video, book, software etc.
IPR ISSUES AND VIOLATIONS –
Plagiarism – Copying / Stealing someone’s copyrighted work without giving giving due creadit to
the original author.
WEB SERVICES :
WWW : World Wide Web is a combination of all resources and users on the Internet that are using
the Hypertext Transfer Protocol (HTTP) ; Sir Tim Berners -Lee (Born in London, UK) is the inventor
of WWW.
WEB BROWSER - Web browser is software program to navigate the web pages on the internet.
Examples - Google Chrome , Mozilla Firefox, Apple Safari, Internet Explorer etc.
WEB HOSTING -
Web hosting is the process of uploading/saving the web content on a web server to make it available
on WWW (World Wide Web).
Web 2.0 - Web 2.0 refers to new generation of dynamic and interactive websites.
| Page : 58|
HARIKRISHNAN A S | PGT | CS
URL – stands for Uniform Resource Locator - It is a unique address or path for each resource located
on the web. Every page on the web has a unique URL. Examples are: https://www.mhrd.gov.in ,
http://www.ncert.nic.in , http://www.airindia.in etc.
The most general form of a URL syntax is as follows:
Protocol:// <domain name> / <directory path>/<object name>
For example - https://www.ncert.nic.in/textbook/textbook.htm
DNS - Domain Name System / Domain Name Resolution - when the user types a domain name, the
domain names are translated into Internet Protocol (IP) addresses. The computers or machines,access
websites based on IP addresses.
100
meter
| Page : 59|
HARIKRISHNAN A S | PGT | CS
QUESTION BANK
SECTION –A (MULTIPLE CHOICE QUESTIONS)
1. Which of the following is a collection of independent computers and other hardware
interconnected by communication channels?
5. Network formed between computers which are spread across the continents is called
| Page : 60|
HARIKRISHNAN A S | PGT | CS
9. Which of the following topology contains a backbone cable running through the whole length of the
network?
11. Home page helps viewers to find out what they can find on the particular site. Home page is the
12. Which is the name of the network topology in which there are bi-directional links between each
possible node?
13. Computer connected to a star topology fails, the entire network will
15. In specific, if systems use separate protocols, which one of the following devices is used to link two
systems?
(a) connect to Internet (b) create websites (c) view sites on web (d) All of the
above
| Page : 61|
HARIKRISHNAN A S | PGT | CS
18. By default, web pages are saved in the ……… folder.
(a) Satellite
(b) Microwave
(d) Wi-Fi
(a) Optical Fibre Cable (b) Radio wave (c) Bluetooth (d) Satellite
24.In which topology are all the nodes connected through a single Coaxial cable?
25.Which protocol is used for the transfer of hypertext content over the web?
26. Central Computer which is powerful than other computers in the network is called as _____.
| Page : 62|
HARIKRISHNAN A S | PGT | CS
(a) Client (b) Server (c) Hub (d) Switch
28. Which transmission media is capable of having a much higher bandwidth (data capacity)?
(a) Coaxial (b) Twisted pair cable (c) Untwisted cable (d) Fiber optic
29. A device that forwards data packet from one network to another is called a
30.Hub is a
(a) Broadcast device (b) Uni-cast device (c) Multi-cast device (d) None of the above
(a) 32 bit (b) 64 bit (c) 128 bit (d) 256 bit
34. What are two advantages of using fiber-optic cabling instead of UTP ? (Choose two.)
(a) lower cost (b) easier to install (c) allows longer distances (d) less effected by external signals
(a) HTML documents (b) Graphic files (c) audio and video files (d) all the above
37. Which of the following is not a unit for data transfer rate ?
______is a communication methodology designed to deliver both voice and multimedia communications
over Internet protocol.
| Page : 63|
HARIKRISHNAN A S | PGT | CS
39. In which of the topology, network components are connected to the same cable?
40. Network formed between computers which are spread across the continents is called
Ans 2. (d)
Ans 3. (a)
Ans.4 (c)
Ans. 5 (b)
Ans.6 (c)
Ans.7 (a)
Ans.8 (b)
Ans. 9 (b)
Ans.10 (b)
Ans. 11(a)
Ans. 12 (b)
Ans. 13 (b)
Ans. 14 (c)
Ans. 15 (b)
Ans. 16 (d)
Ans.17 (d)
Ans.18 (b)
Ans 20 (a)
Ans 21. ( d )
Ans 22. (a )
Ans 23. ( a )
| Page : 64|
HARIKRISHNAN A S | PGT | CS
Ans 24. ( c )
Ans 25. ( b )
Ans 26. ( b )
This section has ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
Q 2 - Assertion - In circuit switching generally wastage of bandwidth happen more as compared to packet
switching.
Reason - As in packet switching, packets can travel through different paths but in circuit switching all
packets travel through same path.
| Page : 65|
HARIKRISHNAN A S | PGT | CS
Q 3 Assertion - Cookies help to load website faster on next visit.
Reason - Cookies are small files which store website related data.
Reason:- It is a technology that allows you to make voice calls using a broadband internet connection
instead of a regular phone line.
Reasoning:- They may only change if the actual HTML file is manually edited.
Q6. Assertion:- The internet is the world wide system of computer networks.
Reasoning:-All computers on the internet communicate with each other using POP/IMAP protocol which is
the basic protocol of Internet.
Q7. Assertion:- Browser is the software to access internet based webpages in the computer.
Reasoning:-LAN Is a network where two or more computers are connected within few Kms.
1. C
2. A
3. A
4. A
5. A
7. B
Ans:- The disadvantage of VoIP is that the call quality is dependent on the internet speed.
| Page : 66|
HARIKRISHNAN A S | PGT | CS
Q5.Identify the following devices
(i) An intelligent device that connects several nodes to form a network and redirects the received
information only to intended node(s).
(ii) A device that regenerates (amplifies) the received signal and re-transmits it to its destinations.
Q7:- Aman wants to connect 5 computers located at different locations in school.NAme the network
formed in school
Ans:- LAN
Ans:- Internet.
Ans :- MAN.
Ans:- Telnet
Ans:
Q13:-Which type of network (out of LAN, PAN and MAN) is formed, when you connect two mobiles using
Bluetooth to transfer a video?
Ans: PAN
b)Each node is connected with the help of independent cable with central switching.
Ans:
| Page : 67|
HARIKRISHNAN A S | PGT | CS
a)Bus topology
b)Star topology
Q15:- Manu wants to transfer data within a city at very high speed. Write the wired transmission medium
and type of network.
Ans: Wired transmission medium – Optical fibre cable Type of network – MAN.
Q16. Which protocol helps us to transfer files to and from a remote computer ?
Ans Computer networking refers to interconnected computing devices that can exchange data and share
resources with each other. These networked devices use a system of rules, called communications
protocols, to transmit information over physical or wireless technologies.
Ans PAN/LAN/MAN/WAN
Ans:- Cookies are small pieces of text sent to your browser by a website you visit. They help that website
remember information about your visit, which can both make it easier to visit the site again and make the
site more useful to you.
| Page : 68|
HARIKRISHNAN A S | PGT | CS
Q6. Write a short note on Web Hosting.
Ans: Hosting (also known as Web site hosting, Web hosting, and Webhosting) is the business of housing,
serving, and maintaining files for one or more Web sites. More important than the computer space that is
provided for Web site files is the fast connection to the Internet.
Ans: A browser is software that accesses and displays pages and files on the web. Browsers require a
connection to the Internet (e.g., through a cable modem, a direct Ethernet connection, or Wi-Fi). Popular
web browsers include Firefox, Internet Explorer, and Safari
Ans. In message switching, data packets are stored on the disk while in packet switching, all the packets of
fixed size are stored in main memory making it more efficient as compared to other switching techniques.
Internet Intranet
Q10. Write one advantage and one disadvantage of using optical fibre cable.
Ans. Advantage of using optical fibre cable It is immune to electrical and magnetic interference, i.e. the
data does not get disturbed and pure data is retrieved on the other end.
Disadvantage of using optical fibre cable Connecting either two fibres together or a light source to a fibre is
a difficult process.
| Page : 69|
HARIKRISHNAN A S | PGT | CS
Q12. What is the difference between star topology and bus topology of network?
Ans. Differences between star topology and bus topology are as follows :
All the nodes are directly connected with the central node or server.
There is a single length of transmission medium on which various nodes are attached and the server can be
anywhere in the transmission cable.
It is fast in transmission
Ans. A tree topology is an extension and variation of bus topology. Its basic structure is like an inverted
tree, where the root acts as a server.
Limitations
Q14. What is protocol? Which protocol is used to copy a file from/to a remote server?
Ans. Protocol is a set of rules that two or more computers must follow to communication on network. FTP
(File Transfer Protocol) is used to copy a file from/to a remotely located server.
Ans:- The definition of an e-mail is a message sent from one computer to another over the Internet, using a
set webmail server address. An example of an e-mail is a happy birthday message a person sends from
their Yahoo account to their mom at her Gmail account.
Ans. A hub connects several computers together and acts as a central node or server.
Function of a hub
● All the incoming data packets received by the hub are send to all hub ports and from their, the data
is sent to all the computers, connected in a hub network.
(i) Active hub It acts as repeater. It amplifies the signal as these move from one device to another.
| Page : 70|
HARIKRISHNAN A S | PGT | CS
(ii) Passive hub It simply passes the signal from one connected device to another.
Web browser is a software application for retrieving, presenting and traversing information on the world
wide web.
Ans. XML was designed to describe data and to focus on what data is. HTML was designed to display data
and to focus on how data looks.
Ans:
The sharing of compute resources (dedicated, time-shared, or dynamically shared servers) and related
infrastructure components (load balncers, firewalls, network storage, developer tools, monitors and
management tools) to facilitate the deployment and operation of web and network based applications.
Cloud computing relies on sharing of resources to achieve coherence and economies of scale, similar to a
utility (like the electricity grid) over a net-work.
Ans: A repeater is an electronic device that receives a signal and retransmits it at a higher level and/ or
higher power, or onto the other side of an obstruction, so that the signal can cover longer distances.
Q23. Differentiate between packet switching and message switching technique in network communication.
Answer:
In packet switched network, data are transmitted in discrete units of potentially variable length blocks called
packets, while in message switching mechanism, a node receives a message stores it until the appropriate
route is free, then sends it along.
| Page : 71|
HARIKRISHNAN A S | PGT | CS
SECTION-E LONG ANSWER QUESTIONS (CASE STUDY/ CCT BASED QUESTIONS)
Q1. Be Happy Corporation has set up its new centre at Noida, Uttar Pradesh for its office and web-based
activities. It has 4 blocks of buildings.
A to B -40m
B to C - 120 m
C to D - 100m
A to D - 170 m
B to D - 150m
A to C - 70m
Block A 25
Block B 50
Block C 125
Block D 10
(a) Suggest and draw the cable layout to efficiently connect various blocks of buildings within the Noida
centre for connecting the digital devices.
(i) Repeater : between C and D as the distance between them is 100 mts
(ii)Hub/ Switch : in each block as they help to share data packets within the devices of the network in each
block
(c) Which kind of network (PAN/LAN/WAN) will be formed if the Noida office is connected to its head office
in Mumbai?
Ans: WAN
(d) Which fast and very effective wireless transmission medium should preferably be used to connect the
head office at Mumbai with the centre at Noida?
Ans: Satellite
Q2. In the mid-’80s another federal agency, the NSF created a new high capacity network called NSFnet,
which was more capable than ARPANET.
| Page : 72|
HARIKRISHNAN A S | PGT | CS
The only drawback of NSFnet was that it allowed only academic research on its network and not any kind
of private business on it.
Now, several private organisations and people started working to build their own networks, named private
networks, which were later (in the 1990s) connected with ARPANET and NSFnet to form the Internet. The
Internet really became popular in the 1990s after the development of the World Wide Web.
Ans. c
Ans. b
Ans. b
Internet society
| Page : 73|
HARIKRISHNAN A S | PGT | CS
Different computer
Ans. c
v) Internet access by transmitting digital data over the wires of a local telephone network is
provided by:
Leased line
Ans. b
vi) A piece of icon or image on a web page associated with another webpage is called ______
URL
Hyperlink
Plugin
Extension
Ans. b
Q3. Web server is a special computer system running on HTTP through web pages. The web page is a
medium to carry data from one computer system to another. The working of the web server starts from
the client or user. The client sends their request through the web browser to the web server. Web server
takes this request, processes it and then sends back processed data to the client. The server gathers all of
our web page information and sends it to the user, which we see on our computer system in the form of a
web page. When the client sends a request for processing to the web server, a domain name and IP
address are important to the web server. The domain name and IP address are used to identify the user on
a large network.
(a) IP addresses
Ans:- (b)
| Page : 74|
HARIKRISHNAN A S | PGT | CS
(ii) What does the web server need to send back information to the user?
(c) IP address
Ans:- (d)
Ans :- (a)
(iv) The ……… translates Internet domain and host names to IP address.
Ans :- (a)
(v) Computer that requests the resources or data from another computer is called as ……… .
(a) server
(b) client
ANs:- (b)
Q4. Hindustan Connecting World Association” is planning to start their offices in four major cities in India to
provide regional IT infrastructure support in the field of Education & Culture. The company has planned to
set up their head office in New Delhi in three locations and have named their New Delhi offices as “Sales
Office”, “Head Office” and “Tech Office”. The company’s regional offices are located at “Coimbatore”,
“Kolkata” and “Ahmedabad”. A rough layout of the same is as follows:
| Page : 75|
HARIKRISHNAN A S | PGT | CS
Approximate distances between these offices as per the network survey team is as follows:
In continuation of the above, the company experts have planned to install the following number of
computers in each of their offices:
1. Suggest network type (out of LAN, MAN, WAN) for connecting each of the following set of their offices: -
Head Office and Tech Office - Head Office and Coimbatore Office
2. Which device will you suggest to be procured by the company for connecting all the computers within
each of their offices out of the following devices? - Modem - Telephone - Switch/ Hub
3. Which of the following communication media, will you suggest to be procured by the company for
connecting their local offices in New Delhi for very effective and fast communication? -
4. Suggest a cable/ wiring layout for connecting the company’s local offices located in New Delhi.
5. The organization is planning to link its front office situated in the city in the hilly region where cable
connection is not feasible, so, suggest an economic way to connect it with reasonably high speed.
| Page : 76|
HARIKRISHNAN A S | PGT | CS
Ans 5:- Radiowave.
Q5:-Mr. GopiNath Associate Manager of Unit Nations corporate recently discovered that the
communication between his company’s accounts office and HR office is extremely slow and signals drop
quite frequently. These offices are 120 metre away from each other and connected by an Ethernet cable.
(i) Suggest him a device which can be installed in between the office for smooth communication.
(ii) What type of network is formed by having this kind of connectivity out of LAN, MAN and WAN?
Ans. (i) The device that can be installed between the office for smooth communication is repeater.
Q6:- Samarth is the harware engineer of “Happy School”. He has been given the task of installing a
i). Suggest the most suitable type of network topology he should use in order to maximise speed and
a. Bus Topology
b. Star Topology
c. Ring Topology
d. Mesh Topology
Ans : b
ii). In order to allow data transfer from server to only the intended computers which network device
Ans : a
iii). After setting up the lab and internet in the lab, Samarth is now required to enable videos and
animations to be played on the web browser for students of multimedia class. Which browser tool /service
can be used for the same?
Ans:- b
| Page : 77|
HARIKRISHNAN A S | PGT | CS
iv). During an international exchange programme the students need to connect to a classroom in Russia
using Skype. Samarth helps the students to connect. Which type of network service is being used ?
Ans: c
Q 7 Ramanpreet has to work on his science project which deals with electromagnetic waves. A lot of
research workis required by him for the same. He uses Google Chrome to search for the relevant matter.
a. Website
b. Web browser
c. Web Page
d. Web Page
Ans. (b)
ii). He finally locates some useful information and clicks on the link provided to access the website. The
a. Domain name
b. Web Page
c. URL
d. IP address
Ans. (c)
iii). As Ramanpreet works on his project, he collects and curates information. Whenever he clicks on the
link the same piece of information is shown and the content is not clickable. Ramanpreet is accessing a/an
_______ website.
a. Dynamic
b. Textual
c. Outdated
d. Static
Ans. (d )
a. sent from a website and stored in user’s web browser while a user is browsing a website
b. sent from user and stored in the server while a user is browsing a website
c. sent from root server to all servers
d. sent from the root server to other root servers
Ans. (a)
| Page : 78|
HARIKRISHNAN A S | PGT | CS
b. Hyper Text Markup Language
c. Hybrid Text Markup Language
d. Hyper Text Manipulation Language
Ans. (c)
Web server is a special computer system running on HTTP through web pages. The web page is a medium
to carry data from one computer system to another. The working of the webserver starts from the client or
user. The client sends their request through the web browser to the webserver. Web server takes this
request, processes it and then sends back processed data to the client. The server gathers all of our web
page information and sends it to the user, which we see on our computer system in the form of a web
page. When the client sends a request for processing to the web server, a domain name and IP address are
important to the webserver. The domain name and IP address are used to identify the user on a large
network.
Computer systems
Webpages of a site
Ans. b
ii) What does the webserver need to send back information to the user?
Home address
Domain name
IP address
Both b and c
Ans. d
iv) The _____ translates internet domain and host names to IP address
Domain name system
Routing information protocol
| Page : 79|
HARIKRISHNAN A S | PGT | CS
Google
Network time protocol
Ans. a
v) Computer that requests the resources/data from othercomputer is called ____ computer.
Server
Client
None of the above
a and b
ans. b
34 bit
32 bit
16 bit
64 bit
Ans. b
Q9:- TCP/IP, or the Transmission Control Protocol/Internet Protocol, is a suite of communication protocols
used to interconnect network devices on the internet. TCP/IP can also be used as a communications
protocol in a private computer network (an intranet or an extranet).TCP defines how applications can
create channels of communication across a network. It also manages how a message is assembled into
smaller packets before they are then transmitted over the internet and reassembled in the right order at
the destination address.
IP defines how to address and route each packet to make sure it reaches the right destination. Each
gateway computer on the network checks this IP address to determine where to forward the message.
TCP/IP uses the client-server model of communication in which a user or machine (a client) is provided a
service (like sending a webpage) by another computer (a server) in the network. Collectively, the TCP/IP
suite of protocols is classified as stateless, which means each client request is considered new because it is
unrelated to previous requests. Being stateless frees up network paths so they can be used continuously.
HTTP
DHCP
DNS
| Page : 80|
HARIKRISHNAN A S | PGT | CS
All of the above
Ans. d
ii)Which one of the following is not an application layer protocol used in internet?
iii) Which protocol assigns IP address to the client connected to the internet?
DHCP
IP
RPC
RSVP
Ans. a
computers on a network
standard
metropolitan communication
bandwidth
Ans. A
Q10. )Intelligent Hub India is a knowledge community aimed to uplift the standard of skills and knowledge in
the society. It is planning to setup its training centres in multiple towns and villages pan India with its head
offices in the nearest cities. They have created a model of their network with a city, a town and 3 villages as
given.
As a network consultant, you have to suggest the best network related solution for their issues/problems
raised
in (i) to (iv) keeping in mind the distance between various locations and given parameters.
| Page : 81|
HARIKRISHNAN A S | PGT | CS
Shortest distance between various locations:-
• In Villages, there are community centres, in which one room has been given as training center to
this organiza¬tion to install computers.
• The organization has got financial support from the government and top IT companies.
1. Suggest the most appropriate location of the SERVER in the YHUB (out of the 4 locations),
to get the best and effective connectivity. Justify your answer.
2. Suggest the best wired medium and draw the cable layout (location to location) to efficiently
connect vari¬ous locations within the YHUB.
3. Which hardware device will you suggest to connect all the computers within each location of
YHUB?
4. Which server/protocol will be most helpful to conduct live interaction of Experts from Head
office and people at YHUB locations?
| Page : 82|
HARIKRISHNAN A S | PGT | CS
(ii) Optical Fiber. Star topology
Q11. Vidya Senior Secondary Public School in Nainital is setting up the network between its different wings.
There are 4 wings named as SENIOR(S), JUNIOR(J), ADMIN(A) and HOSTEL(H).
Ans:- 1.
| Page : 83|
HARIKRISHNAN A S | PGT | CS
1. Server should be in Wing S as it has the maxi-mum number of computers. 1
2. All Wings need hub/switch as it has more than
one computer.
3. Since the distance is more, wireless transmission would be better. Radiowaves are reliable
and can travel through obstacles.
| Page : 84|
HARIKRISHNAN A S | PGT | CS
DATABASE MANAGEMENT
What is a Database?
Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. Let's discuss few examples.
WHY DO WE NEED DATABASE
Accuracy: *Ease of updating data:
Security of data: *Data integrity:.
Advantages of Database System
● Databases reduce Redundancy:. * Database controls Inconsistency:
● Database facilitates *Sharing of Data;
● Database ensures Security:. *Database maintains Integrity:
● Database enforce standards:
What is a Database Management System (DBMS)?
Database Management System (DBMS) is a collection of programs which enables its users to access
database, manipulate data, reporting / representation of data.
What is Relational Model
The relational model represents the database as a collection of relations. A relation is nothing but a table of
values. Every row in the table represents a collection of related data values. These rows in the table denote
a real-world entity or relationship.
Relational Model Concepts
Attribute: Each column in a Table. Attributes are the properties which define a relation. e.g.,
Student_Rollno, NAME,etc.
Tables – In the Relational model the, relations are saved in the table format. It is stored along with its
entities. A table has two properties rows and columns. Rows represent records and columns represent
attributes.
Tuple – It is nothing but a single row of a table, which contains a single record.
Relation Schema: A relation schema represents the name of the relation with its attributes.
Degree: The total number of attributes which in the relation is called the degree of the relation.
Cardinality: Total number of rows present in the Table.
Column: The column represents the set of values for a specific attribute.
Relation key - Every row has one, two or multiple attributes, which is called relation key.
Attribute domain – Every attribute has some pre-defined value and scope which is known as attribute
domain
Domain :It is a collection of values from which the value is derived for a column.
What is a Primary Key?
PRIMARY KEY is a column or group of columns in a table that uniquely identify every row in that table.
The Primary Key can't be a duplicate meaning the same value can't appear more than once in the table. A
table cannot have more than one primary key.
What is the Alternate key?
ALTERNATE KEYS is a column or group of columns in a table that uniquely identify every row in that
table. A table can have multiple choices for a primary key but only one can be set as the primary key. All
the keys which are not primary key are called an Alternate Key.
Example:
What is a Candidate Key?
| Page : 85|
HARIKRISHNAN A S | PGT | CS
CANDIDATE KEY is a set of attributes that uniquely identify tuples in a table. Candidate Key is a super
key with no repeated attributes. The Primary key should be selected from the candidate keys. Every table
must have at least a single candidate key. A table can have multiple candidate keys but only a single primary
key.
| Page : 86|
HARIKRISHNAN A S | PGT | CS
Getting listings of databases;
mysql> SHOW DATABASES;
Creating a database-
mysql> CREATE database <databasename>;
mysql> CREATE database myschool;
Deleting a database
mysql> DROP database <databasename>;
mysql> DROP database myschool;
After we have created the database we use the USE statement to change the current
mysql> USE <database name>;
mysql> USE myschool;
Getting listings of tables in database (myschool)
mysql> SHOW TABLES;
The command DESCRIBE is used to view the structure of a table.
mysql> DESCRIBE <tablename>;
mysql> DESCRIBE student;
To remove a table (DROP)
mysql> drop table <tablename>;
mysql> drop table student;
| Page : 88|
HARIKRISHNAN A S | PGT | CS
The GROUP BY clause combines all those records that have identical values in a particular field or a group
of fields. This grouping results into one summary record per group.
We can group records by using GROUP BY <column> clause with Select command. A group column is
chosen which has non-distinct (repeating) values like City, Job etc.
Lastname Fname City Class
Sharma Rajesh Jaipur 12
Kumar Kamal Kota 12
Saxena Rajeev Kota 10
Singh Rohit Ajmer 10
Verma Sachin Jaipur 11
Example:
| Page : 89|
HARIKRISHNAN A S | PGT | CS
s
EQUI-JOIN
The join, in which columns are compared for equality is called Equi-Join. A non-equi join specifies
condition with non-equality operator. In equi-join we put (*) in the select list therefore the common column
will appear twice in the output.
To understand the output, let's take 2 table one for employee (contains employee detail with deptno) and
another for department contains deptno and other department details.
Natural Join
The JOIN in which only one of the identical columns exists is called Natural Join. It is similar to Equi-join
except that duplicate columns are eliminated in Natural join that would otherwise appear in Equi-Join.
In natural join we specify the names of column to fetch in place of (*) which is responsible for
appearing common column twice in output.
Till now we have performed joining using traditional SQL method which is common to most of the RDBMS
software now we will learn MySQL style of joining using JOIN clause. MySQL support various options
with JOIN
Cartesian product using JOIN
Select * from shades JOIN color;
Or
Select * from shades CROSS JOIN color;
Equi – Join using JOIN
Select * from emp JOIN dept ON emp.deptno = dept.deptno;
Select * from emp JOIN dept ON emp.deptno = dept.deptno where salary>50000;
Natural – Join using JOIN
Select * from emp NATURAL JOIN dept
In NATURAL JOIN condition the join condition is not required it automatically joins based on the
common column value.
1. The clause of SELECT query allows us to select only those rows in the
results that satisfy a specified condition.
(a) Where (b) from (c) having (d) like
2. Which of the following function is used to FIND the largest value from the given
data in MYSQL?
(a) MAX () (b) MAXIMUM () (c) LARGEST () (c) BIG ()
3. The data types CHAR (n) and VARCHAR (n) are used to
create and
types of string/text fields in a database.
(a) Fixed, equal (b) Equal, variable (c) Fixed, variable (d) Variable, equal
4. The term _ is use to refer to a record in a table.
(a) Attribute (b) Tuple (c) Row (d) Instance
5. A relational database consists of a collection of
(a) Tables (b) Fields (c) Records (d) Keys
6. Which is the subset of SQL commands used to manipulate database structure including tables?
| Page : 91|
HARIKRISHNAN A S | PGT | CS
(a) Data Definition Language (DDL) (b) Data Manipulation Language (DML)
(c) Both (a) and (b) (d) None
7. The term is used to refer to a field in a table.
(a) Attribute (b) Tuple (c) Row (d) Instance
8. Consider the following table namely employee:
Employee_id Name Salary
5001 Amit 60000
| Page : 92|
HARIKRISHNAN A S | PGT | CS
VERY SHORT ANSWER QUESTIONS (1 MARKS EACH)
Q1. Name the command/clause which is used to display the records in ascending or
descend
ing order.
Answer: Order by
Q2. Give example of any two DML commands.
Answer: Insert , Delete
Q3. What is the purpose of SQL?
Answer: SQL is
structured query language. It is a standard language of all the RDBMS
Q4. What is primary key?
Answer: A field
which is unique for each and every record in table is called primary key.
Q5. Which command is used to display a list of already existing tables?
Answer: show tables;
Q6. Which command is used to change the structure of table?
Answer: Alter
Q7. Which command is used to change the data of the table?
Answer: Update
Q8. Which command is used to delete data of the table?
Answer: Delete
Q9. Which command delete the structure of table?
Answer: Drop
Q10. Identify the DDL and DML commands from the following: Create, Delete
Answer: DDL: create, DML:insert
Q11. Which clause is used with aggregate functions? (Group by/ Where)
Answer: Group by
Q12. What do you mean by candidate key?
Answer: Those
fields which can act as primary key is called candidate key.
Q13. Correct the error in the following query.
Select * from RECORD where Rname = %math%;
Answer: Select *
from RECORD where Rname like %math%;
Q14. What is max () function in SQL?
Answer: Ans. It
returns the largest value from a particular column.
Q15. What do you mean by degree and cardinality of table?
Answer: Number of
columns in table is called degree. Number of rows in a table is
called cardinality.
Q16. Expand DDL and DML
Answer: DDL – Data Definition Language, DML – Data Manipulation
Language.
Q17. Which command is used to increase the salary of workers in table salary? (Update / Alter)
Answer: Update
Q18. What is the difference between char and varchar?
| Page : 93|
HARIKRISHNAN A S | PGT | CS
Answer: Char is fixed length data type and varchar is variable length data type.
in select list.
Answer: Distinct
5. To obtain all columns, use a(n) instead of listing all the column
names in the select list.
Answer: Asterisk (*)
6. The SQL clause contains the condition that specifies which rows
are to the selected. WHERE
Answer:
7. To sort the rows of the result table, the clause is specified.
Answer: Order by
8. Columns can be sorted in descending sequence by using the SQL keyword
Answer: DESC
9. When two conditions must both be true for the rows to be selected, the
conditions are separated by the SQL keyword
Answer: AND
10. To refer to a set of values needed for a condition, we can use the SQL operation
Answer: IN
11. To exclude one or more values (a list of values) using a condition, the SQL keyword
should be used.
Answer: NOT IN
12. The SQL keyword is used in SQL expressions to select based on patterns.
Answer: LIKE
13. The SQL built-in function totals values in numeric columns.
Answer: SUM
14. The SQL built-in function obtains the largest value in a numeric column.
Answer: MAX
| Page : 94|
HARIKRISHNAN A S | PGT | CS
SHORT ANSWER QUESTIONS (2 MARKS EACH)
def Search(eno):
#Assume basic setup import, connection and cursor is created
query="select * from emp where empno=
".fo
rmat(eno) mycursor.execute(query)
results = mycursor.
print(results)
Q. 5 Differentiate between DDL and DML with one Example each.
Q.6 Answer the following:
i) Name the package for connecting Python with MySQL database.
ii) What is the purpose of cursor object?
Q.7 What do you mean by domain of an attribute in DBMS? Explain with an example.
Q.8 Differentiate between fetchone() and fetchmany() methods with suitable examples.
Q.9 What is Constraint ? Give example of any two constraints.
Q.10 Write the steps to perform an Insert query in database connectivity
application. Table ‘student’ values are rollno, name, age
(10,’Ashok’,26)
Q.11 Define Candidate Key and Alternate Key with suitable examples from a table
containing some meaningful data.
Q.12 Define RDBMS. Name any two RDBMS software.
Q.13 What is the purpose of the following clauses in a select statement?
i) ORDER BY ii) HAVING
Q.14 Write SQL queries for the following:
i. Create the table Product with appropriate data types and constraints.
ii. Identify the primary key in Product.
Q.15 Write any two differences between Single_row functions and Aggregate functions.
| Page : 95|
HARIKRISHNAN A S | PGT | CS
ANSWERS-(SHORT ANSWER QUESTIONS (2 MARKS EACH)
ANS .1 Degree - The number of attributes or columns in a relation is called the Degree of
the relation.
Cardinality - The number of tuples/ rows in a relation is called the Cardinality
of the relation.
ANS.2 WHERE clause is used to select particular rows that satisfy a condition whereas
HAVING clause is used in connection with the aggregate function, GROUP BY clause.
For ex. – select * from student where marks > 75;
This statement shall display the records for all the students who have scored more than
75 marks. On the contrary, the statement – select * from student group by stream
having marks > 75; shall display the records of all the students grouped together on the
basis of stream but only for those students who have scored marks more than 75.
Ans.3 Primary Key- one or more attribute of a relation used to uniquely identify each
and every tuple in the relation. For Example : In the below Table Student, RollNo can
be the Primary
Key
| Page : 97|
HARIKRISHNAN A S | PGT | CS
CASE STUDY BASED QUESTIONS/SQL-OUTPUT QUESTIONS (3 MARKS)
Q1. Consider the following tables FACULTY and COURSES and give outputs for SQL queries
(i) to (iii)
FACULTY
F_ID Fname Lname Hire_date Salary
102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-5-2001 14000
105 Rashmi Malhotra 11-9-2004 11000
106 Sulekha Srivastava 5-6-2006 10000
COURSES
C_ID F_ID Cname Fees
C21 102 Grid Computing 40000
C22 106 System Design 16000
C23 104 Computer Security 8000
C24 106 Human Biology 15000
C25 102 Computer Network 20000
C26 105 Visual Basic 6000
i) Select COUNT(DISTINCT F_ID) from COURSES;
ii) Select MIN(Salary) from FACULTY,COURSES where
COURSES.F_ID = FACULTY.F_ID;
iii) Select avg(Salary) from FACULTY where Fname like ‘R%’
Q.2Write output for (i) & (iii) basedon a table COMPANY and CUSTOMER.
COMPANY
CUSTOMER
CUSTID NAME PRICE QTY CID
| Page : 98|
HARIKRISHNAN A S | PGT | CS
102 Deepak Kumar 50000 10 666
Q.3 Write output for (i) to (iii) based on the tables ‘Watches’ and ‘Sale’ given below.
Table: Watches
Watchid Watch_Name Price Type Qty_Store
W001 HighTime 10000 Unisex 100
W002 LifeTime 15000 Ladies 150
W003 Wave 20000 Gents 200
W004 HighFashion 7000 Unisex 250
W005 GoldenTime 25000 Gents 100
Table: Sale
Watchid Qty_Sold Quarter
W001 10 1
W003 5 1
W002 20 2
W003 10 2
W001 15 3
W002 20 3
W005 10 3
W003 15 4
i. select quarter, sum(qty_sold) from sale group by quarter;
ii. select watch_name,price,type from watches w, sale s wherew.watchid!=s.watchid;
iii. select watch_name, qty_store, sum(qty_sold), qty_store-sum(qty_sold)
“Stock” from watches
w, sale s where w.watchid=s.watchid group by s.watchid;
Q.4 Write the output for SQL queries (i) to (iii), which are based on the table:
Employees
| Page : 99|
HARIKRISHNAN A S | PGT | CS
244 Manila Sengupta Clerk New Delhi 50000
300 Robert Samuel Clerk Washington 45000
335 Ritu Tondon Clerk GZB 40000
400 Rachel Lee Salesman New York 32000
441 Peter Thompson Salesman Paris 28000
(i) Select Designation , count(*) from Employees Group by Designation Having
count(*)>=3;
(ii) Select Max (salary), Min(Salary) from Employees Where City in (‘GZB’,
‘Paris’);
(iii) Select Firstname, Lastname from Employees where Firstname like ‘R%’;
Q.5 Write output for queries (i) to (iii), which are based on the table:
Books.
Ans4.
(i) Mana ger 3
Clerk 3
(ii) 80000 28000
(iii) Ravi Kumar
Robert
Samuel Ritu
Tondon
Rachel Lee
Ans .5
(i) 3 (ii)650 (iii)TDH
Table: GRADUATE
S.N DI
NAME STIPEN D SUBJECT AVERAG E
O. V
1 KARAN 400 PHYSICS 68 1
2 DIVAKAR 450 COMPUTER SC 68 1
3 DIVYA 300 CHEMISTRY 62 2
4 ARUN 350 PHYSICS 63 1
5 SABINA 500 MATHEMATICS 70 1
6 JOHN 400 CHEMISTRY 55 2
7 ROBERT 250 PHYSICS 64 1
8 RUBINA 450 MATHEMATICS 68 1
9 VIKAS 500 COMPUTER SC 62 1
10. MOHAN 300 MATHEMATICS 57 2
(a) List the names of those students who have obtained DIV 1 sorted by NAME.
(b) Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend received
in a year assuming that the STIPEND is paid every month.
(c) To count the number of students who are either PHYSICS or COMPUTER SC graduates.
(d) To insert a new row in the GRADUATE table:
11, “KAJOL”, 300, “COMPUTER SC”, 75, 1
(e) Display Name of the students whose average is more than 65.
Q.2 Write SQL commands for (a) to (e) on the basis of table CLUB.
Table: CLUB
| Page : 101|
HARIKRISHNAN A S | PGT | CS
COACH COAC H AGE SPORTS DATEOFAP P PAY SE X
ID NAME
Table: NEWONES
NO ITEMNAME TYPE DATEOFSTOCKS PRICE DISCOUNT
11 White wood Double bed 23/03/03 20000 20
12 James 007 Sofa 20/02/03 15000 15
13 Tom look Baby cot 21/02/13 7000 10
(a) To show all information about the sofas from the INTERIORS table.
(b) To list the ITEMNAME which are priced at more than 10,000 from the INTERIORS table.
(c) To list ITEMNAME and TYPE of those items, in which DATEOFSTOC is before 22/01/02 from
the INTERIERS table in the descending order of discount
(d )To display ITEMNAME and DATEOFSTOCK of those items, in which the Percentage is more than 15
from INTERIORS table.
( e )To count the number of items, whose type is “Double Bed” from INTERIOR table.
4. Write SQL command for (a) to (e) on the bases of tables FURNITURE AND ARRIVALS.
Table: FURNITURE
| Page : 102|
HARIKRISHNAN A S | PGT | CS
NO. ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
1 White lotus Double Bed 23/02/02 30000 25
Table: ARRIVALS
NO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
a) To show all information about the baby cots from the FURNITURE table.
b) To list the ITEMNAME which are priced at more than 15000 from the FURNITURE table.
c) To list ITEMNAME AND TYPE of those items, in which DATEOFSTOCK is before 22/01/02from
the FURNITURE table in descending order of ITEMNAME.
d) To display ITEMNAME and DATEOFSTOCK of those items, in which the DISCOUNTpercentage
is more than 25 from FURNITURE table.
e) To insert a new row in the ARRIVALS table with the following data:14, “Velvet touch”, Double
bed”, {25/03/03}, 25000, 30
ANSWERS:
| Page : 103|
HARIKRISHNAN A S | PGT | CS
3. (a) Select * From INTERIORS Where TYPE = “Sofa”;
(b) Select ITEMNAME From INTERIORS Where PRICE > 10000;
(c) Select ITEMNAME, TYPE From INTERIORS Where DATEOFSTOCK < {22/01/02} Order by
ITEMNAME desc;
(d) Select ITEMNAME, DATEOFSTOCK From INTERIORS Where DISCOUNT
> 15;
(e) Select Count (*) From INFERIORS Where TYPE = “Double Bed”;
4. (a) Select * From FURNITURE Where TYPE = “Baby cot”;
(b) Select ITEMNAME From FURNITURE Where PRICE > 15000;
(c) Select ITEMNAME, TYPE From FURNITURE Where DATEOFSTOCK < {22/01/02} Order by
ITEMNAME desc;
(d) Select ITEMNAME, DATEOFSTOCK From FURNITURE Where DISCOUNT > 25.
(e) Insert Into ARRIVALS Values (14, “Velvet touch”, “Double bed”,{ 25/03/03},25000,30);
⮚ Database : It is defined as a collection of interrelated data stored together. It should be accurate, private
and protected from damage.
⮚ Domain : It is a pool of values from which the actual values appearing in a given column are drawn.
⮚ Degree : The number of attributes in a relation are known as the degree of a relation.
⮚ Cardinality : The number of rows in a relation are known as the degree of a relation.
⮚ Candidate Key : All attribute combinations inside a relation that can serve as primary key are
candidate keys as they are candidates for the primary key position.
⮚ Primary Key : It is a set of one or more attributes that can uniquely identify tuples within the relation.
⮚ Alternate Key : A candidate key that is not the primary key is called an alternate key.
⮚ Foreign Key : A non key attribute whose values are derived from the primary key of some other
tables.
| Page : 104|
HARIKRISHNAN A S | PGT | CS
⮚ Constraint : Rule and conditions set for data being stored in a database.
⮚ View : It is a virtual table that does not really exist in its right but is instead derived from one or more
underlying tables.
⮚ MySQL : It is a freely available open source Relational database management system that uses
structured query language.
⮚ Char vs Varchar : Char field has fixed length and varchar has variable length field.
1. A is a property of the entire relation, which ensures through its value that each tuple is 1
unique in a relation.
(a) Rows (b) Key (c) Attributes (d) Fields
3. Which one of the following uniquely identifies the tuples / rows in a relation. 1
(a) Secondary Key (b) Primary Key (c) Composite Key (d) Foreign Key
5. Which of the following is a group of one or more attributes that uniquely identifies a row? 1
(a) Key (b) Determinant (c) Tuple (d) Relation
6. Which of the following attributes cannot be considered as a choice for Primary Key ? 1
(a) Id (b) License number (c) Dept_Id (d) Street
| Page : 105|
HARIKRISHNAN A S | PGT | CS
11. In SQL, which of the following will select only one copy of each set of duplicate rows from a
table.
(a) SELECT UNIQUE
(b) SELECT DISTINCT
(c) SELECT DIFFERENT
(d) All of these.
12. Which of the following keywords will you use in the following query to display the unique 1
values of the column dept_name?
SELECT dept_name FROM COMPANY;
(a) All (b) From (c) Distinct (d) Name
13. The clause of SELECT query allows us to select only those rows in the result that satisfy a 1
specified condition.
(a) where (b) from (c) having (d) like
14. Which operator can take wild card characters for query condition? 1
(a) BETWEN (b) LIKE (c) IN (d) NOT
15. Which operator checks a value against a range of values? 1
(a) BETWEEN (b) LIKE (c) IN (d) NOT
16. Which of the following SQL commands retrives data from table(s) ? 1
(a) UPDATE (b) SELECT (c) Union (d) All of these
17. Which of the following queries contains an error ? 1
Which of the names will not be displayed by the below given query ?
(a) Misha, Khushi (b) Khushi, Japneet (c) Japneet (d)Misha, Japneet
19. Which operator perform pattern matching ? 1
(a) BETWEN (b) LIKE (c) IN (d) NOT
20. Consider the following query 1
SELECT name FROM class WHERE Subject LIKE ‘ Informatics Practices’;
Which one of the following has to be added into the blank space to select the subject
which has informatics practices as its ending string?
| Page : 106|
HARIKRISHNAN A S | PGT | CS
21. Which operator tests a column for the absence of data(i.e. NULL value) ? 1
(a) Exist Operator (b) NOT Operator (c) IS Operator (d) None of these
30.Consider the following SQL Statement. What type of statement is this ? INSERT INTO instructor VALUE
(10211, ‘SHREYA’ , ‘BIOLOGY’, 69000);
(a) Procedure (b) DML (c) DCL (d) DDL
31.Which of the following statements will delete all rows in a table namely mytablewithout deleting the table’
structure.
(a) DELETE FROM mytable;’
(b) DELETE TABLE mytable;
(c) DROP TABLE mytable;
(d) None of these.
| Page : 107|
HARIKRISHNAN A S | PGT | CS
32.Which of the following query will drop a column from a table ?
(a) DELETE COLUMN column_name;
(b) DROP COLUMN column_name;
(c) ALTER TABLE table_name DROP COLUMN column_name;
(d) None of these
33.Logical operator used in SQL are:
(a) AND, OR, NOT (b) &&, ||, ! (c) $,|,! (d) None of these
34. Which of the following requirement can be implemented using a CHECK constraint?
(a) Student must be greater than 18 years old.
(b) Student must be form a BRICS Country (Brazil, Russia, India, China, South Africa)
(c) Student’s roll number must exist in another table(say, namely Eligible)
(d) None of these
35. An attribute in a relation is termed as a foreign key when it reference the of another
relation.
(a) Foreign Key (b) Primary Key (c) Unique Key (d) Check Constraint
36. Data integrity constraints are used to : 1
(a) Control the access and rights for the table data.
(b) Ensure the entry of unique records in a table.
(c) Ensure the correctness of the data entered in the table as per some rule or condition
etc.
(d) Make data safe from accidental changes.
37. A relationship is formed via that relates two tables where one table references other table’s 1
key.
(a) Candidate Key (b) Primary Key (c) Foreign Key (d) Check Constraint
38. What is the maximum value that can be stored in NUMBERIC(4,2)? (a) 9999.99 (b) 99.99991
(c) 99.99 (d) 9.99
39. What should be the data type for the column Pricestoring values less than Rs.1000 e.g. 200.211
(a) VARCHAR(50) (b) NUMBER (c) NUMBER(5,2) (d) NUMBER(6)
41. Data manipulation language (DML) includes statements that modify the of the tables of 1
database.
(a) Structure (b) Data (c) User (d) Size
42. All aggregate functions ignore NULLs except for the function. 1
(a) Distinct (b) Count(*) (c) Average() (d) None of these
| Page : 108|
HARIKRISHNAN A S | PGT | CS
44. Identify the correct INSERT queries from the following : 1
(a) INSERT INTO Persons(‘xxx1’, ‘yyy1’);
(b) INSERT INTO Persons(LastName, FirstName) Values (‘xxx’, ‘yyy’);
(c) INSERT INTO Persons Values(‘xxx1’ , ‘yyy1’);
(d) INSERT INTO Persons Value(‘xxx1’ , ‘yyy1’);
2. The command of SQL lets you make queries to fetch data from tables. 1
3. To remove duplicate rows from the result of a query, specify the SQL qualifier in 1
select list.
4. To obtain all columns, use a(n) instead of listing all the column names in the select 1
list.
5. The SQL clause contains the condition that specifies which rows are to be selected. 1
6. The SQL keyword is used in SQL expressions to select records based on patterns. 1
8. The null values in a column can be searched for in a table using in the 1
WHERE clause of SELECT query.
10. Columns can be sorted in descending sequence by using the SQL keyword . 1
| Page : 109|
HARIKRISHNAN A S | PGT | CS
20. command removes a table from a database permanently. 1
24. A column added via ALTER TABLE command initially contains value for all rows. 1
30. The clause is used in SELECT queries to specify filtering condition for groups. 1
33. The SQL built-in function computes the average of values in numeric columns. 1
34. The SQL built-in function obtains the largest value in a in numeric columns. 1
35. The SQL built-in function obtains the smallest value in a in numeric columns. 1
36. The SQL built-in function computes the number of rows in a table. 1
37. The functions that work with one row at a time are functions. 1
3. A common attribute of two tables is called a foreign key it is the primary key in one table and 1
the other table reference it.
4. Part of SQL which creates and defines tables and other database objects, is called DDL 1
| Page : 110|
HARIKRISHNAN A S | PGT | CS
5. Part of SQL which manipulates data in tables, is called TCL 1
6. Part of SQL which access and manipulates data in tables is called DML 1
10. The condition in a WHERE clause in a SELECT query can refer to only one value. 1
11. SQL provides the AS keyword, which can be used to assign meaningful column name to the 1
results of queries using the SQL built-in functions.
13. SELECT DISTINCT is used if a user wishes to see duplicate columns in a query. 1
15. DELETE FROM <table> command is same as DROM TABLE <table> command. 1
16. The unique constraint can only be defined once in the CREATE TABLE command. 1
18. Tuple based constraints can use multiple columns of the table. 1
Q1. Name the command/clause which is used to display the records in ascending or descending order.
| Page : 111|
HARIKRISHNAN A S | PGT | CS
Q6. Which command is used to change the structure of table?
Q10. Identify the DDL and DML commands from the following: Create, Delete
Q11. Which clause is used with aggregate functions? (Group by/ Where)
Q17. Which command is used to increase the salary of workers in table salary? (Update / Alter)
Q21. Name an aggregate function in SQL which return the average of numeric values.
Q25. Write two wild card characters which are used with like operator?
| Page : 112|
HARIKRISHNAN A S | PGT | CS
SHORT ANSWER QUESTION (2 MARKS EACH)
Q.3 Define Primary Key of a relation in SQL. Give an Example using a dummy table.
Q.4 Consider the following Python code is written to access the record of CODE passed to function:
def Search(eno):
#Assume basic setup import, connection and cursor is created query="select * from emp where
Q5. Differentiate between DDL and DML with one Example each.
Q.7 What do you mean by domain of an attribute in DBMS? Explain with an example.
Q.8 Differentiate between fetchone() and fetchmany() methods with suitable examples.
Q.10 Write the steps to perform an Insert query in database connectivity application. Table ‘student’
Q.11 Define Candidate Key and Alternate Key with suitable examples from a table containing
| Page : 113|
HARIKRISHNAN A S | PGT | CS
CASE STUDY BASED QUESTIONS (3 MARKS EACH)
Q1. Consider the following tables FACULTY and COURSES and give outputs for SQL queries
(i) to (iii)
FACULTY
F_ID Fname Lname Hire_date Salary
102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-5-2001 14000
105 Rashmi Malhotra 11-9-2004 11000
106 Sulekha Srivastava 5-6-2006 10000
COURSES
C_ID F_ID Cname Fees
C21 102 Grid Computing 40000
C22 106 System Design 16000
C23 104 Computer Security 8000
C24 106 Human Biology 15000
C25 102 Computer Network 20000
C26 105 Visual Basic 6000
Q2. Write output for (i) & (iii) basedon a table COMPANY and CUSTOMER.
COMPANY
CID NAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE
666 DELL DELHI LAPTOP
CUSTOMER
| Page : 114|
HARIKRISHNAN A S | PGT | CS
(i) SELECT COUNT(*) ,CITY FROM COMPANY GROUP BY CITY;
(ii) SELECT MIN(PRICE), MAX(PRICE) FROM CUSTOMER WHERE QTY>10 ;
(iii) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
Q.3 Write output for (i) to (iii) based on the tables ‘Watches’ and ‘Sale’ given below.
Table: Watches
Watchid Watch_Name Price Type Qty_Store
W001 HighTime 10000 Unisex 100
W002 LifeTime 15000 Ladies 150
W003 Wave 20000 Gents 200
W004 HighFashion 7000 Unisex 250
W005 GoldenTime 25000 Gents 100
Table: Sale
Watchid Qty_Sold Quarter
W001 10 1
W003 5 1
W002 20 2
W003 10 2
W001 15 3
W002 20 3
W005 10 3
W003 15 4
Q4. Write the output for SQL queries (i) to (iii), which are based on the table:
Employees
| Page : 115|
HARIKRISHNAN A S | PGT | CS
400 Rachel Lee Salesman New York 32000
441 Peter Thompson Salesman Paris 28000
Q5. Write output for queries (i) to (iii), which are based on the table: (Relation name : BOOKS)
1. Write SQL commands for (a) to (e) on the basis of table GRADUATE.
(a) List the names of those students who have obtained DIV 1 sorted by NAME.
(b) Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend received in a year
assuming that the STIPEND is paid every month.
(c) To count the number of students who are either PHYSICS or COMPUTER SC graduates.
| Page : 116|
HARIKRISHNAN A S | PGT | CS
(e) Display Name of the students whose average is more than 65.
2. Write SQL commands for (a) to (e) on the basis of table CLUB.
COAC H COAC H AGE SPORTS DATEOFAP P PAY SE X
ID NAME
(a) To show all information about the swimming coaches in the club.
(b) To list names of all coaches with their date of appointment (DATOFAPP) in descending order.
(c) To display a report, showing coachname, pay, age and bonus (15% of pay) for all the coaches.
(d) To insert in a new row in the CLUB table with the following data: 11, “PRAKASH”, 37, “SQUASH”,
{25/02/98}, 2500, “M”
3. Write SQL commands for (a) to (e) on the basis of table INTERIORS and NEWONES.
| Page : 117|
HARIKRISHNAN A S | PGT | CS
(a) To show all information about the sofas from the INTERIORS table.
(b) To list the ITEMNAME which are priced at more than 10,000 from the INTERIORS table.
( c) To list ITEMNAME and TYPE of those items, in which DATEOFSTOCK is before 22/01/02 from
the INTERIERS table in the descending order of ITEMNAME.
(d ) To display ITEMNAME and DATEOFSTOCK of those items, in which the discount percentage is
more than 15 from INTERIORS table.
( e )To count the number of items, whose type is “Double Bed” from INTERIOR table.
4. Write SQL commands for (a) to (e) on the basis of table FURNITURE AND ARRIVAL.
ARRIVAL
(b) To list the ITEMNAME which are priced at more than 15000 from the FURNITURE table.
| Page : 118|
HARIKRISHNAN A S | PGT | CS
(c) To list ITEMNAME AND TYPE of those items, in which DATEOFSTOCK is before 22/01/02from
the FURNITURE table in descending order of ITEMNAME.
(d) To display ITEMNAME and DATEOFSTOCK of those items, in which the DISCOUNTpercentage is
more than 25 from FURNITURE table.
(e) To insert a new row in the ARRIVALS table with the following data:14, “Velvet touch”, Double bed”,
{25/03/03}, 25000, 30.
5. Write SQL commands for (a) to (e) on the basis of table TEACHER.
TEACHER
6. A library uses a database management system (DBMS) to store the details of the books that it stocks, it
registered members and the book-loans that the library has made. These details are stored in a database using
the following three relations.
(a) Identify the table that uses a composite primary key from the library database.
(i) Book Table (ii) Member Table (iii) Loan Table (iv) all of these
| Page : 119|
HARIKRISHNAN A S | PGT | CS
(b) Identify the possible alternate keys from relations Book and Member.
(i) Book : Title (ii) Books Author (iii) Member:EmailID (iv) Member:FirstName
(c) Can the Loan relation have an alternate key ?Why ?
(d) Write an example of the valid record for the loan relation. Write a query to insert a valid record in the
Loan relation.
(e) Write a SQL query to retrieve the names and email addresses of the members who have not returned
their books.
7. A library uses database management system(DBMS) to store the details of the books that it stocks, its
registered membes and the book-loan that the library has made. These details are stored in a database using
the following three relations.
Name of the Database : KV Library
(a) Identify following types of keys from all the relations of the given database Foreign keys along with parent
relations.
(b) Can a relation have multiple foreign keys? Give example.
(c) Can a foreign key be part of a primary key? Give example.
(d)Write a SQL query to retrieve the names and email addresses of the members belonging to KVS (they have
email ids as [email protected]) and wo have not returned their books.
8. FurnFly is a furniture company selling furniture to customers of its store and operates a follows:
• The store does not keep the furniture in stock.
• The company places orders for the furniture required from its suppliers ONLY AFTER a customer places
an order at the store.
• When the ordered furniture arrives at the store, the customer is informed via telephone or e-mail that it is
ready for delivery.
• Customers often order more than one type of furniture on the same order, for example, a sofa, two puffy
chairs and centre table.
Details of the furniture, customers and orders are to be stored in a relational database using the following four
relations :
Database Name : FurnFly Furnishers
Furniture (FurnitureID : Char(7), FurnitureName : Varchar(50), Category : Varchar(25), Price : Float,
SupplierName : Varchar(100))
| Page : 120|
HARIKRISHNAN A S | PGT | CS
CustomerOrder(OrderId : Number(8,0), CustomerID : Char(10), OrderDate:Date) CustomerOrderLine
:(OrderID : Number(8,0), FurnitureID: Char(7), Quantity: Number(4,0))
Customer :(CustomerID : Char(10), CustomerName:Varchar(100), EmailAddress : Varchar(30),
TelephoneNumber: Number(15,0))
(a) Identify the relationships among tables.
(b) Identify the relation having composite primary key and its primary key.
(c) Write a SQL query to create table customerOrder. It should also define required primary key and foreign
key(s)
(d) A fault has been identified with the furnitureID number 6281. The manager needs to
known how many orders need to be recalled. Write a SQL query for the same.
(e) A customer with ID number ‘C5104’ wants to change his registered telephone number
as 9988776655. Write a SQL query to achieve this.
9. Rachana Mittal runs a beauty parlor. She uses a database management system(DBMS) to store the
information that she needs to manage her business. This information includes customer contact details, staff
names, the treatments that the parlor offer (for example, ‘’Hair Massage’) and appointment that customers
have made for treatments. A separate appointment must be made for each treatment.
The details are stored in a database using the following four relations:
Customer: (CustomerID, FirstName, LastName, TelephoneNumber, EmailAddress)
Staff :(StaffID, FirstName,LastName, IsQualified)
Treatment: (TreatmentName,Price,TimeTaken,NeedsQualification)
Appointment : (CustomerID,TreatmentName,ApDate,ApTime)
• The IsQualifiedattribute for a member of staff stores one of the value True or False, to indicate if the member
of staff is fully qualified or not.
• The NeedsQualifictionattribute for a treatment stores True or False to indicate if the treatment can only be
given by a qualified member of staff.
• The TimeTakenattribute for a treatment is the number of minutes (a whole number) that the treatment takes.
(a) Write a SQL statement to create the table staff.
(b) Write a query to Insert a record in the table Staff with following data ; (2009, ‘Sheril’, ‘Mark’, ‘True’)
(c) Which table’s records can be deleted without affecting any other table?
(i) Customer (ii) Staff (iii) Treatment (iv) Appointment
(d) Write a query to Modify table Appointment to add a new column StaffID, which should hold a legal
StaffID value from the staff table.
(e) Rachana wants to send e-mail advertisement to all the customers who had a ‘RF
Facial’ treatmentin 2020. To send the email, the customer’s email address, firstname and lastname are needed.
Write a SQL query to retrieve the email address, firstname and lastname of each customer to whom email
should be sent.
| Page : 121|
HARIKRISHNAN A S | PGT | CS
RollNo Name Class DOB Gender City Marks
1 Anand XI 6/6/97 M Agra 430
2 Chetan XII 7/5/94 M Mumbai 460
3 Geet XI 6/5/97 F Agra 470
4 Preeti XII 8/8/95 F Mumbai 492
5 Saniyal XII 8/10/95 M Delhi 360
6 Maakhiy XI 12/12/94 F Dubai 256
7 Neha X 8/12/95 F Moscow 324
8 Nishant X 12/6/95 M Moscow 429
10. Consider the table STUDENT given below :
(i) Select Name from student where class= ‘XI’ and class=‘XII’;
(ii) Select Name from student where not class= ‘XI’ and class=‘XII’;
(iii) Select Name from student where city = ‘Agra’ or city = ‘Mumbai’;
(iv) Select Name from student where city IN(‘Agra’ , ‘Mumbai’);
Choose the correct option :
(i) Both (i) and (ii)
(ii) Both (iii) and (iv)
(iii) any of the option (i) , (ii) and (iv)
(iv) Only (iii)
(ii)
| Page : 122|
HARIKRISHNAN A S | PGT | CS
(iii)
Gender Marks
F 256
F 324
F 470
F 492
Gender Marks
F 492
F 470
F 324
F 256
(iv)
(c) Prachi has given the following command to obtain the highest marks.
SELECT max(Marks) from student where group by class;
But she is not getting the desired result. Help her by writing the correct command.
(a) Select max(Marks) from student where group by class;
(b) Select class, max(Marks) from student group by Marks;
(c) Select class, max(Marks) group by class from students;
(d) Select class, max(Marks) from student group by class;
(d) State the command to display the average marks scored by students of each gender who
are in class XI?
(a) Select Gender, avg(Marks) from student where class= ‘XI’ group by gender;
(b) Select Gender, avg(Marks) from student group by gender where class= ‘XI’;
(c) Select Gender, avg(Marks) group by Gender from student having class= ‘XI’;
(d) Select Gender, avg(Marks) from student group by Gender having class= ‘XI’;
(e) Help Ritesh to write the command to display the name of the youngest student.
(a) Select Name, min(DOB) from student;
(b) Select Name, max(DOB) from student;
(c) Select Name, min(DOB) from student group by Name;
| Page : 123|
HARIKRISHNAN A S | PGT | CS
(d) Select Name, maximum(DOB) from student;
SOLUTIONS
MULTIPLE CHOICE QUESTION
1 (b) Key 2 (d) All of these 3 (b) Primary Key 4 (c) Candidate Key
5 (a) Key 6 (d) Street 7 (b) Primary 8 (d) ID
9 (b) QAL 10 (b) ALTER 11 (b) SELECT 12 (c) Distinct
DISTINCT
13 (a) where 14 (b) LIKE 15 (a) BETWEEN 16 (b) SELECT
17 (d) 18 (a) Misha, Khushi 19 (b) LIKE 20 (d) %
21 (c) IS Operator 22 (a) Order By 23 (d) Ascending 24 (c) Desc, Asc
25 (d) 26 (a) ALTER 27 (d) All of these 28 (c)
TABLE
29 (a) Unique 30 (b) DML 31 (a) 32 (c)
33 (a) 34 (a) and (c) 35 (b) Primary Key 36 (c)
37 (b)Foreign Key 38 (c)99.99 39 (c) NUMBER(5,2) 40 (b) column Name
41 (b) Data 42 (b)Count(*) 43 (b)And (c) 44 (b)And (c)
| Page : 124|
HARIKRISHNAN A S | PGT | CS
VERY SHORT ANSWER QUESTIONS (1 MARKS EACH)
| Page : 125|
HARIKRISHNAN A S | PGT | CS
SHORT ANSWER QUESTIONS (2 MARKS EACH)
1. Degree - The number of attributes or columns in a relation is called the Degree of the relation.
Cardinality - The number of tuples/ rows in a relation is called the Cardinality of the relation.
2. WHERE clause is used to select particular rows that satisfy a condition whereas HAVING clause is used
in connection with the aggregate function, GROUP BY clause.
For ex. – select * from student where marks > 75;
This statement shall display the records for all the students who have scored more than 75 marks. On the
contrary, the statement – select * from student group by stream having marks > 75; shall display the records
of all the students grouped together on the basis of stream but only for those students who have scored
marks more than 75.
3. Primary Key- one or more attribute of a relation used to uniquely identify each and every tuple in the
relation. For Example : In the below Table Student, RollNo can be the Primary Key RollNo Name Marks
1 Pratham 75
2 Srishti 80
4. { } and fetchone()
5. DDL- Data definition language. Consists of commands used to modify the metadata of a table. For
Example- create table, alter table, drop table
DML-Data manipulation language. Consist of commands used to modify the data of a table. For Example-
insert, delete, update
6.
i) import mysql.connector
ii) It is the object that helps to execute the SQL queries and facilitate row by row processing of records in
the resultset.
7. Domain of an attribute is the set of values from which a value may come in a column. E.g. Domain of
section field may be (A,B,C,D).
8. fetchone() is used to retrieve one record at a time but fetchmany(n) will fetch n records at a time from the
table in the form of a tuple.
| Page : 126|
HARIKRISHNAN A S | PGT | CS
9. Constraints are the checking condition which we apply on table to ensure the correctness of data .
Example primary key, not null, default, unique etc
11. A table may have more than one such attribute/group of attributes that identifies a tuple uniquely, all
such attribute(s) are known as Candidate Keys. All the candidate key except
In the above table Employee, empno,aadhar_no, voter_id all are candidate key If we define empno as
primary key then remaining candidate keys will be alternate key.
12. RDBMS stands for Relational Database Management System. It is a program that offers commands to
create, update, and manage the data with multiple tables. Examples of RDBMS are
1. MySQL
2. Oracle
3. Microsoft SQL Server.
13.
i) Order By : This clause is used to arrange the records in ascending or descending order. for example Select
* from book order by price;
ii) Having : HAVING Clause in SQL is used to specify conditions on the rows with GROUP BY clause. for
example Select sum(price) from book group by (subject) having price > 100;
Ans.2
Ans.3
(iii)
watch_name qty_store qty_sold Stock
HighTime 100 25 75
LifeTime 150 40 110
Wave 200 30 170
GoldenTime100 10 90
Ans4.
(i) Manager 3
Clerk 3
(ii) 80000 28000
(iii) Ravi Kumar Robert Samuel Ritu Tondon Rachel Lee
Ans5.
(i) 3 (ii)650 (iii)TDH
1.
(a) Select Name From GRADUATE Where DIV = 1 Order by Name;
(b) Select Name, stipend, subject, stepend *12 From GRADUATE
(c) Select count (*) From GRADUATE
where subject IN (“PHYSICS”, “COMPUTER SC”);
(d) insert into GRADUATE Values (11, “KAJOL”, 300, “COMPUTER SC”, 75,1);
(e ) Select name from Graduate where average>65;
| Page : 128|
HARIKRISHNAN A S | PGT | CS
2.
(a) Select * From CLUB Where sports = “SWIMMING”;
(b) Select COACHNAME From CLUB order by DATOFAPP desc
(c) Select coachname, pay, age, 0.15 * pay From CLUB;
(d) Insert into CLUB Values (11, “PRAKASH”, 37, “SQUASH”, {25/02/98], 2500, “M”);
( e) Select Coachname ,Sports,Pay from Club .
3.
(a) Select * From INTERIORS Where TYPE = “Sofa”;
(b) Select ITEMNAME From INTERIORS where PRICE > 10000;
(c) Select ITEMNAME, TYPE From INTERIORS where DATEOFSTOCK < {22/01/02} Order by
ITEMNAME desc;
(d) Select ITEMNAME, DATEOFSTOCK From INTERIORS Where DISCOUNT > 15;
( e )Select Count (*) From INFERIORS Where TYPE = “Double Bed”;
4.
(a) Select * From FURNITURE Where TYPE = “Baby cot”;
(b) Select ITEMNAME From FURNITURE Where PRICE > 15000;
(c) Select ITEMNAME, TYPE From FURNITURE where DATEOFSTOCK < {22/01/02} Order by
ITEMNAME desc;
(d) Select ITEMNAME, DATEOFSTOCK From FURNITURE Where DISCOUNT > 25.
(e) Insert Into ARRIVALS Values (14, “Velvet touch”, “Double bed”,{25/03/03}, 25000,30);
5.
(a) SELECT * FROM Teacher WHERE Department = “History”;
(b) SELECT Name FROM Teacher WHERE Department = “Hindi” and Sex = “F”;
(c) SELECT Name, Dateofjoin FROM Teacher ORDER BY Dateofjoin;
(d) SELECT Name, Salary, Age FROM Teacher WHERE Age > 23 AND Sex = ‘M’;
(e) SELECT COUNT (*) FROM Teacher where Age > 23;
6.
(a) (iii) Loan Table
(b) I. (i) Book : Title (ii) Member: EmailID
(c). No, the Loan relation cannot have alternate key as its primary key is a composite key having foreign
key.
(d) INSERT INTO Loan Values(‘M1255’, ‘B3100’, ‘02/02/2020’, ‘09/02/2020’, False)
| Page : 129|
HARIKRISHNAN A S | PGT | CS
(e) Select FirstName, LastName, EmailID From Member, Loan
Where Member.MemberID=Loan.MemberID AND Returned = ‘False’;
7.
(a) Foreign Keys in Relation Loan MemberID(Parent Table Member) BookID (Parent Table Book)
(b) Yes, a relation can have multiple foreign keys, e.g., the loan relation given above has
two foreign keys – MemberID and BookID
(c) Yes, a foreign key can be a part of composite primary key, e.g., the primary key of relation loan is :
(MemberID, BookID, LoanDate), which contains two foreign keys : MemberID and BookID.
(d) Select FristName,LastName, EmailID From Member, Loan Where
Member.MemberID=Loan.MemberID AND EmailID LIKE “%@kvs.in” AND Returned = ‘False’;
8.
CustomerOrder Customer(CustomerID)
CustomerOrderLine CustomerOrder(OrderID)
CustomerOrderLine Furniture (FurnitureID)
9.
(a) Create Table Staff
( StaffID Number(4,0) NOT NULL PRIMARY KEY,
FirstName Varchar(20) NOT NULL, LastNameVarchar(20),
ISQualifiedChar(4) Check (IsQualified IN(‘True’, ‘False’)));
(b) INSERT INTO Staff Values(2009, ‘Sheril’, ‘Mark’, ‘True’);
| Page : 130|
HARIKRISHNAN A S | PGT | CS
(c) (ii) Staff table’s records can be deleted without affecting any other table as of now, because this table is
not linked with any other table yet.
(d) Alter Table Appointment Add StaffIDNumber(4,0) NOT NULL Reference Staff(StaffID);
(e) Select EmailAddress, FirstName,LastName From Customer C, Appointment A
Where C.CustomerID=A.CustomerID AND TreatmentName= ‘RF Facial’;
10.
(i) (b) Both (iii) and (iv)
(ii) (b)
(iii) (d)
(iv) (b) Both (ii) and (iv)
(v) (b)
| Page : 131|
HARIKRISHNAN A S | PGT | CS