XII Computer Science
XII Computer Science
PATRON
Shri Vikas Gupta, IAS, Commissioner, KVS
CO-PATRON
Ms. Chandana Mandal, Additional Commissioner (Academic), KVS (HQ)
COVER DESIGN
KVS Publication Section
EDITOR:
Mr. T. Prabhudas, Director, ZIET Mumbai
MR. HEMANT
PGT CS PM SHRI KV CME PUNE MUMBAI
MR. VIKAS
PGT CS PM SHRI KV OF CHANDA MUMBAI
MRS. BINDHIYA N
PGT CS PM SHRI KV KANJIKODE ERNAKULUM
MRS. HEMA C N
PGT CS PM SHRI KV NO.1 NAVAL BASE KOCHI ERNAKULUM
MRS. SOUMYAMOL D
PGT CS PM SHRI K V KANHANGAD ERNAKULUM
MRS. SOMA SEAL GUHA PGT CS KENDRIYA VIDYALAYA CISF BHILAI RAIPUR
11 REFERENCES 170
Computer Science (2026-27)
CLASS XII Code No. 083
Unit wise Syllabus
Unit 1: 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.
Unit 2: 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
Unit 3: 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)
● Structured Query Language: Introduction, Data Definition Language and Data
Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints (not
1|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
2|Page
UNIT I:COMPUTATIONAL THINKING AND PROGRAMMING
PYTHON REVISION TOUR
About Python:
• Python programming language 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”
• Keywords: Reserved words having special meaning.
• 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
✔ 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)
3|Page
Arithmetic Operators +, -, *, /, //, %, **
Relational Operators <, <=, >, >=, ==, !=
Logical Operators not, and, or
Identity Operator is, is not
Membership Operator in, not in
Assignment Operator =, +=, -=, *=, /=, //=, %=
• 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:
‘ “ # \ ( ) [ ] { } @ , : . = ;
Note: Python also offers a special literal (datatype) None which is used to create a variable without
giving ut any significant value.
• Variables: Variables are containers for storing data values.
Key points:
⮚ Variables do not need to be declared or defined in advance.
4|Page
⮚ A variable is created when you first assign a value to it.
⮚ Python is dynamically typed language where data type of the variable is not required
statically.
⮚ Example:
# Initially assigning an integer value
x = 88 # x assigned as integer type
print ("x =", x, " Type:", type(x))
# Reassigning a string value to the same variable
x = "Dynamic Typing in Python" # x assigned as string type
print ("x =", x, " Type:", type(x))
Note: Dynamic typing allows user to assign different values to same variable at different
places in a program
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 value import random
Float between 0.0 and 1.0. random. random ( )
(0.0 <= X < 1.0)
5|Page
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 (does not include 100), step 5
STRING
• A string is a sequence of characters enclosed in single (' '), double (" "), or
triple (''' ''' / """ """) quotes for multiline text.
• Strings are immutable — once created, they cannot be changed.
• Strings are indexed, starting from 0 (left to right) and -1 (right to left).
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, starting from 0 (left to right) and -1 (right to left).
• 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
7|Page
List Functions and Methods
8|Page
Tuple Functions and Methods
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 [Link]( ): Iterates through key- value name John
items print(k, v) pairs age 16
city Delhi
9|Page
10 | P a g e
Multiple Choice Questions
1 What will be the output of the following code snippet?
a = "10"
b = "20"
print (int (a + b) + int(a) * int(b))
a) 1220 b) 410 c) 620 d) 30
2 Which of the following code snippets correctly checks if a string s is a palindrome (case-
insensitive)?
a) s == s[::-1] b) [Link]( ) == [Link]( )[::-1]
c) [Link]( ) == [Link]( )[::-1] d)s== [Link]( )
3 What will be the output of the following code?
x=5
y = "2"
print (x * int(y) + len(y + str(x)))
a) 11 b) 12 c) 15 d) 10
4 Which of the following code snippets will raise an error for s = "Python"?
a) print(s[10]) b) print(s[1:10]) c) print (s [-1: -3]) d) print(s[:2])
5 What will be the output of following python code:
s = 'Programming'
print([Link]("m"))
a. ['Progra', ' ', 'ing'] b. ['Progra', 'ing']. c. ['Progra', 'm', 'ing'] d. [Progra', 'ming']
6 What will be the output of following python code:
t1 = 1,2,3
t2 = (1,2,3)
print(t1 is t2)
a. True b. 1 c. False d. 0
7 State whether the following statement is True or False:
An exception may be raised even if the program is syntactically correct.
8 Which of the following is not a type conversion function?
a) int( ) b) str ( ) c) input ( ) d) float ( )
9 Select the correct output of the code:
a = "foobar"
a = [Link]("o")
print(a)
a. ["fo","","bar"] b. ["f","oo","bar") c. ["f","o","bar"] d. ("f","o","obar")
10 Write the output of the following:
a= (10, 12, 13, 12, 13, 14, 15)
print(max(a) + min(a) + [Link](2))
a) 13. b) 25 c) 26 d) Error
11 What will be the output of the following statement ?
print(6+5/4**2//5+8)
a.-14.0 b.14.0 c.-14 d. 1
12 Select the correct output of the code:
S = "text#next"
print([Link]("t"))
11 | P a g e
a. ext#nex b. ex#nex c. text#nex d. ext#next
13 Identify the valid Python identifier from the following :
a. 2user b. user@2 c. user_2 d. user 2
14 Consider the statements given below and then choose the correct output from the given
options :
Game="World Cup 2023"
print(Game[-6::-1])
a. CdrW b. ce o c. puC dlroW d. Error
15 Predict the output of the following Python statements :
import statistics as s
[Link] ([10, 20, 10, 30, 10, 20, 30])
a. 30 b. 20 c.10 d. 18.5
16 What will be the output of the following statement :
print (16*5/4*2/5–8)
a. – 3.33 b. 6.0 c. 0.0 d. –13.33
17 Identify the invalid Python statement from the following :
a. d = dict( ) b. e = {} c. f = [ ] d. g = dict{}
18 Consider the statements given below and then choose the correct output from the given
options :
myStr = "MISSISSIPPI"
print(myStr[:4]+"#"+myStr[–5:])
a. MISSI#SIPPI b. MISS#SIPPI c. MISS#IPPIS d. MISSI#IPPIS
19 Identify the statement from the following which will raise an error :
a. print("A"*3) b. print(5*3) c. print("15" + 3) d. print("15" + "13")
20 What will be the output of the following code?
L = ["India", "Incredible", "Bharat"]
print(L[1][0] + L[2][-1])
a) IT b) it c) It d) iT
21 State True or False.
“ Comments are not executed by interpreter.”
22 Given the following dictionary
Day={1:"Monday", 2: "Tuesday", 3: "Wednesday"}
Which statement will return "Tuesday"?
a. [Link]( ) b. [Link](2) [Link](1) [Link]("Tuesday")
23 Consider the given expression :
7<4 or 6>3 and not 10==10 or 17>4
What will be the output of the above expression?
[Link] b. False c. NONE d. NULL
24 Select the correct output of the code :
S="Amrit Mahotsav @ 75"
A=[Link](" ",2)
print(A)
a.['Amrit', 'Mahotsav','@','75') b. ('Amrit', 'Mahotsav','@ 75)
c. ['Amrit','Mahotsav','@ 75'] d.['Amrit','Mahotsav','@','75']
25 What will the following expression be evaluated to in Python ?
print(6/3 + 4**3//8-4)
(a) 6.5 (b) 4.0 (c) 6.0 (d) 4
12 | P a g e
26 State True or False: “A Python List must always contain all its elements of same data type.”
27 What will be the output of the following statement?
print(14%3**2*4)
a. 16 b. 64 c. 20 d. 256
28 Identify the correct output of the following code snippet:
game="Olympic2024"
print([Link]("C"))
(A) 0 (B) 6 (C) -1 (D) ValueError
29 Which of the following is the correct identifier?
(A) global (B) Break (C) def (D) with
30 Identify the invalid Python statement out of the following options:
(A) print("A",10,end="*") (B) print("A",sep="*",10)
(C) print("A",10,sep="*") (D) print("A"*10)
31 Consider the statements given below and then choose the correct output from the given
options:
L=['TIC', 'TAC']
print(L[::-1])
(A) ['CIT', 'CAT'] (B) ['TIC', 'TAC']
(C) ['CAT', 'CIT'] (D) ['TAC', 'TIC']
32 Which of the following operator evaluates to True if the variable on either side of the operator
points towards the same memory location and False otherwise?
(A) is (B) is not (C) and (D) or
33 Consider the statements given below and then choose the correct output from the given
options:
D={'S01':95, 'S02':96 }
for I in D:
print(I,end='#')
(A) S01#S02# (B) 95#96# (C) S01,95#S02,96# (D) S01#95#S02#96#
34 What will be the output of the following Python code?
my_dict = {"name": "Alicia", "age": 27, "city": "DELHI"}
print(my_dict.get("profession", "Not Specified"))
a) Alicia b)DELHI c)None d)Not Specified
35 Which of the following built-in function/method returns a dictionary ?
(A) dict( ) (B) keys( ) (C) values( ) (D) items( )
ANSWERS
1 A 2 C 3 b 4 A 5 a
6 a 7 True 8 c 9 D 10 B
11 B 12 A 13 C 14 C 15 C
16 C 17 D 18 B 19 C 20 c)
21 True 22 B 23 True 24 B 25 C
26 False 27 C 28 D 29 B 30 B
31 D 32 A 33 A 34 D 35 A
13 | P a g e
Assertion/Reasoning Type 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): Lists can store only elements of the same data type.
Reason (R): Python is a dynamically typed language
2 Assertion(A): List is an immutable data type.
Reasoning(R): When an attempt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in memory
3 Assertion. Dictionaries are mutable, hence its keys can be easily changed.
Reason. Mutability means a value can be changed in place without having to create new
storage for the changed value.
4 Assertion (A): You can add an element in a dictionary using key:value pair.
Reasoning (R): A new (key:value) pair is added only when the same key doesn't exist in the
dictionary. If the key is already present, then the existing key gets updated and the new entry
will be made in the dictionary.
5 Assertion (A): Tuples hold a sequence of homogenous elements.
Reason (R): Tuples are immutable
6 Assertion (A): The expression "Hello".sort( ) in Python will give an error.
Reason (R): sort( ) does not exist as a method/function for strings in Python
7 Assertion(A): List is an immutable data type
Reasoning(R): When an attempt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in memory
8 Assertion(A): Python Standard Library consists of various modules.
Reasoning(R): A function in a module is used to simplify the code and avoids repetition
ANSWERS ASSERTION REASONING
1 (D) A is false but R is true
2 (D) A is false but R is true
3 (D) A is false but R is true
4 (A) Both A and R are true and R is the correct explanation of A
5 (D) A is false but R is true
6 (A) Both A and R are true and R is the correct explanation of A
7 (D)A is false but R is True
8 (B) Both A and R are true but R is not the correct explanation for A
Short Answer Questions/Long Answer Questions
1 Write the output displayed on execution of the following Python code :
LS=["HIMALAYA","NILGIRI","ALASKA","ALPS"]
D={}
for S in LS :
if len(S)%4 == 0:
D[S] = len(S)
for K in D :
print(K,D[K], sep = "#")
14 | P a g e
2 Write the Python statement for each of the following tasks using built-in functions/methods
only :
(i) To remove the item whose key is "NISHA" from a dictionary named Students. For example,
if the dictionary Students contains {"ANITA":90, "NISHA":76, "ASHA":92}, then after
removal the dictionary should contain{"ANITA":90,"ASHA":92}
(ii) To display the number of occurrences of the substring "is" in a string named message.
For example if the string message contains "This is his book", then the output will be 3.
3 A tuple named subject stores the names of different subjects. Write the Python commands to
convert the given tuple to a list and thereafter delete the last element of the list.
4 Predict the output of the following code :
d={"IND":"DEL","SRI”:"COL","CHI":"BEI"}
str1=""
for i in d:
str1=str1+str(d[i])+"@"
str2=str1[:–1]
print (str2)
5 Write the Python statement for each of the following tasks using BUILT-IN functions/methods
only :
(i) To delete an element 10 from the list lst.
(ii) To replace the string "This" with "That" in the string str1.
6 A dictionary dict2 is copied into the dictionary dict1 such that the common key’s value gets
updated. Write the Python commands to do the task and after that empty the dictionary dict1.
7 Write difference between mutable and immutable data types? Write name of any two mutable
data types.
8 i. Which operator in python has right to left associativity?
ii. Evaluate the following expression and write output: 5//4**3%6+2
9 If str1= “foundation stone” and str2= “strong base”, then
Write the Python statements for each of the following tasks using Built-in functions/methods
only:
• To count the occurrence of the letter ‘n’ in str1.
• To convert the string str2 in a list and each word of the string should become the
element of the list
10 Explain the difference between explicit and implicit type conversion in Python with a
suitable example.
11 How is a mutable object different from an immutable object in Python? Identify one mutable
object and one immutable object from the following:
(1,2), [1,2], {1:1,2:2}, ‘123’
12 if L1=[1,2,3,2,1,2,4,2, . . . ], and L2=[10,20,30, . ..], then(Answer using built in functions only)
I) A) Write a statement to count the occurrences of 4 in L1.
B) Write a statement to sort the elements of list L1 in ascending order.
(II) A) Write a statement to insert all the elements of L2 at the end of L1.
B) Write a statement to reverse the elements of list L2.
13 Write the Python statement for each of the following tasks using BUILT-IN functions/methods
only:
(i) To insert an element 200 at the third position, in the list L1.
(ii) To check whether a string named, message ends with a full stop/ period or not
15 | P a g e
14 A list named studentAge stores age of students of a class. Write the Python command to
import the required module and (using built-in function) to display the most common age
value from the given list.
15 (a) Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-2])
(b) Write the output of the code given below:
my_dict = {"name": "Aman", "age": 26}
my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items( ))
16 Predict the output of the Python code given below:
tuple1 = (11, 22, 33, 44, 55 ,66)
list1 =list(tuple1)
new_list = [ ]
for i in list1:
if i%2==0:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
17 Predict the output of the code given below:
s="welcome2cs"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper( )
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper( )):
m = m + s[i].lower( )
else:
m = m +'&'
print(m)
18 Write a suitable Python statement for each of the following tasks using built-in
functions/methods only:
i To delete an element Mumbai:50 from Dictionary D.
ii To display words in a string S in the form of a list
Answers
1 HIMALAYA#8
ALPS#4
2 i) [Link]("NISHA")
(ii) print([Link]("is"))
[Link]("is")
3 subject=list(subject)
[Link]( )
4 DEL@COL@BEI
16 | P a g e
5 (i) [Link](10)
ii) [Link]("This","That")
6 [Link](dict2)
[Link]( )
7 Mutable Data Type Immutable Data Type
17 | P a g e
WORKING WITH FUNCTIONS
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 (.).
18 | P a g e
Example: >>> value= [Link] (25) # dot notation
▪ From Statement: It is used to get a specific function in the code instead of the complete
module file. For modules having large no. of functions, it is recommended to use from instead
of import.
Example:
def area_of_circle(radius ): # radius Formal Parameter OUTPUT
print (“Area of circle = “,3.1416*radius*radius) Enter radius of circle 10
Area of circle = 314.16
r=int (input (“Enter radius of circle”))
ar=area_of_circle(r) # r - Actual Parameter or Argument
20 | P a g e
FUNCTION RETURNING VALUE(S)
A function can returns multiple values. The return values should be a comma separated list of values.
The multiple return values are returned as a tuple. We can unpack the received value by specifying
the same number of variables on the left side of the function call.
If the function does not return any value, by default it returns None value to the function call.
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)
global KEYWORD:
The global keyword is used when a programmer wants to access and/or change the variables created in
global space from a local space i.e. from the functions.
Example: First example below shows the use of global keyword in function, the secon example creates
a local variable.
Flow of Execution of programs with functions:
Whenever the interpreter observes the def keyword during execution of the program, it omits the
execution of the body of that function. The interpreter only executes the function body when it is called.
When the interpreter executes the function body after a function call, it executes the function until the
return keyword is encountered or until the last statement of the function body is executed.
If the function returns any value, the execution will go to the statement of function call. If the function
does not return any value, the function call goes to the statement next to the function call.
Examples:
1. def fun(x, y): 1. def fun(x, y): 1. def fun(x, y):
2. z=x+y 2. z=x+y 2. z=x+y
3. print(z) 3. print(z) 3. return z
4. return 4. a, b = 10, 20 4. a, b = 10, 20
5. a, b = 10, 20 5. fun(a, b) 5. c = fun(a, b)
6. fun(a, b) 6. print(“Back to main”)
Behaviour of Mutable and Immutable Data Types when [Link]
print(c)
Functions in Python
7. print(“Back to main”) 7. print(“Back to main”)
Output: Output: Output:
30 30 30
21Back
| P atog main
e Back to main Back to main
Flow of execution: Flow of execution: Flow of execution:
1→5→6→1→2→3→4→7 1→4→5→1→2→3→6 1→4→5→1→2→3→5 →6→7
When arguments are passed to a function in Python, the function receives a reference to the object.
The behaviour depends on whether the object is mutable or immutable.
• Mutable data types can be changed after creation.
Examples: list, dictionary
• Immutable data types cannot be changed after creation.
Examples: int, float, str, tuple
If a mutable object is modified inside the function, the changes are reflected outside the function.
If an immutable object is modified, a new object is created inside the function and the original value
remains unchanged.
23 | P a g e
a) named parameter b) default parameter
c) keyword parameters d) all of the above
18 Consider the statements given below and then choose the correct output from the given options:
def Change(N):
N=N+10
print(N,end='$$')
N=15
Change(N)
print(N)
(A) 25$$15 (B) 15$$25 (C) 25$$25 (D)2525$$
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
24 | P a g e
Reasoning (R): It is accessible through out all the functions.
4 Assertion (A): Built-in function is predefined in the language that are used directly.
Reason (R): print ( ) and input ( ) are built-in functions
5 Assertion (A): - In Python, statement return [expression] exits a function.
Reasoning (R): - Return statement passes back an expression to the caller.
A return statement with no arguments is the same as return None.
6 Assertion (A): - If the arguments in a function call statement match the number and order of
arguments as defined in the function definition, such arguments are called positional
arguments.
Reasoning (R): - During a function call, the argument list first contains default argument(s)
followed by positional argument(s).
ANSWERS
1 (c) A is True but R is False
2 (b) Both A and R are true and R is not the correct explanation for A
3 (a) Both A and R are true and R is the correct explanation for A
4 (a) Both A and R are true and R is the correct explanation for A
5 (a) Both A and R are true and R is the correct explanation for A
6 (c) A is true but R is false
Short Answer Questions/Long Answer Questions
1 Rewrite the following Python program after removing all the syntactical errors (if any),
underlining each correction:
def checkval
x = input ("Enter a number")
if x % 2 =0:
print (x, "is even")
elseif x<0:
print (x, "should be positive")
else:
print (x, "is odd")
2 Mani Ayyar, a python programmer, is working on a project which requires him to define a
function with name CalculateInterest( ).
He defines it as:
def CalculateInterest (Principal, Rate=.06, Time): # Code
But this code is not working; Can you help Mani Ayyar to identify the error in the above
function and with the solution?
3 Predict the possible output(s) of the following code. Also specify the maximum and minimum
value that can be assigned to the variable R when K is assigned value as 2.
import random
Signal=[‘stop’, ’wait’, ’go’]
for K in range (2,0, -1):
R=[Link](K)
print (Signal[R], end=” #”)
a. Stop#wait#go# b. wait#stop# c. go#wait# [Link]#stop#
25 | P a g e
4 Predict the output of the following code fragment
def display (x=2, y=3):
x=x+y
y+=2
print(x,y)
display ( )
display (5,1)
display (9)
a) 5 5 b)12 5
6 3 6 3
12 5 55
c) 5 6 d) 5 5
12 5 7 7
63 6 6
5 Predict the output of the following code snippet:
def Execute(M):
if M%3==0:
return M*3
else:
return M+10;
def Output(B=2):
for T in range (0, B):
print (Execute(T),"* ", end="")
print ( )
Output (4)
Output ( )
Output (3)
6. Find the output of the following program:
def ChangeIt(Text,C):
T=""
for K in range(len(Text)):
if Text[K]>='F' and Text[K]<='L':
T=T+Text[K]. lower ( );
elif Text[K]=='E' or Text[K]=='e':
T=T+C;
elif K%2==0:
T=T+Text[K]. upper ( )
else:
T=T+T[K-1]
print(T)
OldText="pOwERALone"
ChangeIt(OldText,"%")
7 What possible outputs are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum value that can be assigned to each
of the variables L and U.
import random
Arr= [10,30,40,50,70,90,100]
L=[Link](1,3)
26 | P a g e
U=[Link](3,6)
for i in range (L, U+1):
print (Arr[i],"@”, end="")
i) 40 @50 @ ii) 10 @50 @70 @90 @
iii) 40 @50 @70 @90 @ iv) 40 @100 @
27 | P a g e
a=changer(a,b)
print(a,"$",b)
a=changer(a)
print(a,"$",b)
12 Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the
function. The function returns another list named ‘indexList’ that stores the indices of all Non-
Zero Elements of L.
For example: If L contains [12,4,0,11,0,56] The indexList will have – [0,1,3,5]
13 Write a program in Python named which takes the dictionary S as an argument. The
dictionary, S contains Name:(Eng,Math,Science] as key:value pairs. The function displays the
corresponding grade obtained by the students according to the following grading rules :
28 | P a g e
7 Ans. Options i and iii
i)40 @50 @
iii) 40 @50 @70 @90 @
Maximum value of L and U : L=2 ,U=5
8 Ans : a)12
12
9 Ans. iv) 7 $
Maximum value of x is 2
Minimum value of x is 1
10 def checkNumber(N): # Def should be def
status = N%2
return status
#main-code
num=int( input(“ Enter a number to check : “)) # Message not enclosed within quotation mark
k=checkNumber(num)
if k == 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)
11 Ans.
10.0 # 10.0
10.0 $ 20
1.0 # 1.0
1.0 $ 20
12 def INDEX_LIST(L):
indexList= []
for i in range(len(L):
if L[i]! =0:
[Link](i)
return indexList
13 def showGrades(S):
for K, V in S. items( ):
if sum(V)/3>=90:
Grade="A"
elif sum(V)/3>=60:
Grade="B"
else:
Grade="C"
print(K,"–",Grade)
S={"AMIT":[92,86,64],"NAGMA":[65,42,43],"DAVID":[92,90,88]}
showGrades(S)
29 | P a g e
EXCEPTION HANDLING IN PYTHON
Exception: An error that occurs during program execution is called an exception.
Exceptions interrupt the normal flow of a program.
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]: # it is optional to specify Exception
# Code that runs if the exception occurs
except [Exception Type]: # can have multiple blocks
finally:
# Code that will run no matter what (optional)
30 | P a g e
print("Execution complete.") print("Thank you!")
Output 1 (if denominator is 0): Output 2 (normal input):
Enter numerator: 10 Enter numerator: 10
Enter denominator: 0 Enter denominator: 2
Error: Cannot divide by zero! Result = 5.0
Execution complete. Execution complete.
Important Points
• try must be followed by at least one except, finally, or both.
• If no exception occurs, except block is skipped.
• finally block is always executed, even if:
• An exception occurs
• No exception occurs
• return, break, or continue statements are used inside try/except
QUESTIONS:
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:
In Python, if an exception is raised inside a try block and not handled, the program will
terminate without executing any remaining code in the finally block.
ANSWERS
1 (B) WORD5#OVER
2 False
3 False
4 True
5 False
31 | P a g e
DATA FILE HANDLING
TEXT FILE
32 | P a g e
• A file is a collection of data stored on a storage device.
• Used to store data permanently for later use.
• Files can be read from and written to using programming languages like Python, C++, Java, etc.
Types of Files
1. Text Files
•
Store data in readable characters (ASCII or Unicode).
•
Extensions: .txt, .py, .html
•
Can be opened and edited with any text editor.
• CSV Files (Comma-Separated Values)
• Special type of text files that stores tabular data.
• Each line represents a row; values separated by commas.
• Extension: .csv
• Easily used with spreadsheet tools and data processing libraries.
2. Binary Files
• Store data in binary (0s and 1s).
• Not human-readable.
• Extensions: .exe, .jpg, .dat
•
Used for images, audio, video, and compiled programs.
NOTE: A text file can be understood as a sequence of characters consisting of alphabets, numbers and
other special symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
✔ While opening a text file, the text editor translates each ASCII value and shows us the equivalent
character that is readable by the human being.
✔ Each line of a text file is terminated by a special character, called the End of Line (EOL). For
example, the default EOL character in Python is the newline (\n).
Note: if file mode is not mentioned in open function, then default file mode, 'r' is used
33 | P a g e
<rb> Opens the file in binary and read-only mode. Beginning of the file
<r+> Opens the file in both read and write mode. Beginning of the file
<w> Opens the file in write mode. If the file already exists, all Beginning of the file
the contents will be overwritten. If the file doesn’t exist,
then a new file will be created.
<wb> Opens the file in binary mode for writting. If the file Beginning of the file
already exists, all its contents will be overwritten. If the
file does not exist, a new file will be created.
<wb+> Opens the file in read, write, and binary mode. If the file Beginning of the file
already exists, its contents will be overwritten. If the file
does not exist, a new file will be created.
<a> Opens the file in append mode. If the file doesn’t exist, End of the file
then a new file will be created.
<a+> Opens the file in append and read mode. If the file doesn’t End of the file
exist, then it will create a new file.
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
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
[Link](n) from a file but maximum up each list element ends with a newline
to the newline character character (‘\n’)
(\n)
[Link](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 using seek( ) is:
file_object.tell( ) file_object.seek(offset [, reference_point])
36 | P a g e
9. What is the correct way to ensure a file is automatically closed after reading?
a) [Link]( ) b) with open('[Link]') as file:
c) open('[Link]').close( ) d) read([Link])
10. State True or False.
The writelines( ) method automatically adds newline characters (\n) after each line.
ANSWERS:
1 b) Opens a file for reading only 2 c) seek( )
3 d) [Link]( ) 4 d) Write "Hello" and "World" on
separate lines
5 a) file_object.seek(offset [, reference_point]) 6 b) at 30 bytes behind from end-of file
7 b) open("[Link]", "r") 8 c) both iii and iv
9 b) with open('[Link]') as file: 10 False
ASSERTION (A) and REASONING (R)
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.
1. Assertion (A): Opening a file in 'a' mode will delete its previous content.
Reason (R): The 'a' mode appends new data at the end of the existing file content.
2. Assertion (A): The with statement ensures a file is properly closed after its block finishes.
Reason (R): Using with avoids the need to explicitly call close( ) on a file object.
3. Assertion (A): Files must be closed using the close ( ) function to ensure data is saved properly.
Reason (R): Not closing a file may result in data loss or corruption
4. Assertion (A): Opening a file in write mode ‘w’ will delete its existing contents.
Reason (R): In Python, the ‘w’ mode creates a new file if it doesn't exist, but preserves old
content if the file exists.
5. Assertion (A): The writelines( ) method adds newline characters automatically after each line.
Reason (R): writelines( ) writes a list of strings.
6. Assertion (A): File objects in Python have methods like read( ), write( ), and close( ).
Reason (R): These methods are built-in for managing file operations in Python.
7. Assertion (A): seek(0) moves the file pointer to the beginning of the file.
Reason (R): The seek( ) function is used to move the file pointer to a specific location.
8. Assertion (A): The with open( ) statement automatically closes the file after its block is
executed.
Reason (R): It helps prevent memory leaks and is a best practice in file handling.
9. Assertion (A): The readline( ) function reads one line from a file.
Reason (R): readline( ) can be used in a loop to read the entire file line by line.
10. Assertion (A): The read( ) function reads the entire content of a file as a single string.
Reason (R): The read( ) function returns a list of lines from the file.
Answers
1 a 2 d 3 a 4 c 5 d
6 a 7 a 8 a 9 a 10 c
4 read( ) readlines( )
returns the entire file content as a single returns a list of strings, where each string
string. is a line from the file.
41 | P a g e
[Link](i)
[Link]()
[Link]()
def showcontent () :
fin=open("d:\\xiic\\[Link]","r"}
text=[Link]()
print(text)
[Link]()
filter()
showcontent()
9 Write a function RevText( ) to read a text file " d:\xiic\[Link] " and print only the words starting
with 'I' in reverse order.
Example: If value in text file is: INDIA IS MY COUNTRY Output will be: AIDNI SI MY COUNTRY
An def revtext():
s f=open("D:\\xiic\\[Link]","r")
S=" "
while True:
d=[Link]()
if not d:
break
else:
m=[Link]( )
for i in m:
if i[0]=='i' or i[0]=='I':
S=S+" "+(i[::-1])
else:
S=S+" "+i
print (s)
S=""
revtext()
10 Read a text file and display the number of vowels/consonants/uppercase/lowercase. characters
in the file.
An with open("d:\\xiic\\[Link]","r") as f:
s str=[Link]()
vowelst=['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', '0', 'U']
vowel=0
consonants=0
uppercase=0
lowercase=0
for i in str:
if i in vowelst:
vowel+=1
elif [Link]():
consonants+=1
if [Link]():
uppercase+=1
elif [Link]():
42 | P a g e
lowercase+=1
print('vowel:',vowel,'\n','consonants:',consonants,'\n','uppercase:',uppercase,'\n','lowercase:',lo
wercase,'\n')
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 one
from one computer system to another. computer system to another due to variations.
2. It stores data using ASCII format or It stores data in binary format i.e. with the help of
UNICODE characters i.e. human-readable 0 and 1.
graphic characters.
3. These files are easily readable and These files are not easily readable and modifiable
modifiable because the content written in because the content written in binary files is not
text files is human readable. human-readable and it is encrypted content.
4. These files create portability problems. These files are easily portable.
5. Error in a textual file can be easily Error in a binary file corrupts the file and is not
recognized and eliminated. easily detected.
6. Text files are used to store data more user Binary files are used to store data more
friendly. compactly.
7. Mostly .txt and .rtf are used as extensions Can have any application defined extension.
to text files.
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.
43 | P a g e
FILE MODES:
Mode Description
Rb Open file in binary mode for reading only. The file pointer stands at the beginning of
the file. Gives error if file does not exist
rb+or r+b Open file in binary mode for both reading and writing. The file pointer stands at the
beginning of the file. Gives error if file does not exist
Wb Open file in binary mode for writing only. It creates the file if it does not exist. If the
file exists, then it erases all the contents of the file. The file pointer stands at the
beginning of the file.
wb+ or w+b Open file in binary mode for both reading and writing. It creates the file if it does not
exist. If the file exists, then it erases all the contents of the file. The file pointer stands
at the beginning of the file.
Ab Open file in binary mode for appending data. Data is added to the end of the file. It
creates the file if it does not exist. The file pointer stands at the end of the file.
ab+ or a+b Open a file in binary mode for reading and appending data. Data is added to the end
of the file. It creates the file if it does not exist. The file pointer stands at the end of
the file.
Import pickle Module in Python
To write data to a binary file and read it subsequently, we need to use the Python module pickle.
The module pickle is used for serializing and de-serializing any Python object structure
Pickling/Serialization: The process of converting the structure (lists and dictionary etc.) into a byte
stream just before writing to the file.
Unpickling/De-serialization: The reverse of pickling process where information from byte stream gets
converted into object structure.
45 | P a g e
break
except FileNotFoundError:
print("The file [Link] does not exist")
if flag==False:
print("Record not found...")
[Link]()
bf_search()
Append data in Binary File
To append data in binary follow these steps:
1. Open the file in append mode using “ab” Ex.: f = open (“[Link]”,”ab”)
2. Enter data to append
3. Append entered data into the dictionary/list object
4. Use [Link]( ) method to write the dictionary/list data
5. Close the file
Example:
def bf_append():
import pickle
f=open("[Link]","ab")
print("Append Data")
pcode=int(input("Enter the Player code:"))
pname = input("Enter Player Name: ")
score =int(input("Enter individual score:"))
rank =int(input("Enter Player Rank:"))
rec={'Pcode':pcode,'Pname':pname,'Score':score,'Rank':rank}
[Link](rec,f)
[Link]()
bf_append()
Update record in Binary file
To update record, you can use the search record code if you wish. To update the record follow these
steps:
1. Open the file using read mode
2. Declare a variable for unique value to be updated
3. Use try-except and while loop as explained above
4. Add record fetched from binary file into a list
5. Enter the new record information to update
6. Compare the fetched records with entered record and assign the new values to update
7. Write the data using dump( ) function
8. Close the file
Example:
def bf_update():
import pickle
f=open('[Link]','rb')
reclst=[]
while True:
try:
rec = [Link](f)
[Link](rec)
46 | P a g e
except EOFError:
break
[Link]()
pc=int(input("Enter player code to update:"))
pn=input("Enter new name:")
ps=int(input("Enter Player Score:"))
pr=int(input("Enter Player Rank:"))
for i in range(len(reclst)):
if reclst[i] ['Pcode']== pc:
reclst[i]['Pname']= pn
reclst[i]['Score']= ps
reclst[i]['Rank']= pr
f=open('[Link]','wb')
for i in reclst:
[Link](i,f)
[Link]()
bf_update()
Multiple choice Questions
1. Which file mode can be used to open a binary file in both append and read mode?
a) w+ b) wb+ c) ab+ d) a+
2. Nila wants to store a list of dictionaries into a binary file. Which of the following Python
modules should she use?
a) os b) csv c) pickle d) json
3. Pick the correct syntax to read a binary file using pickle:
a) [Link](file) b) [Link](file)
c) [Link](file) d) [Link](file)
4. What does the [Link](obj, file) function do?
a) Reads binary data from a file
b) Writes text data to a file
c) Converts a Python object into byte stream and writes it to a file
d) Appends an object to a list
5. Which file mode should be used to write a binary file in Python?
a) 'w' b) 'r' c) 'wb' d) 'rb'
6. What will happen if you try to read a binary file using 'r' mode instead of 'rb'?
a) It will read data correctly.
b) It will raise a SyntaxError.
c) It will convert binary data into text
d) It may raise an error or return incorrect data
7. Which of the following is a key advantage of binary files over text files?
a) Easy to read with any text editor
b) Allows direct storage of complex Python objects
b) Consumes more storage space
d) Cannot be shared across system
Answers :
1 2 3 4 5 6 7
c c b c c d b
47 | P a g e
Assertion and Reasoning
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, but R is not the correct explanation of A.
c) A is true, but R is false.
d) A is false, but R is true.
[Link] (A): A binary file in python is used to store collection objects like lists and
dictionaries that can be later retrieved in their original form using pickle module.
Reasoning (A): A binary files are just like normal text files and can be read using a text editor
like notepad
2. Assertion (A): The pickle module in Python is used to store and retrieve Python objects in
binary files.
Reason (R): The [Link]( ) method reads data from a binary file and the [Link]( )
method writes data to a binary file.
3. Assertion (A): Binary files are used to store data in the same format as it is stored in
memory.
Reason (R): Binary files convert Python objects into byte streams which are machine-
readable.
4. Assertion (A): You can open a binary file using only 'r' or 'w' mode in Python.
Reason (R): Binary files should be opened with 'rb' or 'wb' modes to ensure correct handling
of byte streams.
5. Assertion (A): Binary files are preferred when large volumes of data need to be stored with
structure.
Reason (R): Binary files are human-readable and can be opened using any text editor.
6. Assertion (A): Binary files are preferred when large volumes of data need to be stored with
structure.
Reason (R): Binary files are human-readable and can be opened using any text editor.
Answers:
1 c) A is True and R is False
2 c) A is true, but R is false.
3 a) Both A and R are true, and R is the correct explanation of A
1 2 3 4 5 6
c c a d c a
48 | P a g e
2 State two advantages of using binary files over text files in Python.
3 How many times should [Link]( ) be called while reading a binary file?
Explain your answer with reference to the number of times [Link]( ) was used while
writing the file.
Answers :
1 The pickle module is used for serializing and de-serializing Python objects into binary
format.
It allows saving complex data types like dictionaries, lists, etc., into a binary file and
retrieving them later.
2 Binary files can store complex Python objects (like dictionaries, lists) directly.
They are more secure and efficient in terms of storage space and speed.
3 The number of times [Link]( ) should be called is equal to the number of times
[Link]( ) was called when the file was written.
If the file was written using [Link]( ) 3 times, then you must call [Link]( ) 3 times to
read all the data.
Since we may not know the exact count, load( ) is usually called inside a loop until EOFError
occurs.
Long Answer Type Questions:
1. Karthik is a manager working in a recruitment agency. He needs to manage the records of
various candidates. For this, he wants the following information of each candidate to be
stored:
Candidate_ID – integer
Candidate_Name – string
Designation – string
Experience – float
You, as a programmer of the company, have been assigned to do this job for Karthik.
i. Write a function to input the data of a candidates and append it in a binary file
ii. Write a function to update the data of candidates whose experience is less than 10
years and change their designation to "Assistant Manager".
iii. Write a function to read the data from the binary file and display the data of all those
candidates who are not "Assistant Manager".
Ans import pickle
1(i) def input_candidates( ):
f=open("[Link]","ab")
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
candidate_id = Candidate ID: "))
candidate_name = input("Enter Candidate Name: ")
designation = input("Enter Designation: ")
experience = float(input("Enter Experience (in years):")):
[Link]([candidate_id, candidate_name, designation, experience],f)
print("Candidate data appended successfully. ")
(ii) import pickle
def update_assistant_manager():
updated_candidates=[]
try:
49 | P a g e
with open('[Link]', 'rb') as file:
while True:
try:
Candidate= [Link](file)
if candidate[3] < 10: # If experience <10 years
candidate[2] = 'Assistant Manager'
updated_candidates.append(candidate)
except EOFError:
break # End of file reached
except FileNotFoundError:
print("No candidate data found. Please add candidates first")
with open('[Link]', 'wb') as file:
for candidate in updated_candidates:
[Link](candidate, file)
1(iii) import pickle
def display_non_assistant_managers( ):
try:
with open('[Link]', 'rb') as file:
while True:
try:
candidate [Link](file)
if candidate[2] != 'Assistant Manager':# Check if not Assistant Manager
print("Candidate ID: ",candidate[0])
print("Candidate Name:",candidate[1])
print("Designation:",candidate[2])
print("Experience:",candidate[3])
print("________________")
except EOFError:
break # End of file reached
except FileNotFoundError:
print("candidate data found. Please add candidates first.")
2 A school is maintaining student records in a binary file [Link]. Each record stores the
following data:
Roll Number (int)
Name (str)
Percentage Marks (float)
Write Python functions to do the following
i. Create a binary file by entering student data in the form of dictionaries.
ii. Count and display the number of students who scored less than 40% (i.e., need
academic improvement).
Ans import pickle
2(i) def create_file( ):
with open('[Link]', 'wb') as file:
n = int(input("Enter number of students:"))
for I in range(n):
student = {}
student['roll'] = int(input("Enter Roll No:"))
student['name'] =input("Enter Name:")
50 | P a g e
student['percentage'] = float(input("Enter Percentage:"))
[Link](student, file)
2(ii) import pickle
def count_low_score( ):
count = 0
try:
with open('[Link]', 'rb') as file:
while True:
try:
student = [Link](file)
if student['percentage'] < 40:
Count+= 1
except EOFError:
break
print("Number of students with less than 40% marks:", count)
except FileNotFoundError:
print("File not found!")
3 A binary file [Link] contains records of books. Each record is stored as a dictionary with
the following fields:
bid- (Book ID – integer)
title- (Book Title – string)
price- (Book Price – float)
The librarian wants to perform the following operations efficiently:
i. Define a function add_books(n) that adds n book records to the binary file.
ii. Define a function update_price(Bid, new_price) that updates the price of the book
whose Book ID is Bid.
iii. Define a function count_books_in_range(low, high) that returns the number of books
whose price lies between low and high (inclusive).
3(i) import pickle
def add_books(n):
with open("[Link]","ab") as f:
for i in range(n):
book ={}
book['bid']=int(input("Enter Book ID:"))
book['title']= input("Book Title:")
book['price']= float(input("Enter Book Price: "))
[Link](book, f)
(ii) import pickle
def update_price(Bid, new_price):
updated = False
temp_list =[]
try:
with open("[Link]", "rb") as f:
while True:
try:
book = [Link](f)
if book['bid'] == Bid:
book['price'] = new_price
51 | P a g e
updated = True
temp_list.append(book)
except EOFError:
break
with open("[Link]", "wb") as f:
for book in temp_list:
[Link](book, f)
if updated:
print("Price updated successfully.")
else:
print("Book ID not found.")
except FileNotFoundError:
print("File not found.")
(iii) import pickle
def count_books_in_range(low,high):
count = 0
try:
with open("[Link]","rb") as f:
while True:
try:
book = [Link](f)
if low <=book['price'] <=high:
count +=1
except EOFError:
break
print("Total books priced between",low,"and",high,":",count)
except FileNotFoundError:
print("File not found.")
4. A binary file [Link] stores records of patients in a hospital. Each record is stored as a
dictionary with the following fields:
pid- (Patient ID – integer)
pname- (Patient Name – string)
age- (integer)
bill- (float – hospital bill amount)
Perform the following tasks using three user-defined functions:
i. Define a function add_patients(n) to add n new patient records to [Link].
ii. Define a function update_bill(Pid, amount) that updates the bill of a patient by adding
the given amount to the existing bill using their Patient ID.
iii. Define a function list_senior_patients( ) to display details of all patients aged 60 and
above.
Ans import pickle
4(i) def add_patients(n):
with open("[Link]", "ab") as f:
for i in range(n):
patient = {}
patient['pid'] = int(input("Enter Patient ID: "))
patient['pname'] = input("Enter Patient Name: ")
patient['age'] = int(input("Enter Age: "))
52 | P a g e
patient['bill'] = float(input("Enter Bill Amount: "))
[Link](patient, f)
4(ii) import pickle
def update_bill(Pid, amount):
updated = False
patients = []
try:
with open("[Link]", "rb") as f:
while True:
try:
patient = [Link](f)
if patient['pid'] == Pid:
patient['bill'] += amount
updated = True
[Link](patient)
except EOFError:
break
with open("[Link]", "wb") as f:
for p in patients:
[Link](p, f)
if updated:
print("Bill updated successfully.")
else:
print("Patient ID not found.")
except FileNotFoundError:
print("File not found.")
4(iii) import pickle
def list_senior_patients():
try:
with open("[Link]", "rb") as f:
print("Senior Patients (Age 60+):")
found = False
while True:
try:
patient = [Link](f)
if patient['age'] >= 60:
print(patient)
found = True
except EOFError:
break
if not found:
print("No senior patients found.")
except FileNotFoundError:
print("File not found.")
5. A binary file, [Link] has the following structure : [Emp_Id, Name, Salary] where
Emp_Id : Employee id
Name: Employee Name
Salary: Employee Salary
53 | P a g e
Write a user defined function, disp_Detail( ), that would read the contents of the file
[Link] and display the details of those employees whose salary is below 25000.
Ans import pickle
def Copy_new():
F2=open("new_items.dat", "wb")
try:
F1=open("[Link]","rb")
Datal=[Link](F1)
Data2={}
for K,V in [Link]():
if v[1]>1000:
Data2[K]=V
[Link] (Data2, F2)
[Link]()
except:
print("File not found!")
[Link]()
6. Mr. Ashok is working on a Toy Shop project to manage toys records using Python. The toys
data is stored in a binary file named [Link]. The binary file [Link] contains
each record in given format:
{“Toy_ID”: T_ID, “TName”:toy_name, “Price”:price}
Where
● Toy_ID: Toy ID (string)
● TName: Toy name (string)
● Price: Price of toy (integer)
You as a programmer, help him to write following python functions:
i. ADD_Data( ) : To write n records in binary file [Link] by taking the values
for each record from user.
ii. SHOW_Data( ) : Read all records from binary file and display them.
iii. Remove_Toy( ) : that deletes the record of a toy in the file [Link] based on
the Toy ID provided by the user. If the Toy ID does not exist in the file, display an
appropriate message.
Ans import pickle
6(i) def ADD_Data():
f=open("[Link]", "wb")
L=[]
n=int(input("How many records you want to enter: "))
for i in range(n):
T_ID=input("Enter Toy ID: ")
toy_name=input("Enter Toy Name: ")
price=int(input("Enter Price: "))
D={"Toy_ID":T ID, "TName": toy name, "Price":price}
[Link](D)
[Link](Lf)
[Link]()
6(ii) def SHOW_Data():
f=open("[Link]", "rb")
L=[Link](f)
54 | P a g e
print(L)
[Link]()
6(iii) def Remove_Toy():
Toy_ID=input("Enter Toy ID: ")
f=open("[Link]", "rb+")
found=0
L=[Link](f)
M=[]
for D in L:
if Toy ID not in D["Toy_ID"]:
[Link](D)
else:
found=1
if found==1:
[Link](0)
[Link](M,f)
print("Record Deleted successfully")
else:
print("Record not found")
[Link]()
7. A file, [Link], stores the records of passengers using the following structure :
[PNR, PName, BRDSTN, DESTN, FARE]
where :
PNR – Passenger Number (string type)
PName – Passenger Name (string type)
BRDSTN – Boarding Station Name (string type)
DESTN – Destination Station Name (string type)
FARE – Fare amount for the journey (float type)
Write user defined functions in Python for the following tasks :
(i) Create( ) – to input data for passengers and write it in the binary file [Link].
(ii) SearchDestn(D) –to read contents from the file [Link] and display the details
of those Passengers whose DESTN matches with the value of D.
(iii) UpdateFare( ) – to increase the fare of all passengers by 5% and rewrite the updated
records into the file [Link].
Ans import pickle
7(i) def Create():
F=open ("[Link]", "wb")
PNR=input("PNR No: ")
PName=input("Name: ")
BRDSTN=input ("Boarding at: ")
DESTN=input("Destination: ")
FARE=float(input("Fare: "))
Rec=[PNR, PName, BRDSTN, DESTN, FARE]
[Link] (Rec, F)
[Link]()
7(ii) def SearchDestn(D):
try:
F=open ("[Link]", "rb")
55 | P a g e
Rec=[Link](F)
for R in Rec:
if R[3]==D:
print(R)
[Link]()
except:
print("File not found!")
7(iii) def UpdateFare():
try:
FR=open ("[Link]", "rb+")
Rec=[Link](FR)
for I in range (len (Rec)):
Rec [1] [4] += (Rec [I] [4] * 0.05)
print("Updation Done!")
[Link](0)
[Link] (Rec, FR)
[Link]()
except:
print("File not found!")
8. Consider a binary file, [Link], containing records stored in the given format : {item_id:
[item_name,amount]}
Write a function, Copy_new( ), that copies all records whose amount is greater than 1000
from [Link] to new_items.dat.
Ans import pickle
def Copy_new():
F2=open("new_items.dat", "wb")
try:
F1=open("[Link]","rb")
Datal=[Link](F1)
Data2={}
for K,V in [Link]():
if v[1]>1000:
Data2 [K]=V
[Link] (Data2, F2)
[Link]()
except:
print("File not found!")
[Link]()
56 | P a g e
COMMA SEPARATED VALUES(CSV) FILES
CSV stands for Comma Separated Values CSV file is a type of plain text file means data stored in form of
ASCII or Unicode characters Each line is a row and in row each piece of data is separated by a comma It
is common format for data interchange.
Steps to Process CSV Files:
1. First of all we have to import csv module for file operation.
2. For writing to CSV Files ,
i. We open file in ‘w’ writing or ‘a’ append mode using open( ) method
f=open(‘[Link]’,’w’,newline=’ ’)
By setting newline='', Python don’t modify the newline characters at all. This is commonly used
when working with the csv module to ensure that the [Link] handles the newline characters
correctly (i.e., without adding extra blank lines between rows).
i. Creating a writer object, associated with the file object. The writer object allows you to write rows
of data into the file in CSV format. Through [Link]( ) method ,we create it.
w_obj=[Link](f)
ii. Perform writing operation (read data from user and write on to csv file)
writerow( ) used for writing single row
writerows( )used for writing multiple rows
3. For Reading from CSV File
i. Creating a reader object, associated with the file object we use [Link]( ) method. It Creates a CSV
reader object that can iterate over the rows of the file object.
r_obj=[Link](f)
ii. Perform reading operation (read data from csv file and display using python)
57 | P a g e
[Link] the file using close( ) method
[Link]( )
[Link]( ) The [Link]() 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.
[Link](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('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
[Link]( ) The [Link]( ) 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.
[Link](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 (,).
58 | P a g e
• It returns a writer object that lets you write rows (lists or tuples) to the CSV
file.
Common Methods:
• [Link](row) → Writes a single row.
• [Link](list_of_rows) → Writes multiple rows.
Example:
import csv
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
# Write header
[Link](['Name', 'Age', 'City'])
# Write multiple data rows
[Link]([['Alice', 23, 'Delhi'],['Bob', 30, 'Mumbai'] ])
1 2 3 4 5 6 7 8 9 10
59 | P a g e
d a a b c d True a a c
1 2 3 4 5
b c a a d
def wonCount():
f=open('[Link]','r')
62 | P a g e
csvreader=[Link] (f, delimiter=',')
head=list (csvreader)
print (head [0])
for x in head:
if x[3]=="WON":
print(x)
[Link]()
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 [Link], to store the details. The
structure of [Link] 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,
"[Link]".
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("[Link]","a")
W=[Link](F)
sport_id=int(input("Sport id:"))
competition=input("Competition:")
prize_won=input("Prize won:")
L=[sport_id,competition,prize_won]
[Link](L)
[Link]( )
def Count_Medal( ):
F=open("[Link]","r")
L=list([Link](F))
for D in L:
if D[2]=="Gold":
print("Competition:",D[1])
[Link]()
6 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 ‘[Link]’. 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("[Link]","a",newline="\n")
T_id=int(input("Enter Teacher id: "))
63 | P a g e
Tname=input("Enter Teacher name: ")
desig=input("Enter Designation: ")
rec=[T_id,Tname,desig]
csvw=[Link](fout)
[Link](rec)
[Link]()
def Search_Teacher():
fin=open("[Link]")
csvr=[Link](fin)
for record in csvr:
if record[2]=="PGT":
print(record)
[Link]()
Add_Teacher()
Search_Teacher()
7. Write a program in Python that defines and calls the following user defined functions:
(i) COURIER_ADD( ) : It takes the values from the user and adds the details to a csv file
'[Link]'. Each record consists of a list with field elements as cid, s_name, Source,
destination to store Courier ID, Sender name, Source and destination address respectively.
(ii) COURIER_SEARCH( ) : Takes the destination as the input and displays all the courier
records going to that destination
Ans import csv
def COURIER_ADD() :
f1=open("[Link]","a",newline="\n")
writ=[Link](f1)
cid=int(input("Enter the Courier id"))
s_name=input ("Enter the Sender Name")
Source=input("Enter the Source Address")
destination=input("Enter Destination Name")
detail=[cid, s_name, Source, destination]
[Link] (detail)
[Link]()
def COURIER_SEARCH():
f1=open("[Link]", "r") # ignore newline
detail=[Link](f1)
name=input("Enter the Destination Name to be searched")
for i in detail :
if i[3]==name:
print("Details of courier are: ",i)
[Link]()
64 | P a g e
DATA STRUCTURES
Concept: A specialized format for organizing, processing, and storing data in a computer so it can be accessed
and modified efficiently, so It is a way to store data in a structured way.
Need: provide a systematic way to organize, manage, and store data so it can be used effectively.
key in a database is an attribute or a set of attributes used to uniquely identify a record in a table and establish
relationships between tables.
• Built-in data structures available in Python: List, Tuple, Dictionary and Set.
• User Defined data structures in Python: Stack, Queue, Tree, Linked List etc.
65 | P a g e
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.
66 | P a g e
Stack Implementation in Python (Using List)
stack = [ ]
# Function to push element into the stack
def push( ):
element = input("Enter element to push: ")
[Link](element)
print("Element pushed to stack.")
# Function to pop element from the stack
def pop_element( ):
if not stack:
print("Stack is empty!")
else:
element = [Link]( )
print("Element popped from stack.")
# Function to display stack
def display( ):
if not stack:
print("Stack is empty!")
else:
print("Stack elements (top to bottom):")
for item in reversed(stack):
print(item)
# 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( )
67 | P a g e
elif choice == 4:
print("Exiting program...")
break
else:
print("Invalid choice! Please try again.")
70 | P a g e
If the list N contains:
[10,5,3,8,15,4]
Then the stack, EVEN should store
[10,8,4]
And the output should be
4 8 10 Stack Empty
Ans EVEN=[ ]
def pushEven(N):
for z in N :
if z%2==0 :
[Link](z)
def popEven(EVEN):
while EVEN :
print([Link]( ), end=' ')
else :
print('Stack Empty')
5. Write the definition of a user defined function PushNV(N) which accepts a list of strings in
the parameter N and pushes all strings which have no vowels present in it, into a list named
NoVowel.
Write a program in Python to input 5 Words and push them one by one into a list named
All.
The program should that use the function PushNV( ) to create a stack of words in the list
NoVowel so that it stores only those words which do not have any vowel present in it, from
the list All.
Thereafter, pop each word from the list NoVowel and display the popped word. When the
stack is empty, display the message
"EmptyStack".
For example:
If the Words accepted and pushed into the list All are
['DRY', 'LIKE', 'RHYTHM', 'WORK', 'GYM']
Then the stack NoVowel should store
['DRY', 'RHYTHM', 'GYM']
And the output should be displayed as
GYM RHYTHM DRY EmptyStack
Ans def PushNV(N):
for W in N :
flag = True
for C in W:
if [Link]() in 'AEIOU':
flag = False
break
if flag:
[Link](W)
All=[ ]
NoVowel=[ ]
71 | P a g e
for i in range(5) :
[Link](input('Enter a Word: '))
PushNV(All)
while NoVowel :
print([Link]( ), end=' ')
else :
print('EmptyStack')
6. Write the definition of a user defined function Push3_5(N) which accepts a list of integers
in a parameter N and pushes all those integers which are divisible by 3 or divisible by 5
from the list N into a list named Only3_5.
Write a program in Python to input 5 integers into a list named NUM. The program should
then use the function Push3_5( ) to create the stack of the list Only3_5. Thereafter pop each
integer from the list Only3_5 and display the popped value. When the list is empty, display
the message "StackEmpty".
For example:
If the integers input into the list NUM are :
[10,6,14,18,30]
Then the stack Only3_5 should store
[10,6,18,30]
And the output should be displayed as
30 18 6 10 StackEmpty
Ans NUM=[ ]
def Push3_5(N):
for i in N:
if i%3==0 or i%5==0:
Only3_5.append(i)
Only3_5=[ ]
for i in range(5):
[Link](int(input('Enter an Integer: ')))
Push3_5(NUM)
while Only3_5:
print (Only3_5.pop( ), end=' ')
else:
print('StackEmpty')
7. A list contains following record of customer :
[Customer_name, Room Type]
Write the following user defined functions to perform given operations on the stack
named 'Hotel' :
(i) Push_Cust( ) – To Push customers’ names of those customers who are staying in ‘Delux’
Room Type.
72 | P a g e
(ii) Pop_Cust( ) – To Pop the names of customers from the stack and display them. Also,
display “Underflow” when there are no customers in the stack.
For example :
If the lists with customer details are as follows :
["Siddarth", "Delux"]
["Rahul", "Standard"]
["Jerry", "Delux"]
The stack should contain
Jerry
Siddharth
The output should be:
Jerry
Siddharth
Underflow
Ans Hotel=[ ]
Customer=[["Siddarth", "Delux"],["Rahul", "Standard"], ["Jerry", "Delux"]]
def Push_Cust( ):
for rec in Customer:
if rec[1]=="Delux":
[Link](rec[0])
def Pop_Cust( ):
while len(Hotel)>0:
print([Link]( ))
else:
print("Underflow")
8. Write a function in Python, Push (Vehicle) where, Vehicle is a dictionary containing details
of vehicles – {Car_Name: Maker}.
The function should push the name of car manufactured by ‘TATA’ (including all the
possible cases like Tata, TaTa, etc.) to the stack.
For example:
If the dictionary contains the following data :
Vehicle={"Santro":"Hyundai","Nexon":"TATA","Safari":"Tata"}
The stack should contain
Safari
Nexon
Ans stack=[ ]
def Push(Vehicle) :
for v_name in Vehicle:
if Vehicle [v_name]. upper( ) == "TATA" :
[Link](v_name)
73 | P a g e
UNIT 2
COMPUTER NETWORKS
Concept Map:
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: [Link]
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.
75 | P a g e
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:
76 | P a g e
NETWORK DEVICES
NETWORKING TOPOLOGIES
77 | P a g e
78 | P a g e
79 | P a g e
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.
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
[Link] [Link]
[Link] [Link]
80 | P a g e
The process of converting a hostname (such as [Link]) into the corresponding IP address
(such as [Link]) 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:
The URL consists of four basic parts, namely, protocol, hostname, folder name and the filename. Each
one of these has a specific function.
1) The “protocol” indicates the type of Protocol (http/https/ftp etc.) being used. The protocol is
always followed by “://” and the host name.
2) The host name/domain name is the Internet address of a remote computer on which the files
reside.
3) The folder name indicates the name of the directory in which the files are located.
4) The filename specifies the name of the specific document to be displayed in the browser. The
filename itself consists of two pieces of information, the name of the file to be displayed and the
file extension, which specifies the file type (.htm for HTML file, .txt for a text file, .bmp for a bitmap
image, etc.)
The structure of a URL can be represented as follows:
Websites: A website is a collection of linked web pages (plus their associated resources) that share a
unique domain name.
Web page: Web page is an electronic document designed using HTM linked with hyperlinks.
Web Browser: Web browser is software program to navigate the web pages on the internet. E.g., Google
Chrome, Mozilla Firefox, Internet Explorer, Safari, Opera etc.
Cookie: A cookie is a small text file that stores information stored on your computer. Cookies often store
your settings for a website, such as your preferred language or location, pages visited.
Web Server: A web server is a computer or a group of computers hosting one or more websites. E.g.,
Apache, IIS etc.
Web Hosting: Web hosting is the process of uploading/saving the web content on a web server to make
it available on WWW.
81 | P a g e
Multiple Choice Questions
1 What are the three common types of computer networks?
a. ROM, MAN, LAN b. RAM, WAN, LAN
c. MAN, LAN, WAN d. None of the above
2 What is the Full form of LAN?
a. Local Area Network b. Local Access Network
c. Line And Networking d. Line-less Networking
3 Define what a LAN is?
a. Connected devices share the resources of a single processor or server within a small
geographic area
b. Normally find within a business and school
c. These are computers that share resources over a large area
d. None of the above
4 Mr. John is a small businessman who runs Hardware store. He has been experiencing problems
with his small accounting department, which he depends on to provide sales reports. Mr. John
wants to share information between his 7 computer stations and have one central printing
area. What type of network would you recommend to Mr. John?
a. MAN b. LAN c. WAN d. SAN
5 WAN covers a larger geographical area than MAN?
a. True b. False
6 A network that consists of both LANs and MANs is called a Wide area network?
a. True b. False
7 Arrange the Following Types of Networks according to their size, from largest to smallest?
a. LAN, WAN, MAN b. WAN, LAN, MAN
c. MAN, LAN, WAN d. WAN, MAN, LAN
8 You are a member of a club that deals with computer networks. The club has to take a project
to build a MAN. Where would this project likely take place?
a. A small building/organization b. University or college
c. Home d. None of the above
9 What is the full form of MAN ?
a. Magnetic Access Network b. Metropolitan Area Network
c. Multi-Area Network d. Multi-Access net
10 In your school there is a library, and you can use the internet to do research, this library will
most likely be a WAN network?
a. True b. False
11 Types of Networks are Categories by their Geographical Area cover?
a. True b. False
12 What’s a web browser?
a) A kind of spider
b) A computer that store www files
c) A person who likes to look at websites
82 | P a g e
d) A software program that allows you to access sites on the World Wide Web
13 A _____ is a document commonly written and is accessible through the internet or other network
using a browser?
a) Accounts b) Data c) Web page d) Search engine
14 Which of the following is used to read HTML code and to render Webpage?
a) Web Server b) Web Browser c) Web Matrix d) Weboni
15 Which of the following is a Web Browser?
a) MS-office b) Notepad c) Firefox d) Word 2007
16 Which of the following is not a web browser?
a) Chrome b) Microsoft Edge c) Safari d) Ubuntu
17 URL stands for
(a) Uniform Research Limited (b) Uniform Resource Locator
(c) Uniform Resource Labs (d) Uniform Research Locator
18 LinkedIn is an example for _____________________ website.
(a) E-learning (b) E-commerce
(c) Video conferencing (d) Social networking
19 Which of the following is not a web service?
(a) Distance Learning (b) E-mailing
(c) Video conferencing (d) Social networking
20 Web browsers are also called as _______________
(a) Web Servers (b) Web Clients (c) Web Hosting (d) Web Designing
21 Working of WWW based on ___________________ architecture.
(a) Peer-To-Peer architecture (b) Client-Client architecture
(c) Client-Server architecture (d) Server-Server architecture
22 ________________ is computer software capable of requesting, receiving & displaying information
in the form of webpages.
(a) Web Servers (b) Web Browser (c) Web Designers (d) Web Camera
23 ________________ is a mark-up language that helps in developing web pages.
(a) HTTP (b) HTML (c) XML (d) C++
24 ________________ is a language used to transport data over internet.
(a) HTTP (b) HTML (c) XML (d) C++
25 .___________ is a set of rules for communication between two computers over a network.
(a) Modem (b) Protocol (c) Switch (d) IP address
ANSWERS
1. c 2. a 3. a 4. b 5. a
6. a 7. d 8. b 9. b 10. b
11. a 12. d 13. c 14. b 15. c
16. d 17. b 18. d 19. a 20. b
21. c 22. b 23. b 24. a 25. b
Assertion Reason Questions
83 | P a g e
(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
1 Assertion (A): A Repeater is a device that amplifies the network over geographical distance.
Reasoning (R): A Hub is a device which is used to connect more than one device in the
network.
2 Assertion (A): VoIP stands for Voice over Internet Protocol.
Reasoning (R): VolP is a technology that allows us to make voice calls using a broadband
connection instead of a regular phone line.
3 Assertion (A): A protocol defines the set of rules that are applicable for data sharing and
communication over a network.
Reasoning (R): Local Area Network (LAN) is an example of protocol.
4 Assertion (A): A Gateway is a network device that connects dissimilar networks.
Reasoning (R): A Gateway establishes a connection between local network and external
network.
5 Assertion(A): On a computer network the users work on network nodes only.
Reason(B): A server cannot act as a network node.
Assertion Reason Answers
1 (b)Both A and R are true but R is not the correct explanation of A.
2 (a) Both A and R are true and R is the correct explanation for A
3 (c) A is True but R is False
4 (a) Both A and R are true and R is the correct explanation for A
5 (c)A is True but R is False
Very Short Answer Type Questions
1 Name the transmission media best suitable for connecting to hilly areas
2 How many pair of wires are there in twisted pair cable (Ethernet)?
3 Name a device that forwards data packets along networks.
4 What is the full form of WWW?
5 What is the full form of Internet?
6 Who invented the WWW in 1989?
7 Special software’s that is used to view webpages are ____________
8 ________ are used to store webpages, so whenever a request, it will serve the request.
9 ____________ are programs /computers used to store information’s in the form of webpages.
10 Web pages that are linked to each other via __________
11 ____________ protocol is used to transfer web pages over internet.
12 Full form of HTTP?
13 ._____________ is a massive collection of digital pages to access information over the Internet
14 Write any 2 differences between HTML & XML?
15 .___________ is a real-time communication between two or more users via computer.
84 | P a g e
16 .___________ helps us to learn anywhere using Internet.
17 .___________ allows customers to conduct financial transactions on a secure Website.
18 Internet can be used to get reservation of trains and air planes through _______ service.
19 ___________ helps to create and maintain social relationship over web.
20 Expand the following abbreviations:
a. HTTP b. XML c. HTTPS d. HTML e. VoIP
21 Name any two common web browsers.
22 Full form of email is ______________________
23 What out of the following, you will use to have an audio-visual chat with an expert sitting in
a faraway place to fix-up technical issues?
(i) E-mail (ii) VoIP (iii) FTP
ANSWERS
1 Microwave / Radio wave
2 4 pairs of twisted copper wires
3 Router
4 World Wide Web
5 Interconnected Network
6 Tim Berners-Lee
7 Web browsers
8 Web servers
9 Web server or server
10 hyperlinks
11 HTTP- HyperText Transfer Protocol
12 HyperText Transfer Protocol
13 World Wide Web(WWW) or Web
14 HTML XML
HTML stands for Hyper Text Mark-up XML stands for eXtensible Mark-
Language up Language
HTML is a case insensitive. XML is case sensitive.
Predefined tags (commands). User defined tags (commands).
It is used for transportation of the
It is used for presentation of the Data.
Data.
Small errors can be ignored. Errors not allowed.
Closing tags are optional. Compulsory to use closing tags.
15 Chat
16 E-learning
17 Internet banking
18 E-reservation
19 Social networking websites
85 | P a g e
20 HTTP- HyperText Transfer Protocol
XML – eXtensible Mark-up Language
HTTPS - HyperText Transfer Protocol Secure
HTML - HyperText Mark-up Language
VoIP-Voice over Internet Protocol
21 Google Chrome, Mozilla Firefox
22 Electronic mail
23 VoIP
Short Answer Type Questions
1 What are Protocols? Name the protocol used to transfer a file from one device to the other.
2 What is meant by an IP Address? Give an example for IP Address
3 Explain how an IP Address become helpful in investigating cyber-crimes
4 Why Protocols are needed in the case of Data Communication?
5 What is the difference between World Wide Web & Internet?
6 What is a protocol, give some examples?
7 What is the difference between E-mail and chat?
8 What are cookies?
9 What is the difference between domain name and IP address?
10 Give one suitable example of each URL and domain name?
11 Differentiate between XML and HTML.
12 Distinguish between website and web browser.
13 Differentiate between the terms Domain Name and URL in context of web services. Also write
one example of each to illustrate the difference.
14 Differentiate between communication using Optical Fiber and Ethernet Cable in context of
wired medium of communication technologies
ANSWERS
1 Protocols are set of rules that are followed while transmitting data through a computer network.
Protocols determines how to data can be moved securely from a source device to a destination
device. The protocol used for transferring a file from one device to another is the File Transfer
Protocol (FTP)
2 An IP Address is a numerical address that uniquely identifies every device connected to a network
or internet. The user’s physical location can be tracked by using an IP Address. IP V4 (IP Version
4) is a popular version of IP Address. IP Address (in IP V4) consists of four set of numbers
separated by a dot. These numbers can range from 0 to 255.
An example IP Address format is given below:
[Link]
3 IP address can be used to trace the physical location of a user connected to a network. By this
many cyber crime can be investigated and traced out efficiently tracking the exact location from
where the cybercrime is carried out.
86 | P a g e
4 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 i.e., Protocols to ensure the secure
communication of data
5 Internet means interconnected networks that spread all over the world (i.e. the physical
infrastructure), while WWW means the information’s (available in the form of webpages) that
can be accessed through internet.
6 Protocols are set of rules that are followed while transmitting data through a computer network.
Protocols determines how to data can be moved securely from a source device to a destination
device. The protocol used for transferring a file from one device to another is the File Transfer
Protocol (FTP)
7 In order to chat, you need to have an account on the same service as the person you are chatting
with. e.g. on the other hand, in case of E-mail, it is not necessary, i.e. you can have an account from
any provider and you can communicate with any email provider.
8 Cookies are temporary files stored on the user's computer by a web browser, which allow the
www server to store persistent information associated with browsing user on user’s system
9 IP addresses look like this: [Link].
Domain names look like this: “[Link]”
Domain names are easier for us to remember and use, while computers are quite handy with
numbers. Thus, we use DNS (Domain Naming System) to translate domain names into the IP
addresses.
IP address is a unique identifier for a computer or device on internet. A domain name (website
name) is a name that identifies one or more IP addresses (when hosted at different servers for
load balancing).
10 URL: [Link]
Domain name: [Link]
11 XML was designed to describe data and to focus on what data is.
HTML was designed to display data and to focus on how data looks.
HTML is about displaying information while XML is about describing information.
12 Website: - It is a collection of inter-linked web pages stored in a server.
Web Browser: - It is a software application for retrieving, presenting and traversing through
information resources in the form of web pages available on the World Wide Web
13 Domain Name URL
A domain name or website name is a URL is a string that represents the complete web
human-friendly text form of the IP address of any web page. It’s used to locate a webpage.
address.
It is the part of the URL that is more It is the string that represents a complete web address
human friendly. that contains the domain name.
Example: [Link] Example: [Link]
14 Optical Fibre - Very Fast - Expensive - Immune to electromagnetic interference
Ethernet Cable - - Slower as compared to Optical Fiber - Less Expensive as compared to Optical
Fiber - prone to electromagnetic interference.
87 | P a g e
Long Answer Type Questions
1 MyPace University is setting up its academic blocks at
Naya Raipurand is planning to set up a network. The
University has 3 academic blocks and one Human
Resource Center as shown in the diagram below: Study
the following structure and answer questions (a) to (e)
distances between Block are as follows: No. of computers in each Block is:
Law Block to business Block 40m Law Block 15
Law block to Technology Block 80m Technology Block 40
Law Block to HR Block 105m HR center 115
Business Block to technology Block 30m
Business Block to HR Block 35m Business Block 25
Technology block to HR Block 15m
a) Suggest the most suitable place (i.e., Block/Center) to install the server of this University with
a suitable reason.
b) Suggest an ideal layout for connecting these blocks/centers for a wired connectivity
c) 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?
d) Suggest the placement of a Repeater in the network with justification.
e) 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 your
answer
2 XYZNova Inc. is planning a new campus in Hyderabad while maintaining its headquarters in
Bengaluru. The campus will have four buildings: HR, Finance, IT, and Logistics. As a network
expert, you are tasked with proposing the best network solutions for their needs based on the
following: No. of computers in each Center is:
FROM TO DISTANCE HR 60
HR Finance 50 Finance 40
HR IT 175 IT 90
HR Logisic 90 Logistic 35
Finance IT 60
Finanace Logisic 70
IT Logisic 60
a) Suggest the best location for the server in the Hyderabad campus and explain your reasoning.
b) Suggest the placement of the following devices:
i) Repeater ii) Switch
c) Suggest and draw a cable layout of connections between the buildings inside the campus.
d) 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?
e) What is the use of VoIP?
88 | P a g e
OR
Which type of network (PAN, LAN, MAN, or WAN) will be formed while connecting the
Hyderabad campus to Bengaluru Headquarters?
ANSWERS:
1. a) HR center should house the server as it has maximum number of computers.
b)
LOGISTIC IT BLOCK
d) Optical Fibre BLOCK
e) Voice over Internet Protocol (VoIP) is a technology that allows users to make phone calls and
other communications over the Internet instead of a traditional phone line.
OR
WAN will be formed.
89 | P a g e
UNIT 3
DATABASE MANAGEMENT
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)
90 | P a g e
Database Management System (DBMS):
It is software which is responsible for storing, manipulating, maintaining and utilizing the databases.
Database System:
A database along with the DBMS is referred to as database system.
Eg: Oracle, MySQL Server, MySQL, Sybase, SQLite, PostgreSQL, FoxPro, SAP , dBase
91 | P a g e
Keys:
In a relation each record should be unique i.e. no two records can be identical in a database. A key
attribute identifies the record and must have unique values.
Primary Key – A primary is an attribute or set of attributes in a relation that uniquely identifies tuples
(rows) in that relation.
Candidate Key –It is an attribute or a set of attributes or keys participating for Primary Key, to uniquely
identify each tuples in that relation.
Alternate Key – A candidate key that is not the primary key is called alternate key or secondary key.
Foreign Key – Foreign keys are the attributes of a relation that points to the primary key of another
relation.
92 | P a g e
Multiple choice Questions(MCQ):
1 DBMS stands for_____________
a)Data Base Management Software b) Data Base Maintenance System
c)Data Basic Management System d) Data Base Management system
2 In RDBMS, R stands for_________
a)Relational b) Rotational c) Rational d)None of the above
3 A Database contains one or more_______
a)Data b) Tables c) Files d)Links
4 What is not true in respect of DBMS?
a)Database enforces standards b)Database increases redundancy
c)Database facilitates sharing of data d) Database helps to maintain integrity
5 Cardinality is total ___________
a)number of rows in a table b)number of columns in a table
c)number of data items in a table d) none of the above
6 Degree refers to total_________
a) number of rows in a table b) number of columns in a table
c) number of data items in a table d) none of the above
7 Data about data is _________
a) Data redundancy b) Meta Data
b) Database schema d) None of the above
8 Repetition of data is called _________
a) Data redundancy b) Data Description
c) Data inconsistency d) None of the above
9 Mismatched redundant copies of data is known as data ___________
a)Dependence b) Inconsistency c) Isolation d) Redundancy
10 A ________________is an organized collection of structured data.
a)Database b) File c) DBMS d) Information
11 A data ______________ is a set of rules that define valid data.
a)Query b) Constraint c) Dictionary d) All of the above
12 A relational database consists of a collection of ______________
a)Fields b) Records c) Keys d) Tables
13 A row in a database is called ______________
a)Fields b) Records c) Keys d) Tables
14 The term ____________ is used to refer to a field in a table.
a)Attribute b) Row c) Tuple d) Instance
15 Which of the following statements is not true about relational database?
a) Relational data model is the most widely used data model.
b) The data is arranged as a collection of tables in relational database.
c) Relational database increases data redundancy and inconsistency.
d) None of the above.
16 Which of the following is a disadvantage of file processing system?
a)Data redundancy b) Data isolation
c) Data inconsistency d) All of the above
93 | P a g e
17 Table: Employee
EMPID ENAME SALARY DEPTNO Email
1001 George 30000 10 George23@[Link]
1002 Mary 32000 12 Mary_123@[Link]
1003 Alwin 25000 12 Al_win@[Link]
1004 Sumit 20000 11 Sumit_222@[Link]
Answer the questions based on the table Employee.
a) The cardinality of the table Employee is ……
i.5 ii. 4 iii. 3 iv. 6
b) The degree of the table Employee is …….
i.3 ii. 4 iii. 5 iv. 6
c) Which column can be made as the primary key in the table Employee?
[Link] ii. EMAIL
iii. Both i and ii iv. None of the above
d) If two columns are added to the table Employee, then the cardinality and
degree of the table is …… and …… respectively.
i. 4, 7 ii. 7, 4 iii. 6,5 iv. 5,6
ANSWERS:
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 16 d
17a) (ii) 17b) (iii) 17c) (iii) 17d) (ii)
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
94 | P a g e
3 It is an attribute or a set of attributes capable of being the Primary Key, to uniquely
identify each record in that table.
SQL(Structured Query Language) is a language that is used to manage data that is held in a relational
database management system. It uses tables to manipulate and retrieve information from databases for
analysis.
By using SQL commands, one can search for any data in the database and perform other functions
like creating tables, adding records, modifying data, removing rows, dropping tables etc.
SQL Commands
• SQL commands are instructions. It is used to communicate with the database. It is also used
to perform specific tasks, functions, and queries of data.
• SQL can perform various tasks like create a table, add data to tables, drop the table, modify
the table, set permission for users.
Types of SQL Commands
• There are five types of SQL commands: DDL, DML, DCL, TCL
95 | P a g e
ALTER: This is used to alter the structure of the database.
DML (Data Manipulation Language):
The SQL commands that deal with the manipulation of data present in the database belong to DML or
Data Manipulation Language and this includes most of the SQL statements. It is the component of the
SQL statement that controls access to data and to the database. Basically, DCL statements are grouped
with DML statements.
List of DML commands:
INSERT : It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE : It is used to delete records from a database table.
98 | P a g e
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;
Note : Delete or remove all records(tuples) from the table but Structure will be remains.
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.
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.
99 | P a g e
Syntax: SELECT * FROM table_name WHERE condition;
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.
100 | P a g e
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 column 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.
Syntax:
SELECT DISTINCT (column1) FROM table_name;
101 | P a g e
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
102 | P a g e
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;
AGGREGATE (GROUP) FUNCTIONS
• Aggregate functions are the functions that operate on a set of rows to give one result per group.
• These sets of rows on which group function is applied may be the whole table or the table split
into groups.
103 | P a g e
Table: employee
count( ) function
Count ( ) has got three formats:
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
104 | P a g e
count(DISTINCT <col name>)
This function returns the number of unique, not null values in the specified column.
Example
Q: Count the number of different grades of the employee
105 | P a g e
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.
106 | P a g e
Q: To display the name of the employees and their department name.
JOINS IN MYSQL
• A join is used when data from two or more tables is required.
• Rows in one table can be joined to the rows in another table based on the common values existing
in corresponding columns of two tables.
• Joins are used to retrieve data from tables related to each other with primary- foreign key
relationships.
• There are many types of joins:
EQUI JOIN
• Specified columns from the joining tables are checked for equality.
• Values from joining tables are retrieved only if the condition in where clause is satisfied.
SYNTAX:-
SELECT <column_name (s)>
FROM <table_name1>, <table_name2>, ...., <table_nameN>
WHERE <table_name1>.<column_name> = <table_name2>.<column_name>;
Q: To display the name of the employee and their department
Note-
107 | P a g e
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;
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.
109 | P a g e
9 Assertion (A): The between operator in SQL is used to match a value with in a range of
values.
Reason(R): The between operator can only be used with numerical values in SQL.
10 Assertion (A): The LIKE operator in SQL is used to match a value with a pattern.
Reason(R): The % and _ wildcard characters can be used with the LIKE operator in SQL
ANSWERS
1 b 2 b 3 a 4 b 5 a
6 b 7 a 8 b 9 c 10 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 [Link], 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.
15 What constraint should be applied on a table column so that NULL is not allowed in that
column, but duplicate values are allowed.
16 Which command is used to open a database?
17 [Link] is working as Database Administrator .He designs the following database table
to store the information on candidates who register for examination.
110 | P a g e
Table:Candidates
112 | P a g e
Empid Firstname Lastname Address City
010 Ravi Kumar Raj nagar GZB
105 Harry Waltor Gandhi nagar GZB
152 Sam Tones 33 Elm St. Paris
215 Sarah Ackerman 440 U.S. 110 Upton
244 Manila Sengupta 24 Friends street New Delhi
300 Robert Samuel 9 Fifth Cross Washington
335 Ritu Tondon Shastri Nagar GZB
400 Rachel Lee 121 Harrison St. New York
441 Peter Thompson 11 Red Road Paris
Table: EmpSalary
Empid Salary Benefits Designation
010 75000 15000 Manager
105 65000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
441 28000 7500 salesman
Write the SQL commands for the following:
a) To show first name, last name, address and city of all employees who lives in Paris.
b) To display the details of Employees table in descending order of First name.
c) To display the first name, last name and salary of all employees from the tables
Employee and EmpSalary, who are working as Manager.
Give the Output of following SQL commands:
d) Select designation, sum(salary) from empsalary group by
designation having count(*) > 2;
OR
d) Select sum(benefits) from empsalary where designation =’clerk’;
3 Consider the following table DOCTOR given below and write the output of the SQL Queries
that follows :
D_ID D_NAME D_DEPT GENDER EXPERIENCE
101 JOSEPH ENT MALE 10
104 GUPTA MEDICINE MALE 12
106 SUMAN ORTHO FEMALE 7
111 HANEEF ENT MALE 12
123 DEEPTI CARDIOLOGY FEMALE 6
132 VEENA SKIN FEMALE 12
a)SELECT D_NAME FROM DOCTOR WHERE GENDER=MALE AND EXPERIENCE=12 ;
b)SELECT DISTINCT(D_DEPT) FROM DOCTOR ;
c)SELECT D_NAME , EXPERIENCE FROM DOCTOR ORDER BY EXPERIENCE ;
4 Consider the table PRODUCT and CLIENT given below:
113 | P a g e
PR_ID PR_NAME MANUFACTURER PRICE QTY
BS101 BATH SOAP PEARSE 45.00 25
SP210 SHAMPOO SUN SILK 320.00 10
SP235 SHAMPOO DOVE 455.00 15
BS120 BATH SOAP SANTOOR 36.00 10
TB310 TOOTH BRUSH COLGATE 48.00 15
FW422 FACE WASH DETOL 66.00 10
BS145 BATH SOAP DOVE 38.00 20
C_ID C_NAME CITY PR_ID
01 DREAM MART COCHIN BS101
02 SHOPRIX DELHI TB310
03 BIG BAZAR DELHI SP235
04 LIVE LIFE CHENNAI FW422
Write SQL Queries for the following:
i) Display the details of those clients whose city is DELHI
ii) Increase the Price of all Bath soap by 10
iii) Display the details of Products having the highest price
iv) Display the product name, price, client name and city with their corresponding
matching product Id.
5 Write SQL Commands for (a) to (e) and write the outputs for (f) on the basis of table:
FURNITURE
NO ITEM NAME TYPE DATEOFSTOCK PRICE DISCOUNT
1 White Lotus Double Bed 2002-02-23 3000 25
2 Pink feathers Baby Cot 2002-01-29 7000 20
3 Dolphin Baby Cot 2002-02-19 9500 20
4 Decent Office Table 2002-02-01 25000 30
5 Comfort zone Double Bed 2002-02-12 25000 30
6 Donald Baby cot 2002-02-24 6500 15
7 Royal Finish Office Table 2002-02-20 18000 30
8 Royal tiger Sofa 2002-02-22 31000 30
9 Econo sitting Sofa 2001-12-13 9500 25
10 Eating Paradise Dinning Table 2002-12-19 11500 25
1. To show all the information about the Baby cots from the furniture table.
2. To list the itemname which are priced at more than 15000 from the furniture table.
3. To list itemname and type of those items, in which dateofstock is after 2002-02-01 from
the furniture table in descending order of itemname
4. To display itemname and dateofstock of those items, in which the discount percentage
is more than 25 from the furniture table.
ANSWERS:
1 i)select sname, qty, price , [Link], tname
from stock, traders where [Link] = [Link];
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;
114 | P a g e
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 [Link] = [Link] where [Link] = '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, [Link], c.c_name, [Link] 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;
115 | P a g e
INTERFACE PYTHON WITH MySQL DATABASE
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 [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("CREATE TABLE FEES (ROLLNO INT, NAME VARCHAR(20), AMOUNT INT);")
116 | P a g e
b) TO SHOW THE TABLES IN MYSQL USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("SHOW TABLES")
for data in cur:
print(data)
c) TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("DESC STUDENT")
for data in cur:
print(data)
d) TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("select * from student")
r=[Link]( )
while r is not None:
print(r)
r=[Link]( )
e) TO EXECUTE SELECT QUERY WITH WHERE CLAUSE USING A PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("select * from student where marks>90")
r=[Link]( )
count=[Link]
print("total no of rows:",count)
for row in r:
print(row)
f) TO UPDATE A DATA IN A TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
[Link]( )
print([Link],"RECORD UPDATED")
g) TO DELETE A RECORD FROM THE TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("DELETE FROM STUDENT WHERE MARKS<50")
[Link]( )
print([Link],"RECORD DELETED")
117 | P a g e
h) TO DROP AN ENTIRE TABLE FROM MYSQL DATABASE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("DROP TABLE STUDENT")
i) TO ADD A COLUMN IN THE EXISTING TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("ALTER TABLE STUDENT ADD AGE NT”)
[Link]( )
j) TO DROP A COLUMN FROM THE TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("ALTER TABLE DROP AGE ”)
[Link]( )
k) TO ALTER THE DATATYPE OF A COLUMN IN A TABLE USING PYTHON INTERFACE
import [Link] as m
con =[Link](host="localhost",user="root", passwd="system", database="student")
cur=[Link]( )
[Link]("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
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)
[Link](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 "
[Link](query)
(c)
118 | P a g e
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’ "
[Link](query)
119 | P a g e
Answers
1 2 3 4 5 6 7 8 9 10 11 12
c d c c b a b c c c a c
Assertion Reasoning Questions
Each question contains Assertion (A) and Reason (R). Choose the correct option from:
a) Both A and R are true and R is the correct explanation of A.
b) Both A and R are true but 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 cursor( ) method is used to execute SQL queries in Python.
Reason (R): The cursor object allows interaction with the database.
2 Assertion (A): [Link]( ) is used to delete all records from a table.
Reason (R): fetchall( ) retrieves all records returned by a SELECT query.
3 Assertion (A): [Link]( ) requires parameters like host, user, password,
and database to connect successfully.
Reason (R): [Link]( ) 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.
6 Assertion (A): fetchone( ) returns all rows from a query result.
Reason (R): fetchone( ) returns only a single record from the result set.
7 Assertion (A): The execute( ) method can only be used with SELECT queries.
Reason (R): execute( ) is a method of the cursor object used to run SQL commands.
8 Assertion (A): Without calling commit( ), changes made by an INSERT query might not be
saved in the database.
Reason (R): commit( ) finalizes the transaction and writes changes to the database.
Answers
1 2 3 4 5 6 7 8
a d a d a d c a
VERY SHORT ANSWER QUESTIONS
1 Which command is use to install MySQL library in python?
2 Which method we use to establish the connection?
3 Which statement we use to access the MySQL module?
4 What is the Database Connector?
5 Which function is used to check the successful connection?
Answers
1 pip install MySQL. Connector
2 connect( ) method with connection object.
3 import [Link]
4 A database connector is a software that connects an application to any database.
120 | P a g e
5 .is_connected( ) method
122 | P a g e
[Link](“update student set marks =67 where admn_no=306”)
[Link]( )
8 import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”, database = ‘education’)
cursor=[Link]( )
[Link](“delete from student where admn_no=308 ”)
[Link]( )
9 Line1:-mysql, Line2:-connect, Line3:cursor, Line4: execute, Line5: fetchall, Line6: rowcount
10 A cursor is an object which helps to execute the query and fetch the records from the database.
import [Link] as m
mycon= [Link](host=”localhost”,user=”root”,password=”tiger”, database = ‘education’)
mycursor=[Link]( )
[Link]("MySQL Command")
[Link]( )
11 fetchone( )
• Returns: A single row from the result set as a tuple (or None if no more rows).
fetchmany(size)
• Returns: A list of up to size rows, each as a tuple.
fetchall( )
• Returns: A list of all remaining rows as tuples in the result set.
126 | P a g e
CBSE QUESTION PAPER 2025-26
Computer Science (083)
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.
Q. No. SECTION-A (21 x 1 = 21 Marks) Marks
1 State True or False : 1
In Python, data type of 74 is same as the data type of 74.0.
2 Identify the output of the following code snippet : 1
s = "the Truth"
print([Link]())
(A) The truth (B) THE TRUTH
(C) The Truth (D) the Truth
3 Which of the following expressions in Python evaluates to True ? 1
(A) 2>3 and 2<3 (B) 3>1 and 2
(C) 3>1 and 3>2 (D) 3>1 and 3<2
4 What is the output of the following code snippet ? 1
s='War and Peace by Leo Tolstoy'
print([Link]("by"))
127 | P a g e
6 What will be the output of the following code snippet ? 1
t = tuple('tuple')
t2 = t[2],
t += t2
print (t)
(A) ('tuple') (B) ('tuple', 'p') (C) ('t', 'u', 'p', '1', 'e', 'p') (D) ('t', 'u', 'p', '1', 'e')
7 Which of the following statements is true about dictionaries in Python ? 1
(A) A dictionary is an example of sequence datatype.
(B) A dictionary cannot have two elements with same key.
(C) A dictionary cannot have two elements with same value.
(D) The key and value of an element cannot be the same.
8 If L is a list with 6 elements, then which of the following statements will raise an 1
exception ?
(A) [Link](1) (B) [Link](6) (C) [Link](1,6) (D) [Link](6,1)
9 What will be the output of the following code ? 1
def f1(a,b=1):
print (a+b, end='-')
c=f1(1,2)
print (c, sep='*')
(A) 3-2 (B) 3-2* (C) 3-None (D) 3*None-
10 Consider the statement given below : 1
f1 = open("[Link]","____________")
Which of the following is the correct file mode to open the file in read only mode ?
(A) a (B) rb (C) r+ (D) rb+
11 State whether the following statement is True or False : 1
In Python, Logical errors can be handled using try ...... except ...... finally statement.
12 A table has two candidate keys, one of which is chosen as the primary key. 1
How many alternate keys does this table have ?
(A) 0 (B) 1 (C) 2 (D) 3
13 Which of the following SQL command can change the degree of the 1
existing relation ?
(A) DROP TABLE
(B) ALTER TABLE
(C) UPDATE ... SET
(D) DELETE
128 | P a g e
14 What will be the output of the query ? 1
SELECT MACHINE_ID, MACHINE_NAME FROM INVENTORY WHERE QUANTITY <=
100;
(A) All columns of INVENTORY table with quantity greater than 100
(B) ID and name of machines with quantity less than 100 from INVENTORY table
(C) All columns of INVENTORY table with quantity greater than or equal to 100
(D) ID and name of machines with quantity less than or equal to 100 from INVENTORY
table.
15 A relation in MySQL database consists of 2 tuples and 3 attributes. If 2 attributes are 1
deleted and 4 tuples are added, what will be the cardinality of the relation ?
(A) 4 (B) 5 (C) 6 (D) 7
16 Which aggregate function in SQL returns the smallest value from a column in a table ? 1
(A) MIN () (B) MAX() (C) SMALL () (D) LOWER ()
17 With respect to computer networks, which of the following is the correct expanded 1
form of RJ 45 ?
(A) Radio Jockey 45 (B) Registered Jockey 45
(C) Radio Jack 45 (D) Registered Jack 45
18 Which network device serves as the entry and exit point of a network, as all data 1
coming in or going out of a network must first pass through it in order to use routing
paths ?
(A) Modem (B) Gateway (C) Switch (D) Repeater
19 Expand the term XML. 1
Q.20 and Q.21 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
21 Assertion (A): The PRIMARY KEY constraint in SQL ensures that each value in the 1
column(s) is unique and cannot be NULL.
Reason (R): Candidate keys are not eligible to become a primary key.
129 | P a g e
23 Write a Python statement to perform the following tasks : (USE BUILT_IN FUNCTIONS 2
METHODS ONLY)
(i) To create a new list L1 containing the elements of list L arranged in ascending
order, without modifying list L.
(ii) A statement to check whether the given character, ch is an alphabet or a number.
24 Assuming that D1 is a dictionary in Python, 2
(i) (a) Write a Python expression to check if the key, 'RNo' is present in D1.
OR
(b) Write a Python expression to check if any key in D1 has a value 12.
(ii) (a) Write a single statement using a BUILT_IN function to add the key : value pair
'RNo' : 12, if the key 'RNo'is not present in D1. However, if the key 'RNo' is
present, the function should return its value.
OR
(b) Write a single statement to delete all the elements from D1.
25 What possible output(s) from the given options will NOT be displayed when the 2
following code is executed ? Also, mention, for how many iterations the for loop in the
given code will run ?
import random
a = [1,2,3,4,5,6]
for i in range (4) :
j = random. randrange (i, 5)
print (a[j],end='-')
print ()
Options :
(A) 3-4-5-4- (B) 2-2-4-5- (C) 4-3-3-5- (D) 5-1-2-4-
26 The function given below is written to accept a string s as a parameter and return the 2
number of vowels appearing in the string. The code has certain errors. Observe the
code carefully and rewrite it after removing all the logical and syntax errors. Underline
all the corrections made.
130 | P a g e
27 Ms. Zoya is a Production Manager in a factory which packages mineral water. She 2
decides to create a table in a database to keep track of the stock present in the factory.
Each record of the table will have the following fields :
W_Code - Code of the item (type - CHAR (5))
W_Description - Description of the item (type - VARCHAR (20))
B_Qty - Balance quantity of the item (type - INTEGER)
U Price - Unit Price of the item (type - FLOAT)
The name of the table is W_STOCK.
(i) (a) Write an SQL command to create the above table (W_Code should be the
primary key).
OR
(b) Can U_Price be the primary key of the above table? Justify your answer.
(ii) (a) Assuming that the table W_STOCK is already created, write an SQL command to
add an attribute E_Date (of DATE type) to the table.
OR
(b) Assuming that the table W_STOCK is already created, write an SQL command to
remove the column B_Qty from the table.
28 (a) List one advantage and one disadvantage of Bus topology. 2
OR
(b) What is protocol in the context of computer networks? Which protocol is used to
transmit hypertext across the web?
SECTION-C ( 3 x 3 = 9 Marks)
29 (A) Write a Python function that counts and returns the number of digits appearing in 3
the text file "Space. txt". For example, if the file contains :
Space exploration has unlocked incredible advancements in technology and science since
the first moon landing in 1969, space agencies have sent probes to Mars, Jupiter and
beyond. The ISS, orbiting Earth at about 400 km, serves as a hub for research. With
missions planned for 2030, humanity's cosmic journey continues!
Then the function should return 11.
OR
(B) Write a Python function that displays the words in which the lowercase letter ‘e’
appears at least twice in the text file ‘[Link]’. For example, if the file contains :
Space exploration has unlocked incredible advancements in technology and science since
the first moon landing in 1969, space agencies have sent probes to Mars, Jupiter and
beyond. The ISS, orbiting Earth at about 400 km, serves as a hub for research. With
missions planned for 2030, humanity's cosmic journey continues!
Then the function should display:
incredible advancements science. agencies serves research.
131 | P a g e
30 A stack named FruitStack, implemented using list, contains records of some fruits. Each 3
record is represented as a dictionary with keys 'Name', 'Origin', 'Price', and 'Expiry'. A
sample record is given here :
{ 'Name' : 'Apple', 'Origin' : 'France' , ' Price' : 120, 'Expiry' : '12-08-2025' }
(ii) pop_fruit(FruitStack): This function pops the topmost record from the stack and
returns it. If the stack is already empty, the function should display "UNDERFLOW".
(iii) display (FruitStack): This function displays all the elements of the stack starting
from the topmost element. If the stack is empty, the function should display 'EMPTY
STACK'.
OR
Write a Python program to accept 10 integers from the user. If the entered number is a
three-digit even integer, push it onto a stack. After all inputs are taken, pop all the
three-digit even integers from the stack and display them. For example, if the user
enters 12, 31, 320, 457, 6, 92, 924, 220, 1, 218, then the stack should contain :
320, 924, 220, 218
and the output of the program should be :
218 220 924 320
31 (a) Write the output of the following code : 3
def Exam2026 (given) :
new=[]
for ch in given[1 :- 1] :
if [Link]():
[Link] ()
elif ch not in new:
new. append (ch)
elif ch in new:
[Link] ()
print (new)
Exam2026 ("Gold-24Medals")
OR
(b) Write the output of the following code :
def Exam2026 (given) :
new = 0
132 | P a g e
while given:
if new % 2:
new += given % 10
else:
new += given % 5
print(new, end='-')
given //= 10
Exam2026 (123456)
SECTION-D ( 4 x 4 = 16 Marks)
32 Abhishek has created a table, named STOCK, with a set of records to maintain the data 4
of packaged milk in his shop. After creating the table, he entered the data and the table
looked as follows -
(a) Based on the data given above, write the SQL queries for the following tasks :
(i) To display Type and the maximum Price for each Type of milk.
(ii) For each record, increase the Price by 0.5 where Type is 'F'.
(iii) To display the total value of the stock (total of Qty x Price).
(iv) To display the details of all records where Code starts with 'A'.
OR
(b) Considering the table STOCK as given above, write the output on execution of the
following queries :
(i) SELECT Volume, Qty, Price FROM STOCK WHERE Type IN ('F', 'D');
(ii) SELECT Code, Qty FROM STOCK WHERE Price BETWEEN 30 AND 50;
(iii) SELECT DISTINCT Type FROM STOCK;
(iv) SELECT Volume, count (*) FROM STOCK GROUP BY Volume;
133 | P a g e
33 A csv file "States. csv" contains some data about all the states of India. 4
Each record of the file contains the following data :
- Name of the State
- Capital of the State
- Population of the State
- Official Language of the State
For example, a sample record in the file is :
['Andhra Pradesh', 'Amaravati ', 52221000, 'Telugu']
Write a Python program which reads the data from this file and appends all those
records where population is more than 10000000 into another csv file 'More. csv'.
Note : "[Link]" also contains the Header row. The Header row should NOT be
copied to "More. csv".
34 Assume that you are the Manager of the Loans department of a Finance House. To keep 4
track of the loans you have created two tables : CUSTOMERS and LOANS. The sample
data in these tables is given below :
Note : The tables may contain more records than shown here.
The management of the Finance House needs certain reports from you.
Write the queries to extract the following data to create the reports :
(i) Number of records from LOANS table where Rate of Interest (RoI) is above
7.0.
(ii) Names of the customers whose loan amount (L_Amt) is above 1000000.
(iii) C_ID, C_Name and Terms of all those records where Loan Date (L_Date) is
after 31st December, 2024.
(iv) (a) Details of all the loans in the descending order of RoI.
OR
(b) C_ID and average term for each C_ID from the LOANS table.
134 | P a g e
35 Peter has created a table named Account in MySQL database, SCHOOL, having 4
following structure :
Stud_id - integer
Sname - string
Class - string
Fees - float
Help him in writing a Python program to display records of those students whose fees
is less than 5000.
Note the following to establish connectivity between Python and MySQL :
- Username - admin
- Password - root
- Host – localhost
SECTION-E (2 X 5 = 10 Marks)
36 NextStep is an organization which has a pool of resource persons to conduct training 5
workshops on various topics related to ICT. The data of all its Resource Persons is
stored in a binary file RESOURCES. DAT using the following record structure (each
record is a tuple) : (R_ID, R_Name, R_Expertise, Charges)
where :
R_ID - Resource Person's ID (An integer)
R Name - Resource Person's Name (A string)
R Expertise - Area of expertise of the Resource Person
Charges - Charges (in rupees) per hour to conduct a workshop
For example, a record in the file is :
(12, 'P. Velusami', 'Machine Learning', 5000)
37 Sanjeevani is a big group of educational institutions with its head office in Hyderabad. 5
It is planning to set up a new University in Amritsar. The Amritsar University Campus
will have four blocks/buildings - ADMIN, ACADEMIC, HOSTEL, SPORTS.
You, as a network expert, need to suggest the best network-related solutions for them
to resolve the issues/problems mentioned in points (i) to (v), keeping in mind the
distances between various blocks / buildings and other given parameters.
135 | P a g e
Distance of Hyderabad Head Office from Amritsar University Campus =
2000 km.
Number of computers in each block is as follows :
(i) Suggest the most appropriate location of the server inside the Amritsar University
Campus. Justify your choice.
(ii)) Draw the cable layout to efficiently connect various blocks within the Amritsar
University Campus.
(iii) Name any two wired media that can be used to connect various computers of a
block inside Amritsar Campus.
(iv) For the academic purpose, the University will provide its own 24 x 7 FM channel
within the University Campus. Which communication medium, out of the following, is
used by FM ?
(A) Radio Waves
(B) Micro Waves
(C) Infrared Waves
V) (A) The students will be attending a lot of online academic sessions and workshops.
These will involve audio-visual communication. Write the full name of the
protocol which will be used for such a communication through the internet.
OR
136 | P a g e
CBSE: 2025-26
MARKING SCHEME: 2025-26
Computer Science (083)
Subject: Computer Science (Theory) Class: XII
SECTION A (21x1=21)
1. False 1
2. (A) The truth 1
3. (C) 3>1 and 3>2 (B) 3>1 and 2 1
4. (A) ('War and Peace ', 'by', ' Leo Tolstoy') 1
5. mroPo 1
6. (C) ('t', 'u', 'p', 'l', 'e', 'p') 1
7. (B) A dictionary cannot have two elements with same key. 1
8. (B) [Link](6) 1
9. (C) 3–None 1
10. (B) rb 1
11. False 1
12. (B) 1 1
13. (B) ALTER TABLE 1
14. (D) ID and name of machines with quantity less than or equal to 100 from 1
INVENTORY table.
15. (C) 6 1
16. (A) MIN() 1
17. (D) Registered Jack 45 1
18. (B) Gateway 1
19. Extensible Markup Language 1
20. (A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct 1
explanation for Assertion (A).
21. (C) Assertion (A) is true, but Reason (R) is false. 1
SECTION B (7x2=14)
22. ● Default parameters have default values whereas positional parameters are 2
assigned values to them based on their position in the function call.
● In a function header, default parameters are always written after
positional parameters(if any).
Example def Q22(X, Y=10):
23. (i) L1=sorted(L) 2
OR
L1=list(L)
[Link]()
137 | P a g e
(ii) [Link]() OR
[Link]() or [Link]()
24. (i) (a) 'RNo' in D1 2
OR
'RNo' in [Link]()
(b) 12 in [Link]()
(ii) (a) [Link]('RNo',12)
OR
if [Link]('RNo'):
print(D1['RNo']) # return D1['RNo'] else:
D1['RNo']=12
(b) [Link]() OR D1={} OR D1=dict()
25. (D) 5–1–2–4– 2
The for loop will run for 4 iterations.
26. def CountVowels(s): c=0 2
for ch in s: #Correction-1
if ch in 'aeiouAEIOU': #Correction-2
c+=1 #OR c=c+1 #Correction-3
return(c) #Correction-4
27. (i) (a) CREATE TABLE W_STOCK (W_Code CHAR(5) PRIMARY KEY, 2
W_Description VARCHAR (20), B_Qty INTEGER, U_Price FLOAT);
(b) No, U_Price cannot be the primary key because it may contain duplicate
and Null values.
ii) (a) ALTER TABLE W_STOCK ADD COLUMN E_Date DATE;
OR
ALTER TABLE W_STOCK ADD E_Date DATE;
(b) ALTER TABLE W_STOCK DROP COLUMN B_Qty;
OR
ALTER TABLE W_STOCK DROP B_Qty;
28. (a) Advantages : 2
● Cost-effective: As it requires less cable.
● Easy to install
● Easy to extend for small networks.
Disadvantages :
● Failure of the main backbone brings down the entire network.
● Fault isolation is difficult.
● Not suitable for large networks
● Data collisions are frequent when many devices are connected.
● Network speed slows down with heavy traffic.
● Security is low as all devices can access transmitted data.
(b) A protocol is a set of rules that need to be followed by the communicating devices
in order to have successful and reliable data communication. The protocol used to
transmit hypertext across the web is Hypertext Transfer Protocol (HTTP).
138 | P a g e
SECTION C (3x3=9)
29. (a) def CountDigits():
with open("[Link]",'r') as F:
Data=[Link]()
C=0
for CH in Data:
if [Link](): # OR if CH in '0123456789'
C+=1 # OR if CH >= '0' and CH <= '9'
return C
(b) def showWords():
with open("[Link]",'r') as F:
All=[Link]()
Words=[Link]()
for word in Words:
if [Link]('e')>=2:
print(word, end=' ')
30. (a)
(i) def push_fruit(FruitStack, Fruit):
if Fruit['Price']<100:
[Link](Fruit)
(ii) def pop_fruit(FruitStack):
if FruitStack==[]: # OR if len(FruitStack)==0:
print('UNDERFLOW')
else:
return [Link]()
(iii) def display(FruitStack):
if FruitStack==[]: # OR if not FruitStack: # OR if len(FruitStack)==0:
print('EMPTY STACK')
else:
for ele in FruitStack[::-1]:
print(ele)
(b) Stack=[] #Stack
for C in range(10):
Num=int(input("Integer:"))
if Num>=100 and Num<=999 and Num%2==0: #
if len(str(Num))==3 and Num%2==0:
[Link](Num)
while Stack:
print([Link](), end=' ')
31. (a) ['4', '2', '-', 'd', 'l', 'o']
(b) 1-6-10-13-15-16-
SECTION D (4x4=16)
32. (a)
(i) SELECT TYPE, MAX(PRICE) FROM STOCK GROUP BY TYPE;
(ii) UPDATE STOCK SET PRICE=PRICE+0.5 WHERE TYPE='F';
139 | P a g e
(iii) SELECT SUM(QTY*PRICE) FROM STOCK;
(iv) SELECT * FROM STOCK WHERE CODE LIKE 'A%';
(b)
(i) VOLUME QTY PRICE
0.5 300 38.00
0.5 250 36.50
1.0 50 52.00
(ii) CODE QTY
AF0.5 300
MF0.5 250
PT0.5 78
(iii) DISTINCT TYPE
F
T
D
(iv) VOLUME COUNT(*)
0.5 3
1.0 3
33. import csv
with open('[Link]') as F1 :
with open('[Link]','a',newline='') as F2: # file mode 'w' is also acceptable
R=[Link](F1)
W=[Link](F2)
RECS=list(R)
for rec in RECS[1:]:#skipping the Header row
if int(rec[2])>10000000:
[Link](rec)
34. (i) SELECT COUNT(*) FROM LOANS WHERE RoI > 7.0;
(ii) SELECT C_Name
FROM CUSTOMERS
JOIN LOANS ON CUSTOMERS.C_ID = LOANS.C_ID WHERE L_Amt
> 1000000;
(iii) SELECT L.C_ID, C_NAME, TERMS FROM CUSTOMERS C, LOANS L
WHERE C. C_ID = L.C_ID AND L_DATE > '2024-12-31';
(iv)(a) SELECT * FROM LOANS ORDER BY RoI DESC;
OR
(iv) (b) SELECT C_ID, AVG(TERMS) FROM LOANS GROUP BY C_ID;
35. import pymysql as pm # OR import [Link] as pm
DB = [Link](host='localhost',user='admin', password='root', database = 'SCHOOL'))
CUR = [Link]()
SQL = "SELECT * FROM Account WHERE Fees<5000"
[Link](SQL)
Data=[Link]( )
for D in Data:
140 | P a g e
print(D)
[Link]()
SECTION E (2x5=10)
36. (i) import pickle
def Append(): #Assuming independent tuples in file
F=open("[Link]","ab")
R_ID = int(input("Resource Person ID:"))
R_Name = input("Resource Person Name:")
R_Expertise = input("Area of Expertise:")
Charges = int(input("Hourly Charges:"))
Rec=(R_ID, R_Name, R_Expertise, Charges)
[Link] (Rec, F)
[Link]()
(iii) Twisted pair cable, Ethernet cable, Coaxial Cable, Optical Fiber Cable (any two)
(iv) (A) Radio waves
(v) (a) Voice over Internet Protocol
(b) Between Academic and Sports block because distance is more than 100m.
141 | P a g e
KENDRIYA VIDYALAYA SANGATHAN
UNSOLVED SAMPLE QUESTION PAPER-1
Subject: Computer Science (Theory) Class: XII
Time Allowed: 3:00 Hours Max. Marks - 70
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.
Q. SECTION-A (21 x 1 = 21 Marks) Mar
No. ks
142 | P a g e
(A) ValueError (B) IndexError (C) NameError (D) TypeError
6. What will be the output of the following code? 1
Bparts=['ear','nose','eye']
print('2'.join(Bparts))
143 | P a g e
13. Which SQL command can decrease cardinality of a relation? 1
14. Which aggregate function in SQL displays the number of values in the specified column 1
ignoring the NULL values?
(A) len( ) (B) count( ) (C) number( ) (D) num( )
15. In MySQL, Which type of value should not be enclosed within quotation marks? 1
(A) Date (B) Varchar (C) Float (D) Char
16. State True or False: 1
If table A has 6 rows and 3 columns, and a table B has 5 rows and 2 columns, the
Cartesian product of A and B will have 30 rows and 5 columns.
17. Which device is primarily used to amplify and regenerate signals in a network, allowing 1
data to travel longer distances?
(A) Gateway (B) Repeater (C) Router (D) Switch
18. _________ is used for point-to-point communication or unicast communication such as 1
radar and satellite.
(A) Infrared (B) Bluetooth (C) Microwaves (D)Radio waves
19. In ___________ switching technique, data is divided into chunks of packets and travels 1
through different paths and finally reach the destination.
Q.20 and Q.21 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 return statement in a Python function is optional. 1
Reason (R): If no return statement is used, the function returns None by default.
21. Assertion (A): In SQL, the GROUP BY clause is used to arrange identical data into 1
groups.
Reason (R): The GROUP BY clause is mandatory when using aggregate functions like
SUM( ) or AVG( ).
22. Write difference between mutable and immutable data types? Write name of any two 2
mutable data types.
23. i. Which operator in python has right to left associativity? 2
ii. Evaluate the following expression and write output:
>>> 5//4**3%6+2
24. Consider T=(10,20,30) and L=[60,50,40] and answer the question I and II. 2
(I) A. Write command(s) to add tuple T in list L.
144 | P a g e
OR
B. Write command to find and delete element 20 from tuple T
(II) A. Write command to add 50 in L at position 2.
OR
B. Write command to delete the variable T.
25. Look at the following python code and find the possible output(s) from the options (i) 2
to (iv) following it. Also, write the highest and lowest values that can be pointed by label
p.
import random
text = "NewYear"
p=[Link](0,2)
q=[Link](1,2)
for j in range(0, p+q):
print(text[j], end='@')
i. e@w@Y@ ii. N@
iii. N@e@w@Y@ iv. N@e@w@Y@e@
26. The code provided below is intended to check a number whether it is perfect number 2
or not. However, there are syntax and logical errors in the code. Rewrite the code in
python after removing all error(s). Underline each correction done in the code.
def Perfect_Number( ):
n=input(int("Enter a number: "))
sum=0
for i in range(1,n):
if n%i==0:
sum=+i
if N==sum:
print("Perfect number")
else:
print("Not a perfect number")
Perfect_Number( ):
27. i. A. What constraint should be applied on a table column so that NULL is not 2
allowed in that column, but duplicate values are allowed.
OR
B. Categorize the following commands as DDL and DML:
INSERT, UPDATE, ALTER, DROP
ii. A. Write the SQL command to change the size of the attribute Salary in the table
Employee to allow the maximum value of 99999.99 to be stored in it.
OR
B. Write an SQL command to change a table name from Employee to Emp.
28. Write two points of difference between XML and HTML. 2
OR
145 | P a g e
Write two points of difference between Circuit Switching and Packet switching.
SECTION-C ( 3 x 3 = 9 Marks)
29. Mr. Ashutosh has written a poem in a text file named as “[Link]”. Now he wants to 3
count number of lines which start with the character ‘W’ (including uppercase and
lowercase) in the text file “[Link]”.
Help him to write a user defined function CountLineW( ) in python to solve the
problem.
Example: If the “[Link]” contents are as follows:
A tiny ant goes marching by,
With little legs and wings to fly.
Carrying crumbs, oh so small,
Working together, one and all.
OR
Write a function CountYouMe( ) in python which reads the content of a text file
“[Link]” and counts the words ‘You’ and ‘Me’ separately. (Not case sensitive).
Example:
If the contents in “[Link]” are as follows:
146 | P a g e
Write a user defined function PUSH_DATA(Stationery_Item), to push the name of
those items into the stack named as PriceStack which have price more than 75 and
display stack. Also display the number of elements pushed into the stack.
For example: If the dictionary contains the following data:
Stationery_Item={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
The stack should contain
['Pen', 'Notebook']
The output should be:
Number of elements in stack: 2
31. Predict the output of the following code: 3
d={ }
V="programs"
for x in V:
if x in [Link]( ):
d[x]=d[x]+1
else:
d[x]=1
print(d)
OR
Predict the output of the following code:
V="interpreter"
L=list(V)
L1=""
for x in L:
if x in ['e','r']:
L1=L1+x
print(L1)
SECTION-D ( 4 x 4 = 16 Marks)
147 | P a g e
iv. Count the number of trains which have train type as superfast and source is
‘Delhi’.
OR
B) Write the output:
i. Select TNAME, Fare from TRAIN Where Fare<2000 order by TName;
ii. Select avg(fare) from TRAIN group by Train_Type;
iii. Select TName, Destination, Fare from TRAIN where fare <>2500 and destination
IS NULL;
iv. Select min(fare) from TRAIN where Train_Type= “Express”;
33. Ms. Pallavi is a python programmer working in a software company. She has to develop 4
a simple inventory management system of all books in a library. She has created a csv
file named [Link], to store the details of books. The structure of [Link]
is:
[Book_Number, Book_Name, Author, Price]
Ms. Pallavi wants to write a Program in Python that defines and calls the following user
defined functions:
i. Insert_Books( ) – To accept and add data of n number of books to a CSV file
‘[Link]’.
ii. Display( ) – To show the record of those books which have the price more than
400 in the CSV file named ‘[Link]’.
34. Ms. Nishi has been entrusted with the bank Database. She needs to access some 4
information from LOAN and BORROWER tables for a survey analysis. Help her to
extract the following information by writing the desired SQL queries as mentioned
below.
Table: LOAN
loan_number branch_name Amount
L123 Nagpur 45000
L456 Pune 60000
L347 Delhi 80000
L987 Delhi 25000
L901 Pune 45000
Table : BORROWER
customer_name loan_number
Ajit Das L456
Rohan Yadav L901
Suman Verma L123
Ayesha Tiwari L987
Saurav L347
i. To display customer name and branch name of those customers who have taken
loan from Delhi branch.
ii. To display loan number, customer name and amount of those customers who
have taken loan more than 40000.
148 | P a g e
iii. To display branch name and average amount of that branch which has given
average loan amount more than 50000.
iv. A. To display customer name and amount in descending order of amount.
OR
B. What will be degree of resultant table after performing natural join of
these two tables.
35. Consider a database named ‘DB’ containing a table named ‘Vehicle’ with the following 4
structure
Field Type
Model char(10)
Make_year Int(4)
Qty Int(3)
Price Number(8,2)
Write the following Python functions to perform the following operation as mentioned:
i. Add_Vehicle( ) - which takes input of data and store it to the table
ii. Search_vehicle( ) – which can search a model given by user and show it on
screen
* Assume the following for Python – Database connectivity:
Host: localhost, User: root, Password: work
SECTION-E (2 X 5 = 10 Marks)
36. Mr. Ashok is working on a Toy Shop project to manage toys records using Python. The 5
toys data is stored in a binary file named [Link]. The binary file
[Link] contains each record in given format:
{“Toy_ID”: T_ID, “TName”:toy_name, “Price”:price}
Where
• Toy_ID: Toy ID (string)
• TName: Toy name (string)
• Price: Price of toy (integer)
37. “MyTech Services” is planning to set up its India campus at Jaipur with its Head Office 5
at Mumbai. The Jaipur campus has 3-main blocks-HR, Technical and Marketing. You
as a network expert have to suggest the best network related solutions for their
problems raised in (i) to (v).
149 | P a g e
Jaipur Campus
HR
Technical
Head Office
Marketing
Mumbai
i. Suggest the most appropriate location of the server inside the JAIPUR campus
(out of the 3 blocks), to get the best connectivity for maximum number of
computers. Justify your answer.
ii. Which among the following devices will you suggest to be procured by the
company for connecting all the computers within each of their offices?
● Switch/Hub
● Modem
● Bridge
iii. Suggest network type (out of LAN, MAN, WAN) for connecting each of the following
set of their offices:
a. HR and Marketing Block
b. Head Office and Jaipur office
iv. Which of the following communication medium, you will suggest to be procured by
the company for connecting their local offices in Jaipur for very effective and fast
communication?
● Telephone cable
● Optical fiber
● Ethernet cable
v. A. In JAIPUR Campus, in between which offices repeater should be installed?
Justify the answer.
OR
B. Suggest and draw the cable layout to efficiently connect various blocks
within the JAIPUR campus for connecting the computers.
150 | P a g e
KENDRIYA VIDYALAYA SANGATHAN
UNSOLVED SAMPLE QUESTION PAPER-2
Subject: Computer Science (Theory) Class: XII
Time Allowed: 3:00 Hours Max. Marks - 70
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.
Q. No. SECTION-A (21 x 1 = 21 Marks) Marks
(A) The ball is in y*r court (B) The ball is in y*r c*rt
(C) The ball is in y**r c**rt (D) The ball is in your court
(A) ('cutting corner', 's', '') (B) ('cutting corner', '', '')
(C) ('cutting corner', 's') (D) ('cutting corners', '', '')
151 | P a g e
7. Which of the following operator evaluates to False if the variable on either side of 1
the operator points towards the same memory location and False otherwise?
(A) is (B) is not (C) and (D) or
11. Write the name of block / command(s) that can be used to handle the 1
error/exception in Python.
13. Which type of command is used to delete the structure of the relation? 1
(A) DDL (B) DML (C) Select (D) Cannot delete structure
15. A result set is extracted from the database using a cursor object by giving the 1
following statement:
records=[Link]( )
What will be the data type of records, after the execution of above statement?
152 | P a g e
(A) tuple (B) string (C) dictionary (D) list
16. The degree and cardinality of a table named SONG are 2 and 4, respectively. The 1
degree and cardinality of another table named SINGER are 3 and 5, respectively.
There is one common field in both tables. After performing the Cartesian product
of both tables, what will be the new degree and cardinality of the resultant table?
(A) 4 and 20 (B) 5 and 20
(C) 5 and 9 (D) 4 and 9
18. Which among the following network devices, is used to connect two dissimilar 1
networks:
(A) Modem (B) Gateway (C) Switch (D) Repeater
19. Which network device converts digital data from a computer into analog signals 1
for transmission over phone lines?
Q.20 and Q.21 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
21. Assertion (A): A Python function can return multiple values using a tuple. 1
Reason (R): In Python, when a function returns multiple values, they are
automatically packed into a tuple and returned as a single entity.
22. Define dynamic data typing in python. Write an example to illustrate your answer. 2
153 | P a g e
ii. A. To convert the string str2 in capital letters.
OR
B. To convert the first character of each word to uppercase of str1.
25. Identify the correct output(s) of the following code. Also write the minimum and 2
the maximum possible values of the variable b.
import random
a="Wisdom"
b=[Link](1,6)
for i in range(0,b,2):
print(a[i],end='#')
26. The code given below accepts N as an integer argument and returns the sum of all 2
integers from 1 to N. Observe the following code carefully and rewrite if after
removing all syntax and logical errors. Underline all the corrections made.
def Sum(N)
for I in range(N):
S=S+I
return S
print(Sum(10)
27. (I) 2
A) Benjamin a database administrator created a table with few columns. He
wants to stop duplicating the data in the table. Suggest how he can do so.
OR
B) Consider two tables student (rno, name, class) and marks (rno, mrk_obt,
percent). You as a database administrator how will your stop redundancy
of data in the table students and how the tables students and marks can be
connected with each other .
(II)
A) Write an SQL command to change the data type of a column named price
to number (10,2) in a table named stationary
OR
B) Write an SQL command to change the values of all the rows of the column
price of table stationary to Null
SECTION-C ( 3 x 3 = 9 Marks)
29. Write a function Show_Words( ) in python to read the content of a text file 3
154 | P a g e
“[Link]” and display those words in capital letters which start with any
vowel.
Example, if the file contains:
“Comparing apples to oranges”
30. A. Ms. Aarti has a stack named ToysStack that contains records of toys. Each toy 3
record is represented as a list containing toy_name, brand_name and
year_of_manufacture.
You as a python programmer help her to write the following user-defined
functions in Python to perform the specified operations on the stack ToysStack:
i. PUSH_TOY(ToysStack, new_toy): This function takes the stack ToysStack
and a new toy record new_toy as arguments and pushes the new toy record
onto the stack.
ii. POP_TOY(ToysStack): This function pops the topmost toy record from the
stack and returns it. If the stack is already empty, the function should
display "Underflow".
iii. PEAK(ToysStack): This function displays the topmost element of the stack
without deleting it. If the stack is empty, the function should display 'None'.
OR
B. Consider a list named Space which contains the terms related to space.
Write the following user defined functions in python and perform the specified
operations on a stack named MyStack.
i. Push_Term( ): It checks every term from the list Space and pushes all such
terms which have 5 or more characters into the stack, MyStack.
ii. Pop_Term( ): It pops the terms from stack, MyStack and displays them.
The function should also display “Stack is Empty” when there are no more
elements left in the stack.
155 | P a g e
k=b+a**2
print(k, end="@")
p=10
q=15
DataWork(p,q)
DataWork(b=3, a=8)
OR
Write the output of the code given below:
a =30
def call (x) :
global a
if a%2==0:
x+=a
x=5
else:
x-=a
return x
print(call(35),end="#")
print(call(40),end= "@")
SECTION-D ( 4 x 4 = 16 Marks)
156 | P a g e
ii. Select Category, avg(Quantity) from Food group by Category;
iii. Select Food_Name, Expiry_date from Food where Category= “Fruit” and
Quantity<110;
iv. Select min(Expiry_date) from Food where Category= “Vegetable”;
33. A csv file "[Link]" contains the data collected from an online 4
application form for selection of candidates for different posts, with the
following data
• Candidate Name
• Qualification
• Percent_XII
• Percent_Qualification
E.g. [‘Kartik, ‘MCA’, 80, 76]
Write the following Python functions to perform the specified operations on this
file:
a) READ( ) function which can read all the data from the file and display only
records with Percent_XII more than 75.
b) IDENTIFY( ) function which can find and print the number of such records
which are having Percent_XII not more than 75.
34. Aman has been entrusted with the management of Law University Database. He 4
needs to access some information from FACULTY and COURSES tables for a
survey analysis. Help him extract the following information by writing the desired
SQL queries as mentioned below.
Table: 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
Table: 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 complete details (from both the tables) of those Faculties whose
salary is less than 12000.
157 | P a g e
ii. To display the details of courses whose fees is in the range of 20000 to
50000 (both values included).
iii. To increase the fees of all courses by 500 which have "Computer" in their
Course names.
iv. (A) To display names (FName and LName) of faculty taking System Design.
OR
(B) To display the Cartesian Product of these two tables.
35. Mr. Sanjeev wants to create a table named SHOP in the MARKET database, which 4
should have the following structure:
SECTION-E (2 X 5 = 10 Marks)
36. Mr. Mohit is working on a school project to manage student records using Python. 5
The student data is stored in a binary file named [Link]. The binary file
[Link] contains each record in given format:
{“Admn_No”:admn, “SName”:name, “Marks”:marks}
Where
• Admn_No: Admission Number (integer)
• SName: Student Name (string)
• Marks: Marks (integer)
You as a programmer, help him to write following python functions:
i. ADD_Data( ) : To write 7 records in binary file [Link] by taking the
values for each record from user.
ii. Display_Data( ) : Read all records from binary file and display them.
iii. Modify_Marks( ) : that updates the marks of a student in the file
[Link] based on the admission number provided by the user. If the
admission number does not exist in the file, display an appropriate message.
37. “Deccan Tech Services” is planning to set up its India campus at Delhi with its Head 5
Office at Mumbai. The Delhi campus has 4-main blocks-BUSINESS, TECHNOLOGY,
158 | P a g e
LAW and HR. You as a network expert have to suggest the best network related
solutions for their problems raised in (i) to (v).
MUMBAI DELHI
LAW
CAMPUS
Head Office
TECHNOL
BUSINE
HR
159 | P a g e
suggest to be procured by the company:
a) Telephone cable
b) Twisted Pair Cable
c) Optical Fiber Cable
OR
B. Suggest the placement of the following devices with appropriate
reasons:
a) Switch / Hub
b) Repeater
160 | P a g e
KENDRIYA VIDYALAYA SANGATHAN
UNSOLVED SAMPLE QUESTION PAPER-3
Subject: Computer Science (Theory) Class: XII
Time Allowed: 3:00 Hours Max. Marks - 70
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.
Q. No. SECTION-A (21 x 1 = 21 Marks) Marks
10. What is the value of ‘p’ and how many characters will be there in the variable 1
‘data’ in the following statement
with open ("[Link]","r",encoding="utf-8") as F:
data = [Link](100)
p=[Link](10,0)
print(p)
(A) 10, 100 (B) 100, 10 (C) 10, 110 (D) 110, 10
14. Which function in SQL is used to count the total number of records regardless of 1
NULL from table in a database?
(A) sum(*) (B) total(*) (C) count(*) (D) count( )
15. Which of the following statements about the CHAR and VARCHAR datatypes in SQL 1
is False?
162 | P a g e
(A) CHAR is a fixed-length datatype, and it pads extra spaces to match the
specified length.
(B) VARCHAR is a variable-length datatype and does not pad extra spaces.
(C) The maximum length of a VARCHAR column is always less than that of a CHAR
column.
(D) CHAR is generally used for storing data of a known, fixed length.
18. Which of the following options is the correct protocol used for phone calls over the 1
internet?
(A) PPP (B) FTP (C) HTTP (D) VoIP
Q.20 and Q.21 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): We can retrieve records from more than one table in MYSQL. 1
Reason (R): Foreign key is used to establish a relationship between two tables.
21. Assertion (A): A function in Python can have any number of arguments. 1
Reasoning(R): variable length parameter can be used to deal with such number
of arguments.
22. Your Vidyalaya decided to conduct Solo singing competition. CCA in charge wants 2
to store the admission numbers of the participants. Help your CCA in charge in
choosing the correct/suitable data structure (data type) in Python for the
following.
i. To store all the admission numbers of the registered candidates. May get
changed any time till completion of registration process.
ii. To store the admission numbers of all the winners which never gets
changed.
163 | P a g e
24. If M1=[60,25,30,……] and M2=[3,6,9,12, …….], then 2
Write the Python statements for each of the following tasks using Built-in
functions/methods only:
i.
A. To delete an element 25 from the list M1.
OR
B. Write a statement to add an element 85 in the list M2 between the
elements 9 and 12.
ii.
A. Write a statement to sort the elements of list M1 in descending order.
OR
B. Write the statement to delete the last element of list M2.
25. Look at the following python code and find the possible output(s) from the options 2
(i) to (iv) following it. Also, write the highest and lowest values that can be pointed
by label VALUE.
import random
for y in range(4):
VALUE = [Link](4,11) + y
print(VALUE, "#", end=" ")
i. 6 # 7 # 12 # 13 # ii. 5 # 11 # 8 # 11 #
iii. 4 # 7 # 12 # 14 # iv. 9 # 15 # 8 # 6 #
26. The code provided below is intended to find the factorial of an integer number. 2
However, there are syntax and logical errors in the code. Rewrite the code in
python after removing all error(s). Underline each correction done in the code.
27. i. 2
A. Which SQL command is used to save changes permanent in the database
after executing data manipulation operations like INSERT, UPDATE or
DELETE?
OR
164 | P a g e
B. What constraint should be applied on an attribute in a relation so that the
values under that attribute must not have NULL value and duplicate
values?
ii.
A. Write the SQL command to list the details (all column names, data type,
size, constraint) of a table named as “MUSIC”.
OR
B. Write an SQL command to remove a primary key which is applied on the
attribute “Book_ID” of integer data type in existing table “BOOKS”.
28. Write one advantage and one disadvantage of using Optical Fiber cable. 2
OR
Expand the term PPP. What is the use of PPP?
SECTION-C ( 3 x 3 = 9 Marks)
29. Write a function Show_Words( ) in python to read the content of a text file 3
“[Link]” and display those words in capital letters which start with any
vowel.
Example, if the file contains:
“Comparing apples to oranges”
Then the function should display the output as:
APPLES
ORANGES
OR
Write a function count_my( ) in python to read the text file “[Link]” and
count the number of times the word “my” (Including uppercase and lowercase)
occurs in the file.
For example, if the file “[Link]” contains:
“This is MY website. I have displayed my preferences in the CHOICE section”
The count_my( ) function should display the output as :
The word my occurs :2 times
30. You have a stack named MovieStack that contains records of movies. Each movie 3
record is represented as a list containing movie_title, director_name, and
release_year.
Write the following user-defined functions in Python to perform the specified
operations on the stack MovieStack:
i. add_movie(MovieStack, new_movie): This function takes the stack
MovieStack and a new movie record new_movie as arguments and pushes
the new movie record onto the stack and display the stack.
ii. remove_movie(MovieStack): This function removes the topmost movie
record from the stack and returns it. If the stack is already empty, the
function should display "Underflow".
iii. view_top(MovieStack): This function displays the topmost element of the
stack without deleting it. If the stack is empty, the function should display
'None'.
OR
165 | P a g e
Stationery_Item is a dictionary containing the details of stationary items.
Write a user defined function PUSH_DATA(Stationery_Item), to push the name
of those items into the stack named as PriceStack which have price more than
75 and display stack. Also display the number of elements pushed into the stack.
OR
Write the output of the code given below:
def FindOutput(p, q=2, r=40):
x=p**2*4
y=x+r
print(x, "@", y)
return y
c=FindOutput(q=5, r=7, p=4)
a,b=4,3
c=FindOutput(b,a,c)
print(a,"@",b,"@",c)
Q. No SECTION-D (4 x 4 = 16 Marks)
166 | P a g e
A) Write the following queries:
i To display the total Quantity for each Product, excluding Products with
total Quantity less than 5.
ii To display the orders table sorted by total amount in descending order.
iii To display the distinct customer names from the Orders table.
iv Display the sum of amount of all the orders for which the quantity is null.
OR
B) Write the output:
i Select c_name, sum(quantity) as total_quantity from orders group by
c_name;
ii Select * from orders where product like '%phone%';
iii Select o_id, c_name, product, quantity, price from orders where price
between 1500 and 12000;
iv Select max(price) from orders;
34. Ms. Pooja has been entrusted with the online shopping Database. She needs to 4
access some information from CUSTOMER and ORDER tables for a survey
analysis. Help her to extract the following information by writing the desired SQL
queries as mentioned below.
Table: CUSTOMER
CUST_ID Customer_name Gender City
C011 Hemali F Pune
C025 Gaurang M Mumbai
C031 Kiran F Nagpur
C045 Payal F Pune
C050 Manish M Mumbai
Table : ORDERS
ORDER_ID Product_Name Amount CUST_ID
OD01 TV 75000 C031
OD02 Laptop 80000 C050
OD03 Mobile 25000 C011
OD04 Mobile 40000 C031
OD05 TV 30000 C045
i. To display customer name and city of those customers who have placed
order for TV.
167 | P a g e
ii. To display Customer name, Product name and amount of those orders
which have the amount more than 60000.
iii. To display Order ID, Product name and customer name of those orders
which have been placed by any male customer.
iv.
A. To display customer name, city and amount in descending order of
order amount.
OR
B. What will be cardinality of resultant table after performing cartesian
product of CUSTOMER table and ORDERS table.
35. A table, named STATIONERY, in ITEMDB database, has the following structure: 4
Field Type
itemNo int(11)
itemName varchar(15)
price float
qty int(11)
Write the following Python function to perform the specified operation:
AddAndDisplay( ) : To input details of an item and store it in the table
STATIONERY. The function should then retrieve and display all records from the
STATIONERY table where the Price is greater than 120.
Assume the following for Python-Database connectivity:
Host: localhost, User: root, Password: Pencil
Q. No
SECTION-E (2 X 5 = 10 Marks)
37. “Tech_AI Services” is planning to set up its India campus at Pune with its Head 5
Office at Delhi. The Pune campus has 3-main blocks-App Development,
Generative AI and Web Designing. You as a network expert have to suggest the
best network related solutions for their problems raised in (i) to (v).
Distance between various building blocks:
168 | P a g e
App Development to Generative AI BLOCK 90 m
App Development to Web Designing BLOCK 110 m
Generative AI to Web Designing BLOCK 40 m
Head Office to Pune Campus 1390 KM
Number of computers in each Block:
App Development BLOCK 50
Generative AI BLOCK 100
Web Designing BLOCK 60
i. Suggest the most appropriate location of the server inside the Pune campus
(out of the 3 blocks), to get the best connectivity for maximum number of
computers. Justify your answer.
ii. Suggest the placement of following devices in various blocks at Pune
campus:
a. Switch/Hub
b. Repeater
iii. What would be your recommendation for enabling live visual
communication between the Generative AI Block at Pune campus and Delhi
Head Office from the following options:
• Video Conferencing
• Telephony
• E-Mail
• Instant Messaging
iv. Which of the following communication medium, you will suggest to be
procured by the company for connecting their local offices in Pune for very
effective and fast communication?
● Telephone cable
● Optical fiber
● Ethernet cable
v.
A. What type of network (out of LAN, MAN, WAN, PAN) would be setup
among the computers within the Pune campus.
OR
B. Suggest and draw the cable layout to efficiently connect various blocks
within the Pune campus for connecting the computers.
*************END***************
169 | P a g e
REFERENCES
2. CBSE Curriculum and Guidelines for Class XII Computer Science (083)
Central Board of Secondary Education
[Link]
170 | P a g e