Chapter-Wise Concepts 2025
Chapter-Wise Concepts 2025
TABLE OF CONTENTS
SNO TOPIC
4 EXCEPTION HANDLING
6 DATA STRUCTURE
7 COMPUTER NETWORKS
8 DATABASE MANAGEMENT
1|Page
● Structured Query Language: introduction, Data Definition Language and Data
Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints
(not
2|Page
null, unique, primary key), create database, use database, show databases, drop
database, show tables, create table, describe table, alter table (add and remove an
attribute, add and remove primary key), drop table, insert, delete, select, operators
(mathematical, relational and logical), aliasing, distinct clause, where clause, in, between,
order by, meaning of null, is null, is not null, like, update command, delete command,
aggregate functions (max, min, avg, sum, count), group by, having clause, joins: cartesian
product on two tables, equi-join and natural join
● Interface of python with an SQL database: connecting SQL with Python, performing
insert, update, delete queries using cursor, display data by using connect( ), cursor( ),
execute( ), commit( ), fetchone( ), fetchall( ), rowcount, creating database connectivity
applications, use of %s format specifier or format( ) to perform queries.
Distribution of Marks
2 Computer Networks 10
3 Database Management 20
Total 70
UNIT I:COMPUTATIONAL THINKING AND PROGRAMMING
PYTHON REVISION TOUR
About Python:
Python programming language was developed by Guido Van Rossum in February 1991.
Python is based on two programming languages, ABC language and Modula-3
It is a case-sensitive programming language.
Python is one of the languages that are not strict about data types.
Python works in to modes – interactive and script
Python is Interpreted and Cross Platform Language, Free and Open Source, used for both
procedural and object-oriented programming.
Basic terminologies:
TOKEN / LEXICAL UNIT: Smallest individual unit in a Programming Language.
Types of Tokens (Keywords, Identifiers, Literals, Operators, Punctuators)
NOTE: Mnemonic: "Kind Intelligent Lions Often Prey”
TOKENS
Identifiers: These are the names given to variables, objects, classes or functions etc.
Identifier Naming Rules:
✔ Python identifiers must begin with a letter (A-Z or a-z) or an underscore (_)
✔ It can be followed by letters, digits (0-9), or underscores.
✔ However, Python keywords cannot be used as Identifiers
✔ Special characters like @, #, or $ cannot be while naming Identifiers.
✔ Length of identifier is endless and is case sensitive.
Literals / Constants: Data items that have a fixed value are called Literals.
Example: 5 (integer), 5.9 (float), True (Boolean), “Hello” (string)
Punctuators: Symbols that are used to organize sentence structure. These are used to give
syntactic and semantic meaning to the program statement.
Some commonly used punctuators are:
‘ “ # \ ( ) [ ] { } @ , : . = ;
Python Modules:
A module is a file containing Python code (functions, variables, classes) that can be imported
and used in other Python programs.
Modules help organize code and reuse functionality.
Random Number generation
random Module:
The random module in Python is a powerful tool for generating random numbers and
performing random operations.
To use the random module, you must import it first:
import random
It provides several functions to produce random values, simulate randomness,
and shuffle data.
Name of Method Description Example
method
Random random ( ) Generate a random float number import random
Float between 0.0 and 1.0. random. random ( )
Random randint ( ) Generate a random integer import random
Integer within a specified range (both random. randint (1, 10)
values inclusive)
Random randrange( ) Generate a random number import random
Range within a specified range with a random. randrange (0, 100, 5)
step. # Random number between 0 and
100, step 5
STRING
A string is a sequence of characters enclosed in single (' '), double (" "), or
triple (''' ''' / """ """) quotes.
Strings are immutable — once created, they cannot be changed.
Strings are indexed, starting from 0 (left to right) and -1 (right to left).
Use triple quotes (''' ''' or """ """) for multiline text.
Use \ to include special characters (e.g., \n for newline, \t for tab).
LIST
A list is a collection of items (elements) which are ordered.
Lists are mutable, meaning their contents can be changed after creation.
Lists can contain elements of different data types: integers, strings, floats, even other lists.
Lists are indexed, with the first element at index 0.
Defined using square brackets [].
Example:
my_list = [10, "Hello", 3.14, True]
TUPLE
Ordered – Elements are stored in a specific order.
Immutable – Once created, elements cannot be changed.
Allow duplicates – Tuples can contain repeated values.
Can hold different data types – Integers, strings, lists, etc.
Indexing – Elements can be accessed using indexes.
Faster than lists – Due to immutability.
Tuples written in parenthesis ( ).
Multiple element tuple Single element tuple
(d)
s[start:end:step]
"Hello"[::2]
"Hlo"
List lst=[10,20,30,40] [1,2] + [3,4] [0] * 3 3 in [1, 2, 3] L=[11,12,14,17]
[1,2,3] for i in lst: L[1:3]
print(i) [1,2,3,4] [0,0,0] True [12,14]
L[:3]
for i in range(len(lst)): [11,12,14]
print(lst[i])
Function /
Explanation Syntax Example Output
Method
Returns the number of
len( ) len(list) len([1, 2, 3]) 3
elements in the list
Converts an iterable (like
list ( ) list(iterable) list("abc") ['a', 'b', 'c']
string, tuple) to a list
Adds a single element at a = [1, 2]
append ( ) list.append(item) [1, 2, 3]
the end of the list a.append(3)
Adds elements of another a = [1]
extend ( ) list.extend(iterable) [1, 2, 3]
list to the end a.extend([2, 3])
Inserts an element at a list.insert(index, a = [1, 3]
insert ( ) [1, 2, 3]
given position item) a.insert(1, 2)
Returns number of times
count ( ) list.count(item) [1, 2, 2, 3]. count (2) 2
an element appears
Returns index of first a=[10, 20, 30]
index ( ) list.index(item) 1
occurrence of element a.index(20)
Removes first occurrence a = [1, 2, 3, 2];
remove ( ) list.remove(item) [1,3,2]
of a specified element a.remove(2)
Removes and returns 3
a = [1, 2, 3];
pop ( ) element at given index list.pop([index]) list becomes
a.pop( )
(default: last) [1, 2]
a = [1, 2, 3];
reverse ( ) Reverses the list in place list.reverse( ) [3, 2, 1]
a.reverse( )
Sorts the list in ascending
a = [3, 1, 2];
sort ( ) order (modifies original list.sort( ) [1, 2, 3]
a.sort( )
list)
Returns a new sorted list
sorted ( ) sorted(list) sorted ([3, 1, 2]) [1, 2, 3]
(original list unchanged)
Returns the smallest item
min ( ) min(list) min ([2, 3, 1]) 1
in the list
Returns the largest item
max ( ) max(list) max ((2, 3, 1]) 3
in the list
Returns the sum of all
sum ( ) sum(list) sum ((1, 2, 3]) 6
numeric items in the list
Tuple Functions and Methods
Function Description Syntax Example Output
Returns the number of
len( ) elements in the tuple len(t) len((10, 20, 30)) 3
Add a new pair D['city'] = 'Delhi' Adds new key-value to the {'city': 'Delhi'}
dictionary
Modify a value d['age'] = 17 Changes the value of existing {'age': 17}
key
Delete a pair del d['grade'] Deletes key-value pair Removes 'grade' key
Check key 'name' in d Returns True if key exists True
existence
Loop through for k in d: Iterates over keys 'name', 'age', etc.
keys
Loop through for k, v in d.items( ): Iterates through key- value name John
items print(k, v) pairs age 16
city Delhi
Dictionary Functions & Methods
b) Functions defined in module: A module is a file containing Python definitions (i.e., functions) and
statements. To use these modules in the program, a programmer needs to import the module by
using either the import statement or the from statement.
import statement: It is simplest and most common way to use modules in our code. syntax
is:
import modulename1 [, modulename2, ]
Example: import math
To use/ access/invoke a function, you will specify the module name and name of the function-
separated by dot (.).
Output Output:
(20, 30, 40) 20 30 40
SCOPE OF VARIABLES:
The part of the program where a variable is accessible can be defined as the scope of that variable.
There are two types of scope for variables:
1. Local Scope: A variable declared in a function-body is said to have local scope. It cannot be accessed
outside the function.
2. Global Scope: A variable declared in top level segment (main) of a program is said to have a global
scope.
Example:
def Sum (x, y) : # x,y,z local
z=x+y
return z
a=5 # a,b,s global
b=7
s = Sum (a, b)
print(s)
Multiple Choice Questions
1 Which of the following is a valid function name?
a) Start_game( ) b) start game ( ) c) start-game( ) d) All of the above
2 If the return statement is not used in the function, then which type of value will be
returned by the function?
a) int b) str c) float d) None
3 What is the minimum and maximum value of c in the following code snippet?
import random
a=random.randint(3,5)
b = random.randint(2,3)
c=a+b
print(c)
a) 3, 5 b) 5, 8 c) 2, 3 d) 3, 3
4 pow ( ) function belongs to which library?
a) math b) string c) random d) maths
5 What is the data type of the object below?
L = (1, 23, ‘hello’,1)
a) list b) dictionary c) array d) tuple
6 What is returned by int (math.pow(3, 2))?
a) 6 b) 9 c) error, third argument required d) error, too many arguments
7 Which of the following is not a type conversion function?
a) int( ) b) str ( ) c) input ( ) d) float ( )
8 Identify the module to which the following function load ( ) belong to?
a) math b) random c) pickle d) sys
9 How many argument(s) a function can receive?
a) Only one b) 0 or many c) Only more than one d) At least one
10 Give the output
def fun ( ):
global a
a=10
print(a)
a=5
fun ( )
print(a)
a) 10 b) 5 c) 5 d) 10
10 10 5 5
11 Value returning functions should be generally called from inside of an expression
a) True b) False
12 The variable declared inside the function is called a variable
a) global b) local c) external d) none of the above
13 These are predefined functions that are always available for use. For using them we don’t
need to import any module
a) built in function b) pre-defined function
c) user defined function d) none of the above
14 The of a variable is the area of the program where it may be referenced
a) external b) global c) scope d) local
15 If you want to communicate between functions i.e. calling and called statement, then you
should use
a) values b) return c) arguments d) none of the above
16 Find the flow of execution of the following code:
1. def calculate (a, b):
2. res=a**b
3. return res
4.
5. def study(a):
6. ans=calculate(a,b)
7. return ans
8.
9. n=2
10. a=study(n)
11. print(a)
a) 1 > 5 > 9 > 10 >5>6 >1> 2 > 3 >6 7 > 10>11 b) 5 > 9 > 10 > 6 > 2 > 3 > 7 > 11
c) 9 > 10 > 5 > 1 > 6 > 2 > 3 > 7 > 11 d) None of the above
17 A can be skipped in the function call statements
a) named parameter b) default parameter
c) keyword parameters d) all of the above
18 Write the output of the following:
a= (10, 12, 13, 12, 13, 14, 15)
print(max(a) + min(a) + a.count(2))
a) 13. b) 25 c) 26 d) Error
19 What is wrong with the following function definition?
def greet (name="Guest", age):
print (name, “is”, age, “years old”))
a). The syntax of print statement is wrong
b). Default parameter must follow required parameter
c). Function name cannot be greet
d). Nothing is wrong
20 Which of the following function definitions is INVALID?
a). def func(a, b=2, c=3): pass. b). def func(a=1, b, c=2): pass
c). def func(a, b, c=5): pass. d). def func(a=1, b=2, c=3): pass
ANSWERS
1 A 2 D 3 B 4 A 5 D 6 B
7 C 8 C 9 B 10 A 11 A 12 B
13 A 14 C 15 C 16 A 17 B 18 B
19 B 20 B
Keyword Purpose
try Used to write code that may cause an exception.
except Used to catch and handle the exception.
finally Used to execute code whether an exception occurs or not (cleanup code).
try:
# Code that might raise an exception
except ExceptionType:
# Code that runs if the exception occurs
finally:
# Code that will run no matter what (optional)
1 Consider the statements given below and then choose the correct output from the given
options:
N='5'
try:
print('WORD' + N, end='#')
except:
print('ERROR',end='#')
finally:
print('OVER')
(A) ERROR# (B) WORD5#OVER C) WORD5# (D) ERROR#OVER
2 State whether the following statement is True or False:
While handling exceptions in Python, name of the exception has to be compulsorily added
with except clause.
3 State whether the following statement is True or False: The finally block in Python is
executed only if no exception occurs in the try block.
4 State whether the following statement is True or False: An exception may be raised even if
the program is syntactically correct.
5 State True or False:
“raise and assert statements are used to raise exceptions”
ANSWERS
1 (B) WORD5#OVER
2 False
3 False
4 True
5 True
DATA FILE HANDLING
TEXT FILE
Note: if file mode is not mentioned in open function, then default file mode, 'r' is used
Reads the entire file as one string Reads one line at a time Reads all lines into a list of strings
Use when you want to load the Call multiple times to read useful for looping through lines
whole file at once multiple lines
f.read( ) f.readline( ) f.readlines( )
Output Output "Hello\ Output
"Hello\nWorld\nPython" n" ["Hello\n","World\n", Python"]
to read a specified number of used to read a specified using readlines( ) function, lines in the
bytes use number (n) of bytes of data file become members of a list, where
f.read(n) from a file but maximum up each list element ends with a newline
to the newline character (\ character (‘\n’)
n)
f.readline(n)
SETTING OFFSETS IN A FILE
The tell ( ) method The seek ( ) method
This function returns an integer that This method is used to position the file object at a
specifies the current position of the file particular position in a file.
object in the file.
The position specified is the byte position In the given syntax, offset is the number of bytes by
from the beginning of the file till the current which the file object is to be moved. reference_point
position of the file object. indicates the starting position of the file object.
That is, with reference to which position, the offset
has to be counted. It can have any of the following
values:
0 - beginning of the file
1 - current position of the file
2 - end of file
The syntax of using tell ( ) is: The syntax of seek ( ) is:
file_object.tell( ) file_object.seek(offset [, reference_point])
BINARY FILE
A binary file is a file whose content is in a binary format (0s and 1s). It stores data as a sequence
of bytes (each byte = 8 bits). Binary files include a wide range of file types, including executables,
libraries, graphics, databases, archives and many others.
There are mainly two types of data files — text file and binary file.
Differences between text files and binary files.
S. No. Text file Binary File
1. The text files can easily be transferred Binary files cannot easily be transferred from
from one computer system to another. one computer system to another due to
variations.
2. It stores data using ASCII format i.e. It stores data in binary format i.e. with the help
human-readable graphic characters. of 0 and 1.
3. These files are easily readable and These files are not easily readable and
modifiable because the content written in modifiable because the content written in binary
text files is human readable. files is not human-readable and it is encrypted
content.
Steps to process a binary file
Opening a file
Writing data into a file
Reading data from a file
Closing a file
Opening a Binary file in Python
Opening a file refers to getting the file ready either for reading or for
writing. To open a file in Python, we use the open ( ) function.
1 C 2 C 3 B 4 C
5 C 6 D 7 B
csv.reader( ) The csv.reader( ) function in Python is used to read data from a CSV (Comma
Separated Values) file. It is part of Python’s built-in csv module.
csv.reader(file_object, delimiter=',')
Parameters:
file_object: A file object opened using open( ).
delimiter: (Optional) Specifies the character used to separate fields. Default
is comma (,).
It returns an iterator that returns each row in the CSV file as a list of strings.
Example
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
csv.writer( ) The csv.writer( ) function in Python is used to write data to a CSV file. It is part of
Python’s built-in csv module and writes rows as comma-separated values.
csv.writer(file_object, delimiter=',')
Parameters:
file_object: A file object opened in write ('w') or append ('a') mode.
delimiter: (Optional) Character that separates values. Default is comma (,).
It returns a writer object that lets you write rows (lists or tuples) to the CSV
file.
Common Methods:
writer.writerow(row) → Writes a single row.
writer.writerows(list_of_rows) → Writes multiple rows.
Example:
import csv
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
# Write header
writer.writerow(['Name', 'Age', 'City'])
# Write multiple data rows
writer.writerows([['Alice', 23, 'Delhi'],['Bob', 30, 'Mumbai'] ])
def wonCount( ):
f=open('Result.csv','r')
csvreader=csv.reader (f, delimiter=',')
head=list (csvreader)
print (head [0])
for x in head:
if x[3]=="WON":
print (x)
f.close( )
5 Mr. Mahesh is a Python Programmer working in a school. He has to maintain the records of
the sports students. He has created a csv file named sports.csv, to store the details. The
structure of sports.csv is :
[sport_id, competition, prize_won]
where
sport_id, is Sport id (integer)
competition is competition name
(string) prize_won is ("Gold", "Silver",
"Bronze")
Mr. Mahesh wants to write the following user-defined functions :
Add_detail( ): to accept the detail of a student and add to a csv file,
"sports.csv".
Count_Medal( ): to display the name of competitions in which students have
won "Gold" medal.
Help him in writing the code of both the functions.
Ans import csv
def Add_detail( ):
F=open("sports.csv","a")
W=csv.writer(F)
sport_id=int(input("Sport id:"))
competition=input("Competition:")
prize_won=input("Prize won:")
L=[sport_id,competition,prize_won]
W.writerow(L)
F.close( )
def Count_Medal( ):
F=open("sports.csv","r")
L=list(csv.reader(F))
for D in L:
if D[2]=="Gold":
print("Competition:",D[1])
F.close( )
6. Sangeeta is a Python programmer working in a computer hardware company. She has to
maintain the records of the peripheral devices. She created a csv file named Peripheral.csv,
to store the details.
The structure of Peripheral.csv is:
[P_id,P_name,Price]
where
P_id is Peripheral device ID (integer)
P_name is Peripheral device name (String)
Price is Peripheral device price (integer)
Sangeeta wants to write the following user defined functions :
Add_Device( ) : to accept a record from the user and add it to a csv file,
Peripheral.csv
Count_Device( ) : To count and display number of peripheral devices whose price
is less than 1000.
Ans import csv
def Add_Device( ):
F=open("Peripheral.csv","a",newline='')
W=csv.writer(F)
P_id=int(input("Enter the Peripheral ID"))
P_name=input("Enter Peripheral Name")
Price=int(input("Enter Price"))
L=[P_id,P_name,Price]
W.writerow(L)
F.close( )
def Count_Device( ):
F=open("Peripheral.csv","r")
L=list(csv.reader(F))
Count=0
for D in L:
if int(D[2])<1000:
Count+=1
print(Count)
F.close( )
7 Write a program in Python that defines and calls the following user defined functions:
(i) Add_Teacher( ) : It accepts the values from the user and inserts record of a teacher to a
csv file ‘Teacher.csv’. Each record consists of a list with field elements as T_id,Tname and
desig to store teacher ID, teacher name and designation respectively.
(ii) Search_Teacher( ) : To display the records of all the PGT (designation) teachers.
Ans import csv
def Add_Teacher( ):
fout=open("Teacher.csv","a",newline="\n")
T_id=int(input("Enter Teacher id: "))
Tname=input("Enter Teacher name: ")
desig=input("Enter Designation: ")
rec=[T_id,Tname,desig]
csvw=csv.writer(fout)
csvw.writerow(rec)
fout.close( )
def Search_Teacher( ):
fin=open("Teacher.csv")
csvr=csv.reader(fin)
for record in csvr:
if record[2]=="PGT":
print(record)
fin.close( )
Add_Teacher( )
Search_Teacher( )
8. Write a program in Python that defines and calls the following user defined functions:
(i) Add_Device( ) : The function accepts and adds records of the peripheral devices to a csv
file ‘peripheral.csv’. Each record consists of a list with field elements as P_id, P_name and
Price to store peripheral device ID, device name, and price respectively.
(ii) Count_Device( ) : To count and display number of peripheral devices, whose price is less
than ₹ 1000.
Ans import csv
def Add_Device( ):
fout=open("perpheral.csv","a",newline="\n")
P_id=int(input("Enter Device Id: "))
P_name=input("Enter Device name: ")
Price=int(input("Enter Price: "))
rec=[P_id,P_name,Price]
csvw=csv.writer(fout)
csvw.writerow(rec)
fout.close( )
def Count_Device( ):
fin=open("peripheral.csv")
csvr=csv.reader(fin)
ctr=0
for record in csvr:
if int(record[2])<1000:
ctr=ctr+1
print("Count of Price<1000 is",ctr)
fin.close( )
Add_Device( )
Count_Device( )
DATA STRUCTURES
Data structure is A set of rules and operations to organize and store data in an efficient manner.
It is a way to store data in a structured way.
Operations on data structure-
o Traversal
o Insertion
o Deletion
Types of data structures:
├── Linear Data Structures
│ ├── List (or Array)
│ ├── Stack
│ ├── Queue
│ └── Linked List
│
└── Non-Linear Data Structures
├── Tree
└── Graph
Built-in data structures available in Python: List, Tuple, Dictionary and Set.
User Defined data structures in Python: Stack, Queue, Tree, Linked List etc.
STACK:
A Stack is a Linear data structure which works in LIFO (Last In First Out) manner (or we can say
FILO i.e. First In Last Out manner
Insertion and Deletion of elements will be done only from one end known as TOP.
In Python, we can use List data structure to implement Stack.
Application of Stack:
1. Expression Evaluation
2. String Reversal
3. Function Call
4. Browser History
5. Undo/Redo Operations
Operations on Stack:
The Stack supports following operations:
1. Push: It adds an element to the TOP of the Stack.
2. Pop: It removes an element from the TOP of the Stack.
3. Peek: It is used to know/display the value of TOP without removing it.
4. isEmpty: It is used to check whether Stack is empty.
OVERFLOW: It refers to the condition in which we try to PUSH an item in a Stack which is already FULL.
UNDERFLOW: It refers to the condition in which we are trying to POP an item from an empty Stack.
# Menu-driven program
while True:
print("\nSTACK OPERATIONS")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
push( )
elif choice == 2:
pop_element( )
elif choice == 3:
display( )
elif choice == 4:
print("Exiting program...")
break
else:
print("Invalid choice! Please try again.")
Multiple Choice Questions
1. What is the principle of a stack?
a) FIFO – First In First Out b) LIFO – Last In First Out
c) FILO – First In Last Out d) LILO – Last In Last Out
2. Which Python list method is used to add an element to the stack?
a) insert( ) b) add( ) c) append( ) d) push ( )
3. Which method is used to remove the top element from a stack implemented using a list?
a) remove( ) b) delete( ) c) pop( ) d) discard ( )
4. What will be the output of the following code?
stack = [10, 20, 30]
stack.pop( )
print(stack)
a) [10, 20, 30] b) [10, 20]
c) [20, 30] d ) Error
5. What happens if you call pop ( ) on an empty stack?
a) Returns None b) Raises IndexError
c) Returns -1 d) Does nothing
Answers
1. B 2. C 3. C 4. B 5. B
Network: A group of two or more similar things or people interconnected with each other is
called network. Examples are social network and mobile network
Computer Network: A Computer network is an interconnection among two or more computers
or computing devices. The advantages of computer networks are:
Resource Sharing
Collaborative Interaction
Cost Saving
Increased storage
Time Saving
EVOLUTION OF NETWORK:
(I) ARPANET (Advanced Research Project Agency Network)
It came into existence in 1960s
A project for interconnecting, US department of defense with academic and research
organization across different places for scientific collaboration.
(II) NSFNET (National Science Foundation Networks)
It came into existence in 1986
It was the first large-scale implementation of Internet technologies in a complex environment
of many independently operated networks
(III) INTRANET
It is a local or restricted communication system
It is managed by a person or organization.
Intranet users can avail services from internet but Internet user cannot access intranet directly
(IV) INTERNET
It came into existence in 1960s
It is known as Network of Networks
A global computer network providing variety of information and communication facilities
consisting of interconnected networks using standardized communication protocols.
DATA COMMUNICATION TERMINOLOGIES
DATA: Data means information in digital form such as text, audio, video which is stored processed and
exchanged between digital devices like computer, mobile phones or laptop. Computers process the
raw data into meaningful information. Information is processed data.
COMMUNICATION: The exchange of information between two or more networked or interconnected
devices is called communication
COMPONENTS OF DATA COMMUNICATION
a) SENDER: Sender is a device which is capable of sending data over a communication network. In
data communication Sender is also called Source.
b) RECEIVER: Receiver is a device which is capable of receiving data over a communication network.
In data communication Receiver is also called Destination.
c) MESSAGE: message is the information being exchanged between a sender and a receiver over a
communication network.
d) COMMUNICATION MEDIUM: Communication medium is the path or channel through which the
information is moved from the sender to the receiver. A communication medium can be either
wired/guided or wireless/unguided.
e) PROTOCOLS: The set of standard rules which are followed in data communication are known as Data
Communication Protocols. All the communicating devices like sender receiver and other connected
devices in the network should follow these protocols.
Why Protocols are needed?
The communicating devices may be in different geographical areas. The speed of these devices may be
different. Also, the data transfer rates of different networks may be different. These complexities make
it necessary to have a common set of rules to ensure the secure communication of data. Some
commonly used Protocols in data communication are:
Transmission Control Protocol (TCP)
Internet Protocol (IP)
File Transfer Protocol (FTP)
Simple Mail Transport Protocol (SMTP)
Hyper Text Transfer Protocol (HTTP)
IP ADDRESS: IP address or Internet Protocol address is a unique numeric address assigned to every
device connected to a network. It uniquely identifies every node connected to a local network or
internet. Example IP address: 24.171.248.170
SWITCHING TECHNIQUES
In large networks, there may be more than one paths for transmitting data from sender to receiver.
The process of selecting a path of data out of the available paths is called switching. There are two
popular switching techniques – circuit switching and packet switching.
1. Circuit Switching : In circuit switching, whenever a source end node wants to send a message to the
destination end node a physical link is first established between the source and the destination. Then
only the data transmission takes place. Example: telephone network
2. Packet Switching : In the packet switching technique, the whole message is split into small packets.
Now, these packets are transmitted one by one from sender to the receiver through the intermediary
switches in the network. The packets will take shortest path as possible.
TRANSMISSION MEDIA
Transmission media are the channels used to carry data signals.
They are broadly classified into
o Wired / Guided Media
Includes:
Twisted pair cable
Coaxial cable
Fiber-optic cable
Features:
High Speed
Secure
Used for comparatively shorter distances
o Wireless/Un-guided media
Includes:
Radio waves
Microwaves
Infrared waves.
Features:
The signal is broadcasted through air
Less Secure
Used for larger distances
NETWORK DEVICES
Modem: Stands for "modulator-demodulator.", converts digital data from a computer into analog
signals for transmission over telephone lines or cable systems. Also it converts incoming analog signals
back into digital data for the computer. Used to connect to the internet via ISP (Internet Service Provider).
Ethernet Card: Also known as a network interface card (NIC)., enables a computer to connect to an
Ethernet network using Ethernet cables, Essential for wired network connections. Provides a physical
interface for networking using an RJ45 connector
RJ45 Connector: Registered Jack 45 connector, used to connect Ethernet cables to devices such as
computers, switches, and routers, Ensures a secure and reliable physical connection. Repeater:
Amplifies and retransmits signals in a network, extends the range of network signals, especially in
large or congested environments. Used to combat signal loss over long distances.
Hub: A basic networking device that connects multiple devices in a network, Broadcasts data to all
connected devices, causing network congestion and inefficiency, which can lead to collisions.
Switch: Intelligent device that connects devices in a network, Forwards data only to the device that
needs it, improving network performance and efficiency by reducing collisions.
Router: Manages traffic between different networks, such as your home network and the internet,
performs functions like assigning IP addresses, directing data, and providing security.
Gateway: Acts as an entry and exit point for data traveling between different networks or protocols
(e.g., LAN to WAN), translates data between different formats or protocols to ensure smooth
communication.
Wi-Fi Card: A wireless network adapter that allows a computer to connect to Wi-Fi networks.
Commonly found in laptops and mobile devices for wireless internet access
Star
All computers are connected using cable segments to a central component called a switch. The signals
from the transmitting computer go through the switch to all the others.
Tree
Tree Topology is a topology which is having a tree structure in which all the computers are connected
like the branches which are connected with the tree.
NETWORK PROTOCOL: A protocol means the rules that are applicable for a network. Protocols
defines standardized formats for data packets, techniques for detecting and correcting errors etc.
TCP/IP (Transmission Control Protocol/ Internet Protocol)
The IP protocol ensures that each computer or node connected to the Internet is assigned an IP
address, which is used to identify each node independently.
TCP ensures that the message or data is broken into smaller chunks, called IP packets. Each of
these packets are routed (transmitted) through the Internet, along a path from one router to the
next, until it reaches the specified destination. TCP guarantees the delivery of packets on the
designated IP address. It is also responsible for ordering the packets so that they are delivered
in sequence.
FTP (File Transfer Protocol): It is a standard internet protocol provided by TCP/IP used for
transmitting the files from one host to another. It is mainly used for transferring the web page files
from their creator to the computer that acts as a server for other computers on the internet. It is also
used for downloading the files to computer from other servers.
SMTP (Simple Mail Transfer Protocol.): SMTP is a set of communication guidelines that allow
software to transmit an electronic mail over the internet is called Simple Mail Transfer Protocol.
Point-to-Point Protocol (PPP) is protocol that is used to directly connect one computer system to
another. Computers use PPP to communicate over the telephone network or the Internet.
Post Office Protocol version 3 (POP3) Protocol: (POP3) is a standard mail protocol used to receive
emails from a remote server to a local email client. POP3 allows you to download email messages on
your local computer and read them even when you are offline. J, and JVM
Telnet: Telnet is a program that allows a user to log on to a remote computer. Telnet provides a
connection to the remote computer in such a way that a local terminal appears to be at the remote
side. VoIP: VoIP stands for Voice over Internet Protocol. It is also referred to as IP telephony,
internet telephony, or internet calling.
Web Services: Web Services means the services provided by World Wide Web. The World Wide Web
provides services like chatting, emailing, video conferencing, e-learning, e-shopping, e-reservation, e-
groups and social networking.
World Wide Web (WWW): The World Wide Web commonly referred to as WWW, W3, or the Web is
an interconnected system of public webpages accessible through the Internet. It was invented by Tim
Berners-Lee in 1989. Major components of WWW are:
1. Web Server – It is a computer that stores website resources (web pages, images, videos, etc.).
2. Web Browser (Client) - A software application used to access the web resources.
3. Webpage - Hypertext documents formatted in Hypertext Mark-up Language (HTML) and
displayed in a web browser.
4. Website - A website is a collection of inter-linked web pages that is identified by a common
domain name (website name) and stored on a web server.
5. HTTP Protocol - It governs data (web page) transfer between a server and a client.
6. HTML- A mark-up language used to specify the structure of a webpage.
7. URL- Address used to identify documents and other web resources on the internet.
WEB ARCHITECTURE
Web is working based on a client-server architecture.
Client: It is a computer capable of requesting, receiving & displaying information in the form of web
pages or using a particular service from the service providers (Servers).
Servers: It is a remote computer which provides/transfers information to the client (in the form of
web pages) or access to particular services.
Difference between Internet and WWW
Internet World Wide Web(WWW)
Internet stands for Interconnected Networks WWW stands for World wide Web
Internet is a means of connecting a computer World Wide Web which is a collection of
to any other computer anywhere in the world. information which is accessed via the Internet.
Internet is infrastructure. WWW is service on top of that infrastructure.
Internet is primarily hardware-based WWW is more software-oriented as compared to
the Internet.
Internet uses TCP/IP protocol. WWW uses HTTP Protocol.
HTML (Hypertext Mark-up Language): It is a mark-up language that tells web browsers how to
structure the web pages you visit. It has a variety of tags and attributes for defining the layout and
structure of the web document. A HTML document has the extension .htm or .html. Hypertext is a text
which is linked to another html document via clickable links known as hyperlinks.
XML (eXtensible Mark-up Language): XML is a mark-up language like HTML but it is designed to
transport or store data. It does not have predefined tags but allows the programmer to use customized
tags. An XML document has the extension .xml.
HTML v/s XML
HTML XML
HTML stands for Hyper Text Mark-up Language XML stands for eXtensible Mark-up Language
HTML is a case insensitive. XML is case sensitive.
Predefined tags (commands). User defined tags (commands).
It is used for presentation of the Data. It is used for transportation of the Data.
Small errors can be ignored. Errors not allowed.
Closing tags are optional. Compulsory to use closing tags.
HTTP - Hyper Text Transfer Protocol: HTTP is used to transfer data across the web. HTTP specifies
how to transfer hypertext (linked web documents) between two computers. It allows users of the
World Wide Web to exchange information found on web pages.
Hypertext Transfer Protocol Secure (HTTPS) is an extension of the HTTP which is used for secure
communication over a computer network.
Domain Names: Every device connected to the Internet has a numeric IP address which is very
difficult to remember. Each computer server hosting a website or web resource is given a name known
as Domain Name corresponding to unique IP addresses. For example, IP addresses and domain names
of some websites are as follows:
Domain Name IP Address
ncert.nic.in 164.100.60.233
cbse.nic.in 164.100.107.32
The process of converting a hostname (such as www.google.com) into the corresponding IP address
(such as 172.217.14.196) is called domain name resolution. Specialized DNS servers are used for
domain name resolution (DNS resolution).
URL-Uniform Resource Locator: Every web page that is displayed on the Internet has a specific
address associated with it, this address is known as the URL. The structure of a URL can be
represented as follows:
http://www.example.com/planet/earth/river.jpg
A database is an organized collection of interrelated data that serves many applications. Its is generally
a computer record keeping system. In a database we can not only store the data but we can also change
the data as per the user requirement. These databases are generally managed by special software
called DBMS (Database Management System)
1 d 2 a 3 b 4 b
5 a 6 b 7 b 8 a
9 b 10 a 11 b 12 d
13 b 14 a 15 c
Very Short Answer Questions
1 What is meant by a database?
2 Define primary key?Give an example.
3 What do you mean by candidate key?
4 What is meant by degree and cardinality of a table?
5 What is meant by DBMS?
6 What is meant by database schema?
7 What is meant by data constraint?
8 What is meant by relation?
Very Short Answer Questions: Answers
1 A database is an organized collection of structured information, or inter-related data,
typically stored in a computer system.
2 A primary key is a column or set of columns that contain values that uniquely identify
each row in a table.
For example Rno can be primary key of the table student.
Table:Student
RNO NAME MARK
100 Tanay 30
101 Kiran 50
102 Manu 30
3 It is an attribute or a set of attributes capable of being the Primary Key, to uniquely
identify each record in that table.
CONSTRAINTS
A Constraint is a condition or check applicable on a field or set of fields.
Types of Constraints:
Unique Constraint :-This ensures that no rows have the same value in the specified
column(s)
Example
CREATE TABLE EMP (ecode integer
unique, ename char(20),sex char(1),
grade char(2));
Unique constraint applied on ecode of EMP table ensures that no rows have the same
ecode value .
Primary key Constraint:-
This declares a column as the primary key of the table. This is similar to unique constraint
except that one column (or one group of columns) can be applied in this constraint .
The primary key cannot allow NULL values but Unique key allows NULL values.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
CREATE TABLE
Persons (ID int
NOT NULL,
LastName varchar(255) NOT
NULL, FirstName varchar(255),
Age int PRIMARY KEY (ID));
Not null: -This constraint ensures column should not be NULL
Example:
CREATE TABLE EMP(
ecode integer Not null
unique, ename char(20),
sex
char(1),
grade
char(2));
DATABASE COMMANDS IN MYSQL
CREATE DATABASE
CREATE DATABASE is the SQL command used for creating a database in MySQL.
Imagine you need to create a database with name “movies”. You can create a database in MySQL by
executing following SQL command
Syntax: mysql>CREATE DATABASE movies;
SHOW DATABASES
You can see list of existing databases by running following SQL command.
Syntax: mysql>SHOW DATABASES;
USE
You can use SQL command USE to select a particular database.
Syntax: mysql>USE database_name;
DROP DATABASE
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax: mysql>DROP DATABASE database_name;
CREATE TABLE
The CREATE TABLE statement is used to create a new table in a database.
Syntax:
CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype,.......);
Example: The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons
( PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255) );
SHOW TABLES
We can get the number of table information of a database using the following statement:
mysql> SHOW TABLES;
DESCRIBE TABLE
Use the DESCRIBE command to show the structure of the table, such as column names, constraints on
column names, etc. The DESC command is a short form of the DESCRIBE command. Both DESCRIBE
and DESC commands are equivalent.
Syntax The following are the syntax to display the table structure:
mysql> DESCRIBE | DESC table_name;
ALTER TABLE
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER
TABLE statement is also used to add and drop various constraints on an existing table.
ALTER TABLE - ADD Column/Attribute
ALTER TABLE - ADD A COLUMN
ALTER TABLE table_name ADD column_name datatype;
Example ALTER TABLE Customers
ADD Email varchar(255);
DROP TABLE
The DROP TABLE statement is used to drop an existing table in a database.
Syntax DROP TABLE table_name;
DROP TABLE Shippers;
INSERT:
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax:
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as the
columns in the table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name VALUES (value1, value2, value3, ...);
DELETE:
The DELETE statement is used to delete existing records in a table.
DELETE Syntax:
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all
records in the table will be deleted!
The following SQL statement deletes all rows in the "Customers" table, without deleting the
table: DELETE FROM Customers;
UPDATE
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person
and a new city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
SELECT
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax: SELECT column1, column2, ... FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to
select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
WHERE Clause:
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
WHERE Syntax: SELECT column1, column2, ...FROM table_name WHERE condition;
IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign (%) represents zero, one, or multiple characters
The underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
Alias Column Syntax: SELECT column_name AS alias_name FROM table_name;
Alias Table
Syntax: SELECT column_name(s) FROM table_name AS alias_name;
DISTINCT
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.
SELECT DISTINCT Syntax:
SELECT DISTINCT column1, column2, ...FROM table_name;
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates) values from the "Country" column in
the "Customers" table:
Eg: SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT statement and see the result.
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
SELECT COUNT(DISTINCT Country) FROM Customers;
NULL value
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value. It is not possible to test for NULL
values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names FROM table_name WHERE column_name IS NULL;
IS NOT NULL Syntax
SELECT column_names FROM table_name WHERE column_name IS NOT NULL;
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NULL;
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL;
ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example
SELECT * FROM Customers
ORDER BY Country;
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by
the "Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
and the "CustomerName" column. This means that it orders by Country, but if some rows have the
same Country, it orders them by CustomerName:
Eg: SELECT * FROM Customers ORDER BY Country, CustomerName;
count(*)
This function returns the number of rows in the table that satisfy the criteria of select
statement. In its counting, it includes duplicate rows and rows with NULL values in any of the
column Example:
Q: Count the number of employees in the employee table.
count(<col name>)
This function returns the number of not null values in the specified column, but includes duplicate
values in counting
Example
Q. Display the no of employees in each zone whose salary is greater than 32000
Having clause
This clause is used to restrict rows resulting after grouping.
Steps followed in execution of select with group by and having clause-
1. Rows are grouped according to the columns in the group by clause.
2. Then the group function is applied.
3. Groups matching with having clauses are displayed.
Example
Q. Display only whose departments with sum of salaries whose total salary is greater than 70000.
Note-You should always qualify the columns when joining tables having the same name as
corresponding columns. To qualify the columns we use “.” (dot) operator.
Natural Join
This clause is based on all the columns in the two tables that have the same name. It selects the rows
from two tables that have equal values in the matched columns.
SYNTAX:-
SELECT [column_names / *] FROM table_name1 NATURAL JOIN table_name2;
Example- consider the same tables employee and department.
Q: To display the name of employee and department of all employee.
Note-No need to specify the column names to join. Works with same column name in both the tables.
The Resulting table has unique columns.
MULTIPLE CHOICE QUESTIONS
1 Which of the following SQL commands is used to use/select a particular database?
a. use b. select c. view d. project
2 Which SQL command is used to define and maintain physical structure or schema of table
in database like creating, altering and deleting database object such as table and
constraints?
a. DDL b. DML c. DCL d. TCL
3 Which commands is used to show all table in current using database?
a. display tables; b. show tables; c. view tables; d. select all tables;
4 Identify the MySQL Commands that belongs to DML category :
a. ALTER b. DROP c. DELETE d. CREATE
5 Which command is used in where clause to search NULL values in a particular column?
a. IS NULL b. IN NULL c. NOT NULL d. IS NOT NULL
6 Wild card operator (%,_) are used with?
a. count b. max c. like d. min
7 Prapti is presently working in the database SUBJECT. She wants to change and go to
the database RECORD. Choose the correct statement in MySQL to go to the database
RECORD.
a. GO TO DATABASE RECORD; b. USE DATABASE RECORD;
c. CHANGE DATABASE RECORD; d. USE RECORD;
8 Which SQL clause is used in database table to eliminate duplicate rows from the query
result?
a. group by b. distinct c. describe d. duplicate
9 Which SQL function is used to count the entire number of row in database table?
a. count b. count(*) c. max d. min
10 Which SQL function is used to determine the no. of row or non-null values?
a. min b. max c. count d. sum
ANSWERS
1 a 2 a 3 b 4 c 5 a
6 c 7 b 8 b 9 b 10 c
ASSERTION AND REASONING QUESTIONS
Directions: In the following questions, A statement of Assertion (A) is followed by a statement of
Reason (R). Mark the correct choice as:
(A) Both A and R are true and R is the correct explanation of A
(B) Both A and R are true and R is not the correct explanation of A
(C) A is true but R is false
(D) A is false but R is true
1 Assertion(A): The resultset refers to a logical set of records that are fetched from the
database executing an SQL Query.
Reason (R): Resultset stored in a cursor object can be extracted by using fetch(…)
functions.
2 Assertion(A): In SQL, aggregate function avg( )calculates the average value on a set of
values and produce a single result.
Reason (R): The aggregate functions are used to perform some fundamental arithmetic
tasks such as min( ), max( ), sum( ) etc.
3 Assertion(A): Primary key is a set of one or more attributes that identify tuples in a
relation.
Reason (R): The primary key constraint is a combination of the NOT NULL and UNIQUE
constraints.
4 Assertion(A): Foreign key is a non-key attribute whose value is derived from primary key
of another table.
Reason (R): Each foreign key refers a candidate key in a relation.
5 Assertion(A): The SELECT statement in SQL is used to retrieve data from one or more
tables.
Reason(R): The SELECT statement can be used to retrieve all columns or a subset of
columns from a table.
ANSWERS
1 b 2 B 3 a 4 b 5 a
SHORT ANSWER TYPE QUESTIONS
1 Deepika wants to remove all rows from the table BANK. But she needs to keep the structure
of the table. Which command is used to implement the same?
2 While creating table ‘customer’, Rahul forgot to add column ‘price’. Which command is used
to add new column in the table. Write the command to implement the same.
3 Mitali is a database programmer, She has to write the query from EMPLOYEE table to search
for the employee who are not getting any commission, for this she has written the query as:
SELECT * FROM EMPLOYEE WHERE commission=null; But the query is not producing the
correct output, help her and correct the query so that she gets the desired output.
4 Which clause is used to eliminate the duplicate rows from output?
5 Which command is used to see information like name of columns, data type, size.
6 Differentiate between order by and group by clause in SQL with appropriate example.
7 Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP.
8 Muneer has created a database “school” and table “student”. Now he wants to view all the
databases present in his laptop. Help him to write SQL command for that , also to view the
structure of the table he created
9 Ms. Minakshi has just created a table named “Staff” containing Columns Sname,
Department and Salary. After creating the table, she realized that she has forgotten to add a
primary key in the table. Help her in writing an SQL command to add a primary key - StaffId
of integer type to the table Staff.Thereafter, write the command to insert the following
record in the table: StaffId – 111,Sname- Shalu,Department: Marketing,Salary: 45000
10 Meera working as database developer in Syntel Pvt Ltd Company Agra. She is designing as
SQL table names A & B .If a MySQL table A has 5 columns and 6 rows and another table B has
3 columns and 4 rows, then what will be the degree and cardinality of the cartesian product
of A and B?
11 Sunil decides to delete phoneno column from a table student . Write the SQL command to
remove the column in the student table. Also mention the type of SQL command.
12 Write SQL command to remove the Primary Key constraint from a table, named M_ID is the
primary key of the table MOBILE.
13 Write SQL command to make the column M_ID the Primary Key of an already existing table,
named MOBILE.
14 What constraint should be applied on a table column so that duplicate values are not
allowed in that column, but NULL is allowed.
ANSWERS:
1 delete from BANK;
2 ALTER TABLE customer add price int;
3 SELECT * FROM EMPLOYEE WHERE commission is null;
4 Distinct
5 DESCRIBE or DESC
6 ORDER BY is used to sort the result set based on one or more columns, either in ascending
(ASC) or descending (DESC) order whereas group by is used to group rows that have the
same values in specified columns into summary rows, often used with aggregate functions.
Eg: SELECT name, salary FROM employees ORDER BY salary DESC;
This will list all employees and their salaries, sorted by salary from highest to lowest.
SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY
department;
This will group employees by department and show the average salary for each department.
7 DDL –ALTER , DROP
DML-INSERT , UPDATE
8 SHOW DATABASES;
SHOW TABLES;
9 ALTER TABLE Staff ADD StaffId INT;
ALTER TABLE Staff ADD CONSTRAINT pk_staff PRIMARY KEY (StaffId);
INSERT INTO Staff (StaffId, Sname, Department, Salary) VALUES (111, 'Shalu', 'Marketing',
45000);
10 Degree = 8 Cardinality = 24
11 ALTER TABLE student DROP phoneno
It’s a DDL command.
12 ALTER TABLE mobile DROP PRIMARY KEY;
13 ALTER TABLE mobile ADD PRIMARY KEY (M_ID);
14 UNIQUE constraint makes sure that duplicate values are not allowed in that column, but
NULL will be allowed.
SHORT ANSWER QUESTIONS II
1 Meenu has been entrusted with the management of NSE Database. She needs to access some
information from STOCK and TRADERS tables for a survey analysis.
Help him extract the following information by writing the desired SQL queries as mentioned
below.
ANSWERS:
1 i) select sname, qty, price , stock.tcode, tname
from stock, traders where stock.tcode = traders.tcode;
ii) select * from stock where price between 35000 and 50000;
iii) select scode, sname, qty * price as "total price" from stock
where brand in ('nec', 'hp') order by qty * price asc;
iv) select tcode, count(*) as stock_count from stock group by tcode;
2 i) select firstname, lastname, address, city from employees where city = 'paris';
ii) select * from employees order by firstname desc;
iii) select e. firstname, e. lastname, s. salary from employees e
join empsalary s on e.empid = s.empid where s.designation = 'manager';
iv) manager 215000
clerk 135000
or
32000
3 A) D_NAME
GUPTA
HANEEF
B) D_DEPT
ENT
MEDICINE
ORTHO
CARDIOLOGY
SKIN
C) D_NAME EXPERIENCE
DEEPTI 6
SUMAN 7
JOSEPH 10
GUPTA 12
HANEEF 12
VEENA 12
4 i) select * from client where city = 'delhi';
ii) update product set price = price + 10 where pr_name = 'bath soap';
iii) select * from product where price = (select max(price) from product);
iv) select p.pr_name, p.price, c.c_name, c.city from product p join client c on p.pr_id = c.pr_id;
5 i) select * from furniture where lower(type) = 'baby cot';
ii) select item_name from furniture where price > 15000;
iii) select item_name, type from furniture where dateofstock > '2002-02-01'
order by item_name desc;
iv) select item_name, dateofstock from furniture where discount > 25;
8. ROWCOUNT
It is the property of the cursor object that returns the number of rows fetched from the
cursor object till that moment and not the number of records the executed query will
give.
SYNTAX –
count = cur.rowcount
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( ) # ASSUME TABLE HAS 10 ROWS
cur.execute("select * from student") # All 10 ROWS are now in CURSOR
object data = cur.fetchone( ) # Only 1 ROW is fetched from CURSOR till now
print(cur.rowcount) # Output = 1
data = cur.fetchmany(4) # Total 5 ROWS have been fetched from CURSOR
print(cur.rowcount) # Output = 5
data = cur.fetchone( ) # Total 6 ROWS have been fetched from CURSOR
print(cur.rowcount) # Output = 6
data = cur.fetchall( ) # Remaining 4 ROWS have been fetched as well
print(cur.rowcount) # Output = 10
9. commit( )
After executing insert or update query we must commit our transaction using commit method of
connection object.
Eg: con.commit( )
10. con.close( )
Closing the connection, Since the database can keep limited number of connections at a time, we
must close the connection using connection_object.close( ).
Eg: con.close( )
STATIC QUERIES
Queries which are formed without passing any python object/variable/data.
Now we can execute any MySQL query through Python. Below are few examples static queries.
a) TO CREATE A TABLE IN MYSQL USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("CREATE TABLE FEES (ROLLNO INT, NAME VARCHAR(20), AMOUNT INT);")
b) TO SHOW THE TABLES IN MYSQL USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("SHOW TABLES")
for data in cur:
print(data)
c) TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
mycursor.execute("DESC STUDENT")
for data in cur:
print(data)
d) TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("select * from student")
r=cur.fetchone( )
while r is not None:
print(r)
r=cur.fetchone( )
e) TO EXECUTE SELECT QUERY WITH WHERE CLAUSE USING A PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("select * from student where marks>90")
r=cur.fetchall( )
count=cur.rowcount
print("total no of rows:",count)
for row in r:
print(row)
f) TO UPDATE A DATA IN A TABLE USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
con.commit( )
print(cur.rowcount,"RECORD UPDATED")
g) TO DELETE A RECORD FROM THE TABLE USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("DELETE FROM STUDENT WHERE MARKS<50")
con.commit( )
print(cur.rowcount,"RECORD DELETED")
h) TO DROP AN ENTIRE TABLE FROM MYSQL DATABASE USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("DROP TABLE STUDENT")
i) TO ADD A COLUMN IN THE EXISTING TABLE USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("ALTER TABLE STUDENT ADD AGE NT”)
con.commit( )
j) TO DROP A COLUMN FROM THE TABLE USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("ALTER TABLE DROP AGE ”)
con.commit( )
k) TO ALTER THE DATATYPE OF A COLUMN IN A TABLE USING PYTHON INTERFACE
import mysql.connector as m
con =m.connect(host="localhost",user="root", passwd="system", database="student")
cur=con.cursor( )
cur.execute("ALTER TABLE STUDENT MODIFY GRADE CHAR(3)")
PARAMETERIZED QUERIES
Parameterize the query to add python variables/object into the string query to access values as
per the user’s input.
Example: to display record of a particular rollno.
There are two ways to use parameterized queries:
a) with { }.format pattern
b) with fstring & { } braces
1) Using {}.format pattern
(a)
rn = int(input(‘Enter Roll no. ‘)) # SUPPOSE USER ENTERS 10 AS ROLL NO
query = "select * from student where rollno = { }".format(rn)
cur.execute(query)
Note: “Here the format function will assign the value 10 in place of { } braces inside the
string query. python will convert it to-> query = "select * from student where rollno = 10"
(b)
Suppose we want to display the data based on the column name & value given by user
col_name = eval(input(‘Enter Column Name ‘)) # User entered Rollno
col_value = eval(input(‘Enter Column Value ‘)) # User entered 12
query = "select * from student where { } = { }".format(col_name , col_value)
# python will convert it to ->>> query = "select * from student where Rollno = 12 "
cur.execute(query)
(c)
Suppose we want to display the data from a specific class & section given by user
cls = eval(input(‘Enter Class ‘)) # User entered 12
sec = eval(input(‘Enter Section ‘)) # User entered A
query = "select * from student
where class = { } and section = ‘{ }’ ".format(cls , sec)
# python will convert it to ->>> query = "select * from student
where class = 12 and section = ‘A’ "
cur.execute(query)
Note: Here we add ‘f’ before the string & write the variable inside { } braces which
assigns the value 10 in place of {rn} inside the string query. python will convert it to->
query= "select * from student where rollno = 10"
(b)
Suppose we want to display the data based on the column name & value given by user
col_name = eval(input(‘Enter Column Name ‘)) # User entered Rollno
col_value = eval(input(‘Enter Column Value ‘)) # User entered 12
query = f”select * from student where { col_name } = { col_value } “
cur.execute(query)
Note: python will convert it to ->>> query = "select * from student where Rollno = 12 "
(c)
Suppose we want to display the data from a specific class & section given by user
cls = eval(input(‘Enter Class ‘)) # User entered 12
sec = eval(input(‘Enter Section ‘)) # User entered A
query = f ”select * from student where class = {cls} and section = ‘{sec}’ “
cur.execute(query)
Note: python will convert it to ->>> query = "select * from student where class = 12
and section = ‘A’ "
1 Assertion (A): The cursor( ) method is used to execute SQL queries in Python.
Reason (R): The cursor object allows interaction with the database.
2 Assertion (A): cursor.fetchall( ) is used to delete all records from a table.
Reason (R): fetchall( ) retrieves all records returned by a SELECT query.
3 Assertion (A): mysql.connector.connect( ) requires parameters like host, user, password,
and database to connect successfully.
Reason (R): mysql.connector.connect( ) is used to establish a connection between Python
and MySQL.
4 Assertion (A): commit( ) is used after every SELECT query to save the fetched results.
Reason (R): commit( ) saves changes made by INSERT, UPDATE, and DELETE operations.
5 Assertion (A): The close( ) method is mandatory after the database operations are
completed.
Reason (R): Keeping database connections open unnecessarily may lead to resource
leakage.
Answers
1 A 2 D 3 A 4 D 6 A
Answers:
1 import mysql.connector as m
mycon= m.connect(host=”localhost”,user=”root”,password=”Pencil”)
mycursor=mycon.cursor( )
def Add(mycursor):
mycursor.execute(‘use ITEMDB’)
n = int(input(‘Enter no. of Items to be entered: ’))
for i in range(n):
ino = int(input(‘Enter Item no: ’))
inm = input(‘Enter Item name: ’)
ipr = float(input(‘Enter Item price: ’))
iq = int(input(‘Enter Item quantity: ’))
query = f ”insert into STATIONARY values({ino},’{inm}’,{ipr},{iq})”
mycursor.execute(query)
mycon.commit( )
def Display(mycursor):
mycursor.execute(‘use ITEMDB’)
query = ‘Select * from STATIONARY where price > 120’
mycursor.execute(query)
data = mycursor.fetchall( )
for record in data:
print(‘Item No = ‘ , record[0])
print(‘Item Name = ‘ , record[1])
print(‘Item Price = ‘ , record[2])
print(‘Item Qty = ‘ , record[3])
Add(mycursor)
Display(mycursor)
mycon.close( )
2 def Display(mycursor):
query = ‘Select * from CLASS where Fee > 5000’
mycursor.execute(query)
data = mycursor.fetchall( )
for record in data:
print(‘Roll No = ‘ , record[0])
print(‘Name = ‘ , record[1])
print(‘DOB = ‘ , record[2])
print(‘Fee = ‘ , record[3])
import mysql.connector as m
mycon=m.connect(host=”localhost”,user=”root”,password=”tiger”, database=’SC’)
mycursor=mycon.cursor( )
Display(mycursor)
mycon.close( )
3 def Add(mycursor):
n = int(input(‘Enter no. of Student Records to be entered: ’))
for i in range(n):
rn = int(input(‘Enter Student Roll No: ’))
nm = input(‘Enter Student name: ’)
dob = input(‘Enter Student DOB as ‘YYYY-MM-DD’ : ’))
fee = float(input(‘Enter Student Fee: ’))
query = f ”insert into CLASS values({rn},’{nm}’,’{dob}’,{fee})”
mycursor.execute(query)
mycon.commit( )
import mysql.connector as m
mycon=m.connect(host=”localhost”,user=”root”,password=”tiger”, database=’SC’)
mycursor=mycon.cursor( )
Add(mycursor)
mycon.close( )
4 def Add(mycursor):
mycursor.execute(‘use COMPANY’)
n = int(input(‘Enter no. of Records to be entered: ’))
for i in range(n):
en = int(input(‘Enter Student Roll No: ’))
enm = input(‘Enter Student name: ’)
dob = input(‘Enter Student DOB as ‘YYYY-MM-DD’ : ’))
sal = float(input(‘Enter Student Fee: ’))
query = f ”insert into EMP values({en},’{enm}’,’{dob}’,{sal})”
mycursor.execute(query)
mycon.commit( )
import mysql.connector as m
mycon=m.connect(host=”localhost”,user=”root”,password=”password”)
mycursor=mycon.cursor( )
Add(mycursor)
mycon.close( )
All Important Abbreviations for CBSE Board Exams
🔹 1. Network Types
Abbreviation Full Form Meaning
PAN Personal Area Network Network within a few meters (Bluetooth).
LAN Local Area Network Network within school/building.
MAN Metropolitan Area Network Network across a city.
WAN Wide Area Network Network across countries (Internet).
🔹 2. Network Devices
Abbreviation Full Form Meaning
NIC Network Interface Card Connects a computer to the network.
MAC Media Access Control Unique address of a device.
HUB — Simple device that broadcasts data.
SWITCH — Smart device that filters and forwards data.
ROUTER — Connects multiple networks.
MODEM Modulator-Demodulator Converts digital ↔ analog signals.
RJ45 Registered Jack 45 Connector for Ethernet cable.
🔹 3. Communication Media
Abbreviation Full Form Meaning
UTP Unshielded Twisted Pair Common cable in LAN.
STP Shielded Twisted Pair Cable with extra protection.
OFC Optical Fiber Cable High-speed data cable.
Wi-Fi Wireless Fidelity Wireless networking.
Li-Fi Light Fidelity Data through light waves.
🔹 4. Internet Protocols
Abbreviation Full Form Use
IP Internet Protocol Addressing system for devices.
TCP Transmission Control Protocol Reliable data transfer.
UDP User Datagram Protocol Fast but unreliable.
HTTP Hyper Text Transfer Protocol Web communication.
HTTPS Hyper Text Transfer Protocol Secure Secure web connection.
FTP File Transfer Protocol File transfer between systems.
SMTP Simple Mail Transfer Protocol Sending emails.
POP3 Post Office Protocol v3 Downloading emails.
IMAP Internet Message Access Protocol Email access without download.
DNS Domain Name System Converts domain to IP address.
URL Uniform Resource Locator Web address of a site.
ISP Internet Service Provider Provides Internet connection.
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 1
Abbreviation Full Form Meaning
OTP One Time Password Temporary password.
IDS Intrusion Detection System Detects network attacks.
DoS Denial of Service Attack that makes network unavailable.
DDoS Distributed Denial of Service Large-scale DoS attack.
FIREWALL — Security barrier between networks.
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 2
SECTION E 02 36-37 05 10
37 70
UNIT1
Q.22
Revision of Python topics covered in Q.23
11 Q.31
Class XI. Q.24
Q.26
Functions: Q.25
Exception handling 1
Introduction to files
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 3
Data Structure: Q.30
UNIT2
Evolution of networking:
Transmission media:
Q.37
Network protocol: 1
UNIT3
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 4
Database concepts:
Q.32
Structured Query Language: 3 Q.27
Q.34
NUMBER OF QUESTION 21 7 3 4 2
TOTAL MARKS 21 14 09 16 10
General Instructions:
This question paper contains 37 questions.
All questions are compulsory. However, internal choices have been provided in some
questions. Attempt only one of the choices in such questions.
The paper is divided into 5 Sections- A, B, C, D and E.
Section A consists of 21 questions (1 to 21). Each question carries 1 Mark.
Section B consists of 7 questions (22 to 28). Each question carries 2 Marks.
Section C consists of 3 questions (29 to 31). Each question carries 3 Marks.
Section D consists of 4 questions (32 to 35). Each question carries 4 Marks.
Section E consists of 2 questions (36 to 37). Each question carries 5 Marks.
All programming questions are to be answered using Python Language only.
In-case of MCQ, text of the correct answer should also be written.
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 5
1 State if the following statement is True or False: 1
Using the statistics module, the output of the below statements will be 20: import
statistics
statistics.median([10, 20, 10, 30, 10, 20, 30])
a) IT b) it c) It d) iT
3 Consider the given expression: 1
print(19<11 and 29>19 or not 75>30)
Which of the following will be the correct output of the given expression?
a) True b) False c) Null d) No output
4 In SQL, which type of Join(s) may contain duplicate column(s)? 1
5 What will be the output of the following Python code? 1
str= "Soft Skills"
print(str[-3::-3])
a) lSf b) Stkl c) StKi d) l
6 Write the output of the following Python code : 1
for k in range(7,40,6):
print ( k + '-' )
7 What will be the output of the following Python statement: 1
print(10-3**2**2+144/12)
8 Consider the given SQL Query: 1
SELECT department, COUNT(*) FROM employees HAVING COUNT(*) > 5 GROUP BY
department;
Saanvi is executing the query but not getting the correct output. Write the correction.
9 What will be the output of the following Python code? 1
try:
x = 10 / 0
except Exception:
print("Some other error!")
except ZeroDivisionError:
print("Division by zero error!")
a) Division by zero error! b) Some other error!
c) ZeroDivisionError d) Nothing is printed
10 What will be the output of the following Python code? 1
my_dict = {"name": "Alicia", "age": 27, "city": "DELHI"}
print(my_dict.get("profession", "Not Specified"))
a) Alicia b)DELHI c)None d)Not Specified
11 What possible output is expected to be displayed on the screen at the time of execution of 1
the Python program from the following code?
import random
L=[10,30,50,70]
Lower=random.randint(2,2)
Upper=random.randint(2,3)
for K in range(Lower, Upper+1):
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 6
17 is a protocol used for retrieving emails from a mail server. 1
a) SMTP b) FTP c) POP3 d) PPP
18 Which of the following is correct about using a Hub and Switch in a computer network? 1
a) A hub sends data to all devices in a network, while a switch sends data to the
specific device.
b) A hub sends data only to the devices it is connected to, while a switch sends data to all
devices in a network.
c) A hub and switch function the same way and can be used interchangeably.
d) A hub and switch are both wireless networking devices.
19 Which of the following is used to create the structure of a web page? 1
a) CSS b) HTML c) JavaScript d) FTP
Q20 and Q21 are Assertion(A) and Reason(R) based questions. Mark the correct choice as:
a) Both A and R are True and R is the correct explanation for A.
b) Both A and R are True and R is not the correct explanation for A.
c) A is True but R is False.
d) A is False but R is True.
20 Assertion (A): The expression (1, 2, 3, 4).append(5) in Python will modify the original 1
sequence datatype.
Reason (R): The append() method adds an element to the end of a list and modifies the list
in place.
21 Assertion (A): A primary key must be unique and cannot have NULL values. 1
Reasoning (R): The primary key uniquely identifies each row in the table.
I. Write a statement to find the index of the first occurrence of the substring
"good" in a string named review.
II. Write a statement to sort the elements of list L1 in descending order.
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 7
OR
B. Predict the output of the following Python code:
text="Learn Python with fun and practice"
print(text.partition("with"))
print(text.count("a"))
25 A. Write a function remove_element() in Python that accepts a list L and a number n. If the 2
number n exists in the list, it should be removed. If it does not exist, print a message
saying "Element not found".
OR
B. Write a Python function add_contact() that accepts a dictionary phone_book, a name,
and a phone number. The function should add the name and phone number to
the dictionary. If the name already exists, print "Contact already exists" instead of
updating it.
26 Predict the output of the Python code given below : 2
emp = {"Arv": (85000,90000),"Ria": (78000,88000),"Jay": (72000,80000),"Tia":
(80000,70000)}
selected = [ ]
for name in emp: salary
= emp[name]
average = (salary[0] + salary[1]) / 2
if average > 80000:
selected.append(name)
print(selected)
27 A. Write suitable commands to do the following in MySQL. 2
I. View the table structure.
II. Create a database named SQP
OR
B. Differentiate between drop and delete query in SQL with a suitable example.
28 A. Define the following terms: 2
I. Modem
II. Gateway
OR
B.
I. Expand the following terms: HTTP and FTP
II. Differentiate between web server and web browser.
Q No. Section-C ( 3 x 3 = 9 Marks) Marks
29 A. Write a Python function that displays the number of times the word "Python" 3
appears in a text file named "Prog.txt".
OR
B. Write and call a Python function to read lines from a text file STORIES.TXT and
display those lines which doesn’t start with a vowel (A, E, I, O, U) irrespective of
their case.
30 A list containing records of products as 3
L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)] Write
the following user-defined functions to perform operations on a stack named Product
to:
I. Push_element() – To push an item containing the product name and price of
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 8
products costing more than 50 into the stack.
Output: [('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]
II. Pop_element() – To pop the items from the stack and display them. Also, display
"Stack Empty" when there are no elements in the stack.
Output: ('Headphones',
1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Emply
31 A. Predict the output of the following Python code: 3
s1="SQP-25"
s2=""
i=0
while i<len(s1):
if s1[i]>='0' and s1[i]<='9':
Num=int(s1[i])
Num-=1
s2=s2+str(Num)
elif s1[i]>='A' and s1[i]<='Z':
s2=s2+s1[i+1]
else:
s2=s2+'^'
i+=1
print(s2)
OR
B. Predict the output of the following Python code:
wildlife_sanctuary = ["Kaziranga", "Ranthambhore", "Jim Corbett", "Sundarbans",
"Periyar", "Gir", "Bandipur"]
output = [ ]
for sanctuary in wildlife_sanctuary:
if sanctuary[-1] in 'aeiou':
output.append(sanctuary[0].upper())
print(output)
Q No. Section-D ( 4 x 4 = 16 Marks) Marks
32 Consider the table SALES as given below: 4
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page 9
III. To display the distinct Product names from the SALES table.
IV. To display the records of customers whose names end with the letter 'e'.
OR
B. Predict the output of the following:
I. SELECT * FROM Sales where product='Tablet';
II. SELECT sales_id, customer_name FROM Sales WHERE product LIKE 'S%';
III. SELECT COUNT(*) FROM Sales WHERE product in ('Laptop', 'Tablet');
IV. SELECT AVG(price) FROM Sales where product='Tablet';
33 Raj is the manager of a medical store. To keep track of sales records, he has created a CSV 4
file named Sales.csv, which stores the details of each sale.
The columns of the CSV file are: Product_ID, Product_Name, Quantity_Sold and
Price_Per_Unit.
Help him to efficiently maintain the data by creating the following user-defined functions:
I. Accept() – to accept a sales record from the user and add it to the file Sales.csv.
II. CalculateTotalSales() – to calculate and return the total sales based on the
Quantity_Sold and Price_Per_Unit.
34 Pranav is managing a Travel Database and needs to access certain information from the 4
Hotels and Bookings tables for an upcoming tourism survey. Help him extract the
required information by writing the appropriate SQL queries as per the tasks mentioned
below:
Table: Hotels
Table: Bookings
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page
10
I. To display a list of customer names who have bookings in any hotel of 'Delhi' city.
II. To display the booking details for customers who have booked hotels in
'Mumbai', 'Chennai', or 'Kolkata'.
III. To delete all bookings where the check-in date is before 2024-12-03.
IV. A. To display the Cartesian Product of the two tables.
OR
B. To display the customer’s name along with their booked hotel’s name.
HR Finance 50
HR IT 175
HR Logistics 90
Finance IT 60
Finance Logistics 70
IT Logistics 60
Number of Computers in Each Block:
Block Number of Computers
HR 60
Finance 40
IT 90
*Please note that the assessment scheme of the Academic Session 2024-25 will continue in the current session i.e.
2025-26.
Page
11
Logistics 35
I. Suggest the best location for the server in the Hyderabad campus and explain your
reasoning.
II. Suggest the placement of the following devices:
a) Repeater b) Switch
III. Suggest and draw a cable layout of connections between the buildings inside the
campus.
IV. The organisation plans to provide a high-speed link with its head office using a
wired connection. Which of the cables will be most suitable for this job?
V. A. What is the use of VoIP?
OR
B. Which type of network (PAN, LAN, MAN, or WAN) will be formed while
connecting the Hyderabad campus to Bengaluru Headquarters?
Page: 1/157
SAMPLE QUESTION PAPER (THEORY)
CLASS: XII SESSION: 2025-26
COMPUTER SCIENCE (083)
Time allowed: 3 Hours Maximum Marks: 70
General Instructions:
2 MCQ 1
What will be the output of the following code?
List slicing
Page: 2/157
3 MCQ 1
Consider the given expression:
Python Relational & Logical expression in print()
Which of the following will be the correct output of the given
expression?
MCQ
What will be the output of the following Python code?
5 String slicing 1
MCQ
What will be the output of the following Python code?
9 Exception handling based 1
MCQ
What will be the output of the following Python code? Dictionary
10 based 1
Page: 3/157
MCQ
What possible output is expected to be displayed on the screen at
11 the time of execution of the Python program from the following 1
code?
Random randint fn
MCQ
What will be the output of the following Python code?
12 Using global fn 1
13 1
14 1
15 1
16 1
MCQ
Fill in the blank Protocol based
17 1
18 1
MCQ Webpage
19 1
Page: 4/157
Q20 and Q21 are Assertion(A) and Reason(R) based questions.
Mark the correct choice as:
(A) Both A and R are true and R is the correct explanation for A
(B) Both A and R are true and R is not the correct explanation for A
(C) A is True but R is False
(D) A is False but R is True
20 Append() 1
21 Primary Key 1
Page: 5/157
24 A. (Answer using Python built-in methods/functions only): 2
I. String based
II. List based.
OR
B. Predict the output of the following Python code:
print( String fn)
print( String fn)
Page: 6/157
Q Section-C ( 3 x 3 = 09 Marks) Mark
No. s
Page: 7/157
32 Consider the table <tablename> as given below: 4
Page: 8/157
Q Section-E ( 3 x 5 = 15 Marks) Mark
No. s
Page: 9/157
MARKING SCHEME
Class: XII Session: 2024-25 Computer
Science (083)
Page:
10/157
13. Alter (or Alter Table) (1)
(1 mark for correct answer)
14. (A) Details of all products whose names start with 'App'
(1)
(1 mark for correct answer)
15. (D) CHAR
(1)
(1 mark for correct answer)
16. (B) count()
(1)
(1 mark for correct answer)
17. (B) FTP
(1)
(1 mark for correct answer)
18. (B) Gateway
(1)
(1 mark for correct answer)
19. (B) Packet Switching
(1)
(1 mark for correct answer)
20. (C) A is True but R is False.
(1)
(1 mark for correct answer)
21. (C) A is True but R is False.
(1)
(1 mark for correct answer)
Page:
11/157
24. (I)
A) L1.count(4)
OR
B) L1.sort() (2)
(1 mark for correct answer)
(II)
A) L1.extend(L2)
OR
B) L2.reverse()
(1 mark for correct answer)
25. (A), (C)
(½ x 2 = 1 Mark)
(2)
Minimum and maximum possible values of the variable b: 1,6
(½ x 2 = 1 Mark)
26. def swap_first_last(tup):
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0],)
return new_tup
(2)
Page:
12/157
28. A) Advantage: Network extension is easy.
OR
def show():
f=open("Email.txt",'r'
) data=f.read()
words=data.split()
for word in words:
if '@cmail' in word:
print(word,end='
')
f.close()
(½ mark for correct function header)
(½ mark for correctly opening the file)
(½ mark for correctly reading from the file)
(½ mark for splitting the text into words) (3)
Page:
13/157
if len(word)>5:
print(word,end='
')
(½ mark for correct function header)
(½ mark for correctly opening the file)
(½ mark for correctly reading from the file)
( ½ mark for splitting the text into words)
(1 mark for correctly displaying the desired words)
Page:
14/157
30. (A)
(I)
def push_book(BooksStack, new_book):
BooksStack.append(new_book)
(II)
def pop_book(BooksStack): if
not BooksStack:
print("Underflow")
else:
return(BookStack.pop())
(III)
def peep(BooksStack): if
not BooksStack:
print("None")
else:
print(BookStack[-1])
(3x1 mark for correct function body; No marks for any function header as it
was a part of the question)
OR
(B)
def push_even(N): (3)
EvenNumbers = []
for num in N:
if num % 2 == 0:
EvenNumbers.append(num)
return EvenNumbers
VALUES = []
for i in range(5):
VALUES.append(int(input("Enter an integer: ")))
EvenNumbers = push_even(VALUES)
def pop_even():
if not EvenNumbers:
print("Underflow")
else:
print(EvenNumbers.pop())
pop_even()
Page:
15/157
def Disp_even():
if not EvenNumbers:
print("None")
else:
print(EvenNumbers[-1])
Disp_even()
(1/2 for identifying even numbers)
(1/2 mark for correctly adding data to stack)
(1/2 mark for correctly poping data on the stack and 1/2 mark for checking
condition)
(1/2 mark for correctly displaying the data with none)
(1/2 mark for function call statements)
31. (A) 15@
7@
9
OR
(3)
(B) 1 #2 #3#
1 #2 #3 #
1#
C_Name | Total_Quantity
|
Jitendra |1
Mustafa |2
Dhwani |1
Page:
16/157
(II)
(IV)
MAX(Price)
12000
Page:
17/157
(½ mark for opening in the file in right mode)
(½ mark for correctly creating the reader object)
(½ mark for correct use of counter)
(½ mark for correctly displaying the counter)
Note (for both parts (I) and (II)):
(i) Ignore import csv as it may be considered the part of the
complete program, and there is no need to import it in
individual functions.
(ii) Ignore next(records, None) as the file may or may not have the
Header Row.
34. (I) Select * from FACULTY natural join COURSES where Salary<12000; Or
Select * from FACULTY, COURSES where Salary<12000 and
facuty.f_id=courses.f_id;
(II) Select * from courses where fees between 20000 and 50000;
(III) Update courses set fees=fees+500 where CName like
'%Computer%';
(IV)
(A) Select FName, LName from faculty natural join courses where
Came="System Design";
Or (4)
Select FName, LName from faculty, courses where Came="System
Design" and facuty.f_id=courses.f_id;
OR
Page:
18/157
(½ mark for correctly importing the connector object)
(½ mark for correctly creating the connection object)
(½ mark for correctly creating the cursor object)
(½ mark for correctly inputting the data)
(½ mark for correct creation of first query)
(½ mark for correctly executing the first query with commit)
(½ mark for correctly executing the second query)
(½ mark for correctly displaying the data)
def input_candidates():
candidates = []
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
candidate_id = int(input("Enter Candidate ID: "))
candidate_name = input("Enter Candidate Name: ")
designation = input("Enter Designation: ")
experience = float(input("Enter Experience (in years): "))
candidates.append([candidate_id, candidate_name, designation,
experience])
return candidates
candidates_list = input_candidates()
def append_candidate_data(candidates):
with open('candidates.bin', 'ab') as file:
for candidate in candidates:
pickle.dump(candidate, file)
print("Candidate data appended successfully.")
append_candidate_data(candidates_list)
(II)
import pickle
def update_senior_manager():
updated_candidates = [] try:
with open('candidates.bin', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[3] > 10: # If experience > 10 years candidate[2]
= 'Senior Manager'
updated_candidates.append(candidate)
except EOFError:
Page:
19/157
break # End of file reached
except FileNotFoundError:
print("No candidate data found. Please add candidates first.")
return
(III)
import pickle
display_non_senior_managers()
(II) Switch
(1 mark for correct answer)
(III)
Page:
20/157
(or Any other correct layout)
(IV) There is no requirement of the Repeat as the optical fibre cable used for the
network can carry the data to much longer distances than within the
campus.
(1 mark for correct answer)