Study Material XII CS 2023-24
Study Material XII CS 2023-24
JABALPUR REGION
STUDY MATERIAL
CLASS XII
COMPUTER SCIENCE (083)
SESSION: 2023-24
1
OUR PATRON
2
SUBJECT CO-ORDINATOR
Mr. RITESH KUMAR PATEL
PRINCIPAL KV HATTA
REVIEWED BY
3
Index
S.No. Topic Page No.
1. SYLLABUS 1
5. Functions in Python 11
6. Exception Handling 15
10. Data-structures 23
4
5
SYLLABUS
Unit I: Computational Thinking and Programming – 2
● Revision of Python topics covered in Class XI.
● Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default parameters,
positional parameters, function returning value(s), flow of execution, scope of a variable (global
scope, local scope)
● Exception Handling: Introduction, handling exceptions using try-except-finally blocks
● Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute paths
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file, opening a
file using with clause, writing/appending data to a text file using write() and writelines(), reading
from a text file using read(), readline() and readlines(), seek and tell methods, manipulation of data
in a text file
● Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+, ab,
ab+), close a binary file, import pickle module, dump() and load() method, read, write/create,
search, append and update operations in a binary file
● CSV file: import csv module, open / close csv file, write into a csv file using writer(),
writerow(),writerows() and read from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack using list.
1
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible Markup
Language (XML), domain names, URL, website, web browser, web servers, web hosting
2
UNIT–1
COMPUTATIONAL THINKING AND PROGRAMMING-2
3
4
1. Revision of Python topics covered in Class XI
Q. What are keywords?
Ans. i. Python Keywords are some predefined and reserved words in python that have special
meanings.
ii. Keywords are used to define the syntax of the coding.
iii. The keyword cannot be used as an identifier, function, or variable name.
iv. All the keywords in python are written in lowercase except True and False.
Keyword Description
and A logical operator
as To create an alias
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception
occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be
executed no matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
None Represents a null value
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
5
iii. In Python, keywords are the reserved names that are built-in to Python, so a keyword
cannot be used as an identifier - they have a special meaning and we cannot use them
as identifier names.
iv. Special symbols like !, @, #, $, %, etc. are not allowed in identifiers.
v. Python identifiers cannot only contain digits.
vi. Identifier names are case-sensitive.
Valid Identifiers Invalid Identifiers Reason
Project_Report Project Report Space not allowed
Position3 3position Can’t start with digit
_temperature #temperature Special symbol not allowed
RETURN return Keywords not allowed
Q. What will be the value of cats, dogs, hens in the following code?
a, b, c = 5, 4, 2
cats, dogs, hens = b, c, a
Ans. 4 , 2, 5
Explanation: a, b, c are variables. first value assign to a first variable, second value assign
to a second variable and so on..
Q. What will be the output for the following code if input is “*”?
ch = input("Enter separator")
print("a","b","c","d",sep=ch)
Ans. a*b*c*d
Explanation: The ‘sep’ parameter allows you to specify a string that will be used to separate
the items being printed by the print() function.
Q. Identify and write the arithmetic, relational and logical operators in the following statement
print(10+15 > 5 + 15 and 100%3!=0)
Ans. Arithmetic Operators +, %
Relational Operators >, !=
Logical Operator ‘and’
Ans. True
True
True
True
7
True
Explanation: islower() returns True if all alphabets in string are in lower case
isupper() returns True if all alphabets in string are in upper case
isdigit() returns True if all characters in string are digits
isalnum() returns True if all characters are either alphabet or digit
isalpha() returns True if all characters in string are alphabets
Q. Write output
L1 = [111, 222, 333]
L2 = [500, 600, 700]
L3 = L1 + L2
print(L3)
Q. Write output
List1 = ["One","Two","Three"]
print(List1*3)
Ans. ['One', 'Two', 'Three', 'One', 'Two', 'Three', 'One', 'Two', 'Three']
Explanation: When * appears between a list and an integer, the expression will be evaluated
as a new list that consists of several copies of the original list concatenated together. The
number of copies is set by the integer.
9
Explanation: len() is a built-in function of Python that returns the total number of items in a
list, array, tuple, dictionary, etc. So 4+3+2 gives 9
Ans. F#R#S#R
Run Rest
Explanation: The split() function in Python is a built-in string method that is used to split a
string into a list of substrings based on a specified delimiter. The function takes the delimiter
as an argument and returns a list of substrings obtained by splitting the original string
wherever the delimiter is found. if delimiter is not provided then any white space is a
separator.
For example
para = "First Run Second Rest"
L = para.split()
print(L)
['First', 'Run', 'Second', 'Rest']
x = 50
def func():
global x
print('x is', x)
x=2
print('Changed global x to', x)
func()
print('Value of x is', x)
Ans. x is 50
Changed global x to 2
Value of x is 2
2. Functions in Python
Q. What is function in a program? What are its advantages?
Ans. Function is used to perform a specific task. Function is a block of code, it executes when
called in a program. When a program is divided into number of functions, it is easy to manage.
Program becomes more readable. It is easy to understand the program. Function can be
called in any part of the program. Function is reusable.
11
ShowMessage("Hello")
Q. Create a user defined function which returns sum of two numbers passed as arguments.
Ans. def SumTwoNum(a, b):
return a + b
for example
#function calling
BodyMI(age = 40, weight = 65, height = 5.6)
#order of argument doesn’t matter
12
Output
Height 5.6
Weight 65
Age is 40
Q. Write down the difference between positional arguments and keyword arguments.
Ans.
Keyword argument Positional argument
Parameter names are used to pass the Arguments are passed in the order of
argument during the function call. parameters. The order defined in the
function declaration
Order of parameter names can be Order of values cannot be changed to avoid
changed to pass the arguments. unexpected output
Syntax Syntax
FunctionName(paramName = value,…) FunctionName(value1, value2, value3…)
Ans. Default values indicate that the function argument will take that value if no argument value is
passed during the function call. The default value is assigned by using the assignment (=)
operator of the form keywordname = value.
When you call a function and pass an argument to the parameter that has a default value,
the function will use that argument instead of the default value.
However, if you don’t pass the argument, the function will use the default value.
example
def NewAdmission(regno,sec='A',category='V'):
print("Admitted")
print("Registration No",regno)
print("Section",sec)
print("Category",category)
print("------------------------------")
In above program, function call 1 has only one argument so python uses default values
(sec='A',category='V') for other two arguments and in another case of function call 2 ,
values for all three parameters are provided so the program uses that value instead of the
default values.
Therefore the output is
Admitted
Registration No 1999
Section A
Category V
------------------------------
Admitted
Registration No 2000
Section B
Category III
------------------------------
13
A return statement is used to end the execution of the function call and “returns” the result
(value of the expression following the return keyword) to the caller. The statements after the
return statements are not executed.
def Grace(marks):
return marks + 5
print(“End”) #this statement will not execute
#calling function
K = Grace(30)
Grace() will return a value which is assigned to the variable ‘K’. value in ‘K’ is 35
function2()
print(a)
def function2():
print("inside function ", p)
p = 100
function2()
print("outside function ",p)
output
inside function 100
outside function 100
The variable ‘p’ is defined as the global variable and is used both inside the function as well as
outside the function.
14
Can be access throughout the Can access only inside the function
Scope
code
Once the value changes it is once changed the variable don’t
Value reflected throughout the code affect other functions of the
program
def mycourse():
subject = subject + " computer"
print(subject)
mycourse()
Error:
An error is obtained as Python treats “subject” as a local variable, and we have not defined any local
variable “subject” inside the function mycourse(). To solve this error, we use the global keyword.
def mycourse():
global subject
subject = subject + " computer"
print("Inside function",subject)
mycourse()
print("Outside function",subject)
output
Inside function optional computer
Outside function optional computer
In Python, the global keyword is used to indicate that a variable declared inside a function should
be treated as a global variable, rather than a local variable. This means that the variable can be
accessed and modified both inside and outside the function.
3. Exception Handling
Q. What is an exception?
Ans. An exception is an error which happens at the time of execution of a program. We know that
exceptions abnormally terminate the execution of a program. An object in Python that
describes an error is called an exception.
Common Examples of Exception
15
Division by Zero
Accessing a file which does not exist.
Addition of two incompatible types
Trying to access a nonexistent index of a sequence
Syntax:
try :
#statements in try block
except :
#executed when error in try block
example
try:
a=5
b='0'
print(a+b)
except TypeError:
print('TypeError Occurred')
except:
print('Some error occurred.')
print ("Out of try except blocks")
16
Ans. The ‘try’ statement is used to run an error-prone piece of code and must always be followed
by the ‘except’ statement. If no exception is raised as a result of the ‘try’ block execution, the
‘except’ block is skipped and the program just runs as expected. In the opposite case, if an
exception is thrown, the execution of the ‘try’ block is immediately stopped, and the program
handles the raised exception by running the alternative code determined in the ‘except’ block.
After that, the Python script continues working and executes the rest of the code.
Example
try:
print(message)
except:
print("Variable not declared")
print("take care")
output
Variable not declared
take care
We can explicitly mention the type of exception that we need to catch and handle right after the
‘except’ command:
try:
print(message)
except NameError:
print("Variable not declared")
print("take care")
Q. What is ‘finally’ in python?
Ans. In Python, the 'finally' keyword is used in the context of exception handling, specifically with
try-except blocks. The 'finally' block contains code that will always be executed, regardless
of whether an exception occurs or not within the “try” block.
try:
x = int(input("Enter number "))
print(2*x)
except ValueError:
print("This is not a number ")
finally:
print("All the best") #Always execute
output
Enter number abc
This is not a number
All the best
17
4. PYTHON FILE HANDLING
18
4. PYTHON FILE HANDLING
Introduction to files:
File: - A file is a collection of related data stored in computer storage for future data retrieval.
Stream: - It refers to a sequence of bytes. File handling refers to reading and writing contents from a file.
Data Files: Data files can be stored in three ways: 1. Text Files 2. Binary Files 3. CSV Files
DIFFERENCE BETWEEN TEXT FILE, BINARY FILE and CSV files
Text Files Binary Files CSV(comma separated values) Files
Stores information in ASCII CSV format is a plain text format where
Stores information in binary format
characters. values separated by commas.
Each line of text is terminated with a
No delimiters are used for a line. No CSV is a format for saving tabular
special character known as EOL
translation occurs in it information into a delimited text file
(End of Line),
Slower than binary files. Binary files are faster Importing CSV files can be much faster
Relative & absolute paths- The files are kept in directory which is also known as folders. Every running program
has a current directory. Which is generally a default directory, python always see the default directory first.
The absolute path (full path) of an entity contains the complete information (from the root to the ending) needed
to locate it. it always includes the root directory as a starting point.
The absolute path to the xiics file is: C:\KVS\XII\Science\xiics.txt
A relative path- It describes the location of a file or folder without starting from the root of the file system. The
relative path of xiics.txt in parent folder is
“..\xiics.txt”
Code to know current working directory >>> import os
>>> cwd=os.getcwd() # getcwd() can be used to identify the
>>> print(cwd) # current working directory
Text Files- A text file is simply a sequence of ASCII or Unicode characters.
Opening and Closing Files:
To perform file operation, it must be opened first then after reading, writing, editing operation can be performed.
Closing a file releases valuable system resource. In case we forgot to close the file,
Python automatically close the file when program ends or file object is no longer referenced in the program
Syntax: file_objectname= open (filename, mode) file-objectname.close( )
Example: f = open("XIICS") f.close()
The code above is the same as: f = open("XIICS", "rt") Where "r" for read mode, and "t" for text are the default values,
you do not need to specify them.
File modes
Text File Binary File Description
r rb Read - Default value. Opens a file for reading, error if the file does not exist.
w wb Write - Opens a file for writing, creates the file if it does not exist
a ab append - Opens a file for appending, creates the file if it does not exist
r+ rb+ Read and Write-File must exist, otherwise error is raised.
w+ wb+ Read and Write-File is created if does not exist.
a+ ab+ Read and write-Append new data
Writing/appending data to a text file- There are 2 types of functions to write the data to a file.
write(): - It returns the number of characters being written on single execution of the write() method.
>>>file.write("Hello Python")
12 # No of characters
writelines (): This method is used to write multiple strings or object to a file. It does not return the number of characters
written in the file.
>>>file.writelines(lines) # lines = ["Hello everyone\n", "Writingmultiline strings\n", "This is third line"]
Example: Open the file "XIICS" and append content to the file:
file= open("XIICS", "a") # if file is open with “w” mode then content will be overwrite
file.write("Welcome to the world of Programmers")
Reading from a text file
The read() method- Read a specified number of bytes of data from a data file. If no argument or a negative number is
specified in read(), the entire file content is read.
>>>file.read(5) 'Hello'
The readline([n]) method- Read one complete line from a file. It can also be used to read a specified number (n) of
bytes of data from a file but maximum up to the newline character (\n).If no argument or a negative number is specified,
it reads a complete line and returns string.
19
>>> myobject.readline(10) 'Hello ever'
The readlines() method- Reads all the lines and returns the lines along with newline as a list of strings.
>>> print(myobject.readlines())
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']
#Count the number of #Count the number of words in a file #Count number of
characters from a file. lines in a text file
FILE=open("D:\\python programs\\XIICS",'r')
FILE=open("XIICS",'r') FILE=open("XIICS",'r')
str=FILE.read()
str=FILE.read() str=FILE.readlines()
L=str.split()
L=str.split() line=0
words=0
Chars=0 for i in str:
for i in L:
for i in L: line=line+1
words+=1
Chars += len(i) print(line)
print(words)
print(Chars) FILE.close()
FILE.close()
The seek and tell methods
The tell() method- Returns the current position of the file object in the file. The syntax of using tell() is:
file_object.tell()
The seek() method- Used to jump file object at a particular position in a file. The syntax of seek() is:
file_object.seek(offset [, reference_point])
offset -Number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object. It can have any of the following values: 0 (By default)-
beginning of the file 1 - current position of the file 2 - end of file
Binary File- They store data in the binary format (0’s and 1’s). In Binary files there is no delimiter for a line. Pickle
module can be imported to write or read data in a binary file.
The pickle module- It is used for serializing and de-serializing any Python object structure.
Serialization/pickling is the process of transforming data or an object in memory to a stream of bytes.
De-serialization/unpickling- where a byte stream is converted back to Python object.
The pickle module provides two methods- dump()for writing onto binary files and load() to read from binary files.
20
Operations on a binary file:
#Read operation
#Searching operation
import pickle import pickle
file=open('emp.dat','rb') f1=open('emp.dat','rb')
try: try:
e=pickle.load(file) e=pickle.load(f1)
for x in e: for x in e
if(e[x]>=25000 and [x]<=30000): print(x)
print(x)
except EOFError:
except EOFError:
f1.close()
file.close()
CSV file-CSV (Comma Separated Values) is a file format for data storage which looks like a text
file. The information is organized with one record on each line and each field is separated by comma.
Advantages Disadvantages
Smaller in size, Easy to generate • No standard way to represent binary data
Human readable, faster to handle • There is no distinction between text and numeric values
Operations in CSV files -The csv module’s reader and writer objects read and write sequences.
Operations are -
• open / close csv file import csv
file = open ('Filename.csv’, ’mode’)
file.close()
Reading a CSV file import csv
newFile=open('d:\\a.csv','r'):
NFReader = csv.reader(newFile) # Reading is done using reader object
for row in NFReader:
print (row)
newFile.close()
Writing with writerow () and writerows ()
import csv;
Fields = ['Name', 'Dept', 'Salary']
Rows = [['Sunil', 'Prod','29000'],['Manoj', 'Sales', '46000'], ['Vinod', 'Prod','45000'],
['Videh','Sales', '78000'], ['Ranjana', 'IT','35000'], ['Rohit', 'IT', '45000']]
csvfile = open(“Emp.csv”, 'w') # open the CSV file in WRITE mode.
csvwriter = csv.writer(csvfile) # The file object is converted to csv.writer object.
csvwriter.writerow(fields) #write the first row which is nothing but the field names.
csvwriter.writerows(rows) # writerows method to write multiple rows at once.
csvfile.close()
21
5. DATA STRUCTURE MIND MAP
22
Data-structures –The logical or mathematical model of a particular organization of data is called data structure. It is a
way of storing, accessing, manipulating data. Types are-
a) Simple Data Structure b) Compound Data Structure
Stacks
A stack is a linear data structure that provides temporary storage of data in such a way that the element stored last will
be retrieved first. This method is also called LIFO – Last In First Out. It is controlled by two operations: PUSH and POP.
Both the operations take place from Top position
Implementation of Stack – Stack can be implemented in list. The basic operations are-
Creation of Stack – Stack can be created using list with the help of statement
Stack= [ ] # this statement creates an empty stack
Push (Insertion): The append () functions adds the new element at the top of the list. Codes are –
Stack.append(data)
Pop (Deletion): The pop () function removes the last (top) data from the stack. Before removing an element from the
stack it is necessary to check whether the stack is empty (underflow condition) or not. Codes are –
If (Stack= = []):
print (“Stack is Empty, Underflow Condition”)
else:
print(Stack.pop()) # remove and print top most element of the stack
Peep (Traversal): Traversal (accessing) means visiting each item of the stack. Codes are –
for i in range(len(stack)-1, -1, -1):
print (stack[i])
Implementation of Stack: Codes for various operations
def PUSH (): #code to push an item
item = int(input(“\t\t\tEnter an item to push: “))
Stack.append(item)
print(“\t\t\t ITEM”, item,” PUSHESD IN THE STACK”)
2. Which of the following mode is used when dealing with non-text files like image or exe files?
(i) Text mode (ii) Binary mode (iii) xls mode (iv) csv mode
4. Which statement is used to change the file position to an offset value from the start?
(i) fp.seek(offset, 0) (ii) fp.seek(offset, 1)
(iii) fp.seek(offset, 2) (iv) None of the above
23
(ii) r+ mode opens the file if it exists, while w+ mode also opens the file, but it deletes all the
content present in the file.
(iii) In w+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the
end for r+
(iv) Depends on the operating system
8. Which of the following modes is used for both writing and reading from a binary file?
(i) wb+ (ii) w (iii) wb (iv) w+
9. Which statement is used to retrieve the current position within the file?
(i) fp.seek() (ii) fp.tell() (iii) fp.loc (iv) fp.pos
12. Every record in a CSV file is stored in reader object in the form of a list using which method?
(i) writer() (ii) append() (iii) reader() (iv) list()
13. In text files, each line of text is terminated, with a special character known as ___________.
(i) EOL ii) EOF iii) EEF iv) All of the above
14. A _________ file is just a file that contains information in the same format in which the information is held in
memory.
(i). Text file (ii) Binary file (iii) Word file (iv) None of the above
15. _________ binary file mode is used to append data in the file using file handling.
(i) ‘ab’ (ii) ‘w’ (iii) ‘a’ (iv) None of the above
16. The input and output devices are implemented as file, also called __________.
(i) Standard streams (ii) Standard Binary (iii) Standard Text (iv) None of the above
17. ________ are the standard streams in file handling.
(i) stdin (standard input) (ii)stdout (standard output)
(iii) stderr (standard error) (iv) All of the above
18. A text file can be opened in ________ file modes.
(i) ‘r’ and ‘w’ (ii) ‘a’ and ‘r+’ (iii) ‘w+’ and ‘a+’ (iv) All of the above
19. .................... method is used for random access of data in a CSV file. Seek()
20. .................... method of pickle module is used to write an object into binary file. Dump()
21. .................... method of pickle module is used to read data from a binary file. Load()
22. .................... statement is given for importing csv module into your program. Import csv
23. To read all the file contents in form of a list, ..................... method is used. Readlines()
24. To write all the file contents, ....................., method may be used. Writelines()
25. To force Python to write the contents of file buffer on to storage file,.... method may be used. Flush()
Q.6. In which of the following file modes the existing data of the file will not be lost?
Rb, ab, w, w+b, a+b, wb, wb+, w+, r+
Ans. In file modes rb, ab, a+b and r+, data will not be lost. In file modes w, w+b, wb, wb+ and w+, data will be lost.
Q.7. Ravi intends to position the file pointer to the beginning of a text file. Write Python statement for the same
assuming “F” is the Fileobject.
Ans. F.seek(0)
Q.8. Which method can be used to determine the name of the current working directory?
Ans. Getcwd()
Q.10 Which sign is used to denote directory and parent directory in python
Ans Single dot and double dot
3 Marks Questions
Q.1. Write a python code to find the size of the file in bytes, number of lines and number of words.
Ans. # reading data from a file and find size, lines, words
f=open(‘Lines.txt’,’r’)
str=f.read( )
size=len(str)
print(‘size of file n bytes’,size)
f.seek(0)
L=f.readlines( )
word=str.split( )
print(‘Number of lines ’,len(L))
print(‘Number of words’,len(word))
f.close( )
Q.2. Write code to print just the last line of a text file “data.txt”.
Ans: fin=open(“data.txt”,”r”)
lineList=fin.readlines()
print(“Last line = “, lineList[-1])
Q.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: Code
def PUSH(Arr):
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)
Q.4. Write a function in Python POP(Arr), where Arr is a stack implemented by a list of numbers. The function returns
the value deleted from the stack.
Ans: Code
def popStack(st) :
# If stack is empty
if len(st)==0:
print(“Underflow”)
else:
return st.pop()
Q.5. Write a function in Python that counts the number of “Me” or “My” words present in a text file “STORY.TXT”.
Ans: Code
def displayMeMy():
25
num=0
f=open(“story.txt”,”rt”)
N=f.read()
M=N.split()
for x in M:
if x==”Me” or x== “My”:
num=num+1
f.close()
print(“Count of Me/My in file:”,num)
Q.6. Write a function AMCount() in Python, which should read each character of a text file STORY.TXT, should count
and display the occurance of alphabets A and M (including small cases a and m too).
Ans: Code
def count_A_M():
f=open(“story.txt”,”r”)
A,M=0,0
r=f.read()
for x in r:
if x==”A” or x==”a” :
A=A+1
elif x==”M” or x==”m”:
M=M+1
f.close()
print(“A or a: “,A)
print(“M or m: “,M)
Q.7. Write a function in python to count the number lines in a text file ‘Country.txt’ which is starting with an alphabet
‘W’ or ‘H’.
Ans. Code
def count_W_H():
f = open (“Country.txt”, “r”)
W,H = 0,0
r = f.readlines()
for x in r:
if x[0] == “W” or x[0] == “w”:
W=W+1
elif x[0] == “H” or x[0] == “h”:
H=H+1
f.close()
print (“W or w :”, W,“\nH or h :”, H)
Q.8. Write a user defined function to display the total number of words present in the file.
Ans. Def countwords():
s = open(“Quotes.txt”,”r”)
f = s.read()
z = f.split ()
count = 0
for I in z:
count = count + 1
print (“Total number of words:”, count)
Q.9. Write a function AddCustomer(Customer) in Python to add a new Customer information NAME into the List of
Cstack and display the information.
Ans.
Def AddCustomer(Customer):
Cstake.append(Customer)
If len(Cstack)==0:
print (“Empty Stack”)
else:
print (Cstack)
Q.10. Write a function DeleteCustomer() to delete a Customer information from a list of Cstack. The function delete
the name of customer from the stack.
26
Ans.
Def DeleteCustomer():
if (Cstack ==[]):
print(“There is no Customer!”)
else:
print(“Record deleted:”,Cstack.pop())
Q.11. Write a function in Python that counts the number of “He” or “She” words present in a text file “STORY.TXT”.
Ans. Def displayMeMy():
num=0
f=open(“story.txt”,”rt”)
N=f.read()
M=N.split()
for x in M:
if x==”He” or x== “She”:
print(x)
num=num+1
f.close()
print(“Count of He/She in file:”,num)
Q.12. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers divisible
by 7 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]%7==0:
s.append(Arr[x])
if len(s)==0:
print(“Empty Stack”)
else:
print(s)
Q.13. Write a python program to create and read the city.txt file in one go and print the contents on the output screen.
Ans. # Creating file with open() function
f=open(“city.txt”,”w”)
f.write(“My city is very clean city.”)
f.close()
Q.15. Write a function count_lines() to count and display the total number of lines from the file. Consider above file –
kvs.txt.
Ans. Def count_lines():
f = open(“kvs.txt”)
cnt =0
for lines in f:
cnt+=1
print(“no. of lines:”,cnt)
f.close()
Q.16. Write a function display_oddLines() to display odd number lines from the text file diary.txt.
Ans. Def display_oddLines():
f = open(“diary.txt”)
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
27
Q.17. Write the file mode that will be used for opening the following files. Also, write the Python statements to open
the following files:
a) a text file “example.txt” in both read and write mode
b) a binary file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
Ans.
a) file = open( “example.txt”, “w+” )
b)file = open(“bfile.dat” , “wb” )
c) file = open ( “try.txt” , “a+” )
Q.18. What is the difference between the following set of statements (a) and (b):
a) P = open(“practice.txt”,”r”)
P.read(10)
Ans. File object P will read 10 characters in part “a” but won’t print anything; in part “b,” however, it will read every
character in the 28ractice file and save it in the variable “x.”
Q.19. Write the use and syntax for the following methods:
a) open() b) read() c) seek() d) dump()
Ans. File_object=open(file_name, mode)
x=file_object.read()
f.seek(offset, from_what)
pickle.dump(data_object, file_object)
Ans –
a) Data files primarily come in two flavours: text files and binary files. Any text editor can open a text file
since it is made up of characters that are human readable. Binary files, on the other hand, contain non-
human readable characters and symbols and need special software to retrieve its information.
b) When called, the readline() function in Python returns a line from the file. The readlines() method will
return every line in a file as a list with each item representing a line in the file.
c) A string is passed as an argument to the write() method, which writes it to a text file. To write several
strings to a file, use the writelines() method. To use the writelines() method, we must supply an iterable
object (such as a list, tuple, etc.) that contains strings.
5 Marks Questions
1. Aditya Vishwakarma of class 12 is writing a program to create a CSV file “user.csv” which will contain user name
and password for some entries. He has written the following code. As a programmer, help him to successfully
execute the given task.
28
(a) Name the module he should import in Line 1. 1
(b) In which mode, Devesh should open the file to add data into the file 1
€ Fill in the blank in Line 3 to read the data from a csv file. 1
(d) Fill in the blank in Line 4 to close the file. 1
€ Write the output he will obtain while executing Line 5. 1
(a) Line 1 : csv
(b) Line 2 : a
€ Line 3 : reader
(d) Line 4 : close()
€ Line 5 : Chandrasst@tgt
Sachinhar@narmade
Pankajfrnd@distance
2. Given a binary file “EMP.dat” has structure (EmpID, EmpName, EmpPay). Write a function in Python countsal()
in Python that would read contents of the file “EMP.dat” and count and display the details of those employee
whose salary is greater than 35000.
with open(filename,’r’) as f:
csv_r=______________(f,delimiter=’,’) #Line4
ans=’y’
while ans==’y’:
found=False
emplid=(input(“Enter employee id to search=”))
for row in csv_r:
if len(row)!=0:
if _____==emplid: #Line5
print(“Name : “,row[1])
print(“Mobile No : “,row[2])
found=True
29
break
if not found:
print(“Employee id not found”)
ans=input(“Do you want to search more? (y)”)
5. Kavy is making a software on “Countries & their Capitals” in which various records are to be stored/retrieved in
CAPITAL.CSV data file. It consists some records(Country & Capital). He has written the following code in
python. As a programmer, you have to help him to successfully execute the program.
Import ___________ # Statement-1
def AddNewRec(Country,Capital): # Fn. To add a new record in CSV
file f=open(“CAPITAL.CSV”,_________) # Statement-2
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
f.__________ # Statement-3
AddNewRec(“INDIA”,”NEW DELHI”)
AddNewRec(“CHINA”,”BEIJING”)
ShowRec() # Statement-5
Ans. (a) csv (b) “a” (c) close() (d) reader € INDIA NEW DELHI CHINA BEIJING
6. Vanshika of class 12 is writing a program to create a CSV file “emp.csv”. She has written the following code to
read the content of file emp.csv and display the employee record whose name begins from “S‟ also show no.
Of employee with first letter “S‟ out of total record. As a programmer, help her to successfully execute the given
task. Consider the following CSV file (emp.csv):
1, Sumit, 6500
2, Arjun, 3500
3, Sandip, 7500
4, Ahmed, 9500
import ________ # Line 1
def SNAMES():
with open(_________) as csvfile: # Line 2
myreader = csv._______(csvfile,delimiter=’,’) # Line 3
count_rec=0 count_s=0
for row in myreader:
if row[1][0].lower()==’s’:
print(row[0],’,’,row[1],’,’,row[2])
count_s+=1
count_rec+=1
print(“Number of ‘S’ names are “,count_s,”/”,count_rec)
a) Name the module he should import in Line 1
30
b) In which mode, Vanshika should open the file to print data
c) Fill in the blank in Line 2 to open the file
d) Fill in the blank in Line 3 to read the data from a csv file
e) Write the output he will obtain while executing the above program
Ans. A) csv b) read mode c) emp.csv d) reader
e) 1, Sumit, 6500
3, Sandip, 7500
Number of “S” names are 1/3
7. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function countrec()
in Python that would read contents of the file “STUDENT.DAT” and display the details of those students whose
percentage is above 90. Also return number of students scoring above 90%
Ans. Import pickle
def CountRec():
fobj=open(“STUDENT.DAT”,”rb”)
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2] > 90:
print(rec[0],rec[1],rec[2],sep=”\t”)
num = num + 1
except:
fobj.close()
return num
Ans.
31
6. Computer Networks
S.N. TOPICS
1 Computer Networks
Unit II: Computer Networks ● Evolution of networking: introduction to computer networks,
evolution of networking (ARPANET, NSFNET, INTERNET) ● Data communication
terminologies: concept of communication, components of data communication
(sender,receiver, message, communication media, protocols), measuring capacity of
communication media (bandwidth, data transfer rate), IP address, switching techniques
(Circuit switching, Packet switching) ● Transmission media: Wired communication media
(Twisted pair cable, Co-axial cable, Fiber-optic cable), Wireless media (Radio waves,
Micro waves, Infrared waves) ● Network devices (Modem, Ethernet card, RJ45,
Repeater, Hub, Switch, Router, Gateway, WIFI card) ● Network topologies and Network
types: types of networks (PAN, LAN, MAN, WAN), networking topologies (Bus, Star,
Tree) ● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET,
VoIP ● Introduction to web services: WWW, Hyper Text Markup Language (HTML),
Extensible Markup Language (XML), domain names, URL, website, web browser, web
servers, web hosting
2 Database concepts
Unit III: Database Management ● Database concepts: introduction to database
concepts and its need ● Relational data model: relation, attribute, tuple, domain,
degree, cardinality, keys (candidate key, primary key, alternate key, foreign key)
Introduction
Computer Network is a collection of autonomous computers interconnected by a single technology.
32
A Computer network is a network of computers which share information and resources from each
other.
A group of computers which are connected to each other and follow similar usage protocols for the
purpose of sharing information and having communications provided by the networking nodes is
called a Computer Network.
Two computers are said to be interconnected if they are able to exchange information.
A computer network is a system that connects independent computers in order to share information
and resources.
A network may be small where it may include just one system or maybe as large as what one may
want. The nodes may further be classified into various types. These include:
Personal Computers
Servers
Networking Hardware
General Hosts
Networking can be classified into three types:
Evolution of Networking
ARPANET
In the 1960s a research project was commissioned by Advanced Research Projects Agency
Network (ARPANET) in the U.S. Department of Defence to connect the academic and research
institutions located at different places for scientific collaborations. The first message was
communicated between the University of California, Los Angeles (UCLA) and Stanford Research
Institute (SRI). Slowly but gradually, more and more organisations joined the ARPANET, and many
independent smaller networks were formed.
NSFNET
NSFNET program was launched by National Science Foundation in 1986 to bring connectivity to
more people. It was popularly used to promote advanced research and education networking in the
United States.
Internet (INTERconnection NETwork)
33
The Internet is a network of the interlinked computer networking worldwide, which is accessible to
the general public. Internet is a huge network of several different interlinked networks relating to the
business, government, academic and even smaller domestic networks. Therefore, Internet is known
as the network of all the other networks.
These networks enable the Internet to be used for various important functions, which include the
several means of communications like the file transfer, the online chat and even the sharing of the
documents and websites on the WWW or the World Wide Web.
Data Communication
Communication is an act of sending or receiving data. Thus, data communication refers to the
exchange of data between two or more networked or connected devices.
Network Terminology
Node- The device connected to a network.
Client – The device that requests for a service
Server – The Device that renders the services
Client-Server - In this model, the data are stored on powerful computers called Server that
can be accessed by a much simpler computer called Client that are connected by a
network.
Network Interface Card or Unit (Network Adapter or LAN card) - It is hardware that allows
a computer (or device) to connect to network.
MAC (Media Access Control) address – Each NIC is assigned a unique 12-digit hexadecimal
number, known a MAC address, is used as network address in communication. The format for
the MAC address is MM : MM : MM : SS : SS : SS Manufacturer ID Card Id
IP Address: Every device on network has unique identifier called IP address. It
consists of 4 bytes (IPv4) decimal number (between 0 to 255) separated by ‘.’
(Period).
Channel – It is communication path through which data is actually transmitted.
Communication Media- It allows data or signal to be communicated across the devices. It is
means of communication.
Data – Information stored within the computer system in form of ‘0’ and ‘1’
Signal- It is electric or electromagnetic encoding of data to be transmitted. It can be
categorized into following two types:
1.Analog Signal – that has infinitely many levels of intensity over a period of time.
2. Digital Signal – that can have only a limited number of defined values.
Bit rate – It defines the amount of data transferred. It is defined as number of bits per
second (bps). [Bps – Bytes per Second]
Baud – The number of changes in signal per second.
34
Bandwidth – It is difference between the highest and the lowest frequencies contained in
the signal.
Switching Technique
A switched network consists of a series of interlinked nodes called switches capable of creating
temporary connections between two or more liked devices.
There are three basic switching technique
Circuit Switching: In circuit switching a dedicated path is established before sending data from
sender to receiver and entire communication is carried out the same path.
Packet Switching – In packet switching in a message is broken into a number of parts called
packet which are sent independently from sender to receiver and reassembled at the destination.
Message Switching: Message switching is a connectionless network switching technique where
the entire message is routed from the source node to the destination node, one hop at a time. It
was a precursor of packet switching.
Circuit Switching vs Packet Switching
Circuit Switching Packet Switching
A dedicated path is established No dedicated path is established
Entire message follows the same path Each packet travels independently to each
other
Network Devices
Modem
It stands for modulator and demodulator It a computer hardware device that converts data from
a digital format into a format suitable for an analog.
A modem transmits data by modulating one or more carrier wave signals to encode digital
information, while the receiver demodulates the signal to recreate the original digital information.
Repeater
Repeaters are network devices that amplify or regenerate an incoming signal before
retransmitting it.
It operates at physical layer of the OSI model.
The repeater allows to transfer the data through large area distance
Hub
It is a multiport device that allows multiple computers to communicate with each other over a
network.
35
It is a non-intelligent network device that sends message to all ports( i.e. Broadcast)
Types of Hubs
Active Hub
It strengthens the signal and may boost noise too.
It is relatively costlier than passive hub.
Passive Hub –
It repeat/copy signals.
It is relatively cheaper than active hub.
Switch
Network Switch or switch is also a network multiport device that allow multiple computers to
connect together.
Network switch inspects the packet, determine source and destination address and route the
packet accordingly.
It operates at Data Link Layer (layer 2) of OSI model.
Bridge
It connects multiple network segments having same protocol
It works at Data Link Layer (Layer 2).
Bridge does not simply broadcast traffic from one network.
Bridges use bridge table to send frames across network segments. It also improves the overall
network performance.
Router
A router is a device that connects two or more packet-switched networks or sub networks.
It serves two primary functions:
Managing traffic between these networks by forwarding data packets to their intended
IP addresses, and
Allowing multiple devices to use the same Internet connection.
It connects LANs (local area networks) and WANs (wide area networks).
It operates on layer 3 or 4 in OSI model
Gateway
It is simply a device or hardware that acts as a "gate" between the networks.
It connects two networks with different transmission protocols together.
It converts information, data or other communications from one protocol or format to another.
It operates on layer 5 of OSI model
RJ45
It stands for Registered Jack.
It is common interface to connect Twisted Pair Cable.
It is used for Ethernet and Token Ring Network.
Ethernet Card
It also known as NIC card.
It enables a computer to access an Ethernet network (LAN)
It has MAC id which gives it unique identity in the network.
Wi-Fi card
It is also known wireless network adaptor.
It is a wireless network technology that allows devices to communicate over wireless signals.
It uses radio waves for the communication
36
Difference between Router and Switch
.A network switch forwards data packets between groups of devices in the same network, whereas
a router forwards data between different networks.
Difference between a Router and a Modem
A router forms networks and manages the flow of data within and between those networks, while a
modem connects those networks to the Internet.
Difference between a Router and Gateway
A gateway is a concept while a router is a device that implements a gateway.
Router Gateway
It ensure that data packets are switched to To connect two networks of different
the right address with the best route. protocols as a translator
It routes the data packets via similar networks It connects two dissimilar networks
It supports dynamic Routing. It does support dynamic Routing.
Type of Network
PAN
It stands for Personal Area Network.
It is a computer network formed around a person.
It generally consists of a computer, mobile, or personal digital assistant.
Appliances use for PAN: cordless mice, keyboards, and Bluetooth systems.
PAN includes mobile devices, tablet, and laptop.
LAN
It is a group of computer and peripheral devices which are connected in a limited area such
as room, building & campus.
Higher Data Speed.
LANs are in a narrower geographic scope (up to 1 Km).
It is a private network.
MAN
A Metropolitan Area Network or MAN is consisting of a computer network that span across a
city.
It mostly covers towns and cities in a maximum 50 km range.
The dual bus in MAN network provides support to transmit data in both directions
concurrently.
WAN
It connects device across globe.
It uses public network
Internet
BSNL
Network Media
37
Guided or Wired
Telephone (T1) cable
Twisted pair cable
STP (Shielded Twisted Pair)
UTP (Unshielded Twisted Pair)
Co-axial cable
Optical Fiber/Fibre
Unguided or Wireless
Infrared
Radio Wave
Microwave
Bluetooth
Satellite
Microwave
1GHz to 300 GHz
Line of sight- antenna of sender and receiver must be aligned
Cannot penetrate obstacles
Rain or other disturbance cause issue with Microwave
Types of microwave propagation
Terrestrial Microwave propagation
Satellite Microwave propagation
Bluetooth
It also uses radio waves
2.4 GHz
Range 10mtr
Short distance
Topology
Physical and Logical arrangement of nodes in the network is called Network Topology.
Types of Topologies
Bus
Ring
Star Bus Topology
Tree
39
Mess
Hybrid
Bus Topology
In Bus Topology all the nodes are connected to single cable or backbone
Both the end has terminators.
Ring Topology
In Ring Topology all the nodes are connected to
each-other to form a loop.
Each workstation is connected to two other components on either side
It communicates with these two adjacent neighbors.
Data is sent and received using Token.
Star Topology
In Star Topology all the nodes are connected to a central device called Hub/Switch.
All communication is controlled by the central Device (Hub/Switch)
Tree Topology
40
In Tree Topology, the devices are arranged in a tree fashion similar to the branches of a
tree.
It has multilayer architecture.
Protocol
It is set of rules or standard that governs communication.
Types of Protocol (Broadly can be kept in two suites of Protocols vis. TCP/IP or OSI)
FTP
HTTP/HTTPS
IMAP
POP3
SMTP
PPP
TELNET
VoIP
Web 3.0
It refers to the 3rd Generation of web where user will interact by using artificial intelligence
and with 3-D portals.
Web 3.0 supports semantic web which improves web technologies to create, connect and
share content through the intelligent search and the analysis based on the meaning of the
words, instead of on the keywords and numbers.
Hyper Text Markup Language (HTML):
HTML stands for Hyper Text Markup Language
HTML is the standard markup language for creating Web pages
HTML describes the structure of a Web page
42
HTML XML
It designed to display the data It is designed to carry data
Its tags are predefined Its tags user defined
It is not case sensitive It is case sensitive
It is static It is dynamic
It is Markup Language It is framework to define Markup language
Closing tags are not necessary in HTML Closing tags are necessary in XML
Domain names
A domain name is a website's address on the Internet.
Domain names are used in URLs to identify to which server belong a specific webpage.
The domain name consists of a hierarchical sequence of names (labels) separated by periods
(dots) and ending with an extension.
URL
Uniform Resource Locator (URL) is a text string that specifies where a resource (such as a web
page, image, or video) can be found on the Internet.
Website
Website is a group of web pages, containing text, images and all types of multi-media files.
Web browser-
A web browser, or simply "browser," is an application used to access and view websites. Common
web browsers include Microsoft Internet Explorer, Google Chrome, Mozilla Firefox, and Apple
Safari.
Web servers:
A web server is a computer that stores web server software and a website's component files (e.g.
HTML documents, images, CSS style sheets, and JavaScript files).
Web hosting:
Web hosting is an online service that enables you to publish your website or web application on the
internet. When you sign up for a hosting service, you basically rent some space on a server on which
you can store all the files and data necessary for your website to work properly.
DNS Server
Instead of remembering IP addresses, we assign a domain name to each IP. But, to access a web
resource, a browser needs to find out the IP address corresponding to the domain name entered.
Conversion of the domain name of each web server to its corresponding IP address is called domain
name resolution. It is done through a server called DNS server. Thus, when we enter a URL on a
web browser, the HTTP protocol approaches a computer server called DNS server to obtain the IP
address corresponding to that domain name. After getting the IP address, the HTTP protocol
retrieves the information and loads it in our browser.
ABBREVIATIONS
1 MARKS QUESTION
1 Fill in the blank: ______is a communication methodology designed to deliver both voice and
multimedia communications over Internet protocol.
(a) VoIP (b) SMTP (c) PPP (d)HTTP
Ans (a) VoIP
2 What is the Use of Bridge?
(a) To Connect two LAN (b) To Connect two LAN Segment
(a) To Connect Internet (d) Amplify Signal
45
9 Each IP packet must contain
A. Only Source address B. Only Destination address
C. Source and Destination address D. Source or Destination address
Ans C. Source and Destination address
10 _______ provides a connection-oriented reliable service for sending messages
A. TCP B. IP C. UDP D. All of the above
Ans A. TCP
11 Which of the following is not a feature of networking?
(a) Resource sharing (b) Uninterrupted Power Supply (UPS)
(c) Reduced cost (d) Reliability
Ans (b) Uninterrupted Power Supply (UPS)
12 Which of these is not a communication channel?
a) Satellite b) Microwave c) Radio wave d) Wi-Fi
Ans d) Wi-Fi
15 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
Ans d) Fiber optic
16 Which type of transmission media is the least expensive to manufacture?
a) Coaxial b) Twisted pair cable c) CAT cable d) Fiber optic
Ans b) Twisted pair cable
17 A device that forwards data packet from one network to another is called a
a) Bridge b) Router c) Hub d) Gateway
Ans b) Router
19 Switch is a
a) Broadcast device b) Unicast device c) Multicast device d) None of the above
Ans b) Unicast device
46
a) Gateways b) Linux c) Routers d) Firewalls
Ans b) Linux
2 MARKS QUESTION
1 Differentiate e between XML and HTML.
Ans HTML( Hyper text mark Up language) XML (Extensible Markup Language)
We use pre-defined tags we can define our own tags and use
them
Static web development language – only Dynamic web development language
focuses on how data looks
It use for only displaying data, cannot as it is used for transporting and storing
transport data data
Not case sensitive Case sensitive
2 How is http different from https?
Ans https (Hyper Text Transfer Protocol Secure) is the protocol that uses SSL (Secure Socket Layer) to
encrypt data being transmitted over the Internet. Therefore, https helps in secure browsing while
http does not.
3 Write two points of difference between Circuit Switching and Packet Switching.
Ans Circuit Switching Packet Switching
Circuit switching is the method of switching Packet switching is the method of switching
which is used for establishing a dedicated where no dedicated path is established from
communication path between the sender the source to the destination.
and the receiver
Data is processed and transmitted at the Data is processed and transmitted, not only
source only. at the source but at each switching station
It is more reliable. It is less reliable.
4 How is http different from https?
Ans https (Hyper Text Transfer Protocol Secure) is the protocol that uses SSL (Secure Socket Layer) to
encrypt data being transmitted over the Internet. Therefore, https helps in secure browsing while
http does not.
5 Differentiate e between LAN and WAN.
47
Ans Difference between LAN and WAN
LAN is private. WAN can be private or public.
The full form of LAN is Local Area The full form of WAN is Wide Area Network.
Network.
The speed of LAN is higher. The speed of WAN is slower.
The configuration and maintenance is easy The configuration and maintenance is harder
in LAN. than LAN.
LAN covers smaller areas like school, WAN covers a large area like a country.
hospital, etc.
Coaxial or UTP cable is the transmission PSTN or satellite link is a transmission
medium used by LAN. medium used by WAN.
6 Explain Any two Wired Media
Ans a. Twisted Pair Cable
A twisted pair cable comprises of two separate insulated copper wires, which are twisted together
and run in parallel.
b. Fibre Optics
Fibre optic cables are mainly used to transmit information over long distances with minimum loss.
The information through optical fibres is transmitted in the form of light pulses. The core of the optical
fibres is made of glass or plastic.
7 Define Any Two Topologies
Ans a. Star
Star topology is a network topology in which each network component is physically connected to a
central node such as a router, hub or switch. In a star topology, the central hub acts like a server
and the connecting nodes act like clients
b. Bus
A bus topology is a type of local area network configuration in which computers or terminals (also
known as nodes) are connected to a single cable (as known as the backbone)
Ans ARPANET (Advanced Research Project Agency Network) is a project sponsored by US Department
of Defense.
NSFNET, developed by the National Science Foundation, was a high-capacity network and strictly
used for academic and engineering research.
48
5 MARKS QUESTION
1 MakeInIndia Corporation, an Uttarakhand based IT training company, is planning to set up training centres in
various cities in next 2 years. Their first campus is coming up in Kashipur district. At Kashipur campus, they are
planning to have 3 different blocks for App development, Web designing and Movie editing. Each block has
number of computers, which are required to be connected in a network for communication, data and resource
sharing. As a network consultant of this company, you have to suggest the best network related solutions for
them for issues/problems raised in question nos. (i) to (v), keeping in mind the distances between various
KASHIPUR
APP CAMPUS
DEVELOPM MOVIE
ENT EDITING
MUSSOORIE
CAMPUS
WEB
DESIGNING
Distance
between various blocks/locations:
Block Distance
App development to Web designing 28 m
App development to Movie editing 55 m
Web designing to Movie editing 32 m
Kashipur Campus to Mussoorie Campus 232 km
Number of computers
Block Number of Computers
App development 75
Web designing 50
Movie editing 80
I Suggest the most appropriate block/location to house the SERVER in the Kashipur campus
(out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
Ans Movie editing block is the most appropriate to house the server as it has the maximum number of computers.
II Suggest a device/software to be installed in the Kashipur Campus to take care of data security.
Ans Firewall
III Suggest the best wired medium and draw the cable layout (Block to Block) to economically connect various
blocks within the Kashipur Campus
Ans Ethernet Cable
Layout:
KASHIPUR
APP CAMPUS
DEVELOP MOVIE
MENT EDITING
WEB
DESIGNING
49
V Suggest a protocol that shall be needed to provide Video Conferencing solution between Kashipur Campus and
Mussoorie Campus.
Ans Protocol: VoIP
2 JNV School at Hyderabad have their offices according to the following diagram. Go through the details
and answer the questions that follows.
JNV,
MESS7
NOIDA
SCHOOL40
5 ADMIN10
Hyderabad
Star Topology
MESS7
SCHOOL40
5 ADMIN10
II Suggest a device/software and its placement that would provide data security for the entire network of the
School.
Ans Firewall
III (a) Which device will you suggest to be placed/installed in each of these wings to efficiently connect all
the computers within these wings.
(b) Suggest the placement of a repeater in the network with justification.
Ans (a)- Switch
(b) Repeater will be placed between MESS and DORMETORY, MESS and ADMIN, DORMETORY and
GATE , DORMETORY and ADMIN because distance in these building is more than 100 meters
IV Suggest a device and the protocol that shall be needed to provide wireless Internet access to all
smartphone/laptop users in the campus of JNV, Hyderabad.
50
Ans WiFi Router
V Which of the following will you suggest to establish the online face to face communication between the
people in the ADMIN office of Hyderabad campus and Noida head office?
a) Cable TV b) Email c) Video conferencing d) Text chat
Ans c) Video conferencing
3 Prime Computer services Ltd. is an international educational organization. It is planning to set up its India
campus at Mumbai with its head office in Delhi. The Mumbai office campus has four main buildings-ADMIN,
ACCOUNTS, EXAMINATION and RESULT.
You as a network expert have to suggest the best network related solutions for their problems raised in (i) to
(v), keeping in mind the distances between the buildings and other given parameters
MUMBAI CAMPUS
ADMIN
RESULT
MUMBAI CAMPUS
EXAMINATION ACCOUNTS
ADMIN RESULT
II Suggest the most appropriate location of the server inside the MUMBAI campus (out of the four buildings) to
get the best connectivity for maximum number of computers. Justify your answer.
51
Ans Admin block, as it has maximum number of computers.
III Which networking device will you suggest to be procured by the company to interconnect all the computers of
various buildings of MUMBAI campus?
Ans Switch
IV Company is planning to get its website designed which will allow students to see their results after registering
themselves on its server. Out of the static or dynamic, which type of website will you suggest?
Ans Dynamic
V Which fast and very effective wireless transmission medium should preferably be used to connect the head
office at DELHI with the campus in MUMBAI?
Ans Microwave
52
4 MyPace University is setting up its academic blocks at Naya Raipur and is planning to
set up a network. The University has 3 academic blocks and one Human Resource
Center as shown in the diagram below:
I Suggest the most suitable place (i.e., Block/Center) to install the server of this
University with a suitable reason.
Ans HR Center, as it has maximum number of computers.
II Suggest an ideal layout for connecting these blocks/centers for a wired connectivity.
III Which device will you suggest to be placed/installed in each of these blocks/centers to
efficiently connect all the computers within these blocks/centers.
Ans Switch
IV Suggest the placement of a Repeater in the network with justification.
Ans Between Law Block to HR center, because distance is more than 100 meters
V The university is planning to connect its admission office in Delhi, which is more than
1250km from university. Which type of network out of LAN, MAN, or WAN will be
formed? Justify our answer.
Ans WAN, because distance is more than 1250 km
53
5 Meticulous EduServe is an educational organization. It is planning to setup its India campus at
Chennai with its head office at Delhi. The Chennai campus has 4 main buildings – ADMIN,
ENGINEERING, BUSINESS and MEDIA
ADMIN ENGINEERING
MEDIA BUSINESS
b Which network device will be used to connect computers in each block to form a local area
network?
Ans Switch
c Which block, in Chennai Campus should be made the server? Justify your answer.
54
Ans Admin block, as it has maximum number of computers.
d The company is planning to link its head office situated in New Delhi with the offices in hilly
areas. Suggest a way to connect it economically.
Ans Microwave
e Is there a requirement of a repeater in the given cable layout? Why/ Why not?
Ans No, a repeater is not required in the given cable layout as the length of transmission
medium between any two blocks does not exceed 70 m.
55
6. Database concepts
Unit III: Database Management ● Database concepts: introduction to database concepts
and its need ● Relational data model: relation, attribute, tuple, domain, degree, cardinality,
keys (candidate key, primary key, alternate key, foreign key)
Database Instance
56
When we define database structure or schema, state of database is empty i.e. no data entry
is there. Afterloading data, the state or snapshot of the database at any given time is the
database instance.
Query
A query is a request to a database for obtaining information in a desired way.
Data Manipulation
Modification of database consists of three operations viz. Insertion, Deletion or Update.
Database Engine
Database engine is the underlying component or set of programs used by a DBMS to create
database and handle various queries for data retrieval and manipulation.
57
Component of a table/relation:
Data Item: smallest unit of named data. It represent one type of information and often
referred to as a field or column information
Record : collection of data items which represent a complete unit of information
Table: collection of all Rows and Columns.
Properties of a Relation:
Each relation has a unique name by which it is identified in the database.
Relation does not contain duplicate tuples.
The tuples of a relation have no specific order.
All attributes in a relation are atomic, i.e., each cell of a relation contains exactly one value.
Properties of a row:
o No two tuples are identical to each other in all their entries.
o All tuples of the relation have the same format and the same number of entries.
o The order of the tuple is irrelevant. They are identified by their content, not by their position.
Properties of an Attribute:
NULL Values
The NULL value of the table specifies that the field has been left blank during record creation. It is
different from the value filled with zero or a field that contains space.
Data Integrity
There are the following categories of data integrity exist with each RDBMS:
Domain integrity: It enforces valid entries for a given column by restricting the type, the format, or
the range of values.
Referential integrity specifies that rows cannot be deleted, which are used by other records.
User-defined integrity: It enforces some specific business rules defined by users. These rules are
different from the entity, domain, or referential integrity.
Concept of Keys
In relation each record must be unique i.e. no two identical records are allowed in the
Database.
A key attribute identifies the record and must have unique values. There are various types
of Keys:
Primary key:
58
A set of one or more attribute that can identify a record uniquely in the relation is called
Primary Key.
There can be only one primary key in a table
Allows only distinct (no duplicate) values and also forces mandatory entry (NOT NULL) i.e.
we can’t leave it blank.
Candidate Key
In a table there can be more than one attribute which uniquely identifies a tuples in a
relation. These columns are known as candidate key as they are the candidate for primary
key.
Among these database analyst select only one attribute as a primary key.
Alternate Key
In case of multiple candidate keys, one of them will be selected as Primary Key and rest of
the column will serve as Alternate Key.
A Candidate Key which is not a primary key is an Alternate Key.
59
Foreign key
Used to create relationship between two tables.
It is a non-key attribute whose value is derived from the Primary key of another table.
Primary Key column table from where values will be derived is known as Primary Table or
Master Table or Parent Table and Foreign key column table will be Foreign Table or Detail
Table or Child table.
REFERENTIAL INTEGRITY:
Used to ensure relationships between records in related tables are valid and user don’t
accidentally delete or change the related data.
Referential integrity can be applied when:
The master table’s column is a Primary Key or has a unique index
The related fields have the same data type
Both tables must belong to same database.
When referential integrity is enforced using Foreign Key you must observe the following
rules:
You cannot enter a value in Child Table which is not available in Master
Table’s Primary key column. However you can enter NULL values in foreign
key
You cannot delete a record from Master Table if matching record exists in
related table.
You cannot modify or change the Primary Key value in Master table if its
matching record is present in related table.
1 MARKS QUESTION
6 What is a database?
a) Organized collection of information that cannot be accessed, updated, and managed
b) Collection of data or information without organizing
c) Organized collection of data or information that can be accessed, updated, and
managed
d) Organized collection of data that cannot be updated
Ans c) Organized collection of data or information that can be accessed, updated, and
managed
8 A…………………. is a non-key attribute whose value is derived from the primary key of
another table.
(a) Primary Key (b) Alternate Key
(c) Candidate Key (d) Foreign Key
Ans (d) Foreign Key
9 A pool of Values from where a column draws its value is called.
(a) Table (b) Attribute c) Domain (d) Data Set
Ans c) Domain
12 In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and another table,
Beta has degree 3 and cardinality 5, what will be the degree and cardinality of the
Cartesian product of Alpha and Beta?
a. 5,3 b. 8,15 c. 3,5 d. 15,8
Ans b. 8,15
61
d.A foreign key is an attribute whose value is derived from the primary key of another
relation.
Ans c.A candidate key that is not a primary key is a foreign key.
15 Special value that is stored when actual data value is unknown for an attribute. (NCERT)
(a) None (b) NULL (c) NaN (d) None of these
Ans (b) NULL
2 MARKS QUESTION
1 Explain the use of ‘Foreign Key’ in a Relational Database Management System.
Ans A foreign key is used to set or represent a relationship between two relations ( or tables) in
a database. Its value is derived from the primary key attribute of another relation
S.
Ans Primary Key Candidate Key
No.
Primary key is a unique and non−null Candidate key is also a unique key
1. key which identify a record uniquely in to identify a record uniquely in a
table. table.
Primary key column value cannot be Candidate key column can have
2.
NULL. NULL value.
Data Integrity - Data integrity is the overall completeness, accuracy and consistency of
data over its entire lifecycle.
7 Define Integrity Constraints in DBMS
Ans In database management systems (DBMS) there is a certain set of rules which are used to
maintain the quality and consistency of data in the database. Every time there is an insertion,
deletion, or updating of data in the database it is the responsibility of these integrity
constraints to maintain the integrity of data and thus help to prevent accidental damage to
the database.
8 What are the characteristics of primary key
Ans The data in a specific column is always unique.
A database table can only have one primary key.
It uniquely identifies a record in a relational database table.
The value of a primary key can't be deleted from the tree structure or the parent table.
It doesn't permit null values.
UNIT-3
RELATIONAL DATABASES
Key Points of the Chapters:
Database:-Collection of interrelated data . It is basically a computer-based record keeping system
that serve multiple applications.
Relational data model:-It is a type of DBMS in which data is organized into tables, these tables are
called relations.
Relation :- Relation is a table that means data is organized into rows and columns.
Domain:-It is a pool of values from which the actual values present in a given column are drawn.
Tuple:-A row in a relation is called a tuple that is horizontal part of a relation and represents a record
of relation
Attribute:- A column in a relation is called an attribute. It is also termed as field or data item.
Degree:- Number of attributes in a relation is called degree of a relation.
Cardinality:-Number of tuples in a relation is called cardinality of a relation.
View:- It is a virtual table that does not really exist in its own but is instead derived from one or more
underlying base table.
Field:- Set of characters that represents specific data element.
Record:-Collection of fields is called a record. A record can have fields of different data types.
Table:-Collection of rows and columns that contains useful data/information is called a table. A table
generally refers to the passive entity which is kept in secondary storage device.
63
Primary Key:-Primary key is set of one or more attributes that can uniquely identifies the
records/tuples in a relation. This key can never be duplicated and NULL.
Candidate Key: Set of all attributes which can serve as a primary key in a relation.
Alternate Key: All the candidate keys other than the primary keys of a relation are alternate keys
for a relation.
Foreign Key: A non-key attribute, whose values are derived from the primary key of some other
table is known as foreign key in its current table.
Employee table
Emp_id Emp_name salary PAN No Dept_no NPS_no
23008 Ramesh 50000 NALK8907P 10 32FG67
24009 kavita 35000 LMSA9845K 14 87KH86
23908 sana 45000 KMSN6789O 11 78PO98
Department table
Dept_no Dept_name Head
10 Marketing Mrs. Sumitra
11 Sales Mr. Raja raman
12 Purchasing Mr. K P Singh
13 Manufacturing Mr. JyotiRanjan
14 Store Miss Suman
DDL(Data Definition language): The DDL provides commands for the creation and deletion
and alteration of tables. DDL commands are: CREATE , ALTER , DROP
DML(Data Manipulation language): The DML provides commands to enter, update, delete
data and perform complex queries on these tables.
DML commands are: SELECT, INSERT, DELETE, UPDATE
TCL(Transaction Control Language) :TCL include commands to control the transactions
in a data base system. The TCL commands are: COMMIT, ROLLBACK , SAVE POINT
Relational Algebra:
CARTESIAN PRODUCT (X)
Let R and S be relations of degree n1 and n2 respectively. Then the Cartesian Product of R and
S, is of degree n1+n2 and Cardinality as n1*n2. It is denoted by R X S
Relation R Relation S
Relation R X S
SQL is a non procedural language that is used for accessing, handling and manipulating in the
databases(relations).
Data types of SQL
Just like any other programming language, the facility of defining data of various types is available
in SQL also. Following are the most common data types of SQL.
a. CREATE TABLE Command: Create table command is used to create a table in SQL. It is a
DDL type of command. The general syntax of creating a table is
1. Arithmetic Operators +, -, *, /
2. Relational Operators =, <, >, <=, >=, <>(not equal to)
3. Logical Operators OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations.
Relational Operators are used when two values are to be compared and
Logical operators are used to combine more than one search conditions in the WHERE Clause in
SQL.
Constraints:
65
Constraints are the conditions that can be enforced on the attributes of a relation. The constraints
come in play whenever we try to insert, delete or update a record in a relation.
After a table has been created using the create table command, tuples can be inserted into the table,
or tuples can be deleted or modified.
INSERT Statement
The simplest way to insert a tuple into a table is to use the insert statement
insert into <tablename> [(<column i, . . . , column j>)] values (<value i, . . . , value j>);
INSERT INTO student VALUES(101,'Rohan','XI',400,'Jammu');
INSERT INTO student VALUES(val1,val2, ………),(val1,val2,…….),(val1,val2,…….);
To retrieve information from a database we can query the databases. SQL SELECT statement is
used to select rows and columns from a database/relation.
SELECT Command
The columns to be selected from a table are specified after the keyword select. This operation is
also called projection. For example, the query select LOC, DEPTNO from DEPT; lists only the
number and the location for each tuple from the relation DEPT. If all columns should be selected,
the asterisk symbol “*” can be used to denote all attributes. The query
Select * from EMP;
retrieves all tuples with all columns from the table EMP. Instead of an attribute name, the select
clause may also contain arithmetic expressions involving arithmetic operators etc.
Eliminating Duplicate/Redundant data
DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement.
e.g. SELECT DISTINCT name FROM student;
The above command returns non-repeating values for name column
Selecting a specific Rows (Where)
it will select only those rows which fulfill the specific criteria.
SELECT <column name>[, <column name>]
FROM <table name>
WHERE <condition>
Eg:- SELECT empno, name From Emp WHERE sal>50000
Relational Operators
compare two values =,>,<,>=,<=,<>
Eg:- SELECT * FROM emp WHERE Dept=20
Logical operator
i) OR :-if one of both condition is true it will select row and show
ii) AND:- if both condition is true then only it will select row and show it
iii) NOT:- show details of those who does not fulfil the criteria
Conditions based on a range
SQL provides a BETWEEN operator that defines a range of values that the column value must fall
for the condition to become true.
67
e.g. SELECT Roll_no, name FROM student WHERE Roll_no BETWENN 100 AND 103;
The above command displays Roll_no and name of those students whose Roll_no lies in the range
100 to 103 (both 100 and 103 are included in the range).
Conditions based on a list
To specify a list of values, IN operator is used. This operator selects values that match any value in
the given list.
e.g. SELECT * FROM student WHERE city IN (‘Jammu’,’Amritsar’,’Gurdaspur’);
The above command displays all those records whose city is either Jammu or Amritsar or
Gurdaspur.
Conditions based on Pattern
SQL provides two wild card characters that are used while comparing the strings with LIKE operator.
a. percent(%) Matches any string
b. Underscore(_) Matches any one character
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “%3”;
displays those records where last digit of Roll_no is 3 and may have any number of characters in
front.
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “1_3”;
displays those records whose Roll_no starts with 1 and second letter may be any letter but ends
with digit 3.
ORDER BY Clause
ORDER BY clause is used to display the result of a query in a specific order(sorted order).
The sorting can be done in ascending or in descending order. It should be kept in mind that the
actual data in the database is not sorted but only the results of the query are displayed in sorted
order.
e.g. SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.
e.g. SELECT * FROM student ORDER BY city DESC;
It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in ascending order.
GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple
records and group the results by one or more columns.
The syntax for the GROUP BY clause is:
68
SELECT column1, column2, ...column_n, aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY column1, column2, ... column_n;
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a
SELECT statement to filter the records that a GROUP BY returns.
The syntax for the HAVING clause is:
Note: select statement can contain only those attributes which are already present in the
group by clause.
JOINS :
Join is a query which fetches the data from multiple tables. There are 4 types of joins.
1.Equi Join :-Which will fetch data from multiple tables when a common attribute is
available among the tables.
E.X 1:-Select ename, deptno, loc from EMP, DEPT where EMP.deptno=DEPT.deptno;
2.Non-Equi Join:- Which will fetch data from multiple tables when no common
attribute is available among the tables.
Select ename, deptno, sal,grade from EMP, SALGRADE where EMP.sal between
SALGRADE .losal and SALGRADE .hisal ;
69
SQL Functions:
SQL provide large collection of inbuilt functions also called library functions that can be used directly
in SQL statements.
1. Mathematical functions
Sum(): to find sum total value of a given attribute.
Select SUM(sal) "total" from emp;
If the where clause is omitted, all tuples are deleted from the table. An alternative command for
deleting all tuples from a table is the truncate table <table> command. However, in this case, the
deletions cannot be undone.
Example:
Delete all projects (tuples) that have been finished before the actual date (system date):
delete from PROJECT where PEND <sysdate;
Note:-sysdate is a function in SQL that returns the system date.
Updates
For modifying attribute values of (some) tuples in a table, we use the update statement:
update<table> set <column i> = <expression i>, . . . , <column j> = <expression j>
70
[where<condition>];
typically, however, only a (small) portion of the table requires an update.
Examples:
• The employee JONES is transfered to the department 20 as a manager and his salary is
increased by 1000:
update EMP set JOB = ’MANAGER’, DEPTNO = 20, SAL = SAL +1000
where ENAME = ’JONES’;
• All employees working in the departments 10 and 30 get a 15% salary increase.
update EMP set SAL = SAL* 1.15 where DEPTNO in (10,30);
In such a case we have a <query> instead of an <expression>.
ALTER TABLE Command
In SQL if we ever need to change the structure of the database then ALTER TABLE command is
used. By using this command, we can add a column in the existing table, delete a column from a
table or modify columns in a table.
Adding a column
71
DROP TABLE Command
Sometimes you may need to drop a table which is not in use. DROP TABLE command is used to
Delete / drop a table permanently.
The general syntax of this command is:-
DROP TABLE <table_name>;
e.g DROP TABLE student;
This command will remove the table student from the database.
____________________________________________________________________
Questions & Answers
1 Mark Questions (MCQ)
1, ______________command is used to change table structure in SQL.
(A) update (B) change (C) alter (D) modify
2. Which of the following commands will remove the entire database from MYSQL?
(A) DELETE DATABASE (B) DROP DATABASE
(C) REMOVE DATABASE (D) ALTER DATABASE
3._________ is a non-key attribute, whose values are derived from the primary key of some
other table.
(A) Primary Key (B) Candidate Key (C) Foreign Key (D) Alternate Key
4.The SELECT statement when combined with clause, returns records without repetition.
(A) DISTINCT (B) DESCRIBE (C) UNIQUE (D) NULL
5. Which function is used to display the total number of records from a table in a database?
(A) total() (B) total(*) (C) return(*) (D) count(*)
6.Which of the following is not part of a DDL query?
(A) DROP (B) MODIFY (C) DISTINCT (D) ADD
7.Which statement in MySql will display all the tables in a database?
(A) SELECT * FROM TABLES; (B) USE TABLES;
(C) DESCRIBE TABLES; (D) SHOW TABLES;
8.Which of the following is a valid sql statement?
72
9. Which command is used to remove a column from a table in SQL.
(a) update (b)remove (c) alter (d)delete
10. Which of the following ignores the NULL values in SQL?
(a) Count(*) (b) count() (c) total(*) (d) None of these
11. Which of the following commands will be used to select a particular database named “Student”
from MYSQL Database?
73
(a) IN (b) BETWEEN (c) IS (d) DISTINCT
22. The SELECT statement when combined with _______clause, returns records in sorted
order.
(a) SORT (b) ARRANGE (c) ORDER BY (d) SEQUENCE
22. Which of the following constraint is used to prevent a duplicate value in a record?
(a) Empty (b) check (c) primary key (d) not null
23. ________keyword is used to obtain unique values in a SELECT query
(A) UNIQUE B) DISTINCT C) SET D) HAVING
Answers:
___________________________________________________________________
2 Marks Questions
1. Differentiate between CHAR() and VARCHAR().
Ans.
CHAR VARCHAR
CHAR datatype is used to store VARCHAR datatype is used to store character
character strings of fixed length strings of variable length
In CHAR, If the length of the string In VARCHAR, If the length of the string is less than the
is less than set or fixed-length then it set or fixed-length then it will store as it is without
is padded with extra memory space. padded with extra memory spaces.
Storage size of CHAR datatypes is The storage size of the VARCHAR datatype is equal to
equal to n bytes i.e. set length the actual length of the entered string in bytes.
We should use the CHAR datatype We should use the VARCHAR datatype when we
when we expect the data values in a expect the data values in a column are of variable
column are of the same length. length.
74
CHAR takes 1 byte for each VARCHAR takes 1 byte for each character and
character some extra bytes for holding length information
Ans. The difference between WHERE and HAVING clause is that WHERE condition
is applicable on individual rows whereas HAVING condition are applicable on
groups as formed by GROUP BY clause.
3. Differentiate between COUNT(column name) AND COUNT(*) with appropriate examples.
Ans. COUNT(*) will count all the rows in the table, including NULL values. On the other hand,
COUNT(column name) will count all the rows in the specified column while excluding NULL
values.
4. What do you understand by the terms Degree, cardinality of a Relation? Explain with an
example.
Degree: No. of columns(attribute) of a table
Cardinality: No.of rows( Tuples) of a table
Ex: EMP Table
5. What do you understand by the terms PRIMARY KEY and UNIQUE KEY of a relation in
relational database?
Ans. PRIMARY KEY: The PRIMARY KEY uniquely identifies each record in a table. Primary
keys contain UNIQUE values, and cannot contain NULL values. A table can have only ONE
primary key in the table, this primary key can consist of single or multiple columns (fields).
UNIQUE KEY: It Uniquely determines a row which isn’t primary key. It can accept NULL
values. More than one Unique key can be defined in one table.
6. What are constraints in SQL? Give two examples.
Ans. SQL constraints are used to specify rules o for the data in a table. Constraints are used
to limit the type of data that can go into a table. This ensures the accuracy and reliability
of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.
Examples
NOT NULL, UNIQUE, PRIMARY KEY, CHECK etc.
75
7. What are aggregate functions in MySql? Give their names along with their use.
Ans. Aggregate functions are also known as group functions. It works on more than one row in a
table. Various aggregate functions in MySql are- sum(), min(), max(),avg() and count().
8. List various DDL and DML commands available in MySql
Ans. DDL commands- CREATE, ALTER, DROP
DML commands- INSERT, UPDATE, DELETE, SELECT
9. Differentiate between DDL and DML? with one Example each.
Ans. 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
10. Write two points of difference between ALTER and UPDATE command in SQL.
ALTER UPDATE
It is a DDL command. It is a DML command.
ALTER Command is used toadd, UPDATE Command is used toupdate
delete, modify the attributes of the existing records in a database.
relations
(tables) in the database.
ALTER Command by default initializes UPDATE Command setsspecified
values of all the tupleas NULL. values in the command to the tuples.
This command make changes This command makes changes
with table structure. with data inside the table.
Ans.
11. Mention two differences between a PRIMARY KEY and a UNIQUE KEY.
Ans.
12. What is the difference between a Candidate Key and an Alternate Key
76
13. Observe the following table and answer the parts (i) and(ii) accordingly
Table:Product
Pno Name Qty PurchaseDate
101 Pen 102 12-12-2011
102 Pencil 201 21-02-2013
103 Eraser 90 09-08-2010
109 Sharpener 90 31-08-2012
113 Clips 900 12-12-2011
(i) Write the names of most appropriate columns, which can be considered as candidate keys.
Ans: Pno
(ii) What is the degree and cardinality of the above table?
Ans: Degree : 4 , Cardinality : 5
14 How is equi-join different from natural-join? Give example.
Ans: Equi-join : It is a sql join where we use the equal sign as the comparison operator while
specifying the join condition. In this, the common column from both the tables will
appear twice in the output.
Natural join : It is similar to Equi-join but only one of the identical columns exist in the
output. Example :
select * from student, course where course.cid = student.cid; (Equi-join) select *
from student natural join course where course.cid = student.cid; (Natural join)
15 Differentiate between an Attribute and a Tuple in a Relational Database
with suitable example.
Ans: Attributes / Field: Columns of the table (Relation) is called as attributes.
Tuple: Rows of the table (relation) is called as a tuple (record).
______________________________________________________________________
03 Marks Questions
1. Observe the following table and answer the question:
TABLE: VISITOR
VisitorID VisitorName ContactNumber
V001 ANAND 9898989898
V002 AMIT 9797979797
V003 SHYAM 9696969696
V004 MOHAN 9595959595
1. Which command will be used to see the Structure of a table Visitor ?
2. What is the degree and cardinality of the table?
77
3. Insert the following data into the attributes VisitorID, VisitorName and ContactNumber
respectively in the given table VISITOR.
VisitorID = “V004”, VisitorName= “VISHESH” and ContactNumber=9907607474
Ans: 1. DESCRIBE VISITOR;
2. Degree= 3, Cardinality=4
3. insert into VISITOR values(“V004”, “VISHESH”,9907607474)
2. Write query for the following:
4. Display number of records along-with sum of salaries for each Individual Designation
Where Number of records are more than 1.
2 102
ii. DISTINCT CODE
101
103
102
104
105
iii. Code Name Vtype
104 Ahmed Khan Car
105 Raveena Suv
ii.
MAX(M_Mf_Date) MIN(M_Mf_Date)
2017-11-20 2010-08-21
iii. 5450
80
_______________________________________________________________________
04 Marks Questions
1. Consider the following tables GAMES and PLAYER. Write SQL commands for the
statements (i) to (iv) .
Table: GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004
Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103
(i) To display the name of all Games with their Gcodes.
(ii) To display details of those games which are having PrizeMoney more than 7000.
(iii) To display the content of the GAMES table in ascending order of ScheduleDate.
(iv) To display sum of PrizeMoney for each of the Number of participation groupings (as
shown in column Number 2 or 4)
Answer
(i) SELECT GameName,Gcode FROM GAMES;
(ii) SELECT * FROM GAMES WHERE PrizeMoney>7000;
(iii) SELECT * FROM GAMES ORDER BY ScheduleDate;
(iv) SELECT SUM(PrizeMoney),Number FROM GAMES GROUP BY Number;
2. Consider the following tables FACULTY and COURSES. Write SQL commands for the
statements (i) to (iv) .
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) To display details of those Faculties whose salary is greater than 12000.
ii) To display the details of courses whose fees is in the range of 15000 to 50000 (both
values included).
iii) To display details of those courses which are taught by ‘Sulekha’ in descending order
of courses ?
81
iv) Select COUNT(DISTINCT F_ID) from COURSES;
Answer
(i) Select * from faculty where salary > 12000;
(ii) Select * from Courses.where fees between 15000 and 50000;
(iii) Select * from faculty fac, courses cour where fac.f_id = cour.f_id and fac.fname =
'Sulekha' order by cname desc;
(iv) 4
4 Consider the following tables Sender and Recipient. Write SQL commands for the
statements (i) to (iv).
Sender
SenderID SenderNam SenderAddress Sendercity
e
ND01 R Jain 2, ABC Appls New Delhi
MU02 H Sinha 12 Newtown Mumbai
MU15 S Jha 27/A, Park Street Mumbai
ND50 T Prasad 122-K,SDA New Delhi
Recipients
RecID SenderID RecName RecAddress recCity
KO05 ND01 R Bajpayee 5, Central Avenue Kolkata
ND08 MU02 S Mahajan 116, A-Vihar New Delhi
MU19 ND01 H Singh 2A, Andheri East Mumbai
MU32 MU15 P K Swamy B5, C S Terminals Mumbai
ND48 ND50 S Tripathi 13, BI D Mayur Vihar New delhi
i. To display the names of all Senders from Mumbai
82
ii. To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every
Recipient
iii. To display Recipient details in ascending order of RecName
iv. To display number of Recipients from each city
Answer-
i.SELECT sendername from Sender where sendercity=’Mumbai’;
ii.Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress
from Sender S, Recepient R
where S.SenderID=R.SenderID ;
iii.SELECT * from Recipent ORDER By RecName;
iv.SELECT RecCity, COUNT( *) from Recipient Group By RecCity;
5 Write SQL queries for (i) to (iv) which are based on the tables.
Table : VEHICLE
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
Note : PERKM is Freight Charges per kilometer , VTYPE is Vehicle Type
Table : TRAVEL
TDAT
NO NAME E KM CODE NOP
101 Janish Kin 2015-11-13 200 101 32
103 Vedika Sahai 2016-04-21 100 103 45
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed Khan 2015-01-10 75 104 2
104 Raveena 2016-05-28 80 105 4
• NO is Traveller Number
• KM is Kilometer travelled
• NOP is number of travellers travelled in vehicle
• TDATE is Travel Date
i. To display NO, NAME, TDATE from the table TRAVEL in descending order of NO.
ii. To display the NAME of all the travellers from the table TRAVEL who are travelling by
vehicle with code 101 or 102.
iii. To display the NO and NAME of those travellers from the table TRAVEL who travelled
between ‘2015-12-31’ and ‘2015-04-01’.
iv. To display all the details from table TRAVEL for the travellers, who have travelled
distance more than 100 KM in ascending order of NOP.
Answer-
i. SELECT NO, NAME, TDATE FROM TRAVEL ORDER BY NO DESC;
ii. SELECT NAME FROM TRAVEL WHERE CODE=‘101’ OR CODE=’102’;
OR
SELECT NAME FROM TRAVEL WHERE CODE IN (101,102);
iii. SELECT NO, NAME from TRAVEL
WHERE TDATE >= ‘2015-04-01’ AND TDATE <= ‘2015-12-31’;
OR
SELECT NO, NAME from TRAVEL WHERE TDATE BETWEEN ‘2015-04-01’ AND
‘2015-12-31’;
iv. SELECT * FROM TRAVEL WHERE KM > 100 ORDER BY NOP;
83
6 Consider the following relations MobileMaster & MobileStock:-
MobileMaster
M_Id M_Company M_Name M_Price M_Mf_Date
MB001 Samsung Galaxy 4500 2013-02-12
MB003 Nokia N1100 2250 2011-04-15
MB004 Micromax Unite3 4500 2016-10-17
MB005 Sony XperiaM 7500 2017-11-20
MB006 Oppo SelfieEx 8500 2010-08-21
MobileStock
S_Id M_Id M_Qty M_Supplier
S001 MB004 450 New Vision
S002 MB003 250 Praveen Gallery
S003 MB001 300 Classic Mobile Store
S004 MB006 150 A-one Mobiles
S005 MB003 150 The Mobile
S006 MB006 50 Mobile Centre
Write the SQL query for questions from (i) to (iv)
i. Display the Mobile company, Mobile name & price in descending order of their
manufacturing date.
ii. List the details of mobile whose name starts with „S‟.
iii. Display the Mobile supplier & quantity of all mobiles except „MB003‟.
iv. To display the name of mobile company having price between 3000 & 5000.
Answer-
i. SELECT M_Compnay, M_Name, M_Price FROM MobileMaster
ORDER BY M_Mf_Date DESC;
ii. SELECT * FROM MobileMaster WHERE M_Name LIKE “S%‟;
iii. SELECT M_Supplier, M_Qty FROM MobileStock WHERE M_Id <> ‘MB003’;
iv. SELECT M_Company FROM MobileMaster WHERE M_Price BETWEEN 3000
AND 5000;
7 Write SQL queries for (i) to (iv) which are based on the tables.
TRAINER
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARG 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000
COURSE
CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C204 DDTP 9000 2018-09-15 104
C205 DHN 20000 2018-08-01 101
C206 O LEVEL 18000 2018-07-25 105
(i) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute in the month of
December 2001.
84
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and
COURSE of all those courses whose FEES is less than or equal to 10000.
(iv) To display number of Trainers from each city.
Answer-
i. SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE;
ii. SELECT TNAME, CITY FROM TRAINER WHERE HIREDATE BETWEEN ‘2001-12-01’
AND ‘2001-12-31’;
iii. SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE
WHERE TRAINER.TID=COURSE.TID AND FEES<=10000;
iv. SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;
85
C_ID ConsumerName Address S_ID
1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
(i) Display the sum of all Loan Amounts whose Interest rate is greater than 10.
(ii) Display the Maximum Interest from Loans table
(iii) Display the count of all loan holders whose names are ending with „Sharma‟
Ans: (i) Select sum(Loan_Amount) from LOANS where Interest >10;
(ii) Select max(Interest) from LOANS;
(iii) Select count(*) from LOANS where Cust_Name Like “%Sharma‟;
Table : DEALERS
Dcode Dname Location
101 Vikash Stationers Lanka Varanasi
102 Bharat Drawing Emporium Luxa Varanasi
103 Banaras Books Corporation Bansphatak Varanasi
To display all the information about items containing the word “pen” in the field
(i)
Itname in the table STOCK.
(ii) List all the itname sold by Vikash Stationers.
(iii) List all the Itname and StkDate in ascending order of StkDate.
(iv) List all the Itname, Qty and Dname for all the items for the items quantity more than 40.
(v) List all the details of the items for which UnitPrc is more than 10 and <= 50.
Ans: (i) SELECT * FROM STOCK WHERE Itname LIKE “%pen%”;
(ii) SELECT DISTINCT(Itname) FROM STOCK,
DEALERS WHERE STOCK.Dcode= DEALERS.Dcode and dname=’
Vikash Stationers’;
(iii) SELECT Itname, StkDate FROM STOCK ORDER BY StkDate;
(iv) SELECT Itname, Qty, Dname FROM STOCK,
DEALERS WHERE STOCK.Dcode= DEALERS.Dcode and qty>40;
(v) SELECT * FROM STOCK WHERE UnitPrc BETWEEN 10 AND 50;
12 Consider the following tables BOOKS and ISSUED in a database named “LIBRARY”.
Write SQL commands for the statements (i) to (iv).
Table: BOOKS
BID BNAME AUNAME PRICE TYPE QTY
COMP11 LET US C YASHWANT 350 COMPUTER 15
GEOG33 INDIA MAP RANJEET P 150 GEOGRAPHY 20
HIST66 HISTORY R BALA 210 HISTORY 25
COMP12 MY FIRST C VINOD DUA 330 COMPUTER 18
LITR88 MY DREAMS ARVIND AD 470 NOBEL 24
Table: ISSUED
BID QTY_ISSUED
HIST66 10
COMP11 5
LITR88 15
(i) Display book name and author name and price of computer type books.
(ii) To increase the price of all history books by Rs 50.
(iii) Show the details of all books in ascending order of their prices.
(iv) To display book id, book name and quantity issued for all books which have been
issued.
Ans: (i) select BNAME,AUNAME,PRICE from BOOKS where TYPE=’COMPUTER’;
(ii) Update BOOKS set PRICE = PRICE+50 where TYPE=’HISTORY’;
87
(iii) Select * from BOOKS order by PRICE asc;
(iv) Select BID,BNAME, QTY_ISSUED from BOOKS,ISSUED where
BOOK.BID=ISSUED.BID;
13 Layna creates a table STOCK to maintain computer stock in vidyalaya. After creation
of the table, she has entered data of 8 items in the table.
Table : STOCK
stockid dopurchase name make Price
101 2020-07-06 CPU ACER 12000
102 2020-09-01 CPU ACER 12750
103 2020-09-01 MONITOR ACER 7500
104 2016-08-03 PROJECTOR GLOBUS 37250
105 2016-05-26 VISUALIZER GLOBUS 17500
106 2020-07-23 WIFI RECEIVER ZEBION 450
107 2015-02-18 PRINTER LEXMARK 38000
108 2020-07-23 HEADPHONE BOAT 750
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If three columns are added and 5 rows are deleted from the table stock, what will be
the new degree and cardinality of the above table?
(iii) Write the statements to:
(a) Insert the following record into the table
Stockid - 201, dateofpurchase – 18-OCT-2022, name – neckphone
Make – BoAT, price - 500
(b) Decrease the price of stock by 5% whose were purchased in year2020
(iii) Write the statements to:
(a) Delete the record of stock which were purchased before year 2015.
(b) Add a column STATUS in the table with datatype as char with 1 characters
Ans: i. stockid
ii. degree = 8, cardinality = 3
iii. (a) insert into stock values(201,’2022-10-18’,’neckphone’,’boat’,500);
(c) update stock set price=price*0.95 where year(dopurchase)=2020;
OR
(a) delete from stock where year(dopurchase) < 2015;
(b) alter table stock add column STATUS char(1);
14 Based on the given set of tables write answers to the following questions.
Table: flights
flightid model company
10 747 Boeing
12 320 Airbus
15 767 Boeing
88
Table: Booking
ticketno passenger source destination quantity price Flightid
10001 ARUN BAN DEL 2 7000 10
10002 ORAM BAN KOL 3 7500 12
10003 SUMITA DEL MUM 1 6000 15
10004 ALI MUM KOL 2 5600 12
10005 GAGAN MUM DEL 4 5000 10
a) Write a query to display the passenger, source, model and price for all bookings whose
destination is KOL.
b) Identify the column acting as foreign key and the table name where it
is present in the given example
Ans: a) SELECT passenger, source, model, price FROM booking, flights
WHERE bookings.flightid = flights.flightid AND destination='KOL';
b Flightid in the bookings table is the foreign key.
15 Write the outputs of the SQL queries (i) to (iii) based on the given relations :
Table: Stationary
Table: Consumer
C_ID ConsumerName Address S_ID
1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
4. To display C_ID, ClientName, City of all the clients and their corresponding
ProductName sold.
Ans: 1. Select ClientName, city from Client where city in(‘Delhi’,’Mumbai’);
2. update Product set Price = Price + Price*0.1;
3. select ProductName, Manufacturer, ExpiryDate from Product
where ExpiryDate<=’2010-12-31’;
4. Select C_ID, ClientName, City ,ProductName from Client, Product
Where Product.P_ID=Client.P_ID;
90