All in One Cs Study Material
All in One Cs Study Material
बेंगलुरु संभाग
KENDRIYA VIDYALAYA SANGATHAN
BENGALURU REGION
Session 2024-2025
के न्द्रीय विद्यालय संगठन
KENDRIYA VIDYALAYA SANGATHAN
बेंगलुरू संभाग / BENGALURU REGION
STUDY MATERIAL SESSION (2024 -25)
CLASS XII COMPUTER SCIENCE
CHIEF PATRON
PATRON
CO-ORDINATOR
SHRI B L MEENA
PRINCIPAL, KV MANDYA
CONTENT PREPARATION TEAM
14 MS. B. SHARADHA
16 MS. LAXMI P.
Interface of Python with Mysql 17 SH. AMIT KUMAR SINHA
3. Distribution of Marks:
3 Database Management 20 25 20
Total 70 110 70
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)
4 Binary File
5 CSV File
6 Data Structure
7 Computer Networks
Multiline comments: Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
Python character set:
A character set is a set of valid characters acceptable by a programming language in
scripting.
Python supports all ASCII / Unicode characters that include:
o Alphabets: All capital (A-Z) and small (a-z) alphabets.
o Digits: All digits from 0-9.
o Alphabets: All capital (A-Z) and small (a-z) alphabets.
o Special Symbols: Python supports all kinds of special symbols - " ' l ; : ! ~ @ # $
%^`&*()_+–={}[]\.
o White Spaces: White spaces like tab space, blank space, newline, and carriage
return.
o Other: All ASCII and UNICODE characters are supported by Python that
constitutes the Python character set.
Python Tokens:
A token is the smallest individual unit in a python program.
All statements and instructions in a program are built with tokens.
Token Types:
o Keywords: Keywords are reserved by python environment and cannot be used
as identifier. There are 35 keywords in python. You may try to use the following
code to get a list of keywords supported in your python version.
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
o Identifier: Identifiers are the names given to any variable, function, class, list,
methods, etc. for their identification. Python is a case-sensitive language, and it
has some rules and regulations to name an identifier. Here are the rules.
An Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an
underscore( _ ).
It can have digits but cannot start with a digit.
An identifier can’t be a keyword.
My_name, __init__, Seven10 are valid examples.
20dollers, my.var, True are invalid examples.
o Literals: Literals are the values stored in program memory and are often referred
to by an identifier.
String Literals: The text written in single, double, or triple quotes
represents the string literals in Python.
Some Interesting operations using operators that are often asked in Examinations:
Expression Output Explanation
2**3**2 512 Since ** is evaluated from
right to left, first 3**2 is
evaluated to 9 and 2**9
evaluated 512
10 or 20 10 If the first operand of an “or”
expression is true, return the
first operand. Otherwise,
evaluate and return the second
operand.
0 or 10 10 0 is False and hence second
operand is returned.
10 and 20 20 If the first operand of an
“and” expression is false,
return the first operand.
Otherwise, evaluate and return
the second operand.
Note: Any value is interpreted as “false” for the above purposes if it is 0, 0.0, None, False, or an
empty collection. Otherwise, it is interpreted as “true” for the above purposes. So, 10 and 20,
being nonzero numbers, are “true.”
25 % -4 -3 Python evaluates the
modulus with negative
numbers using the formula:
(a//b) * b + a%b == a
25//-4 gives -7 with floor
division.
-7 * -4 gives 28.
Hence a%b must be -3 to
make the expression
correctly equate to 25.
Note: The sign of the result
is always that of the divisor.
Questions:
Q.1 Which one of the following is not a valid identifier?
a) true
b) __init__
c) 20Decades
d) My_var
Q.2 Which of the following keywords is a python operator?
a) for
b) break
c) is
d) else
Q.3 What will be the output of the operation print("\\\\\\") ?
a) \\\\\\
b) \\\
c) \\
d) Error
Q.4 What will be the output of the expression print(10+20*10//2**3-5)
a) 30
b) 40
c) 1005
d) 130
Q.5 Evaluate the expression print(20%-3)?
a) -1
b) -2
c) 2
d) Error
Q.6 What will be the result of the expression True of False and not True or True
a) True
b) False
c) None
d) Error
Q.7 What will be the output of the following program?
a = {'A':10,'B':20}
b = {'B':20, 'A':10}
print(a==b and a is b)
a) True
b) False
c) None
d) Error
Q.8 Which of the following statements is false for python programming language?
a) Python is free and Open source.
b) Python is statically typed.
c) Python is portable.
d) Python is interpreted.
Flow of Control in Python
Python supports sequential flow of control.
Python supports branching flow of control using if, elif and else blocks.
Python supports iteration control using for loop and while loop.
Python if, elif and else blocks:
Python uses the relational and logical operators along with if and elif to create
conditional blocks that executes a set of python statements depending on the truth value
of the condition.
The beginning of a block starts from the next line just after the : symbol and the block is
indented.
if block
elif block
block
else block
Nested if block
block
With respect to the CBSE examination the students should thoroughly understand the construct
of if, elif, else and often a question comes where you need to identify the errors in each
program.
Q. Re-write the following program after removing errors, if any, and underline all the
corrections made.
a = input("Enter a number:")
b = int(input("Enter a number:"))
if a = b:
a+b=a
else
b=b+a
print(a,b)
Hint: There are four errors in the program
Python for loop:
Python for loop is used to iterate a set of python statements till a counter reaches its
limit.
Python for loop can also be used to iterate over a collection object (List, tuple)/ iterable
(string, dictionary) using membership operators.
Python while loop is used in situations where we have no idea as when the loop is going
to end since there are no counters.
else block in loop: The else block in a loop is executed when the break statement is not
encountered inside the loop.
Students are advised to go through the above content since various operations involving the
python data structures, user defined functions, data file handling and database interaction will
require a thorough understanding of iteration. In CBSE examination you may not get a direct
question from this topic except for a few MCQ or Assertion-Reasoning based question.
The following question is an ASSERTION AND REASONING based Questions. Mark
the correct choice as:
i) Both A and R are true, and R is the correct explanation for A
ii) Both A and R are true, and R is not the correct explanation for A
iii) A is True but R is False
iv) A is false but R is True
Q. ASSERTION: In python loop else block will be executed if the loop successfully
terminates after complete iteration.
REASON: A python loop else block will not execute if a break statement is encountered
in a loop.
Q. ASSERTION: A continue statement in a loop is mandatory.
REASON: A continue statement will skip the remaining statements in the loop after it is
encountered.
Python Strings
Python strings are a set of characters enclosed in single quotes, double quotes, or triple
quotes.
Python strings are immutable - Once a string is created, it cannot be changed. You can
create a new string with the desired modifications, but the original string remains
unchanged.
Python Strings are ordered: Strings maintain the order of characters in the sequence.
This means that the characters in a string have a definite order, and this order will not
change.
Python Strings are iterable: You can iterate over the characters in a string using loops
like for loops or comprehensions.
Characters in a String are indexable: Each character in a string can be accessed using an
index. Indexing starts from 0, so the first character of a string has an index of 0, the
second character has an index of 1, and so on.
String examples:
String operations:
Concatenation: More than one string can be joined using the (+) operator to create a
new string.
Slicing: A substring can be acquired from an existing string using the slicing
operation.
Str[start:stop:step]
Stop is not
reached.
Traversal: We can traverse a string using iteration and specifically using for loop.
o Iterate
using membership:
The start is 7
hence first two
M’s are not
included.
Python List
Ordered collection of objects - Lists maintain the order of elements as they are inserted.
Lists are mutable - Lists can be modified after creation. You can add, remove, or modify
elements freely.
Heterogenous - Lists can contain elements of different data types. For example, a list can
contain integers, strings, floats, and even other lists.
Dynamic - Lists in Python can grow or shrink in size dynamically. You can append new
elements, insert elements at specific positions, or remove elements as needed.
Indexed - Elements in a list are indexed with integers starting from 0. This allows for easy
access to individual elements using their index.
Nesting - Lists can contain other lists as elements, allowing for the creation of nested data
structures.
Built-in Methods - Python lists come with built-in methods for various operations like
sorting, reversing, searching, etc., making them versatile for a wide range of tasks.
Iterable - Lists can be used in iterations using loops (e.g., for loop)
Slicing - Lists support slicing operations, allowing you to extract sublists by specifying a
range of indices.
List Examples:
Accepting a list from User: eval() method can be used along with input() method to acquire a
list from the console.
List Operations: Like a String, python lists also support operations like Concatenation,
Replication, indexing, slicing and iteration. The only difference is that we can modify the
elements of a list using indexing, slicing and index-based iteration. In this study material we
shall see this component of python list that makes it unique mutable data structure.
Indexing of nested lists:
Changing list elements using indexing: We can change the elements of a list using indexing
and assignment operation.
Changing the list elements using slicing: We can change the replace the contents of a
list using slicing too. Given below are some interesting examples.
Changing list elements using index-based iteration: We can modify the elements of a
list using index-based iteration.
Deleting elements of a list using del command: del command may be used to delete
one or more than one element of a list either using indexing or using slicing.
methodName(list)
o List member methods: These methods have the format
listName.methodName()
clear() – Removes all the elements from a list and makes the list empty.
copy() – Creates a copy of the existing list and both list occupy different memory
locations.
pop(index) – Removes and returns the element from the given index.
remove(element): Removes the element from the given list without returning the
element. Return a ValueError is the element is not in the list.
Note: Unlike count() in String there is only one parameter to count() in list.
index(element, start) – Returns the index of the first occurrence of the given
element from the list.
If the start index is not given, the index() returns the index of first occurrence
only.
sort() – Sorts the list in ascending order. Unlike sorted() this method sorts the
same list and does not return a new list.
reverse() – Reverses the list based on value (ASCII value)
Questions:
Q.1 What will be the output of the following list operations?
data = [10,20,30,[40,50,60],[70,80]]
a) print(data[3]+data[-1])
print(data[-2][-2])
Q.2 What will be the output of the following python program:
data = [10,20,30, 60,70]
data[3:3]=[40,50]
print(data)
data.pop(3)
print(data)
data.extend([10,20])
print(len(data))
Q.3 Ganga is learning to use python Lists. Help her to get the answers of the following
operations based on the given list:
data = [10,20,30]
data[1:3]=[5,10]
print(data)
data.extend([3,4])
x =data.count(10)
print(data[x:])
data.sort()
print(data)
print(data.pop(2))
Q.4 Write a python program that accepts a list of integers from user and creates a new list
from the existing list containing all the numbers that have three or more digits.
Eg: for existing list [10,100, 99,200,1000] the new list should be [100,200,1000]
Q.5 Write a python program that accepts a list of countries from user and prints all the
countries whose number of alphabets is more than 5.
Q.6 Write a python program that accepts a list of integers from user and prints all the
integers that have 8 as the last digit.
Eg: for the list [10, 28, 8, 86, 98] the program should print 28 8 98
Q.7 For the given list
d=[10,30,20,15,45,50,80,90]
what will be the output of the following slicing operation:
d[2:7:2]
a) [20,15,45] b) [20, 45, 80] c) [30, 15, 50] d) [20, 45]
Python Dictionary
Python dictionaries are collection of key value pairs enclosed in {}
Python dictionaries are un-ordered.
Python dictionary keys are immutable (numbers, string, tuple)
Python dictionary values are mutable.
Dictionary Examples:
Dictionary Operations:
Displaying Values for a given Key: We can use dictName[key] to get the value.
sorted()
o Dictionary Member Methods: These methods are called using the syntax
dictName.methodName()
clear() – Removes all the elements from the dictionary and makes it empty.
copy() – Creates a copy of the existing dictionary.
get(key) – Returns the value for a given key.
keys() – Returns a view object containing the keys of the dictionary, that can be
converted to list using a list() method.
values() - Returns a view object containing the values of the dictionary, that can
be converted to list using a list() method.
items() - Returns a view object containing the key-value pairs as tuples of the
dictionary, that can be converted to list of tuples using a list() method.
update() – Used to add the contents of one dictionary as key-value pairs in
another dictionary.
pop(key) – Removes a key-value pair from a dictionary and returns only the
value.
popitem() – Reoves the last added key-value pair from the dictionary and returns
a tuple containing the removed key-value pair.
setdefault(key, value) – Returns the value for the key if the key is in the
dictionary, else adds the key-value pair to the dictionary.
Questions:
Q.1 Which of the following statements is False for a python dictionary?
a) Dictionary Keys can be created using another dictionary.
b) Dictionary values can be a dictionary.
c) Dictionary Values are mutable.
d) dict() function can be used to create a dictionary.
Q.2 What will be the output of the following program?
d={'A':10,'B':20,'C':30,'D':40}
del d['C']
print(d)
x = d.popitem()
print(x)
Questions 3 is an ASSERTION AND REASONING based Questions. Mark the correct
choice as:
i) Both A and R are true, and R is the correct explanation for A
ii) Both A and R are true, and R is not the correct explanation for A
iii) A is True but R is False
iv) A is false but R is True
Q.3 ASSERTION: A python dictionary remains the same even if we interchange the position
of key-value pairs.
REASONING: Dictionaries are un-ordered collection of key-value pairs.
Q.4 What will be the output of the following?
d = {"A":10, "B":20, "C":30, "A":40}
print(d)
a) {"A":10, "B":20, "C":30, "A":40}
b) {"A":40, "B":20, "C":30}
c) {"A":50, "B":20, "C":30}
d) KeyError
Q.5 Sapna wants to understand the concept of methods in a dictionary. Help her to find the
answers of the following operations on a python dictionary:
d = {'M':10, 'N':20, 'O':30, 'P':40}
r = d.popitem()
print(r)
x = d.pop('N')
print(x)
print(list(d.keys()))
d.setdefault('X',60)
print(d)
Q.6 Write a python program that increases the values by 10 for the dictionary alphabets as
keys and numbers as values where ever the key is a vowel.
Python Tuples
Python tuples are a collection of objects enclosed in ().
Python tuples are immutable.
Python tuples are ordered.
Python tuples are indexed like lists and strings.
Python tuples may contain heterogenous elements.
Python tuples can be nested.
Tuple examples:
Tuple operations: Like string and lists tuples too have concatenations, replication, indexing,
slicing and iteration operation. We are not going to discuss them here since you can follow the
list and strings to learn and practice them.
Tuple methods: Tuples have a few global methods and only two member methods.
o Global Methods – tuple(), min(), max(), len(), sum() and sorted(). We shall
discuss here only the sorted() method.
Python Functions
Python Function:- Functions is a block of code that is identified by its name. A function
can be executed by calling it. Writing the name of the function will call a function.
Functions are internally declared in a separate memory area. So a function can declare
variables with the same as declared in the outer part of the program.
Type of function :- Build in function ( all functions defined by python min() max() , lent()
etc, User-defined functions ( defined by the user )
Advantage of function :- (i) Reduces the size of the program (ii) improves reusability of
code
def keyword:- def keyword declares a user defined function followed by parameters
and terminated with a colon.
return keyword :- whenever the return keyword is executed inside a function it returns
the control back to its caller along with some value if passed explicitly. Writing return is
not compulsory and we can write as many return keywords as needed but only one return
keyword is executed.
Actual parameters :- When we call a function and pass some values to the function.
These passed values are called actual parameters.
Formal parameters :- The parameters declared in the header part of the function is
called formal parameters or the values received by the functions from its caller is called
formal parameters.
Default parameters:- It is formal parameters with the assignment of values. These
values are used if the caller does not provide value to that parameter. Remember default
parameters are written after not default parameters.
def << name of the >> (formal parameters ) : function body is always writer in
tab indentation
code hare
code here
out of scope of function. The function call can be placed after this part.
Example :-
def myfunction(a,b,c=10) : a,b and c is formal parameter and c is with default values
print(a,b,c)
return (a+b+c)
total = myfunction(10,20,30) # 10 12 and 30 are actual parameter.
Q. Write a function findbig that take 2 integers as parameters and returns the largest
value.
def findbig(a,b):
if a>b:
return a
else:
return b
x,y=5,10
bigvalue=findbig(x,y)
Practice questions:
Ans :- AlphabetDigit
Alphabet
(vi) def check(x,y):
if x != y:
return x+5
else:
return y+10
print(check(10,5)) Ans :- 15
TEXT FILE HANDLING
Key points:
Data File- A file is a sequence of bytes on the disk/permanent storage where a group of related data is
stored. File handling in Python enables us to create, update, read, and delete the files stored on the file
system through our python program.
Data File handling takes place in the following order.
1- Opening a file.
2- Performing operations (read, write) or processing data.
3- Closing the file.
Types of files in Python:
Python allows us to create and manage three types of data files.
1- Text file
2- Binary file
3- CSV file
Text file: A text file is simply a sequence of ASCII or Unicode characters.A line is a sequence of
characters, stored on permanent storage. In a text file, each line is terminated by a special character, known
as End Of Line (EOL). Text file can be created using any text editor. Ex. Myfile.txt.
Binary file: A binary file stores the data in the same way as stored in the memory. The .exe files, mp3 file,
image files, word documents are some of the examples of binary files. We can’t read a binary file using a
text editor.
CSV file: CSV (Comma Separated Values) is a file format for data storage which looks like a text file. The
information is organized with one record on each line and each field is separated by comma
CSV File (Comma-
Aspect Text File Binary File
Separated Values)
Stores tabular data in plain
Format Contains plain text Contains binary data
text
Content Human-readable Not human-readable Human-readable
Character
ASCII, UTF-8 Not applicable ASCII, UTF-8
Encoding
Data is stored as lines of Data is stored as sequences Data is organized into rows
Structure
text of binary bytes and columns
Suitable for storing textual Suitable for storing non- Ideal for storing structured
Usage
data textual data tabular data
Example File
.txt .jpg, .mp3, .exe .csv
Extensions
1. Opening a Text File
Use the open() function to open a text file.
Syntax: file_object = open("filename.txt", mode)
Replace "filename.txt" with the name of the text file and mode with the desired file open mode.
2. Text File Modes
'r': Read mode. Opens a file for reading only. Raises an error if the file does not exist.
'r+': Read and Write mode. Opens a file for both reading and writing.
'w': Write mode. Opens a file for writing only. Creates a new file if it does not exist. Truncates the
file if it exists.
'w+': Write and Read mode. Opens a file for reading and writing. Creates a new file if it does not
exist. Truncates the file if it exists.
'a': Append mode. Opens a file for appending data. Creates a new file if it does not exist.
'a+': Append and Read mode. Opens a file for appending data and reading. Creates a new file if it
does not exist.
3. Closing a Text File
Always close a file after operations to release system resources.
Use the close() method on the file object: file_object.close().
4. Opening a File Using with Clause
The with statement ensures that the file is properly closed after its suite finishes executing.
Syntax:
with open("filename.txt", mode) as file_object:
# Perform file operations
5. Writing/Appending Data to a Text File
Use the write() method to write data to a file.
The write() function will write the content in the file without adding any extra characters.
file_name.write(content)
Use the writelines() method to write a sequence of lines to a file.
file_name.writelines(sequence_of_lines)
If the file is opened in write mode ('w' or 'w+'), it will overwrite existing content.
If the file is opened in append mode ('a' or 'a+'), new data will be added to the end of the file.
6. Reading from a Text File
Use the read() method to read the entire contents of a file as a single string if value of n is not given
else it will read n characters from the current position.
File_object.read([n])
Use the readline() method to read a single line from the file.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
Use the readlines() method to read all lines from the file into a list.
7. seek() and tell() Methods
seek() method is used to position the file object at a particular position in a file. The syntax of
seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be moved.
reference_point 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
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file.
For example, the statement fileObject.seek(5,0) will position the file object at 5th byte position
from the beginning of the file.
tell() method returns the current file position. This function returns an integer that specifies the
current position of the file object in the file. The position so specified is the byte position from the
beginning of the file till the current position of the file object. The syntax of using tell() is:
file_object.tell()
Questions:
S.No. 1 Mark Questions Answers
1. What is the extension of regular text files? A
a).txt b).dat
c).ppt d) .doc
2. Which files can be opened in human readable form? B
a) binary files b) text files
c) Both a and b d)None
3. What is the default mode in which text file is opened? B
a)write b)read
c)append d)None
4. Which statement is correct for opening the file? C
a) f=open(“c:\\data.txt”,”r”)
b)f=open(r”c:\data.txt”,”r”)
c)Both a and b
d)None
5. Which of the following mode cannot be used for opening the text file? D
a)’r’ b)’w+’
c)’a’ d)’rb+’
6. Which is correct way of closing the text file? A
a)f.close() b)close(f)
c) Both a and b d)None
7. Which statement is correct to read n bytes from text file using f as file A
object?
a)f.read(n) b)f.readline(n)
c)Both a and b d)None
8. Which of the following function is used to read all the lines of the text C
file?
a)readline() b)read()
c)readlines() d)readit()
9. What is the return datatype of read () function? A
a)string b)List
c)Tuple d)Dictionary
10. What is the return datatype of readlines() function? B
a)string b)List
c)Tuple d)Dictionary
11. Which function is used to write group of characters on to the text file? B
a)writegroup() b)write()
c)writechar() d)writeall()
12. Which function is used to write List of strings on to the text file? C
a)writelist() b)writeline()
c)writelines() d)writeall()
13. In which mode text file should be opened to add the data at the end to the C
text file?
a)’r’ b)’w’
c)’a’ d)’b’
14. Which of the following command can be used to open the text file in C
writing as well as reading mode?
a)f=open(“c:\data.txt”,’r’) b)f=open(“c:\data.txt”,’w+’)
c)f=open(c:\\data.txt”,’w+) d) f=open(“c:\\data.txt”,’w’)
15. hich of the following statements is true regarding the opening modes of a A
file?
a) While opening a file for reading, if the file does not exist, an error
occurs.
b) While opening a file for writing ,if the file does not exist, an error
occurs.
c) While opening a file for reading, if the file does not exist, a new file is
created.
d) None of the above.
16. State True or False True
“csv files are special text files”
17. State True or False True
“text files are slower in processing as they requires translation of special
characters”
18. Assertion(A): File opened in’ w’ mode always places the cursor at the A
beginning of the file and never generates an error.
Reason(R): ‘w’ mode creates the file even if the file doesn’t exist.
The readline() function read a single line. If n is specified , read n bytes from the file.
e.g. p=f.readline() # read single line
p=f.readline(7) # read 7 bytes from the file
2. What is the difference between readlines() and readline() function used with the text file?
Ans The function readlines() read all the lines of the text file and store them as elements of the
List.
e.g. s= f.readlines() # all lines of text file will be read and store in list s
The function readline() will read a single line from the text file and if n is specified as the
argument, read n bytes from the file.
e.g. p=f.readline() # read single line
p=f.readline(7) # read 7 bytes from the file
3. Name the functions used to write data on the text files. Explain
Ans The two functions write() and writelines() are used to write data on the text files.
a)write()- This function writes a group of characters on to the text file.
e.g. s=”Computer Science”
f.write(s) # It will write string s to the file using file object f
4. What is the difference between ‘w’ and ‘a’ mode used while opening a text file?
Ans When ‘w’ mode is used while opening the text file , it opens the file in write mode and
places the cursor at the beginning of the file and truncates the data of the file. And if file
doesn’t exist ,it creates the file.
Whereas when ‘a’ mode is used while opening the file, it opens the file in append mode and
places the cursor at the end of the file for adding the data at the end. Here also file is created
, if file doesn’t exist.
5. What is the difference between ‘r+’ mode and ‘w+’ mode used while opening the text file?
Ans With both the modes reading and writing operations can take place, but difference is that if
file is opened using ‘w+’ mode, file is created if file doesn’t exist, whereas if file is opened
using ‘r+’ mode, error is raised if file doesn’t exist.
6. If the focus.txt file contains the following text:
Mindfulness, cognitive training, and a healthy lifestyle may help sharpen your focus.
F=open(“focus.txt”,’r’)
S=F.read(11)
print(S)
F.close()
Mindfulness
Ans
7. Find the output of the following code:
F=open(“focus.txt”,’r’)
S= F.readline()
print(S)
T=F.readline()
print(T)
F.close()
F=open(“focus.txt”,’r’)
L= F.readlines()
for a in L:
print(a.upper())
F.close()
F=open(“focus.txt”,’a+’)
S= “ sleep reduces stress hormones that can be harmful to the brain”
F.write(S)
F.seek(0) # bring cursor to the beginning of the file
L=F.readlines()
print(L)
F.close()
Ans ['Mindfulness, cognitive training, and a healthy lifestyle may help\n', 'sharpen your focus
sleep reduces stress hormones that can be harmful to the brain']
F=open(“wish.txt”, ’w’)
F.write(“Day”)
F.close()
If the file contains “Good” before execution, what will be the contents of the file after
execution of the above code.
Ans After execution, file will contain “Day” only as previous data will be truncated by write
operation over the file.
3 Marks questions
1. Write a program to read text file story.txt and count number of lines starting with
letter ‘A’ or ‘a’.
Ans F=open("story.txt",'r')
count=0
L=F.readlines()
for i in L:
if i[0]=='A' or i[0]=='a':
count=count+1
print("no. of lines starting with a=",count)
F.close()
2. Write a program to read the file data.txt and count number of uppercase, lowercase
in it.
Ans F=open("data.txt",'r')
u=0
l=0
s=F.read()
for i in s:
if i.isupper():
u=u+1
if i.islower():
l=l+1
print("Number of uppercase characters=",u)
print("Number of lowercase characters=",l)
F.close()
3. Write a program to read the file data.txt and count number of spaces in it.
Ans F=open("data.txt",'r')
space=0
s=F.read()
for i in s:
if i.isspace():
space=space+1
print("Number of spaces=",space)
F.close()
4. Write a program to read the file hash.txt and display the number characters up to
first #.
Ans F=open("hash.txt",'r')
count=0
s=F.read()
for i in s:
if i!='#':
count=count+1
else:
break
print("Number of characters up till # =",count)
F.close()
5. Write a program to read the file alphabet.txt and display all the lines in uppercase.
Ans F=open("alphabet.txt",'r')
L=F.readlines()
for i in L:
print(i.upper())
F.close()
6. Write a program to read the file data.txt and count number of lines present in it.
Ans F=open("data.txt",'r')
L=F.readlines()
print("Number of lines in the file=",len(L))
F.close()
7. Write a program to read the file data.txt and display only the digits present in it.
Ans F=open("data.txt",'r')
s=F.read()
for letter in s:
if letter.isdigit():
print(letter)
F.close()
8. Write a program to read the file story.txt and display second last line of the file.
Ans F=open("story.txt",'r')
L=F.readlines()
print(L[-2])
F.close()
9. Write a program to read the file article.txt and count occurrences of words “the” in
the file.
Ans F=open("article.txt",'r')
count=0
s=F.read()
L=s.split()
for word in L:
if word=="the":
count=count+1
print("No. of occurences of word the=",count)
F.close()
10. Write a program to read the file letter.txt and display those words which has less
than or equal to four characters.
Ans F=open("story.txt",'r')
s=F.read()
L=s.split()
for word in L:
if len(word)<=4:
print(word)
F.close()
4 Marks questions
1 Write python statements for opening the following files. Also, write the Python
statements to open the following files:
a) a text file “example.txt” in both read and write mode
b) a text file “bfile.dat” in write mode
c) a text file “try.txt” in append and read mode
d) a text file “btry.dat” in read only mode.
Set of statements (a) would read the file “practice.txt” and returns a string that
Ans contains first 10 characters of the text file.
Set of statements (b) will read the text file “practice.txt” and returns a string that
contains entire contents of the text file.
(ii) Write a command(s) to write the following lines to the text file named hello.txt.
Assume that the file is opened in append mode.
“ Welcome my class”
“It is a fun place”
“You will learn and play”
5 Marks questions
1 (i) Differentiate between Text files and Binary files.
Ans Text file: A text file is simply a sequence of ASCII or Unicode characters.A line is a
sequence of characters, stored on permanent storage. In a text file, each line is
terminated by a special character, known as End Of Line (EOL). Text file can be
created using any text editor. Ex. Myfile.txt.
Binary file: A binary file stores the data in the same way as stored in the memory.
The .exe files, mp3 file, image files, word documents are some of the examples of
binary files. We can’t read a binary file using a text editor.
(ii) Write a method COUNTWORDS() in Python to read data from text file
‘ARTICLE.TXT’ and display the count of words which ends with a vowel.
For example, if the file content is as follows:
An apple a day keeps you healthy and wise
The COUNTWORDS() function should display the output as:
Total words which ends with vowel = 4
Ans def COUNTWORDS():
fil = open('ARTICLE.TXT' , 'r')
data = fil.read()
words = data.split()
count = 0
for w in words:
if w[-1] in 'aeiouAEIOU':
count += 1
fil.close()
print('Total words which ends with vowel =',count)
2 (i) Explain seek() and tell() methods.
Ans seek() method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
For example, the statement fileObject.seek(5,0) will position the file object at 5th
byte position from the beginning of the file.
tell() method returns the current file position. This function returns an integer that
specifies the current position of the file object in the file. The position so specified
is the byte position from the beginning of the file till the current position of the file
object. The syntax of using tell() is:
file_object.tell()
(ii) Write a function COUNT() in Python to read from a text file ‘rhym.txt' and display
the count of words in each line.
Example: If the content of ‘rhym.txt’ is as follows:
Jack and jill
Went up the hill
To enjoy
Then the COUNT() function should display output as:
Line 1 : 3
Line 2 : 4
Line 3 : 2
Ans seek() method is used to position the file object at a particular position in a file.
The syntax of seek() is:
file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be
moved. reference_point 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
By default, the value of reference_point is 0, i.e. the offset is counted from the
beginning of the file.
(ii) A pre-existing text file info.txt has some text written in it. Write a python function
countvowel() that reads the contents of the file and counts the occurrence of
vowels(A,E,I,O,U) in the file.
Binary files store data in the binary format (that is, in the form of 0’s and 1’s) which is understandable by
the machine. So when we open the binary file in our machine, it decodes the data and displays it in a
human-readable format. It is important to note that the binary file contents can be displayed correctly using
only specialized applications that can read binary data. If we open any binary file using a normal text
editor like a notepad, we may see strange characters.
Examples of binary files include files stored with the extension of .dat, .doc, .docx, .mp4, etc. As you may
relate now, these files can be opened correctly using specific applications only, that are different for each
file extension. Try opening any of these binary files using notepad, and observe the magic (file opens but
with unreadable contents). In this chapter of binary file handling, we'll learn to create such files (in their
simple forms), modify its contents and display its contents properly.
Pickle Module: Python Pickle is used to serialize and deserialize a python object structure. Any object on
python can be pickled so that it can be saved on disk.
Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte stream.
To use the picking methods in a program, we have to import the pickle module using import keyword.
Example:
import pickle #don’t write pickel
In this module, we shall discuss two of its useful functions, which are:
i. dump( ) : To store/write the object data to the file.
ii. load( ) : To read the object data from a file and return the object data.
Syntax:
Write the object to the file:
pickle.dump(List_name, file-object ) #To write a list object into a binary file
Example:
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname} # create a dictionary
list.append(student) # add dictionary as element in list
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb")#open file in binary & write mode
pickle.dump(list, file) #imp: first data, then file handle
file.close( )
OUTPUT:
Enter student Roll No:1201
Enter student Name :Anil
Want to add more record(y/n) :y
Enter student Roll No:1202
Enter student Name :Sunil
Want to add more record(y/n) :n
import pickle
file = open("student.dat", "rb")
list = pickle.load(file)
print(list)
file.close( )
OUTPUT:
[{'roll': '1201', 'name': 'Anil'}, {'roll': '1202', 'name': 'Sunil'}]
import pickle
roll = input('Enter roll number whose name you want to update in binary file :')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = [ ]
for x in list:
if roll in x['roll']:
found = 1
x['name'] = input('Enter new name: ')
lst.append(x)
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('roll number does not exist')
file.close( )
OUTPUT:
Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish
Record Updated
import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close( )
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
OUTPUT:
Enter roll number that you want to search in binary file :1202
Name of student is: Harish
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )
Output:
15
seek(offset, reference_point): Change the cursor position by bytes as specified by the offset, from the
reference point.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output:
5
1 Mark Questions
1. The process of converting byte stream back to the original structure is known as
a. Picklingb. b. Unpickling c. Packing d. Zipping
5. Which of the following file mode opens a file for append or read a binary file and moves the files
pointer at the end of the file if the file already exist otherwise create a new file?
a. a b. ab c. ab+ d. a+
6. Which of the following file mode opens a file for reading and writing both as well as overwrite the
existing file if the file exists otherwise creates a new file?
a. w b. wb+ c. wb d. rwb
7. Mr Sharma is working on a binary file and wants to write data from a list to a binary file. Consider list
object as l1, binary file sharma_list.dat, and file object as f. Which of the following can be the correct
statement for him?
a. f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
b. f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c. f = open(‘sum_list’,’wb’); pickle.load(l1,f)
d. f = open(‘sum_list’,’rb’); l1=pickle.load(f)
8. Every file has its own identity associated with it. This is known as:
a. icon b. extension c. format d. file type
10. Which of the following file types allows you to store large data files in the computer memory?
a. Binary Files b. Text Files c. CSV Files d. None of these
2 Marks Questions
1. Write a program in python to write and read structure, dictionary to the binary file.
2. BINARY file is unreadable and open and close through a function only so what are the advantages of
using binary file
3. Write a statement to open a binary file name sample.dat in read mode and the file sample.dat is placed in
a folder ( name school) existing in c drive.
4. When do you think text files should be preferred over binary files?
5. Consider a binary file employee.dat containing details such as empno:ename:salary (separator ':') write a
python function to display details of those employees who are earning between 20000 and 30000(both
values inclusive)
6. Differentiate between pickle.load() and pickle.dump() methods with suitable examples.
7. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].Write a user defined
function CreateFile() to input data for a record and add to Book.dat
8. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of those
students whose percentage is above 75.
9. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price]. Write a function
CountRec(Company) in Python which accepts the Company name as parameter and count and return
number of Items by the given Company are stored in the binary file “Store.dat”.
10. A binary file “Store.dat” has structure [ItemNo, Item_Name, Company, Price]. Write a function
AddRecord() which accepts a List of the record [ItemNo, Item_Name, Company, Price] and appends in the
binary file “Store.Dat”.
3 Marks Questions
3. A binary file “STOCK.DAT” has structure [ITEMID, ITEMNAME, QUANTITY, PRICE]. Write a user
defined function MakeFile( )to input data for a record and add to Book.dat.
4. Write a function GetPrice(ITEMID) in Python which accepts the ITEMID as parameter and returns
PRICE of the Item stored in Binary file STOCK.DAT.
5. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a function
CountRec( ) in Python that would read contents of the file “EMPLOYEE.DAT” and display the details of
those Employees whose Salary is above 20000.
6. A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a function to
display number of employees having Salary more than 20000.
7. A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post, Salary], Write
a user-defined function named NewEmp() to input the details of a new employee from the user and store it
in EMP.dat.
8. Write a user-defined function named SumSalary(Post) that will accept an argument the post of
employees & read the contents of EMP.dat and calculate the SUM of salary of all employees of that Post.
9. A binary file named “TEST.dat” has some records of the structure [TestId, Subject, MaxMarks,
ScoredMarks] Write a function in Python named DisplayAvgMarks(Sub) that will accept a subject as an
argument and read the contents of TEST.dat.
10. Write a python program to search and display the record of the student from a binary file “Student.dat”
containing students records (Rollno, Name and Marks). Roll number of the student to be searched will be
entered by the user.
5 Marks Questions
1. A binary file “student.dat” has structure [rollno, name, marks].
i. Write a user defined function insertRec() to input data for a student and add to student.dat.
ii. Write a function searchRollNo(r) in Python which accepts the student’s rollno as parameter and searches
the record in the file “student.dat” and shows the details of student i.e. rollno, name and marks (if found)
otherwise shows the message as ‘No record found’.
2. Write a python program to create binary file dvd.dat and write 10 records in it:
Dvd id,dvd name,qty,price
Display those dvd details whose dvd price is more than 25.
CSV FILES
A CSV (Comma-Separated Values) file is a plain text file format used to store tabular data, where each
line represents a row, and each value within a row is separated by a comma or other delimiter.
A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to
arrange tabular data.,
CSV File operations in Python Files in the CSV format can be imported to and exported from programs
that store data in tables, such as Microsoft Excel or OpenOffice Calc. •
WHY USE CSV?
• The extensive use of social networking sites and their various associated applications requires the
handling of huge data.
But the problem arises as to how to handle and organize this large unstructured data?
• The solution to the above problem is CSV.
Thus, CSV organizes data into a structured form and, hence, the proper and systematic organization of this
large amount of data is done by CSV.
Since CSV file formats are of plain text format, it makes it very easy for website developers to create
applications that implement CSV.
• The several advantages that are offered by CSV files are as follows:
– CSV is faster to handle.
– CSV is smaller in size.
– CSV is easy to generate and import onto a spreadsheet or database.
– CSV Is human readable and easy to edit manually.
– CSV is simple to implement and parse.
– CSV is processed by almost all existing applications CSV stands for “comma separated values”.
Each line in a file is known as data/record. Each record consists of one or more fields, separated by
commas (also known as delimiters), i.e., each of the records is also a part of this file. Tabular data is stored
as text in a CSV file. The use of comma as a field separator is the source of the name for this file format. It
stores our data into a spreadsheet or a database.
CSV File operations in Python
• For working with CSV files in Python, there is an inbuilt module called CSV.
It is used to read and write tabular data in CSV format.
• To perform read and write operations with CSV file, we must import CSV module.
CSV module can handle CSV files correctly regardless of the operating system on which the files were
created.
• Along with this module, open() function is used to open a CSV file and return file object. We load the
module in the usual way using import:–
1)import csv
• Like other files (text and binary) in Python, there are two basic operations that can be carried out on a
CSV file:
– 1. Reading from a CSV file
– 2. Writing to a CSV file
2) Opening and closing of CSV File
# Open the CSV file in write mode
file = open('data.csv', 'w', newline='')
# Perform operations on the file, such as writing data
file.write("Name, Age, City\n")
file.write("Alice, 25, New York\n")
file.write("Bob, 30, San Francisco\n")
student.xls.
In student.csv (notepad) file, the first line is the header and remaining lines are the data/ records. The
fields are separated by comma. In general, the separator character is called a delimiter, and the comma is
not the only one used. Other popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters.
Every record is stored in reader object in the form of a List. We first open the CSV file in READ mode.
The file object is named f. The file object is converted to csv.reader object. The reader object is used to
read records as lists from a csv file. Iterate through all the rows using a for loop. row is nothing but a list
containing all the field values
STEPS:
1. Write a Python program that reads data from a CSV file named "inventory.csv" using the
csv.DictReader() class. The CSV file contains columns for "Product", "Quantity", and "Price".
Your program should calculate the total value of each product in inventory (quantity * price) and
print a summary report showing each product's name and total value.
2. Identify and correct the error in the following Python code that attempts to open a CSV file named
"data.csv" for writing using the csv.writer() object.
import csv
data = [['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'San Francisco']]
with open('data.csv', 'r') as file:
writer = csv.writer(file) writer.writerows(data)
3. Fill in the blanks in the following code snippet to open a CSV file named "output.csv" in write
mode and write multiple rows of data into it using the csv.writer() object. The data to be written
includes product information (name, quantity, price) stored in a list of dictionaries.
import csv
product_data = [ {'Name': 'Laptop', 'Quantity': 10, 'Price': 1200}, {'Name': 'Mouse', 'Quantity': 50, 'Price':
20}, {'Name': 'Keyboard', 'Quantity': 20, 'Price': 50} ]
with open('output.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Quantity', 'Price']
writer = csv.DictWriter(file, fieldnames=_____)
writer.writeheader()
writer.writerows(_____)
4. Write a Python program that reads data from a CSV file named "sales.csv" using the csv.reader()
object. The CSV file contains columns for "Date", "Product", and "Revenue". Your program should
calculate and print the total revenue earned for each product across all dates.
5. Write a Python program that reads data from two CSV files, "sales.csv" and "inventory.csv", using
appropriate methods like csv.reader() or csv.DictReader().
The "sales.csv" file contains columns for "Date", "Product", and "Revenue", while the
"inventory.csv" file contains columns for "Product" and "Quantity". Your program should combine
these datasets to create a new CSV file named "combined_data.csv" that includes the columns
"Date", "Product", "Revenue", and "Available Quantity". Ensure to handle missing or mismatched
data appropriately.
Case study based questions-4 marks each
1. Imagine you work for a retail company that stores its daily sales data in a CSV file named
"sales_data.csv". Develop a Python script using the csv module to read this file and generate a daily
sales report. The report should include total sales revenue, the number of items sold, and a
breakdown of sales by product category.
2. You are managing a student gradebook for a school, and the grade data is stored in a CSV file
named "gradebook.csv". Design a Python program using the csv module to read and update student
grades. Implement functionalities such as adding new grades, calculating average grades for each
subject, and generating individual progress reports.
3. In a warehouse setting, you have an inventory CSV file named "inventory.csv" containing product
details like name, quantity, and reorder level. Create a Python application using the csv module to
track inventory levels, identify low-stock items (below reorder level), and generate a restocking list
with recommended quantities.
4. A company receives customer feedback through an online survey, and the feedback data is stored in
a CSV file named "feedback_data.csv". Develop a Python script using the csv module to read and
analyze the feedback. Implement sentiment analysis to categorize feedback as positive, neutral, or
negative and generate a summary report highlighting key customer sentiments.
5. You are responsible for managing personal finances and have a CSV file named "expenses.csv"
containing daily expense records. Build a Python application using the csv module to read and
analyze the expense data. Implement functionalities such as calculating total expenses, categorizing
expenses (e.g., food, transportation), and generating a budget overview with spending trends.
ANSWERS
1.A) csv
2.B) To write data into a CSV file
3.B) 'w'
4. C) writerow()
5. B) close()
6. B) writerows()
7. D) newline=None
8. D) for loop
9. C) It ensures universal newline support.
10.D) 'x' (exclusive creation mode)
11.B) Text-based
12.D) list()
13. B) writerow()
14. C) The delimiter character separates values within a CSV file.
15. B) writerows() writes multiple rows at once, while writerow() writes one row at a time.
16.A) It requires less memory compared to other modules.
17.A) It prevents empty lines from being written.
18.C) List
19.D) DictReader() reads data as dictionaries, while reader() reads data as lists.
20. B) To ensure cross-platform compatibility for newline characters.
2 marks questions
1.The csv module in Python is used to work with CSV (Comma Separated Values) files. It provides
functions to read, write, and manipulate data in CSV format, making it easier to handle tabular data.
2.
Newline handling is crucial when working with CSV files because different operating systems use
different newline characters (such as '\n' for Unix/Linux and '\r\n' for Windows). If newline
handling is not done correctly, it can lead to issues like extra blank lines or improper row parsing.
Using newline='' in the open() function ensures universal newline support, preventing such issues.
3.
writerow(): Writes a single row of data into the CSV file.
writerows(): Writes multiple rows of data into the CSV file. It takes an iterable of rows (e.g., a list
of lists) and writes each row as a separate line in the CSV file.
4.
A CSV file is a text-based file format used to store tabular data. Each line in a CSV file represents a
row, and values within each row are separated by a delimiter character, commonly a comma (','),
although other characters like tabs or semicolons can also be used.
5.
The delimiter character is used to separate values within a CSV file. It signifies where one value
ends and the next one begins within a row. Common delimiter characters include commas (','), tabs
('\t'), semicolons (';'), and pipes ('|'). The choice of delimiter depends on the data and the
requirements of the CSV file.
6.
import csv
data = ['Name', 'Age', 'City']
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(data)
7.
import csv
try:
with open('input.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("File not found.")
except Exception as e:
print("Error:", e)
8.
import csv
import random
data = [['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'San Francisco'],
['Charlie', 28, 'Los Angeles']]
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
9
import csv
new_data = [['David', 35, 'Chicago'],
['Emma', 29, 'Houston']]
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerows(new_data)
10.
import csv
def count_rows(csv_file):
try:
with open(csv_file, 'r') as file:
reader = csv.reader(file)
row_count = sum(1 for row in reader)
return row_count
except FileNotFoundError:
return 0
except Exception as e:
print("Error:", e)
return 0
file_path = 'data.csv'
total_rows = count_rows(file_path)
print("Total rows in", file_path, ":", total_rows)
import csv
low_stock_items = []
with open('inventory.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
if int(row[1]) < 10: # Assuming quantity is in the second column
low_stock_items.append(row[0]) # Assuming item name is in the first column
print("Low stock items:", low_stock_items)
3 MARKS QUESTIONS ANSWERS
1.
import csv
low_stock_items = []
with open('inventory.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
if int(row[1]) < 10: # Assuming quantity is in the second column
low_stock_items.append(row[0]) # Assuming item name is in the first column
print("Low stock items:", low_stock_items)
2.
import csv
total_revenue = 0
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
total_revenue += float(row[2]) # Assuming Price is in the third column
print('Total revenue:', total_revenue)
3.
import csv
total_salary = 0
with open('employees.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
total_salary += int(row[2]) # Assuming Salary is in the third column
print('Total salary:', total_salary)
4.
import csv
def write_student_data(file_name):
try:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Grade']) # Write header row
while True:
name = input("Enter student name (or type 'exit' to quit): ")
if name.lower() == 'exit':
break
grade = input("Enter student grade: ")
writer.writerow([name, grade])
except Exception as e:
print("Error:", e)
write_student_data('students.csv')
5.
Delimiter characters in CSV files are used to separate individual fields (data values) within a row.
The most common delimiter character is a comma (,), but other characters like tabs (\t), semicolons
(;), and pipes (|) can also be used.
The significance of delimiter characters when working with the csv module in Python is that they
determine how data is organized and interpreted within a CSV file. When reading a CSV file,
Python uses the specified delimiter character to split each row into individual fields, making it
possible to access and process the data accordingly. Similarly, when writing data to a CSV file, the
delimiter character is used to separate different values within each row. Using the correct delimiter
ensures that the data is correctly formatted and can be read or written without errors.
6.
import csv
# Define the input and output file names
input_file = 'data.csv'
output_file = 'high_scores.csv'
# Open the input and output CSV files
with open(input_file, 'r') as file:
reader = csv.reader(file)
with open(output_file, 'w', newline='') as output_file:
writer = csv.writer(output_file # Write header row to the output file
header = next(reader)
writer.writerow(header)
# Iterate through each row in the input file
for row in reader:
# Check if the value in the second column is greater than 50
if int(row[1]) > 50: # Assuming the second column contains integers
writer.writerow(row)
7.import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(student_data)
8.Correct code:
import csv
student_data = ['Alice', 25, 'A']
with open('output.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(student_data)
output:
Total inventory cost: 500.0
9.
import csv
student_dict = {}
with open('students.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
name, age, grade = row
student_dict[name] = [int(age), grade]
print(student_dict)
10.
import csv
total_sales = 0
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
sales_amount = float(row[2]) # Assuming sales amount is in the third column
total_sales += sales_amount
print('Total sales amount:', total_sales)
5 MARKS QUESTIONS ANSWERS
1. import csv
product_values = {}
with open('inventory.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
product = row['Product']
quantity = int(row['Quantity'])
price = float(row['Price'])
total_value = quantity * price
if product in product_values:
product_values[product] += total_value
else:
product_values[product] = total_value
print("Summary Report - Total Value of Each Product:")
for product, total_value in product_values.items():
print(f"{product}: ${total_value:.2f}")
2.
import csv
data = [['Name', 'Age', 'City'], ['Alice', 25, 'New York'], ['Bob', 30, 'San Francisco']]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
3
import csv
product_data = [
{'Name': 'Laptop', 'Quantity': 10, 'Price': 1200},
{'Name': 'Mouse', 'Quantity': 50, 'Price': 20},
{'Name': 'Keyboard', 'Quantity': 20, 'Price': 50}
]
fieldnames = ['Name', 'Quantity', 'Price']
with open('output.csv', 'w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(product_data)
4.
import csv
product_revenue = {}
with open('sales.csv', 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header row
for row in reader:
product = row[1] # Assuming Product is in the second column
revenue = float(row[2]) # Assuming Revenue is in the third column
if product in product_revenue:
product_revenue[product] += revenue
else:
product_revenue[product] = revenue
print("Total Revenue Earned for Each Product:")
for product, total_revenue in product_revenue.items():
print(f"{product}: ${total_revenue:.2f}")
5.
import csv
# Read data from sales.csv
sales_data = {}
with open('sales.csv', 'r') as sales_file:
reader = csv.DictReader(sales_file)
for row in reader:
date = row['Date']
product = row['Product']
revenue = float(row['Revenue'])
if product not in sales_data:
sales_data[product] = {'Date': date, 'Revenue': revenue}
else:
sales_data[product]['Revenue'] += revenue
# Read data from inventory.csv
inventory_data = {}
with open('inventory.csv', 'r') as inventory_file:
reader = csv.DictReader(inventory_file)
for row in reader:
product = row['Product']
quantity = int(row['Quantity'])
inventory_data[product] = quantity
1. PUSH: The addition of elements is known as PUSH operation. It is done using the TOP position.
2. POP: Removal of elements is known as POP operation. Removal of object is always done from TOP
position.
3. PEEK: To show/ display the element placed at TOP position in the stack. Few applications of stack:
1. Expression evaluation
2. Backtracking (game playing, finding paths, exhaustive searching).
3. Memory management, run-time environment for nested language features.Stack implementation using
List:
1. PUSH: The addition of elements is known as PUSH operation. It is done on the TOP position.
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’]
S.append(‘newElement’) # pushing element in stack at the TOP
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’, ‘newElement’] #List after insertion
2. POP: Removal of elements is known as POP operation. It is also done using the TOP position.
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’, ‘newElement’]
S.pop() # removes element at top
S= [ ‘element1’, ‘element2’, ‘element3’, ‘element4’] #List after deletion
3. PEEK: To show/ display the element placed at TOP position in the stack.
return S[-1] # shows element at top but do not remove it from the stack.
Questions
1. Consider a list named Nums which contains random integers.
Write the following user defined functions in Python and perform the specified
operations on a stack named BigNums.
(i) PushBig(): It checks every number from the list Nums and pushes all
such numbers which have 5 or more digits into the stack, BigNums.
(ii) PopBig(): It pops the numbers from the stack, BigNums and displays
them. The function should also display “Stack Empty” when there are
no more numbers left in the stack.
For example: If the list Nums contains the following data:
Nums=[213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
Then on execution of PushBig(),the stack BigNums should store:
[10025, 254923, 1297653, 31498, 92765]
And on execution of PopBig(), the following output should be displayed:
92765
31498
1297653
254923
10025
Stack Empty
def PushBig(Nums,BigNums):
ANS for N in Nums:
if len(str(N))>=5:
BigNums.append(N)
def PopBig(BigNums):
while BigNums:
print(BigNums.pop())
else:
print(“Stack Empty”)
2. A list, NList contains following record as list elements:
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the
following user defined functions in Python to perform the
specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an
argument and pushes a list object containing name of the city and
country, which are not in India and distance is less than 3500 km
from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays
them. Also, the function should display “Stack Empty” when there
are no elements in the stack.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
ANS
def pop_cust():
if hotel==[]:
return "Underflow"
else:
return hotel.pop()
push_cust()
while True:
if hotel==[]:
print(pop_cust())
break
else:
print(pop_cust())
push(Vehicle)
for i in range(-1,-len(stk)-1,-1):
print(stk[i])
For example:
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Benefits of Network: -
(1) Resource Sharing: Resource Sharing means to make the
applications/programs, data(files) and peripherals available to anyone on the
network irrespective of the physical location of the resources and the user.
(2) Reliability: Reliability means to keep the copy of a file on two or more different
machines, so if one of them is unavailable (due to some hardware crash or any
other) them its other copy can be used.
(3) Cost Factor: Cost factor means it greatly reduces the cost since the resources can
be shared. For example a Printer or a Scanner can be shared among many
computers in an office/Lab.
(4) Communication Medium: Communication Medium means one can send and
receive messages. Whatever the changes at one end are done, can be
immediately noticed at another.
EVOLUTION OF NETWORKING
ARPANET (1969) – US Government formed an agency named ARPANET( Advanced
Research Project Agency Network) to connect computers at various universities and defence
agencies to share data/information efficiently among all of them.
NSFNET (1985) - National Science Foundation Network was a program of coordinated,
evolving projects sponsored by the National Science Foundation (NSF) from 1985 to 1995 to
promote advanced research and education networking in the United States. The program
created several nationwide backbone computer networks in support of these initiatives.
Initially created to link researchers to the NSF-funded supercomputing centers, through
further public funding and private industry partnerships it developed into a major part of
the Internet backbone.
INTERNET (1990)- INTER-connection NETwork , The worldwide network of networks.
Data communication terminologies:
Concept of communication: Communication is the act of sending and receiving data from
one device to another device or vice-versa. Data can be of any form i.e. text, image, audio,
video and multimedia files.
Components of Data communication:
Sender: A device that can send data over a network i.e. computer, laptop, smart phone etc.
Receiver: A device can receive data over a network i.e. computer, laptop, smart phone etc.
The sender and receivers are basically called nodes.
Message: It is the data/information that needs to be shared between the sender and
receiver.
Communication media: It is the medium through which the data/information is travelled
between the
sender and receiver. These may be wired or wireless.
Protocols: A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network. Essentially, it allows connected
devices to communicate with each other, regardless of any differencesin their internal
processes, structure or design.
Measuring Capacity of Communication Media: In data communication, the transmission
medium is also known as channel. The capacity of a channel is the maximum amount of signals
or traffic that a channel can carry. It is measured in terms of bandwidth and data transfer rate
as described below:
Bandwidth
Bandwidth of a channel is the range of frequencies available for transmission of data
through that channel.
Higher the bandwidth, higher the data transfer rate.
Normally, bandwidth is the difference of maximum and minimum frequency contained in the
composite signals.
Bandwidth is measured in Hertz (Hz). 1
KHz = 1000 Hz, 1 MHz =1000
Data Transfer Rate
Data travels in the form of signals over a channel. One signal carries one or more bits over the
channel. Data transfer rate is the number of bits transmitted between source and destination
in one second. It is also known as bit rate. It is measured in terms of bits per second (bps).
The higher units for data transfer rates are:
1 Kbps=1024 bps
1 Mbps=1024 Kbps
1 Gbps=1024 Mbps
IP Address:
An IP address is a unique address that identifies a device on the internet or a local network.
IP stands for "Internet Protocol," which is the set of rules governing the format of data sent
via the internet or local network.
Switching techniques:
In large networks, there may be more than one path for transmitting data from sender to
receiver. Selecting a path that data must take out of the available options is called switching.
There are two popular switching techniques – circuit switching and packet switching.
Circuit switching: Circuit switching is a type of network configuration in which a physical
path is obtained and dedicated to a single connection between two endpoints in the network
for the duration of a dedicated connection. Ordinary landline telephone service uses
circuit switching.
Packet switching: Packet switching is the method by which the internet works; it features
delivery of packets of data between devices over a shared network. For example the school
web server is sending you a webpage over the internet or you sending an email to a friend.
Transmission Media: Transmission media is a communication channel that carries the
information from the sender to the receiver. All the computers or communicating devices in
the network must be connected to each other by a Transmission Media or channel.
A Transmission medium is a medium of data transfer over a network.
The selection of Media depends on the cost, data transfer speed, bandwidth and
distance. Transmission media may be classified as
STAR Topology: -In Star topology, each node is directly connected to a central device like Hub
or Switch. It is most popular topology to form Local Area Networks (LAN).
Advantages:
(i) Easy to troubleshoot
(ii) A single node failure does not affects the entire network.
(iii) Fault detection and removal of faulty parts is easier.
(iv) In case a workstation fails, the network is not affected.
Disadvantages: -
(i) Difficult to expand.
(ii) Longer cable is required.
(iii) The cost of the hub and the longer cables makes it expensive
over others.
(iv) All nodes are dependent on central node. if the central device (Switch) goes down
then entire network breaks down.
TREE Topology: - The tree topology combines the characteristics of the linear bus and the
star topologies. It consists of groups of star – configured workstations connected to a bus
backbone cable.
Advantages:
(i) Eliminates network congestion.
(ii) The network can be easily extended.
(iii) Faulty nodes can easily be isolated from the rest of the
network.
Disadvantages:
Uses large cable length.
Requires a large amount of hardware components and
hence is expensive.
Installation and reconfiguration are very difficult.
Types of Computer Network:
A computer network may be small or big as per number of computers and other network
devices linked together. A computer network may contain devices ranging from handheld
devices (like mobile phones, tablets, laptops) connected through Wi-Fi or Bluetooth within a
single room to the millions of computers spread across the globe. Based on the size, coverage
area, data transfer speed and complexity, a computer network may be classified as:
LAN (Local Area Network): A Local Area Network (LAN) is a network that is limited to a
small area. It is generally limited to a geographic area such as within lab, school or building.
It is generally privately-owned networks over a distance up to a few kilometers. Now-a-days,
we also have WLAN (Wireless LAN) which is based on wireless network.
MAN (Metropolitan Area Network): MAN is the networks cover a group of nearby
corporate offices or a city and might be either private or public. Cable TV network or cable
based broadband internet services are examples of MAN.
WAN (Wide Area Network):These are the networks spread over large distances, say across
countries or even continents through cabling or satellite uplinks are called WAN. Typically, a
WAN combines multiple LANs that are geographically separated. It is a network of network.
The world’s most popular WAN is the Internet.
PAN (Personal Area Network): A Personal Area Network is computer network organized
around an individual person. It generally covers a range of less than 10 meters. Personal Area
Networks can be constructed with cables or wirelessly.
Network Protocols:
Overview of Internet:
Internet is a network of networks that consists of millions of private, public,
academic, business, and government networks, that are linked by various wired,
wireless, and optical networking technologies.
The Internet is a global system of interconnected computer networks that use the
standard Internet protocol suite (TCP/IP) to serve several billion users
worldwide.
The modern Internet is an extension of ARPANET (Advance Research Project
Agency Network), created in1969 by the American Department of Defense.
In 1990 the British Programmer Tim Berners-Lee developed Hypertext and HTML
to create World Wide Web (WWW).
The Internet carries an extensive range of information resources and services,
such as the inter-linked hypertext documents of the World Wide Web (WWW), the
communicational infrastructure to support mail, chat and transfer of Text, Images,
Audio, Video etc.
In the above URL, http is the protocol name, it can be https, http, FTP, Telnet, etc. www is a
sub domain. ncert.nic.in is the domain name. Textbook is directory and textbook.htm is
webpage.
The complete unique address of the page on a website is called URL (Uniform Resource
Locator) e.g. http://www.cbse.nic.in/welcome.html
Since computers on the network are identified by its IP addresses, so it is required to convert
a Domain name or URL typed in the Browser, in to its corresponding IP address. This
process is called Domain Name Resolution. This resolution is done by the designated servers
called DNS servers, provided by the Internet Service Providers (ISP) like BSNL, Airtel, Jio etc.
Website:
Website is a collection of related web pages that may contain text, images, audio
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access a
website.
A website is a collection of web pages related through hyperlinks, and saved on a
web server. A visitor can navigate pages by clicking on hyperlinks.
The main purpose of website is to make the information available to people at
large. For example, a company may advertise or sell its products, a government
organization may publish circulars, float tenders, invite applications for
recruitments etc.
A website can be accessed by providing the address of the website (URL) in the
browser. The main page of website (Home page) will be open when it is opened
on the browser.
Web Page:
A web page is a document on the WWW that is viewed in a web browser. Basic
structure of a web page is created using HTML (Hyper Text Markup Language).
To make web pages more attractive, various styling CSS (Cascading Style Sheets)
and formatting are applied on a web page.
Further, program codes called scripts also used to make webpage interactive and
define different actions and behavior. JavaScript, PHP and Python are commonly
used script language.
The first page of the website is called a home page which contains Menus and
Hyperlinks for other web pages.
A web page is usually a part of a website and may contain information in different
forms, such as: text, images, audio & video, Hyperlinks, interactive contents (chat
etc.)
A web page can be of two types: Static Web Page and Dynamic Web Page
Web Browsers:
A web browser or simply ‘browser’ is a software application used to access
information on the World Wide Web. When a user requests some information, the
web browser fetches the data from a web server and then displays the webpage
on the user’s screen.
The popular web browsers are Google Chrome, Mozilla Firefox, Internet Explorer,
Opera, Safari, Lynx and Netscape Navigator, Microsoft Edge etc.
A web browser essentially displays the HTML documents which may include text,
images, audio, video and hyperlinks that help to navigate from one web page to
another. The modern browsers allow a wide range of visual effects, use encryption
for advanced security and also have cookies that can store the browser settings
and data.
Web Server:
A web server is used to store and deliver the contents of a website to web clients
such as a browser.
A Computer stores web server software and a website's contents (HTML pages,
images, CSS style sheets, and JavaScript files). The server needs to be connected to the
Internet so that its contents can be made accessible to others.
Web server as a software, is a specialized program that understands URLs or web
addresses coming as requests from browsers, and responds to those requests.
The server is assigned a unique domain name so that it can be accessed from
anywhere using Internet. The web browser from the client computer sends a HTTP
request for a page containing the desired data or service. The web server then accepts
request, interprets, searches and responds (HTTP response) against request of the
web browser. The requested web page is then displayed in the browser of the client. If
the requested web page is not found, web server generates “Error: 404 Not found” as
a response.
Web Hosting:
A web hosting service is a type of Internet hosting service that allows individuals and
organisations to make their website accessible via the World Wide Web. In Simple,
uploading of website on Web Server is known as hoisting. To upload the website, we
need some web space on server to upload website. This space is available on some
nominal charges.
All web servers are assigned a unique numeric address called IP address when
connected to the Internet. This IP address needs to be mapped/changed to domain name
(Textual name) of the website using DNS (Domain Name Service). Thus, user can access
website by providing domain name through a browser (URL). The domain name has to
be registered (purchased) with an authorized agency i.e. Registrar Domain Names.
QUESTIONS ON COMPUTER NETWORKING
MULTIPLE CHOICE QUESTIONS(1 MARK EACH)
1. ______ is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) SMTP (B) VoIP (C) PPP (D) HTTP
7. Network in which every computer is capable of playing the role of a client, or a server or
both at same time
is called
a) local area network b) peer-to-peer network c) dedicated server network d) wide
area network
9. Identify the device on the network which is responsible for forwarding data from one
device to another
(a) NIC (b) Router (c) RJ45 (d) Repeater
10. Which of the following device send data to every connected node?
a)Switch b)Repeater c)Router d) Hub
11. In which type of switching first the connection is established between sender
and receiver and then the data is transferred?
a) Circuit b)Message c)Packet d)None
12. Identify the cable which consists of an inner copper core and a second
conducting outer sheath:
(i)Twisted Pair (ii) Co-axial (iii) Fiber Optical (iv) Shielded Twisted Pair
13. In fiber optic transmission, data is travelled in the form of:
(i) Light (ii) Radio link (iii) Microwave Link (iv) Very low frequency
14. Which of the following devices modulates digital signals into analog signals
that can be sent over traditional telephone lines?
(i) Router (ii) Gateway (iii) Bridge (iv) Modem
16. Which of the following device is used for sorting and distribution of data packet
to their destination based on their IP Address?
(i) Gateway (ii) Router (iii) Bridges (iv) Switch
18. Which type of Network is generally privately owned and links the devices in a
single office, building or Campus?
a. LAN b. MAN c. WAN d. PAN
20. Raj is looking for some information about How Router works, for this he
opens the browser and typed the URL of requested site. In few moments he
received the requested page on his browser screen. Identify the type of
protocol, used between Browser (Client) and Web Server for the
communication?
a. TCP/IP b.HTTP c,SMTP d.POP3
2 MARKS QUESTIONS
1. Write two points of difference between Bus topology and star topology.
2. Write two points of difference between XML and HTML.
3. Write the full forms of the following:
(i) HTTP (ii) FTP
4. Discuss the use of TELNET
5. Write two advantages and two disadvantages of circuit switching.
6. Differentiate between Web server and web browser. Write any two popular web browsers.
7. Classify each of the following Web Scripting as Client Side Scripting and
Server Side Scripting :
(i) Java Scripting
(ii) ASP
(iii) VB Scripting
(iv) JSP
10. Write two differences between Coaxial and Fiber transmission media.
5 MARKS QUESTIONS
1. A professional consultancy company is planning to set up their new offices in India with its
hub at
Hyderabad. As a network adviser, you have to understand their requirement and suggest them
the best
available solutions. Their queries are mentioned as (i) to (v) below.
a) Which will be the most appropriate block, where TTC should plan to install their server?
b) Draw a block to block cable layout to connect all the buildings in the most appropriate
manner for efficient communication.
c) What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bengalore with its London based office.
● Satellite Link
● Infrared
● Ethernet
d) Which of the following device will be suggested by you to connect each computer in each
of the buildings?
● Switch
● Modem
● Gateway
e) Company is planning to connect its offices in Hyderabad which is less than1 km. Which
type of network will be formed?
Sol: (i) The company should install its server in finance block as it is having maximum
number of computers.
(ii) The layout is based on minimum cable length required, which is 120 metres in the
above case.
(iii) Satellite Link.
(iv) Switch.
(v) LAN
(i) Suggest the most appropriate block/location to house the SERVER in the Surajpur
center (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to
most efficiently connect various blocks within the Surajpur Center.
(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router
(v) Suggest the best possible way to provide wireless connectivity between Surajpur Center
and Raipur Center.
iv) a) Switch/Hub – In every block to interconnect the devices within every block
b) Router -In development block because server is going to be placed here
v) Satellite
(i) Suggest the most appropriate block/location to house the SERVER in the Kodagu
campus (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
Ans: IoT block, as it has the maximum number of computers.
(ii) Suggest a device/software to be installed in the Kodagu Campus to take care of data
security.
Ans:Firewall
(iii) Suggest the best wired medium and draw the cable layout (Block toBlock) to most
efficiently connect various blocks within the Kodagu Campus.
Ans:Optical fiber
(iv) Suggest the placement of the following devices with appropriate reasons:
a) Switch/Hub b) Router
Sol:a) Switch/Hub: In each block to interconnect the computers in that block.
b) Router: In IoT block (with the server) to interconnect all the three blocks.
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between
Kodagu Campus and Coimbatore Campus.
Sol:VoIP
4. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and web
based activities. The company compound has 4 buildings as shown in the diagram below:
iv) The organisation is planning to link its sale counter situated in various parts of the
same city,
which type of network out of LAN, MAN or WAN will be formed? Justify your answer.
Sol: i)
5. Magnolia Infotech wants to set up their computer network in the Bangalorebased campus
having four
buildings. Each block has a number of computers that are required to be connected for ease of
communication, resource sharing and data security. You are required to suggest the best
answers to
the questions i) to v) keeping in mind the building layout on the campus.
i) Suggest the most appropriate block to host the Server. Also justify your choice.
ii) Suggest the device that should should be placed in the Server building so that they can
connect to Internet Service Provider to avail Internet Services.
iii) Suggest the wired medium and draw the cable block to block layout to economically
connect the various blocks.
iv) Suggest the placement of Switches and Repeaters in the network with justification.
v) Suggest the high-speed wired communication medium between Bangalore Campus and
Mysore campus to
establish a data network.
iv) Switches in all the blocks since the computers need to be connected to the network.
Repeaters between Admin and HR block& Admin and Logistics block. The reason
being the distance is more than 100m.
v) Optical Fiber cable connection.
Unit : 3 Database Management and Mysql
Relational
Database
Model
Introductory
Database
Concepts of
Constraints
Database
Database
Management
Common Database
Database Languages
Operations & SQL
Database
Keys
SQL
Operations in SQL
Database Key
Key in a database is defined as a set of attributes to identify each record uniquely in a table. A Key
must be unique and not null.
Classification of Keys:
Key
Date & Time data types: Used to represent date, time, or both in a column. Data is enclosed
with quotes ‘ ’ or “ “.
e.g. - date, datetime, time
String / Text data types: Used to represent text in a column. Data is enclosed with quotes ‘ ’
or “ “.
e.g. –
char(m) – Fixed length character of length m where 1 character takes 1 Byte in memory.
Memory space is wasted if text size is less than m.
varchar(m) – Variable length character allowing maximum number of characters m. It
saves memory allocation for text having lesser size than m.
Query:
Query is a type of SQL commands which accepts tables (relations), columns (fields or attributes)
and conditions or specifications if any and display the output by means of a temporary table which
consists of data represented through fields and records.
Structure of Query:
SELECT < 1, multiple ( comma i.e. , separated) or all columns >
FROM < 1 table or multiple tables ( comma i.e. , separated) in case of join >
WHERE <condition on column(s)>
GROUP BY <1 column>
HAVING < condition on aggregate function on a column only if group by exists >
ORDER BY <0, 1 or more ( comma i.e. , separated) columns >
Note:
I. Among above SELECT and FROM are mandatory statements in a query and all other
statements are optional.
II. SELECT statement contains one or more columns. * should be used to display all columns.
Functions or expressions on columns can also be done.
III. FROM statement contains multiple tables only if columns from more than one tables are
displayed through SELECT statement in case of product or join operations. Here records
can be fetched from multiple tables.
IV. WHERE clause may contain multiple conditions related with logical OR / AND operators.
Logical NOT operator can be used on a condition also.
V. GROUP BY clause is used if statistical records are to be displayed based on a field/column.
In this case SELECT statements should contain GROUP BY field and aggregate function
on another column at least. Once a group is formed individual records cannot be accessed
in the same query.
VI. ORDER BY clause can be used to arrange the output records in ascending (by default) or
descending order of values in one or more columns.
Order of execution of a query
Step 1: Identify table(s) with FROM clause
Step 2: Filter records using WHERE clause
Step 3: Form group if any using GROUP BY clause
Step 4: Filter groups using HAVING clause only if GROUP BY is used
Step 5: Arrange the output records in ascending or descending order using ORDER BY
Step 6: Display the fields mentioned in SELECT clause.
Database Constraints
Rules imposed on the values of one or more columns in the tables are called database constraints.
The database constraints are:
UNIQUE Ensures that all values in a column are different. No two records have
same values in that column.
NOT NULL Ensures that a column can never have NULL values.
PRIMARY KEY Uniquely identify a record. It is a combination of UNIQUE and NOT
NULL.
CHECK Specify the domain of values with certain criteria for a column.
DEFAULT Provides default value for a column when no value is specified.
REFERENCES / Ensures referential integrity between the foreign key of dependent /
FOREIGN KEY referencing table and primary key of independent / referenced table.
DESC DEPT;
or,
CREATE TABLE EMPL
(
EID VARCHAR(6),
ENAME VARCHAR(30) NOT NULL,
GEN CHAR,
DOJ DATE,
HOMETOWN VARCHAR(20) DEFAULT 'BANGALORE',
SALARY DECIMAL(8, 2) ,
MGR_ID VARCHAR(6) ,
DEPT_ID VARCHAR(4) ,
PRIMARY KEY(EID),
CHECK (GEN IN ('M', 'F', 'T')),
CHECK (SALARY BETWEEN 5000.00 AND 300000.00),
FOREIGN KEY(MGR_ID) REFERENCES EMPL(EID),
FOREIGN KEY(DEPT_ID) REFERENCES DEPT(DEPT_ID)
);
DESC EMPL;
Name of tables defined in current database so far.
SHOW TABLES;
INSERT INTO EMPL VALUES ('E0001', 'RITU SEN', 'F', '2002-06-20', 'KOLKATA',
40000.00, NULL, 'D03');
INSERT INTO EMPL VALUES ('E0004', 'ANISHA RAWAT', 'F', '2019-09-04', 'DELHI',
20000.00, 'E0001', 'D03' );
INSERT INTO EMPL VALUES ('E0005', 'SANA KHAN', 'F', '2017-08-31', 'DELHI',
30000.00, 'E0003', 'D01');
C. Write SQL statements for the following queries and display their outputs.
2. Display name and salary of all the employeEs from table EMPL.
SELECT ENAME, SALARY
FROM EMPL;
4. Display DNAME in ascending order of MAX_STRENGTH.
Note:
Sorting in SQL is by default in ascending order of values be it numeric or alphabetical
order. Hence ASC is default keyword and need not be used in ORDER BY statement.
In case of arranging the output of query in descending order of values DESC keyword must
be used in ORDER BY statement.
Comparison operators
= > < >= <= <> !=
6. Display name of employees and salary in descending order of names where DEPT_ID is
not 'D03'.
SOLUTION OUTPUT
SELECT ENAME,
SALARY
FROM EMPL
WHERE DEPT_ID !=
'D03'
ORDER BY ENAME
DESC;
SOLUTION OUTPUT
SELECT EID, ENAME
FROM EMPL
WHERE DOJ > '2015-01-31' ;
Logical Operators
OR AND NOT
Logical operators are used in where clause. AND, OR are binary operations which require 2
conditions. NOT is unary operator which requires one condition only.
AND : c1 and c2 → If both c1 and c2 are true the overall condition is true.
OR : c1 or c2 → If at least one between c1 or c2 are true the overall condition is true.
NOT : not c1 → If c1 is true the overall condition is false and vice versa.
BETWEEN: BETWEEN operator can be used as a substitute of and operation where the minimum
and maximum value is to be checked for a single column.
8. Display the records of those employees whose salary is between 35000 and 45000.
SOLUTION1 SOLUTION2
SELECT * FROM EMPL SELECT * FROM EMPL
WHERE SALARY >=35000 WHERE SALARY BETWEEN
AND SALARY <=45000; 35000 AND 45000;
Checking a list of values
IN: IN operator is a substitute of OR operation(s) among equality checking of a single column with
multiple values.
NOT IN: NOT IN operator is used for non-equality checking of a column with multiple values.
9. Display name and hometown of employees who belong to departments 'D01' or 'D02'.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT ENAME, SELECT ENAME,
HOMETOWN HOMETOWN
FROM EMPL FROM EMPL WHERE
WHERE DEPT_ID = 'D01' DEPT_ID IN ('D01', 'D02');
OR DEPT_ID = 'D02';
10. Display EID and SALARY of employees whose half of salary is neither 10000 nor 20000.
SOLUTION 1 SOLUTION 2 OUTPUT
SELECT EID, SALARY SELECT EID, SALARY
FROM EMPL FROM EMPL
WHERE NOT (SALARY/2 = WHERE SALARY/2 NOT
10000 OR SALARY/2 = IN (10000, 20000);
20000);
Wildcard Characters
A string constant to be checked with a value stored in a column may have one or more characters
missing in case of sub string checking. Such placeholder can be of two types:
_ → Replacement or placeholder of exactly one character in the string constant value.
(underscore)
% → Replacement or placeholder of 0 or more characters in the string constant value.
LIKE: A string constant containing one or more wildcard characters can be checked for equality
with LIKE operator only, not =.
NOT LIKE: Likewise NOT LIKE operator checks inequality checking with a string constant
containing one or more wildcard characters. It cannot be done using <> or !=.
11. List the name of employees whose name starts with 'S' and have length at least 5.
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE 'S____%';
SOLUTION OUTPUT
SELECT ENAME
FROM EMPL
WHERE ENAME LIKE '%N'
AND ENAME NOT LIKE '%M%';
NULL checking
IS: IS is a special operator which is used to check absence of value i.e. NULL in a column as no
other comparison operator can be used on NULL values.
IS NOT: Likewise, IS NOT is used to check the presence of values i.e. NOT NULL in a column.
13. Print ENAME and DEPT_ID of employees who do not have manager i.e. MGR_ID is blank.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NULL;
14. Print ENAME and DEPT_ID of employees who have manager i.e. MGR_ID is not empty.
SOLUTION OUTPUT
SELECT ENAME, DEPT_ID
FROM EMPL
WHERE MGR_ID IS NOT NULL;
16. List the name of places which are hometown of any employee. (No duplicate values)
SOLUTION OUTPUT
SELECT DISTINCT
HOMETOWN
FROM EMPL;
Aggregate functions
GROUP BY: GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Once the group is formed individual records cannot be accessed in that query. Several
clusters or groups are formed based on the number of different values in the GROUP BY column
present in the table.
For example, if GROUP BY is applied on TYPE field of ITEM table 3 groups are formed – Crops
have 2 records, Leaves and Pulses have one record each.
Renaming field and table
AS is an optional keyword to rename a column a table in FROM clause or an expression on
column(s) in SELECT clause. If there is blank space in alias then it must be surrounded by ' ' or '' ''.
Column renaming is done for customized display of query output.
Table renaming is done for giving convenient names to the tables in join operations for
ease of access by programmers.
17. Display the number of distinct DLOC mentioned in table DEPT.
SOLUTION OUTPUT
SELECT COUNT(DISTINCT DLOC) as 'NO. OF
LOCATIONS'
FROM DEPT;
18. Display the earliest and latest DOJ of employees as per EMPL.
SOLUTION OUTPUT
SELECT MIN(DOJ) 'EARLIEST', MAX(DOJ)
'LATEST'
FROM EMPL;
HAVING: It is a conditional statement used along with group by clause only. It compares the
values with the outcome of aggregate functions belonging to each group already formed by
GROUP BY clause.
Difference between WHERE and HAVING:
21. Display the hometowns and no. of employees belonging to them if the headcount per
hometown is at least 2.
SOLUTION OUTPUT
SELECT HOMETOWN, COUNT(EID) 'NO
OF EMPLOYEE'
FROM EMPL
GROUP BY HOMETOWN
HAVING COUNT(EID) >= 2;
22. Display the number of employees working in each DEPT_ID excepting 'D01' where no. of
employees in the DEPT_ID is more than 1.
SOLUTION OUTPUT
SELECT DEPT_ID, COUNT(*) AS 'NO OF
EMPLOYEE'
FROM EMPL
WHERE DEPT_ID != 'D01'
GROUP BY DEPT_ID
HAVING COUNT(*) > 1;
Cartesian Product
Cartesian product is performed on two tables and it produces all the combination of records in both
tables. It does not require any common column.
If tables A, B have m, n columns and p, q records respectively then resultant table A x B has m+n
columns and p x q records.
23. Perform Cartesian Product between EMPL and DEPT.
SOLUTION 1 SOLUTION 2 SOLUTION 3
SELECT * SELECT * SELECT *
FROM EMPL, DEPT; FROM EMPL INNER JOIN FROM EMPL JOIN
DEPT; DEPT;
[RECOMMENDED
STATEMENT]
JOIN
NATURAL JOIN: Natural join is a binary operator which works on two tables. They should have
one column which have same name and domain. It a combination of Cartesian product and a where
clause with equality checking on the common columns.
Other conditions in that query are ANDed with the join condition.
Natural join is mostly done on Foreign key field of one table and Primary key field of
another table.
If tables A, B have m, n columns and p, q records respectively then resultant table has m+n
columns and minimum(p,q) records.
EQUI JOIN: Equi join is a join operation which works on the equality condition of values in two
columns from two tables having similar data type. NATURAL JOIN, EQUI JOIN are said to be
INNER JOIN.
24. Perform Natural Join between these two tables.
SOLUTION 1 SOLUTION 2
SELECT * SELECT *
FROM EMPL NATURAL JOIN FROM EMPL, DEPT
DEPT; WHERE EMPL.DEPT_ID =
DEPT.DEPT_ID;
[RECOMMENDED STATEMENT]
27. Display no. of employees working in those departments whose DLOC is CHENNAI.
SOLUTION OUTPUT
SELECT COUNT(*) 'NO. OF EMPLOYEES'
FROM EMPL AS E, DEPT AS D
WHERE E.DEPT_ID = D.DEPT_ID
AND DLOC = 'CHENNAI';
28. Display ENAME of employees who have manager along with that display ENAME of their
corresponding manager as well.
SOLUTION OUTPUT
SELECT E.ENAME 'EMPLOYEE', M.ENAME
'MANAGER'
FROM EMPL E, EMPL M
WHERE E.MGR_ID = M.EID;
29. Display ENAME and the amount of bonus to be paid to that employee where bonus = 5000 +
5% of SALARY.
SOLUTION OUTPUT
SELECT ENAME, SALARY,
5000 + 0.05 * SALARY 'BONUS'
FROM EMPL;
DESC DEPT;
3. Modify the datatype of SALARY in table EMPL to an integer of length 6 and drop the existing
check constraint.
SOLUTION OUTPUT
ALTER TABLE EMPL
MODIFY SALARY INT(6);
DESC EMPL;
Questions ;
Q. No. 1 to 20 are MCQs of 1 mark each
18. Assertion(A): DBMS is an application package which arranges the data in orderly
manner in a tabular form.
Reason(R): It is an interface between database and the user. It allows the users to
access and perform various operations on stored data using some tools.
19. Assertion(A): Aggregate function AVG() calculates the average of a set of values
and produces a single value as result.
Reason(R): The aggregate functions are used to perform some basic calculations
like sum, max, min, etc on a set of numbers.
20. Assertion(A): While inserting records in EMP table, value of DateOfBirth field
must be enclosed withing quotes ‘ ‘.
Reasoning(R): Date is represented as char / varchar always.
22. What do you mean by referential integrity? Explain with suitable example.
23. Write MySQL statement to create a table named REMEDIAL based on the
following specification:
Table: REMEDIAL
Attribute Data type Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY
28. A MySQL table, sales have 10 rows. The following queries were executed on
the sales table.
SELECT COUNT(*) FROM sales;
COUNT(*)
10
32. Write output of the SQL queries based on the following tables Projects and
Employee:
i. Define CID in CUSTOMER table as Foreign Key that refers to CID i.e.
Primary Key of COMPANY table.
ii. Display the ‘CUSTOMER NAME’, ‘PRODUCT NAME’ who have purchased
any product from the ‘COMPANY NAME’ ‘SONY’.
iii. Increase the QTY by 15 for the products with PRICE below 40,000.
34. Consider the GAMES table and answer the following questions:
Abhay wants to do the following operations on the STORE table. Please help him
to do by writing appropriate SQL statements.
i. Insert the following record in the STORE table:
(2010, Notebook, 23, NULL)
ii. Add a new column price with data type as decimal.
36. What do you mean b y CHECK constraint and DEFAULT constraint? Explain
with suitable example.
37. Consider the following tables and answer the questions below:
i. What will be the degree and cardinality of the resultant table after performing
Cartesian Product between PRODUCT and CLIENT?
ii. What will be the degree and cardinality of the resultant table after performing
NATURAL JOIN between PRODUCT and CLIENT?
iii. Are these values same? What can be the reason for this?
38. i. Write down the purpose of using aggregate functions in MySql.
ii. Give example of any two aggregate functions and their purposes.
iii. Can we use aggregate functions without GROUP BY clause? Justify.
40. i. Name the aggregate functions valid on a column of DATE data type.
ii. Suggest a keyword for renaming an attribute or a table in MySql.
iii. Write down the syntax of representing the common column CODE while
performing Equi Join between two tables GAME and USER.
ii. Consider the following table and find the output of the following queries:
ii. Display the values in TYPE column of the table CAR after removing the
duplicate values from the output.
select ___________ TYPE from CAR;
iii. Display MODEL, PRICE, COLOUR from CAR whose COLOUR is neither
RED nor BLUE.
select MODEL, PRICE, COLOUR from CAR
where COLOUR _________ (‘RED’, ‘BLUE’);
(i) Display the total PERIODS for each SUBJECT from SCHOOL table.
(ii) Display TEACHERNAME, GENDER from the tables SCHOOL and ADMIN
whose DESIGNATION is ‘COORDINATOR’.
49. Consider the table Fees mentioned in Q. No. 48 and answer the following
questions:
ii. Increase the second quarter fee of class 12th students by 50.
iii. Delete the record of student with Rollno-1212
iv. Aman wants to display the schema (structure) of Fees table. Which command
will he use from the following:
a) CREATE b) ALTER c) SHOW d) DESCRIBE
50. Sagar, a cloth merchant creates a table CLIENT with a set of records to maintain
the client’s order volume in Qtr1, Qtr2, Qtr3 and their total. After creation of the
table, he has entered data of 7 clients in the table.
i. Write the statements to Update a record present in the table with data for
Qtr2 = 200, Qtr3 = 600 , total = sum of all Qtrs where the Client_ID is C660.
ii. Delete all records where total is between 500 to 900.
iii. Make changes in ClientName with data type varchar(20) and not null
constraint.
iv. Remove the column Total from the CLIENT table.
_________
SOLUTIONS
1. B 2. a 3. d 4. c 5. d
6. a 7. b 8. d 9. a 10. b
11. d 12. c 13. b 14. a 15. False
16. False 17. a 18. a 19. b 20. c
21. a) Degree - no. of attributes in a table, Cardinality – no. of records in a table.
b) Degree – 4, cardinality – 6
22. Foreign key of one table refers to the Primary key of another table.
23. CREATE TABLE REMEDIAL
(
SNAME VARCHAR(20) NOT NULL,
ROLL INT(5) UNIQUE,
FEES FLOAT(7,2),
ADMN INT(5) PRIMARY KEY
);
24. a. USE OFFICE;
b. DESC EMPL; or DESCRIBE EMPL;
25. a. PNO as unique throughout table and not null.
b. PNAME, SPORTS, SALARY.
26. a. ALTER TABLE MOTOR MODIFY MODEL VARCHAR(30) NOT NULL;
b. UPDATE MOTOR SET PRICE = PRICE * 1.20 WHERE BRAND = ‘TATA’;
27. DML - INSERT, UPDATE
DDL - ALTER, DROP
28. Count(*) will return the number of records in the table sales. Count(discount) will
return the number of records having not null values in the discount field of sales
table.
29. GROUP BY clause is used if statistical records of a table are to be displayed based
on a field. Groups are formed based on the number of different values in the
GROUP BY column present in the table.
30. In Natural Join the common attribute between two tables appears only once. Where
as in Equi Join the common attribute appears as it is i.e. twice. Hence these
common attributes are accessed as table_name.attribute in the query to resolve the
conflict.
31. i.
Name Project
Ranjan P01
Muneera P01
Alex P02
Akhtar P04
Satyansh P04
ii.
Name Salary
Ranjan 150000
Akhtar 125000
iii.
min(DOJ) max(DOB)
2015-01-21 1996-11-15
32. i.
Project count(*)
P01 2
P04 2
P02 1
ii.
PID PName EID
P01 Road 102 Carpenting E01
P04 Footover Bridge K-13 E02
P01 Road 102 Carpenting E03
P02 Civil Lines Parking E04
P04 Footover Bridge K-13 E05
iii.
avg(Salary)
135000
36. CHECK – Ensure that the attribute contains only permissible set of values.
DEFAULT – Ensure the default value is inserted if no value is mentioned.
e.g. -
CREATE TABLE STOCK
(
SNO INT PRIMARY KEY,
SNAME VARCHAR(20),
LOCATION VARCHAR(15) DEFAULT ‘BANGALORE’,
PRICE FLOAT(7,2) CHECK (PRICE BETWEEN 0.00 AND 10000.00)
)
37. i. After Cartesian product, Degree = 8, Cardinality = 25
ii. After natural join, Degree = 7, Cardinality = 5
iii. No, because cartesian product is the all-possible combination of tuples between
two tables. Where as Natural join selects only those tuples for whom the values of
the common attributes are same.
38. i. Aggregate functions perform calculation on a set of values, and returns a single
value. If used with GROUP BY clause, it returns one value for each group.
SUM() - returns the total sum of a numerical column
MAX() - returns the largest value within the selected column
ii. Yes. Then it returns a single value for the selected attribute by considering all the
records in that table.
39. i. NULL is said to be absence of any value in an attribute. NULL cannot participate
in any operation.
ii. IS
iii. COMMIT
40. i. MAX(), MIN(), COUNT()
ii. AS
iii. SELECT * FROM GAME G, USER U WHERE G.CODE=U,CODE;
41. i. WHERE clause allows to filter data from individual rows of a table based on
certain conditions. In contrast, the HAVING clause allows to filter data from a
group of rows in a query based on conditions involving aggregate functions.
ii.
a)
SEX AVG(SALARY)
M 68666
F 65000
b)
SUBJECT COUNT(*)
Computer Science 2
c)
SUBJECT MIN(SALARY)
Computer Science 75000
English 55000
Economics 71000
42. i. DELETE is used for deleting records from a table. DROP is used to delete the
entire schema of any database object like table.
e.g. –
DELETE FROM STUDENT WHERE ROLL = 5;
DROP TABLE STUDENT;
ii.
E_CODE NAME E_CODE LOCATION
E01 ASHISH E05 MUMBAI
E02 SURESH E05 MUMBAI
iii. d. Cross join
43. i. databases
ii. distinct
iii. not in
iv. count
v. as
44. i. Data integrity, data security
ii. Char data type stores data of fixed length, whereas the Varchar data type stores
variable length data. Varchar is preferable as it is more flexible for data of any size.
iii. It can represent 7 digit real number with 3 digits in the right of decimal point.
45. i. A self-join is a regular join, but the table is joined with itself.
SELECT * FROM EMP A, EMP B where A.ID = B.ID;
ii.
(a) TABLE
(b) DEFAULT
(c) CHECK
46. i.
ITEM_NAME MAX(PRICE) COUNT(*)
Personal Computer 37000 3
Laptop 57000 2
ii.
CNAME MANUFACTURER
N Roy PQR
R Singh XYZ
R Pandey COMP
C Sharma PQR
K Agarwal ABC
iii.
ITEM_NAME PRICE*100
Personal Computer 3500000
Laptop 5500000
iv.
City
Delhi
Mumbai
Bangalore
To save the current transactions of inserting, updating and deleting data we use:
mydb.commit()
6. close() to close the connection and clean up the environment
mydb.close()
1. To establish a connection with MySQL from Python which of the following functions is used?
(a) connection()
(b) connect()
(c) open()
(d) cursor()
3. To establish a connection between Python and sql database, connect() is used. Which of the
following arguments may not necessarily be given while calling connect()?
(a) host
(b) database
(c) user
(d) password
6. To make the changes made by any SQL Queries permanently in database, which function is used
after execution of the query?
(a) save()
(b) commit()
(c) execute()
(d) dump()
9. To get all the records from result set, you may use ___________.
(a) cursor.fetchmany()
(b) cursor.fetchall()
(c) cursor.fetchone()
(d) cursor.execute()
10. Which of the following is not a valid method to fetch records from database in python.
(a) fetchmany()
(b) fetchone()
(c) fetchmulti()
(d) fetchall()
11. Which attribute of cursor is used to get number of records stored in cursor (Assumeg cursor
name is mycursor)?
(a) mycursor.count
(b) mycursor.row_count
(c) mycursor.records
(d) mycursor.rowcount
12. Which of the following package must be imported in Python to create a database connectivity
application?
(a) mysql.connector
(b) mysql.connect
(c) sql.connector
(d) sql.execute
13. Which of the following method reflects the changes made in database permanently?
(a) <connection>.done()
(b) <connection>.final()
(c) <connection>.reflect()
(d) <connection>.commit()
14. Which method of cursor class is used to fetch limited rows from the table?
(a) cursor.fetchsize(SIZE)
(b) cursor.fetchmany(SIZE)
(c) cursor.fetchall(SIZE)
(d) cursor.fetchonly(SIZE)
15. Which method of cursor class is used to get the number of rows affected after any of
the Insert/update/delete database operation executed from Python?
(a) cursor.rowcount
(b) cursor.getaffectedcount
(c) cursor.rowscount
(d) cursor.rcount
16. Which of the following component acts as a container to hold the data returned from the query:
(a) table
(b) cursor
(c) resultset
(d) container
17. To get the next record from the result set, we may use .
(a) cursor.fetch(next)
(b) cursor.fetchmany()
(c) cursor.fetchall()
(d) cursor.fetchone()
18. SQL command is passed to which function to run after establishment of the connection
between python and database
(a) cursor()
(b) execute()
(c) connection()
(d) fetchall()
19. Which of the following function is used to close the connection between python and database?
(a) cursor.close()
(b) is.close()
(c) connection.close()
(d) execute.close()
2 Marks Questions
1. Which method we use to establish the connection and clear the connection?
Ans: connect() and close() methods with connection object.
3 Marks Questions
1. What is a result set? Give example with coding.
Ans: A result set refers to a logical set of records that are fetched from the database by executing a
query and made available to the application-program.
Eg: myresult = mycursor.fetchall()
2. Which package must be imported in Python to create a database connectivity application? Give
example with coding.
Ans:There are multiple packages available through which database connectivity applications
can be created in Python. One such package is mysql.connector.PyMySQL, mysqlclient, etc. can
also be used for connectivity.
Eg: import mysql.connector
4. Write the python script to read the whole data from the table emp and display all the records.
Ans: import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root",database="school")
print (mydb)
mycursor=mydb.cursor()
numrow=mycursor.execute("select * from student")
print(mycursor.fetchall())
mydb.close()
Help your friend Sonia in writing the following missing statements to complete the code:-
Ans:
Statement 1: mysql.connector
Statement 2: mydb.cursor()
Statement 3: mydb.commit()
Statement 4: mydb.close()
2. Avni is trying to connect Python with MySQL for her project. Help her to write the python
statement on the following:
i. Name the library, which should be imported to connect MySQL with Python.
ii. Name the function, used to run SQL query in Python.
iii. Name the function required to make the changes permanent.
iv. Name the fuction to clear the environment.
Ans:
i. mysql.connector
ii. execute()
iii. commit()
iv. close()
3. Your friend Jagdish is writing a code to fetch data from a database Shop and table name Products
using Python. He has written incomplete code. You have to help him to write complete code:
import __________ as m # Statement-1
object1 = m.connect(host="localhost", user="root", password="root", database="Shop")
object2 = object1._________ # Statement-2
query = '''SELECT * FROM Products WHERE NAME LIKE "A%";'''
object2._________(query) # Statement-3
__________.close() # Statement-4
Ans:
Statement 1: mysql.connector
Statement 2: cursor()
Statement 3: execute()
Statement 4: object1
4. The code given below reads the following record from Table named Employee and display those
record salary >= 30000 and <= 90000:
Empno – integer
EName – string
Desig – integer
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is Password
The table exists in a MYSQL database named Bank.
Write the following missing statements to complete the code on behalf of your friend Sandeep:
Statement 1 – to form the cursor object
Statement 2 – to query string.
Statement 3 - to execute the query that extracts records of those Employees whose salary >=30000
and <=90000.
Statement 4 - to close the connection.
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='Password',database='bank')
mycursor=_________________ # statement1
mycursor.________________ #statement 2
data= __________________ # statement 3
for x in data:
print(x)
______________ # statement 4
Ans:
Statement 1: mydb.cursor()
Statement 2: execute('''SELECT * FROM Employee WHERE salary >= 30000 and salary <=
90000;''')
Statement 3: mycursor.fetchall()
Statement 4: mydb.close()
5. The code given below inserts the following record in the table Emp:
Empno – integer
EName – string
Designation – integer
Salary – integer
Bonus - Integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is tiger
The table exists in a MYSQL database named Employee.
The details (Empno, EName, Designation, Salary and Bonus) are to be accepted
from the user.
Help your friend in writing the following missing statements to complete the code:
Statement 1 – to create a connection
Statement 2 – to form the cursor object
Statement 3 – to execute the command that inserts the record in the table Emp.
Statement 4 - to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
mycursor=_________________ #Statement 1
eno=int(input("Enter Employee Number: "))
Ename=input("Enter Employee Name: ")
Designation=input("Enter Designation: "))
Salary=int(input("Enter Salary: "))
Bonus=int(input("Enter Bonus: "))
querry="insert into emp values({},'{}',{},{})".format(eno,ename,designation,bonus)
______________________ #Statement 2
______________________ # Statement 3
print("Employee Data Added successfully")
Ans:
Statement 1: con1= mysql.connect(host="localhost",user="root", password="tiger",
database="Employee")
Statement 2: con1.cursor()
Statement 3: mycursor.execute(querry)
Statement 4: con1.commit()
5 Marks Questions
1. Write the steps to perform an Insert query in database connectivity application. Table Student
values are rollno, name, age (10,’Ashok’,26).
Ans:
Statement 1: c
Statement 2: con.cursor()
Statement 3: mycursor.execute(sql)
Statement 3: mycursor.commit()
Statement 3: con.close()
3. Write the python function to accept the name as parameter and find out whether record present
in the table or not. Table Student columns are rollno, name, age.
Ans:
Statement 1: import mysql.connector as mycon
Statement 2: mycursor.commit()
Statement 3: execute
Statement 4: mycursor.fetchall()
Statement 5: mydb
SECTION – A
1 Which of the following is not a valid Literal in Python: 1
a) True b) 0x2B
c) -2.5E-3 d) KVS
2 What will be the output of the python code given below: 1
P = [20, 50]
Q = [5, 8]
P.extend(Q)
print(P)
a) [20, 50, 5, 8] b) [20, 50, [5, 8]]
c) [20, 50] d) [5, 8, 20, 50]
3 Consider the following string declaration in python: 1
S = ‘PROCEDURE’
Which of the following statements will produce output as ‘RUDE’?
a) print(S[4:8]) b) print(S[-2:3:-1])
c) print(S[-2:-6]) d) print(S[7:-5:-1])
4 Which of the following statement is false? 1
a) Try block tests the excepted error to occur
b) Except block handles the run time error
c) Multiple except blocks cannot be associated to one try block
d) Finally block always gets executed either exception is generated or not
5 Which of the following statement(s) will not create dictionary D? 1
a) D = {2:2, 'A':'A'} b) D = {(2,):(2,),('A'):('A')}
c) D = {[2]:[2], ['A']:['A']} d) D = {(2):[2], ('A'):['A']}
6 A binary file contains details of students in the form of list i.e [RollNo, Name, 1
Age]. Which of the following method(s) will be used to read data from the binary
file?
a) load() b) read()
c) readlines() d) reader()
7 Which of the following statement would give an error during execution of the 1
following code?
tup = (4, 'KVS', 5.5, 3)
print(tup[2]+100) #Statement 1
print(max(tup)) #Statement 2
print(tup.index(5.5)) #Statement 3
del tup #Statement 4
a) Statement 1 b) Statement 2
c) Statement 3 d) Statement 4
8 Which of the following outcome is expected from the following code: 1
import random
SIDES = ('EAST','WEST','NORTH','SOUTH')
N = random.randint(1,3)
OUT=""
for x in range (N,1,-1):
OUT=OUT+SIDES[x]
print(OUT)
a) SOUTHNORTHWEST b) SOUTHNORTH
c) NORTHWEST d) SOUTH
9 What will be the output of the following code? 1
L = [2, 4, '2', 2.0, [2, 20], 'KV2']
print(L.count(2))
a) 1 b) 2
c) 3 d) 4
10 Expand the following terms: 1
(i) POP3
(ii) SMTP
11 DROP in MySQL is which type of command? 1
a) DDL b) DML
c) DCL d) TCL
12 State True or False: 1
“Mutable data types in python allows changes at the same memory location”
13 Consider the following python code: 1
F = open('FILE.TXT')
N = F.read(2)
If FILE.TXT contains text as: 12BENGALURU
What will be the data type of N?
a) Integer b) Boolean
c) String d) None
14 The syntax of seek() is given as follows: 1
file_object.seek(offset [, reference_point])
If the value of reference_point is 2, then which of the following statement is
correct?
a) Value of offset must be positive
b) Value of offset must be negative
c) Value of offset can be positive or negative
d) Value of offset must be zero
15 Which of the following statements is false? 1
a) In circuit switching physical path is required between systems.
b) Message switching data is first stored, then forwarded to the next node.
c) In Message switching data is always divided into equal sized units before
transmission.
d) Internet uses packet switching technique.
16 A ___________ is a network device that connects two networks with different 1
transmission protocols together.
a) Gateway b) Bridge
c) Switch d) NIC
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the
correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion (A):- A python function that accepts parameters can be called without 1
any parameters.
Reasoning (R):- Functions can be defined with default values that are used,
whenever corresponding values are not received in function call statement.
18 Assertion (A):- ‘rb+’ and ‘wb+’ are valid file modes for opening binary files. 1
Reasoning (R):- Python supports simultaneous reading and writing in Binary files.
SECTION – B
19 Write at least two points of differences between Local Area Network(LAN) and 2
Wide Area Network(WAN)
OR
Explain the following terms with examples: 2
(i) URL (ii) Web Server
20 Rewrite the following code in Python after removing all the syntax errors. 2
Underline each correction made by you in the code.
num = 10
for x in range[0, num]:
if x in not [3, 5]:
print(x*4)
else if x = = 8:
print(x+3)
else:
a =+ x
21 Write a function display(PROD) in Python, that takes a dictionary PROD as an 2
argument and increase the price by 10% of those products whose names
contain exactly three characters, finally display the updated dictionary.
Note: Dictionary PROD contains product names and prices as key and value
pairs.
For example if the dictionary is as follows:
PROD = {'RAM':3000, 'MOUSE':250, 'KB':2500, 'HDD':4000}
OR
2
Write a Python Program to implement a function pallin(WORDS), that accepts a
list of words as argument and display only those words which are palindrome.
For example if the list is as follows:
WORDS = ['RADAR', 'HAPPY', 'ROTATOR', 'NOON']
Then the output should be:
RADAR
ROTATOR
NOON
22 What will be the output of the following code? 2
def check(L, a=10):
for x in range(1, len(L)):
if L[x]%a == 0:
L[x-1] = L[x]-1
for z in range(0,len(L),2):
print(L[z], ' ' , L[z+1])
check([25, 40, 15, 25], 5)
23 Write single python statement to perform the following tasks: 2
(i) Given a tuple T = (('OM','JAI','SAAD'),('DELHI','MUMBAI','AGRA'))
Write python statement to display 2nd city name from the above tuple.
(ii) Given a list L = [1,2,3,4,5,6,7,8,9]
Write single python statement to remove elements from index 2 to 4
OR
Write single python statement to perform the following tasks:
Given a string S = "INDIA AND INDIANS ARE GREAT" 2
(i) Write python statement to display number of times ‘INDIA’ appears in the
above string.
(ii) Write python statement to create a new string to add word ‘REMAIN’ in place
of ‘ARE’ and display the string as:
INDIA AND INDIANS REMAIN GREAT
24 Jagdish has created a table in MySQL with the following specifications: 2
Table: FURNITURE
Field Name / Attribute Data type
FID INT(3)
FNAME VARCHAR(20)
COST FLOAT(7,2)
DISCOUNT FLOAT(5,1)
QTY INT(4)
Help Jagdish by writing SQL statements to perform the following tasks:
(i) Write SQL statement to remove column QTY from the table.
(ii) Write SQL statement to increase the value of DISCOUNT by 5% for all the
rows.
OR
2
Differentiate between DDL and DML commands in SQL with appropriate
examples.
25 Consider the following two commands with reference to table EMP given below: 2
Table: EMP
ENAME QTR1 QTR2
JAI 5000 4000
HEPSIBA NULL 6000
YOGESH 4000 0
UMA 3000 2000
(a) SELECT AVG(QTR1) FROM EMP;
(b) SELECT AVG(QTR2) FROM EMP;
If the above two commands are producing different results even though the sum
values of columns QTR1 and QTR2 is same,
(i) What may be the possible reason?
(ii) What will be the output of commands (a) and (b)?
SECTION – C
26 Predict the output of the Python code given below: 3
data = ['P',20,'R',10,'S',30]
times = 0
alpha = ""
add = 0
for C in range(1,6,2):
times = times + C
alpha = alpha + data[C-1] + '$'
add = add + data[C]
print(times, add, alpha)
27 Consider the tables given below:
Table : PARTICIPANTS
PNO NAME
1 Anuradha
Tariban
2 Jhon Fedricks
3 Kanti Desai
Table : EVENTS
EVENTCODE EVENTNAME
1001 It Quiz
1002 Group
Debate 1
(a) What will be the Cardinality and Degree of the cartesian product of above
tables
PARTICIPANTS X EVENTS 2
(b) Write the output of the queries (i) to (iv) based on the table given below:
Table : TRAVEL
CNO CNAME TRAVELDATE KMS RATE
101 K. Niwal 2022-12-13 200 20
103 Fredrick 2023-03-21 120 45
Sym
105 Hitesh Jain 2023-04-23 450 42
102 Ravi Anish 2023-01-13 80 40
107 Jhon Malina 2022-02-10 65 20
(i) SELECT CNO, KMS FROM TRAVEL WHERE RATE BETWEEN 40 AND 45;
(ii) SELECT CNAME FROM TRAVEL WHERE CNAME LIKE ‘%in%’;
(iii) SELECT COUNT(DISTINCT RATE) FROM TRAVEL;
(iv) SELECT TRAVELDATE FROM TRAVEL WHERE KMS >= 200
ORDER BY TRAVELDATE;
28 Write a function COUNT() in Python to read from a text file ‘rhym.txt' and display 3
the count of words in each line.
SECTION – D
31 Consider the following tables STORE and SUPPLIERS and answer (b) and (c) 4
parts of this question.
Table: STORE
ITEMNO ITEM SCODE QTY RATE LASTBUY
1005 Sharpner 23 60 8 2021-12-02
1003 Ball Pen 0.25 22 50 25 2022-01-08
1002 Gel Pen 21 150 12 2023-10-20
Premium
1006 Gel Pen Classic 21 250 20 2022-02-02
1001 Eraser Small 22 220 6 2022-08-24
1004 Eraser Big 22 110 8 2023-11-04
1009 Ball Pen 0.50 21 180 18 2022-10-10
Table: SUPPLIERS
SCODE SNAME
21 Premium Stationers
23 Soft Plastics
22 Tetra Supply
A D
Block Block
C B
Distances between various blocks
Block A to Block B 75 meters
Block A to Block C 50 meters
Block A to Block D 100 meters
Block B to Block C 60 meters
Block B to Block D 90 meters
Block C to Block D 125 meters
Number of Computers
Block A 25
Block B 50
Block C 20
Block D 120
(i) Suggest the most suitable place (i.e. Block) to house the server of this
organisation. Also give reason to justify your suggested location.
(ii) Suggest an ideal wired cable layout of connections between the blocks
inside the campus.
(iii) Suggest the placement of the following devices with justification:
Switch
Repeater
(iv) The organisation is planning to provide link with its head office situated in
NEW DELHI. Since, cable connection is not possible from Shimla, out of the
following suggest the most suitable way to connect with its head office:
Microwave
Satellite
Infrared
(v) Which topology is used in connecting computers in the blocks using switch.
34 (i) What is the difference between text files and binary files? Which is faster in 2
processing?
(ii) Consider a binary file, HOSPITAL.DAT, containing records of the following 3
structure:
[PatientID, PatientName, Gender, WardNo, Doctor]
Write a function, showPatients(doc) that reads content from the file HOSPITAL.DAT
and display the records of those patients whose doctor is same as the value of doc
received as parameter in the function.
For example:-
Assume that the binary file HOSPITAL.DAT contains following lists as records:
[112, ‘JITESH’,’M’,5,’ROHIT’]
[254, ‘IMTIYAZ’,’M’,1,’DEEPALI’]
[412, ‘KAYA’,’F’,5,’ROHIT’]
[212, ‘KOYAL’,’F’,2,’YASHVI’]
OR 2
(i) Write one point of similarity and one point of difference between ‘w’ and ‘a’ file 3
modes of python?
(ii) Consider a binary file, TEAMS.DAT, containing records of the following structure:
[TeamName, no_won, no_lost]
Write a function, BestTeams() that reads contents from the binary file TEAMS.DAT and
display the records of those teams where no_won is more than no_lost.
For example:-
Assume that the binary file contains the following records:
['AUSTRALIA',20,18]
['SRILANKA',15,25]
['INDIA',25,10]
['ZIMBABWE',5,18]
Then the output shown by the function BestTeams() should be:
['AUSTRALIA', 20, 18]
['INDIA', 25, 10]
35 (i) Write at least one point of difference between CHAR and VARCHAR data types of 1
MySQL.
(ii) Siya maintains a database named SCHOOL which contains a table named STUDENT 4
with the structure given below:
• RNO (Roll number )- integer(3)
• SNAME (Student Name) – string
• DOB (Date of Birth in format YYYY-MM-DD) – Date
• PERCENT (Percentage) – float(6,2)
Note the following to establish connectivity between Python and MySQL:
• Username - root
• Password - tiger
• Host – localhost
OR
Help him to display all the records of table emp one by one.
General Instructions:
Please check this question paper contains 35 questions.
The paper is divided into 4 Sections- A, B, C, D and E.
Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
All programming questions are to be answered using Python Language only.
Q.No. Question Marks
SECTION A
1 State True or False: 1
“Variable declaration is implicit in Python.”
2 Which of the following types of table constraints will prevent the entry of 1
duplicate rows?
3 Which of the following is the correct output for the execution of the 1
following Python statement?
print(5 + 3 ** 2 /2)
9 If a=1,b=2 and c= 3 then which statement will give the output as : 2.0 from 1
the following:
a) >>>a%b%c+1
b) >>>a%b%c+1.0
c) >>>a%b%c
d) a%b%c-1
10 import random 1
AR=[20,30,40,50,60,70]
Lower=random.randint(1,3)
Upper=random.randint(2,4)
for K in range(Lower, Upper+1):
print(AR[K], end="#")
11 Which of the following options can be used to read the first line of a text file 1
data.txt?
(a) F=open(‘data.txt’)
F.read()
(b) F=open(‘data.txt’,’r’)
F.read(n)
(c) F=open(‘data.txt’)
F.readline()
(d) F=open(‘data.txt’)
F.readlines()
15 Which function is used to display the total number of records from table in a 1
database?
(a) sum(*) (b) total(*)
(c) count(*) (d) return(*)
16 Fill in the blank 1
Bluetooth is an example of __________
SECTION B
19 How many pair of wires are there in twisted pair cable(Ethernet)?What is the 2
name of port ,which is used to connect Ethernet cable to a computer or a
labtop?
OR
20 Rewrite the following code in python after removing all syntax error(s). 2
Underline each correction done in the code.
250 = Number
WHILE Number<=1000:
if Number=>750:
print(Number)
Number=Number+100
else
print(Number*2)
Number=Number+50
21 Write a function displayCity(CITIES) in Python, that takes the list, CITIES 2
as an argument and displays the names (in uppercase)of the cities whose
names are smaller than 7 characters.
For example, Consider the following list
CITIES=["Delhi","Kolkata","Mumbai","Bangalore","Pune"]
Delhi
Mumbai
Pune
OR
Scores={'Reena':80,'Ajay':50,'Vijay':90,'Geeta':40,'Ritu':80,'Deepak':75}
22 tup = ('geek',) 2
n=5
for i in range(int(n)):
tup = (tup,)
print(tup)
OR
24 Mr. Deepak has just created a table named “Products” containing columns 2
Pcode, Pname, Price and Quantity.
Mistakenly he has taken char datatype for the column “Quantity”. Now he
wants to change datatype for column “Quantity” to integer. Help him in
writing the SQL command to make necessary change in the table “Products”.
Also, write the command to insert the following record in the table:
Pcode- 3345
Pname- Chair
Price: 500
Quantity: 100
OR
SECTION C
26 Msg1="WeLcOME" 3
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print(Msg3)
27 Write output of the following SQL queries on the basis of following table. 3
Table : Hospital
(i) Select * from hospital where pname like ‘M%n’ or pname like ‘%h%’;
(ii) Select PName from hospital where dateofvisit bwteen ‘2018-12-01’ and
‘2019-12-01’ and Gender=’M’;
(iii) Select Pname,Fee from hospital where Fee>200 and gender=’F’;
28 Define a function reverse() that reads the file “poem.txt” and prints the lines 3
of the file in reverse order.
OR
Table : College
No Name Age Department DOJ Basic Sex
1 Shalaz 45 Biology 13-02-88 10500 M
2 Sameera 54 Biology 10-01-90 9500 F
3 Yagyen 43 Physics 27-02-98 8500 M
4 Pratyush 34 Mathematics 22-01-91 8500 M
5 Aren 51 Chemistry 11-01-93 7500 M
6 Reeta 27 Chemistry 14-02-94 9000 F
7 Urvashi 29 Biology 10-02-93 8500 F
8 Teena 35 Mathematics 02-02-89 10500 F
9 Viren 49 Mathematics 03-01-88 9000 M
10 Prakash 22 Physics 17-02-92 8000 M
(i) Write a query to change the Basic salary to 10500 of all those teachers
from college, who joined the college after 01/02/89 and are above the
age of 50
(ii) Write a query to display name and total salary (Basic + 40%of Basic) of
all teachers .
(iii) Write a query to delete the record of Viren from the table.
For example:
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
SECTION D
31 Consider the tables SHOPPE and ACCESSORIES given below: 4
Table: SHOPPE
ID SNAME AREA
S01 ABC Computeronics CP
S02 All Infotech Media GK II
S03 Tech Shoppe CP
S04 Geeks Tecno Soft Nehru Place
S05 Hitech Tech Store Nehru Place
Table : ACCESSORIES
No Name Price Id
A01 Mother Board 12000 S01
A02 Hard Disk 5000 S01
A03 Keyboard 500 S02
A04 Mouse 300 S01
A05 Mother Board 13000 S02
A06 Keyboard 400 S03
A07 LCD 6000 S04
T08 LCD 5500 S05
T09 Mouse 350 S05
T10 Hard Disk 4500 S03
SECTION E
33 Freshminds University of India is starting its first campus Anna Nagar of 5
South India with its centre admission office in Kolkata. The university has
three major blocks comprising of Office Block, Science Block and
Commerce Block in the 5 km area campus.
As a network expert, you need to suggest the network plan as per (i) to (v) to
the authorities keeping in mind the distance and other given parameters.
FRESHMIND
UNIVERSITY
ANNA NAGAR CAMPUS
OFFIC COMMERC
KOLKATA E E
ADMISSIO BLOCK BLOCK
N OFFICE
SCIENCE
BLOCK
Write a function countrec() in Python that would read contents of the file
“STUDENT.DAT” and copy the records of those students whose
percentage is above 75 in the file “ABOVE75.DAT”. Function should
also return the no. of records copied.
OR
i. Which module is imported to read and write data into the binary files?
Also name the methods to read and write data from binary files.
ii. Write a function in python to search and display the details , whose
destination is “Cochin” from binary file “Bus.Dat”. Assuming the binary
file is containing the following elements in the list:
[BusNumber, BusStartingPoint, BusDestination]
OR
General Instructions:
Please check this question paper contains 35 questions.
The paper is divided into 5 Sections- A, B, C, D and E.
Section A, consists of 18 questions (1 to 18). Each question carries 01 Mark each.
Section B, consists of 7 questions (19 to 25). Each question carries 02 Marks each.
Section C, consists of 5 questions (26 to 30). Each question carries 03 Marks each.
Section D, consists of 2 questions (31 to 32). Each question carries 04 Marks each.
Section E, consists of 3 questions (33 to 35). Each question carries 05 Marks each.
All programming questions are to be answered using Python Language only.
SECTION A
1. State True or False. 1
“Identifiers are names used to identify a variable, function.
2. Which of the following is a DDL command?
(a) SELECT (b) ALTER TABLE (c) INSERT INTO (d) UPDATE 1
3. What will be the output of the following statement?
10 > 5 and 7 > 12 or not 18>3 1
4. What will be the output of the following Python Code?
ANIMAL={"dog":10,"tiger":5,"elephant":15,"Cow":3} 1
print("Tiger" not in ANIMAL)
(a) True (b) False (c) Error (d) None
5. What is the degree and cardinality of the following relation?
1
Regno Name Class Date_Admission
10001 Sundar Raj Class XII Science 10/01/2020
10002 Jay Shankar Class X 09/08/2021
10003 Swaroop Rani Class IX 16/12/2016
1004 Jayarani Class XI 23/06/20023
(a) 4, 5 (b) 5, 4 (c) 4, 4 (d) 4, 5
6. --------------- protocol provides access to command line interface on a remote computer. 1
(a) FTP (b) PPP (c) SMTP (d) Telnet
7. Which of the following will delete key-value pair for key = “Red” from a dictionary D1?
(a) delete D1("Red") (b) del D1["Red"] (c) del.D1["Red"] (d) D1.del["Red"] 1
SECTION B
OR
(i) Define the term Protocol with respect to networks.
(ii) How is Hub different from Switch?
20. Rewrite the following code in Python after removing all syntax error(s). Underline each
correction done in the code.
Value=30
for VAL in range(0,Value)
IF val%4==0: 2
print(VAL*4)
Elseif val%5==0:
print(val+3)
else
print(VAL+10)
21. Write a function EOReplace() in Python, which accepts a list L of numbers. Thereafter it
increments all even numbers by 1 and decrement all odd numbers by 1.
2
OR
Write a function CountW(S) in Python to return the number of words in a given string S.
22. What will be the output of the following code? 2
total=20
price=50
def add(a,b):
global price
total=a+b
price=(a+b)/2
print(total,price)
add(6,6)
print(total,price)
23. Write the Python statement for each of the following tasks using BUILT-IN
1+1=
functions/methods only: 2
(i) To insert an element 100 at the Second position, in the list L1.
(ii) To check whether all the characters in the string S1 are digits or not.
OR
How the pop( ) function is different from remove( ) function working withlist in python ?
Explain with example.
Mr.Shyam has created a FLIGHT table with FNO, START, REMARKS, FDATE and FARE
with appropriate data type. Now he wants to delete the attribute REMARKS and to add a 2
24. new column END with string data type and it should not contain NULL value. Please help
Mr.Shyam to complete this task.
OR
SECTION C
26. Predict the output of the following Python Code given below:
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()): 3
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Display('Preboard 2@2023')
27. Consider the table SCHOOL and write the output of the SQL queries given below.
TABLE: SCHOOL
COD TEACHERNAM SUBJ DOJ PERIODS EXPERIENCE
1001 E
RAVI E
SHANKAR ENG E
12/03/2000 24 10
1009 PRIYA RAI PHY C
L
03/09/1998 26 19
1*3=3
1203 LISA ANAND ENG T
I
S
09/04/2000 27 5
1045 YASHRAJ MAT IS
L
24/08/2000 24 15
1123 GANAN PHY H
IC
H
16/07/1999 28 3
1167 HARISH B CHE S
S
19/10/1999 27 5
1215 UMESH PHY IH
M
11/05/1998 22 16
C
I SUBJECT FROM SCHOOL
S
(i) SELECT SUBJECT, SUM (PERIODS),
GROUP BY SUBJECT; IS
ii) SELECT * FROM SCHOOL WHERE EXPERIENCE BETWEEN 12 AND 15;
T
C
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
R
S
Write a function in python to count the number of lines in a text file ‘Country.txt’ which are
Y
28. starting with an alphabet ‘W’ or ‘H’.
For example, If the file contents are as follows:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow. 3
The output of the function should be:
W or w : 1
H or h : 2
OR
Write a user defined function to return the occurrence of the word ‘you’ present in a text file
'Quotes.txt' without using count() function.
For example if the file contents are as follows: Living a life you can be proud of doing
your best Spending your time with people and activities that are important to you Standing
up for things that are right even when it’s hard Becoming the best version of you.
30. Write a function in Python, Push(SItem) where , SItem is a dictionary containing the details
of stationary items– {Sname:price}.
The function should push the names of those items in the stack who have price greater
than 75. Also display the count of elements pushed into the stack.
For example: If the dictionary contains the following data:
3
9 3
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
The stack should contain
Notebook
Pen
The output should be:
The count of elements in the stack is 2
SECTION D
31. Consider the Doctor and Patient table and write the output of (i) to (iv)
Doctor
docid Dname Specializatio Outdoor
n 1*4=4
D1 MANISH PHYSICIAN MONDAY
D2 PARESH EYE FRIDAY
D3 KUMAR ENT SATURDAY
D4 AKASH ENT TUESDAY
Patient
Initially student total field is empty string as example data is given below
2=2=
['1', 'Anil', '40', '34', '90', ''] 4
['2', 'Sohan', '78', '34', '90', '']
['3', 'Kamal', '40', '45', '9', '']
A another file “final.csv” is created which reads records of “result.csv” and copy all
records after calculating total of marks into final.csv. The contents of final.csv should be
['1', 'Anil', '40', '34', '90', '164']
['2', 'Sohan', '78', '34', '90', '202']
['3', 'Kamal', '40', '45', '9', '94']
(a) Define a function createcsv() that will create the result.csv file with the
sample data given above.
(b) Define a function copycsv() that reads the result.csv and copy the same data after
calculating total field into final.csv file.
SECTION E
33. Laxmi Marketing Ltd. has four branches in its campus named Udaipur, Kota, Jodhpur and 1*5=5
Ajmer. Laxmi Marketing Ltd. wants to establish the networking between all the four
offices. A rough layout of the same is as follows:
Udaipur
Office Jodhpur
Office
AjmerO Kota
ffice Office
Approximate distances between these offices as per network survey team are as follows:
Place From Place To Distance
Udaipur Jodhpur 30 m
Jodhpur Kota 40 m
Kota Ajmer 25 m
Udaipur Ajmer 150 m
Jodhpur Ajmer 105 m
Udaipur Kota 60 m
In continuation of the above, the company experts have planned to install the following
number of computers in each of their offices:
Udaipur 40
Jodhpur 80
Kota 200
Ajmer 60
i. Suggest the most suitable place (i.e., Block/Center) to install the server of
this organization with a suitable reason.
ii. Suggest an ideal layout for connecting these blocks/centers for a wired
connectivity.
iii. Which device will you suggest to be placed/installed in each of these
offices to efficiently connect all the computers within these offices?
iv. Suggest the placement of a Repeater in the network with justification.
v The organization is planning to connect its new office in Delhi, which is
more than 1250 km current location. Which type of network out of LAN, MAN, or WAN
will be formed? Justify your answer.
34. (i) Differentiate between rb+ and wb+ file modes in Python.
2+3=
5
(ii) Consider a binary file “employee.dat” containing details such as(empno, ename,
salary) .
Write a python function to display details of those employees who are earning between
20000 and30000 (both values inclusive).
OR
(ii) Write a Python function in Python to search the details of the employees [name,
designation, salary] whose salary is greater than 5000. The records are stored in the file
“emp.dat”. consider each record in the file emp.dat as a list containing name, designation
and salary.
35. (i) How many candidate key and primary key a table can have in a Database? 1+4=
(ii) Manish wants to write a program in Python to create the following table 5
named “EMP” in MYSQL database, ORGANISATION:
Eno (Employee No )- integer
Ename (Employee Name) - string
Edept (Employee Department)-string
Sal (salary)-integer
Note the following to establish connectivity between Python and MySQL:
Username – root , Password – admin , Host - localhost
The values of fields eno, ename, edept and Sal has to be accepted from the user. Help
Manish to write the program in Python to insert record in the above table.
OR
Q. QUESTIONS marks
no
1 State True or False : 1
“In Python, tuple is a mutable data type”.
Answer: FALSE
2 Select the correct output of the code : 1
S = "text#next"
print(S.strip("t"))
(A) ext#nex
(B) ex#nex
(C) text#nex
(D) ext#next
ANS: C) 0.0
ANS: b) MISS#SIPP
6 What will be the output of the following code ? 1
Tuple1=(10,)
Tuple2=Tuple1*2
print(Tuple2)
a) 20
b) (20,)
c) (10,10)
d) Error
ANS: c) (10,10)
ANS: a) 4
8 Select the output of the code: 1
s = “Bring it on”
l = s.split()
s_new = “#”.join([l[0].lower(), l[1], l[2].title()])
print(s_new)
a) bring#it#ON b) bring#it#on
c) Bring#it#On d) bring#it#On
ANS: d) bring#it#On
9 If a table which has one Primary key and two candidate keys. How many Alternate keys will this 1
table have?
(A) 1
(B) 2
(C) 3
(D) 4
ANS: A)1
10 Which of the following modes in Python creates a new file, if file does not exist and overwrites 1
the content, if the file exists ?
(a) r+
(b) r
(c) w
(d) a
ANS: c) w
11 State whether the following statement is True or False: 1
While handling exceptions in python name of the exception has to be compulsorily added with
except clause
ANS: false
12 What will be the output of the following code? 1
c = 10
def add():
global c
c=c+5
print(c,end='#')
add()
c=12
print(c,end='%')
(A) 15%12#
(B) 15%12#
(C) 15#12%
(D) 12%15#
ANS: like
14 Fill in the blank : _________ statement of SQL is used to insert new records in a table. 1
(a) ALTER
(b) UPDATE
(c) INSERT
(d) CREATE
ANS: c) insert
15 In which datatype the value stored is not padded with spaces to fit the specified length, instead it 1
only take up the space they need to store the data.
(A) DATE
(B) VARCHAR
(C) FLOAT
(D) CHAR
ANS: (B) VARCHAR
ANS:b) http
18 Ethernet card is also known as : 1
(a) LIC
(b) NIC
(c) MIC
(d) OIC
ANS: b)NIC
19 Fill in the blank : In _________ switching, before a communication starts, a dedicated path is 1
identified between the sender and the receiver.
(a) Packet
(b) Graph
(c) Circuit
(d) Plot
21 Assertion (A): A SELECT command in SQL can have both WHERE and HAVING clauses. Reasoning 1
(R): WHERE and HAVING clauses are used to check conditions, therefore, these can be used
interchangeably.
SECTION B
22 (i) 1 mark for correct difference 2
(ii) Tuple
1 mark for correct answer
23 (½ x 4 = 2 Marks for each correct operator)
24 (I) A) L1.append(‘maths’) 2
OR
B) L1.sort(reverse=True)
(1 mark for correct answer)
(II) A) L1.pop(0)
OR
B) L1.index(‘cs’)
(1 mark for correct answer)
25 What possible outcome(s) will be produced when the following code is executed? 2
import random
value=random.randint(0,3)
fruit=["APPLE","ORANGE","MANGO","GRAPE"]
for i in range(value):
print(fruit[i],end='##')
a) APPLE##
b) APPLE##ORANGE##
c) APPLE## ORANGE##GRAPE##
d) ORANGE##MANGO##APPLE##
ANS: a) APPLE##
b) APPLE##ORANGE##
OR
i) What is a web browser ?
ii) Define the term Telnet
(1 mark for each correct answer)
SECTION C
29 Write a function in Python to count the number of lines in a text fie ‘EXAM.txt’ which start with 3
an alphabet ‘T’ .
def show():
count=0
f=open("EXAM.txt",'r')
data=f.readlines()
for word in data:
if word[0]==’T’:
count+=1
print(count)
f.close()
(½ mark for correct function header)
(½ mark for correctly opening the file)
(½ mark for correctly reading from the file)
(½ mark for checking the line starts with “T”)
(1/2 mark for correctly counting)
(½ mark for printing the count)
OR
Write a function in Python that count the number of “can” words present in a text file
“DETAILS.txt”
def show():
count=0
f=open("DETAILS.txt ",'r')
data=f.read()
d=data.split()
for word in d:
if word==’can’:
count+=1
print(count)
f.close()
(½ mark for correct function header)
(½ mark for correctly opening the file)
(½ mark for correctly reading from the file)
(½ mark for checking the word can)
(1/2 mark for correctly counting)
(½ mark for printing the count)
30 Thushar received a message(string) that has upper case and lower-case alphabet. He want to 3
extract all the upper case letters separately .Help him to do his task by performing the following
user defined function in Python:
a) Push the upper case alphabets from the string into a STACK
b) Pop and display the content of the stack.
def extract_uppercase_letters(message):
stack = []
for char in message:
if char.isupper():
stack.append(char)
def pop_stack():
while stack:
print(stack.pop(), end=" ")
Or
Consider a list named Nums which contains random integers. Write the following user defined
functions in Python and perform the specified operations on a stack named BigNums.
(i)
PushBig () : It checks every number from the list Nums and pushes all such numbers which have
5 or more digits into the stack, BigNums.
(ii)
PopBig () : It pops the numbers from the stack, BigNums and displays them. The function should
also display "Stack Empty" when there are no more numbers left in the stack.
Ans:
def PushBig(Nums,BigNums):
for N in Nums:
if len(str(N)) >= 5:
BigNums.append(N)
def PopBig(BigNums):
while BigNums:
print(BigNums.pop())
else:
print("Stack Empty")
( No marks for any function header as it was a part of the question)
( ½ Mark for the correct loop in the function PushBig)
( ½ Mark for correctly checking the number of digits in the function PushBig)
( ½ Mark for pushing the correct number into BigNums in the function PushBig)
( ½ Mark for the correct loop in the function PopBig)
( ½ Mark for correctly checking the underflow condition and printing "Stack Empty" in the
function PopBig)
(½ Mark for popping and printing the correct number in the function PopBig)
Note: Ignore the declarations of Nums and/or BigNums
No marks for any function header as it was a part of the question
(2x1½ mark for correct function body;)
or
Predict the output of the following code :
def Total (Num=10):
Sum=0
for C in range(1,Num+1):
if C%2!=0:
continue
Sum+=C
return Sum
print(Total(4),end="$")
print(Total(),end="@")
ANS: 6$30@
(1 ½ mark for each correct value of print) (deduct ½ mark for not printing @$)
SECTION D
32 Consider the table BOOK as given below 4
OR
(B) Write the output:
i. Select Publisher, sum(quantity) as total_quantity from book group by Publisher;
ii. Select Book_name, Author from book where author like '%Kapoor%';
iii. Select * from book where price between 500 and 1000;
iv. Select count(*) from book;
(ii)
Book_name Author_name
Fast Cook Lata Kapoor
(iii)
Book_id Book_name Author_name Publisher Price Quantity
F0001 The Tears William Hopkins First Publ 650 20
F0002 Thunderbolts Anna Roberts First Publ 750 50
(iv) 5
def COUNTR():
f=open(”record.csv",'r')
c=csv.reader(f)
c1=list(c)
cnt=0
for i in c1:
if(i[2]>100000):
cnt+=1
print("No of records in the file:",cnt)
f.close()
(½ mark for opening in the file in right mode)
(½ mark for correctly creating the reader object)
(½ mark for correctly checking the condition)
(½ mark for correctly displaying the count)
34 Aman has been entrusted with the management of some Institution’s Database. He needs 4
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.
Teacher
Posting
(i) To list the names and age of female teachers who are in Mathematics
department.
(ii) To display the name teachers who are posted in Agra
(iii) To display the max(date_to_join), min(date_to_join) of teachers
(iv)
(A) To display name, bonus, department for each teacher where bonus is 10%
of salary
Or
(B) To display the Cartesian Product of these two tables.
Ans:
(i) Select name, age from teacher, posting where teacher.p_id=posting.p_id and
department=’Mathematics’;
(ii) Select name from teacher, posting where teacher.p_id=posting.p_id and
place=’Agra’;
(iii) Select max(date_to_join), min(date_to_join) from teacher;
(iv) Select name, 10/100*salary “Bonus” , department from teacher natural join posting;
(v) Select * from teacher, posting;
35 Arushi has created a table named student in MYSQL database, School: 4
•rno(Roll number )- integer
• name(Name) - string
• clas (Clas) – string
• marks – float
Note the following to establish connectivity between Python and MySQL: • Username - root •
Password - 12345 • Host - localhost
i) Arushi, now wants to add record of student by taking data from user. Help arushi to write the
program in Python.
ii) Also write code to display the total number of records present in the table.
i) S
uggest
the
cable
layout
of
connec
tions
betwee
n the
buildin
gs.
ii)
Sugge
st the
most
suitabl
e place (i.e., building) to house the server of this college, provide a suitable reason.
iii) Is there a requirement of a repeater in the given cable layout? Why/ Why not?
iv) Suggest the placement of hub/switch with justification.
v) The organisation also has inquiry office in another city about 50-60 km away in hilly
region. Suggest the suitable transmission media to interconnect to college and inquiry office
out of the following:
a. Fibre optic cable b. Microwave c. Radio wave
or
What would be your recommendation for enabling live visual communication between the
Admin Office at the Delhi campus and the Mumbai Branch Office from the following
options:
a) Video Conferencing
b) Email
c) Telephony
d) Instant Messaging
ANS: (i)
1 mark for correct layout
(ii) ADMIN Block
as it has
maximum
number of computers. (1 mark for correct answer)
(iii) Repeater can be placed between ADMIN and SENIOR building and ADMIN
and JUNIOR as the distance is more than 100
I mark for placement of repeater in layout
(iv)in all the wings (1 mark for correct answer)
(v) microwave
Or
Video Conferencing
KENDRIYA VIDYALAYA SANGATHAN, CHENNAI REGION
CLASS: XII SESSION: 2024-25
PREBOARD I MARKING SCHEME
COMPUTER SCIENCE (083)
Time allowed: 3 Hours Maximum Marks: 70
27 (I) 2
(A) UNIQUE ,NOT NULL
OR
(B) NOT NULL (PRIMARY KEY CAN BE GIVEN MARK)
(II)
(A) ALTER TABLE flight ADD PRIMARY KEY(F_id);
OR
(B) ALTER TABLE CUSTOMER DROP REMARKS;
28 STAR Adv DisAdv ½ mark each 2
BUS Adv DisAdv ½ mark each
OR
DNS definition 1 mark, IP purpose 1 mark
LOGISTICS
ACCTS
ADMIN
HR
MARKING SCHEME
SECTION-A
1 (D) str 1
2 (C) PYTHON#CKS 1
3 (A) 9 1
4 (A) EN 1
5 (A) 'aeeo' 1
6 (C) (10) 1
7 (A) d['autumn'] 1
8 (B)ceieP0 1
9 (C) Foreign Key 1
10 (C) Seek() 1
11 (B) >=0 1
12 (C) def fun(a=1,b=1,c=2): 1
13 (B) DELETE 1
14 (C) SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM 1
employees);
15 (C) drop database Clients 1
16 (B) COUNT(DISTINCT Col Name) 1
17 (C) SMTP 1
18 (D) Gateway 1
19 (C) alter 1
20 (B) Both A and R are true and R is not the correct explanation for A 1
21 (A) Both A and R are true and R is the correct explanation for A 1
SECTION-B
22 a) LIST 2
b) TUPLE
(1 Mark for each Correct Answer )
23 A. Logical operators: and, or, not 2
(1 mark for correct answer)
B. Membership operators: in, not in
(1 mark for correct answer)
24 PLACES={1: "Delhi", 2: "London"', 3: "Paris", 4: "New York",5: "Dubai "} 2
def countNow (PLACES) :
for place in PLACES.values ():
if len (place) › 5:
print (place. upper ())
countNow (PLACES)
(OR)
# Example usage:
# count_words_in_article()
(½ Mark for function definition , 1 mark for function open & reading, ½ mark for split()
½ mark for count, ½ mark for printing)
OR
def display_success_lines():
try:
with open("Logs.txt", "r") as file:
lines = file.readlines()
for line in lines:
if "success" in line.lower(): # Case-insensitive search
print(line.strip())
except FileNotFoundError:
print("File 'Logs.txt' not found.")
# Example usage:
# display_success_lines()
(½ Mark for function definition , 1 mark for function open & reading, 1 mark for for loop and
condition mark for split() , ½ mark for strip() )
30 travel = [] 3
def Push_element(NList):
for L in NList:
if L[1] != “India” and L[2]<3500:
travel.append(L[0], L[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print(“Stack Empty”)
1 ½ for defining function, checking condition and appending values to list
11/2 marks for using while loop, printing the deleting value and printing stack empty if
stack is empty
OR
1 mark for pushing values into the stack
1 mark for displaying topmost value in the list
1 mark for displaying odd numbers from the list without deleting them and displaying none if no
elements are there
31 (a) 3
4*L
33*4
21*5
10*6
(OR)
(B)
1 #2 #3#
1 #2 #3 #
1#
( 1 mark each for each line of correct output(Maximum 3) )
SECTION-D
32 4
i)
D_NAME
GUPTA
HANEEF
ii)
D_DEPT
ENT
MEDICINE
ORTHO
CARDIOLOGY
SKIN
iii)
EXPERIENC
D_NAME
E
DEEPTI 6
SUMAN 7
JOSEPH 10
GUPTA 12
HANEEF 12
VEENA 12
iv)
Count(*)
3
filename = "WeatherData.csv"
display_hot_cities(filename)
calculate_average_rainfall(filename)
def append_customer_data(customers):
file = open('customers.dat', 'ab')
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
cust_id = int(input("Enter Candidate ID: "))
cust_name = input("Enter Candidate Name: ")
address = input("Enter Designation: ")
receiptno = int(input("Enter receipt no: "))
cust = [cust_id, cust_name, address,receiptno]
pickle.dump(cust, file)
print("Customer data appended successfully.")
file.close()
(II)
import pickle
def update_secunderabad():
file=open('customers.dat', 'rb+')
while True:
try:
pos = file.tell()
customer = pickle.load(file)
if customer[3] == 101:
customer[2] = 'Secunderabad'
file.seek(pos)
pickle.dump(customer, file)
except EOFError FileNotFoundError:
print("No candidate data found or reached end of file.")
break # End of file reached except
print("Customers updated where applicable.")
file.close()
(III)
import pickle
def display_non_sec():
try:
with open('customers.dat', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[2] != 'Secunderabad':
print(candidate)
except EOFError:
break # End of file reached except
FileNotFoundError:
print("No candidate data found. Please add candidates first.")
-------------------
FIRST PRE-BOARD EXAMINATION
(2024-25)
CLASS-12
SUBJECT-COMPUTER SCIENCE (083)
MARKING SCHEME
Time Allowed: 3 hours Maximum Marks: 70
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A has 21 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 04 Short Answer type questions carrying 03 marks each.
6. Section D has 02 Long Answer type questions carrying 05 marks each.
7. Section E has 03 questions carrying 04 marks each.
8. All programming questions are to be answered using Python Language only.
SECTION-A
S.No Question Marks
1 What is the return type of function id? 1
a) int b) float c) bool d) dict
Ans: a) int
2 What error occurs when you execute? 1
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError
Ans: b) NameError
3 Carefully observe the code and give the answer. 1
def example(a):
a = a + '2'
a = a*2
return a
>>>example("hello")
a) indentation Error
b) cannot perform mathematical operation on strings
c) hello2
d) hello2hello2
Ans: a) indentation Error
4 Aryan created a table (Students) with 5 rows and 6 columns. After few days based on the 1
requirement he added 3 more rows to the table. What is the cardinality and degree of the table?
a) cardinality=6,degree=8
b) cardinality=8,degree=6
c) cardinality=5 degree=8
d) None of the above
Ans: b) cardinality=8,degree=6
5 What is the output of the following? 1
print("xyyzxyzxzxyy".count('xyy', 0, 100))
a) 2
b) 0
c) 1
d) error
Ans: a) 2
6 What is the output of the below program? 1
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
Ans: b) count()
20 Assertion(A):Python uses immutable types for call by value mechanism
Reason (R): in the call by value mechanism, the called function makes a separate copy of passed
values and then works with them.
a) Both A and R are wrong
b)A is wrong, but R is right
c)A is right, but R is wrong
d)Both A and B are Right
Ans: d)Both A and B are Right
21 Assertion (A): Python automatically flushes the file buffers before closing a file with close ()
function.
Reason (R): when you open an existing file for writing, it adds the content at the end of the file.
a) Both A and R are wrong
b)A is wrong, but R is right
c)A is right, but R is wrong
d)Both A and B are Right
Ans: c)A is right, but R is wrong
SECTION-B
22 Write the output given by following Python code. 2
x=1
def fun1():
x=3
x=x+1
print(x)
def fun2():
global x
x=x+2
print(x)
fun1()
fun2()
OR
What do you mean by default parameters? Explain with the help of suitable example.
Ans: 4
3
OR
Definition-1
Suitable example-1
23 (i) Write the SQL statement to add a field Country_Code(of type Integer) to the table Countries 1+1
withthe following fields.
Country_id, Country_name, Continent, Region_id
(ii) Which of the following is not a DML command?
DELETE FROM, DROP TABLE, CREATE TABLE, INSERT INTO
Ans: (i) for writing of alter table query-1
(ii) DROP TABLE-1
24 What are the possible outcome(s) executed from the following code? Also specify the maximum 2
and minimum values that can be assigned to variable N.
import random
SIDES=["EAST","WEST","NORTH","SOUTH"]
N=random.randint(1,3)
OUT=""
for I in range (N,1, –1):
OUT=OUT+SIDES[I]
print (OUT)
(i) SOUTHNORTH
(ii) SOUTHNORTHWEST
(iii) SOUTH
(iv) EASTWESTNORTH
Ans: (ii) SOUTHNORTHWEST -1 mark
Maximum value of variable N is 3- ½ mark
Minimum value of variable N is 1- ½ mark
25 Write two points of difference between Bus Topology and Tree Topology. 2
OR
Write two points of difference between Packet Switching and Circuit Switching techniques?
Ans:
BUS TOPOLOGY STAR TOPOLOGY
Bus topology is a topology where each device is connected Star topology is a topology in which all
to a single cable which is known as the backbone. devices are connected to a central hub
In a Bus topology, the failure of the network cable will In star topology, if the central hub fails then
cause the whole network to fail. the whole network fails.
In a bus topology, there is a linear arrangement of nodes in In star topology, there is a non-linear
a network. arrangement of nodes in a network.
OR
DOMAIN OF
CIRCUIT SWITCHING PACKET SWITCHING
COMPARISON
Finds maximum usage in voice-over It has wide utility in the field of data
Utility
or telephonic communication. transmission over networks.
26 2
Write the output of the queries (a) to (d) based on the table SCHOOLADMINgiven below:
a) SELECT max (DOB) FROM SCHOOLADMIN;
b) SELECT Name FROM SCHOOLADMIN WHERE STREAM<>"Business Admin" AND
SECTION IS NULL;
c) SELECT count (NAME) FROM SCHOOLADMIN WHERE SECTION IS NOT NULL;
d) SELECT count (NAME) FROM SCHOOLADMIN WHERE SECTION IS NOT NULL AND
STREAM="FINE ARTS";
Ans: a)Max(DOB)
2005-05-12
b)empty set
c)count(name)
5
d)count(name)
2
27 Rewrite the following Python program after removing all the syntactical errors (if any), 2
underlining each correction:
def checkval:
x = input(“Enter a number”)
if x % 2 = 0:
print x,”is even”
else if x<0:
print x,”should be positive”
else;
print x,”is odd”
Ans: def checkval:
x = int(input(“Enter a number”))
if x % 2 == 0:
print (x,”is even” )
elif x<0:
print( x,”should be positive”)
else:
print( x,”is odd”)
28 (a) What is the output produced by the following code – 1
d1={“b”:[6,7,8],”a”:(1,2,3)}
print(d1.values())
a) { (1,2,3) , [6,7,8] }
b) [[6,7,8],(1,2,3)]
c)[6,7,8,1,2,3]
d) (“b”, “a”)
(b) What is the output of given program code: list1 = range(100,110) 1
print( list1.index(105))
(a) 4 (b) 5 (c) 6 (d) Error
Ans: (b)[[6,7,8],(1,2,3)]
(b) 5
SECTION-C
29 (a)Write a function in python to count the number of lines in “POEM.txt” begins from Upper case 3
character.
OR
Write a function in python to read lines from file “POEM.txt” and count how many times the word
“INDIA” exists in file.
Ans: for function header- ½ mark
for body of the function(including opening of the file,logic) -1 ½ mark
closing of the file- ½ mark
30 Write a function in Python PUSH(Num), where Num is a list of integer numbers. From this list 3
push all positive even numbers into a stack implemented by using a list. Display the stack if it has
at least one element, otherwise display appropriate error message.
OR
Write a function in Python POP(cities), where cities is a stack implemented by a list of city names
for eg. cities=[‘Delhi’, ’Jaipur’, ‘Mumbai’, ‘Nagpur’]. The function returns the value deleted from
the stack.
Ans: For writing of the push function with all syntax and correct logic-3 marks
31 (a)Sonal needs to display name of teachers, who have “0” as the third character in their name. She 1
wrote the following query.
SELECT NAME FROM TEACHER WHERE NAME = “$$0?”;
But the query is’nt producing the result. Identify the problem.
(b)Write output for (i) & (iv) based on table COMPANY and CUSTOMER.
ii. 50000,70000
iii.11
iv.
32 Write a function EVEN_LIST(L), where L is the list of elements passed as argument to the 3
function. The function returns another list named ‘evenList’ that stores the indices of all even
numbers of L.
For example:
If L contains [12,4,3,11,13,56]
The evenList will have - [0,1,5]
Ans: def EVEN_LIST(L):
evenList=[]
for i in L:
if i%2==0:
evenList.append(i)
return(evenList)
SECTION-D
33 Write a python program to create a csv file dvd.csv and write 10 records in it with the following 5
details: Dvdid, dvd name, qty, price.
Display those dvd details whose dvd price is more than 25.
Ans: import csv
f=open("pl.csv","w")
cw=csv.writer(f)
ch="Y"
while ch=="Y":
l=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty "))
p=int(input("enter price(in rupees) "))
l.append(pi)
l.append(pnm)
l.append(sp)
l.append(p)
cw.writerow(l)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.csv","r+")
cw=list(csv.reader(f))
for i in cw:
if l[3]>25:
print(i)
f.close()
34 Consider the tables below to write SQL Queries for the following:
i.To display TEACHERNAME, PERIODS of all teachers whose periods are more than 25.
ii.To display all the information from the table SCHOOL in descending order of experience.
iii. To display DESIGNATION without duplicate entries from the table ADMIN.
iv. To display TEACHERNAME, CODE and corresponding DESIGNATION from tables
SCHOOL and ADMIN of Male teachers.
Ans:
SECTION-E
35 Perfect Edu Services Ltd. is an educational organization. It is planning to setup its India campus at Chennai
with its head office at Delhi. The Chennai campus has 4 main buildings – ADMIN, ENGINEERING,
BUSINESS and MEDIA.
You as a network expert have to suggest the best network related solutions for their problems raised in (i) to
(v), keeping in mind the distances between the buildings and other given parameters.
(i) Suggest the most appropriate location of the server inside the CHENNAI campus (out of the 4
buildings), to get the best connectivity for maximum no. of computers. Justify your answer.
(ii) Suggest and draw the cable layout to efficiently connect various buildings within the
CHENNAI campus for connecting the computers.
(iii) Which hardware device will you suggest to be procured by the company to be installed to
protect and control the internet uses within the campus ?
(iv) Which of the following will you suggest to establish the online face-to-face communication
between the people in the Admin Office of CHENNAI campus and DELHI Head Office ?
(a) Cable TV
(b) Email
(c) Video Conferencing
(d) Text Chat
(v) Name protocols used to send and receive emails between CHENNAI and DELHI office?
(i)admin; it contains the max number of systems. to reduce traffic
(ii)
(iii)firewall
(iv) (c) Video Conferencing
(v) POP and SMTP
36 A binary file “STOCK.DAT” has structure [ITEMID, ITEMNAME, QUANTITY, PRICE]. 5
(i) Write a user defined function MakeFile( )to input data for a record and add to Book.dat.
(ii) Write a function GetPrice(ITEMID) in Python which accepts the ITEMID as parameter and
return PRICE of the Item stored in Binary file STOCK.DAT.
OR
A binary file “EMPLOYEE.DAT” has structure (EMPID, EMPNAME, SALARY). Write a
function CountRec( )in Python that would read contents of the file “EMPLOYEE.DAT” and
display the details of those Employees whose Salary is above 20000. Also display number of
employees having Salary more than 20000.
Ans: For function MakeFile()-2 marks
For function GetPrice()-3 marks
37 (a)Write the outputs of the SQL queries (i) to (ii) based on relations EMP and DESIG given
below:
Table: EMP
E_ID Name Gender Age DOJ Designation
1 Om Prakash M 35 10/11/2009 Manager
2 Jai Kishan M 32 12/05/2013 Accountant
3 Shreya Sharma F 30 05/02/2015 Clerk
4 Rakesh Minhas M 40 15/05/2007 Manager
5 Himani Singh F 33 19/09/2010 Clerk
Table: DESIG
Salary E_ID DEPT_ID
45000 1 D101
35000 2 D102
45000 4 D101
(i) SELECT Designation, count(*) FROM EMP GROUP BY Designation;
(ii) SELECTEMP.Name,EMP.Designation,DESIG.Salary FROM EMP,DESIG WHERE
EMP.E_ID = DESIG.E_ID AND EMP.Age>35;
(b)
Note the following to establish connectivity between Python and MYSQL:
• Username is root
• Password is root@123
• The table exists in a MYSQL database named management.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those employees whose salary are greater
than 53500.
Statement 3- to read the complete result of the query (records whose salary are greater than 53500)
into the object named data, from the table employee in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",password="root@123",
database="management")
mycursor=_______________ #Statement 1
print("Employees with salary greater than 53500 are : ")
_________________________ #Statement2
data=__________________ #Statement 3
for i in data:
print(i)
print()
Ans:
(a) For each output of the query 1 mark
(b)
Statement 1: con1.cursor()
Statement 2: mycursor.execute("select * from student where Marks>75")
Statement 3: mycursor.fetchall()
KENDRIYA VIDYALAYA SANGATHAN
JAIPUR REGION
PRACTICE PAPER-I
CLASS XII
SUBJECT: COMPUTER SCIENCE (083)
Time allowed: 3 Hours Maximum Marks: 70
MARKING SCHEME
31 Based on the given table, write SQL queries for the following:
(i) Select * from activity where prizemoney >=9000;
(ii) Update activity set prizemoney=prizemoney*1.05
where scheduledate>’2004-03-01’;
(iii) Delete from activity where participantsnum<12
SECTION-D
32 import math 4
try:
result = math.pow(2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)
try:
result = math.sqrt(9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)
33 import csv 4
f=open("pl.csv","w")
cw=csv.writer(f)
ch="Y"
while ch=="Y":
l=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty ")) p=int(input("enter
price(in rupees)"))
l.append(pi)
l.append(pnm)
l.append(sp)
l.append(p)
cw.writerow(l)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.csv","r+")
cw=list(csv.reader(f))
for i in cw:
if l[3]>25:
print(i)
f.close()
34
i. SELECT DISTINCT Qty FROM garment;
ii. SELECT SUM(Qty) FROM garment GROUP BY CCode
HAVING COUNT(*)>1;
iii. SELECT GNAME, CNAME, RATE from garment g, cloth c
WHERE g.ccode=c.ccode AND Qty>100;
iv. Select AVG(Rate) FROM garment
WHERE rate BETWEEN 1000 AND 2000;
35 (i) import mysql.connector 4
mycon=mysql.connector.connect(host=’localhost’,
user=’root’, passwd=’KVS@123’,databse=’KV’)
mycur=mycon.cursor()
fn=input(“Enter flight number”) s=input(“Enter
source’)
d=input(“Enter Destination”) f=int(input(“Enter
fare of flight”))
query=”insert into flight values(‘{}’,’{}’, ‘{}’,{}).format(fn,s,d,f)
mycur.execute(query)
mycon.commit()
print(“Data added successfully”)
mycon.close()
½ mark for importing correct module 1 mark for correct connect() ½ mark for
correctly accepting the input 1 ½ mark for correctly executing the query ½ mark
for correctly using commit() )
OR
(i) import mysql.connector
mycon=mysql.connector.connect(host=’localhost’,
user=’root’, passwd=’KVS@123’,databse=’Sports’)
mycur=mycon.cursor()
query=”select * from game
where No_of_Participants>{}”.format(10) mycur.execute(query)
data=mycur.fetchall()
for rec in data:
print(rec)
mycon.close()
(½ mark for importing correct module 1 mark for correct connect()
1 mark for correctly executing the query ½ mark for correctly using fetchall()
1 mark for correctly [15] displaying data)
SECTION - E
36 def Insert(): 5
L=[]
while True:
ClockID = input("Enter Clock ID = ")
ClockName = input("Enter Clock Name = ")
YearofManf = int(input("Enter Year of Manufacture = "))
price = float(input("Enter Price = "))
R = [ClockID, ClockName, YearofManf, price]
L.append(R)
ans = input("Do you want to enter more records (Y/N)=")
if ans.upper()=='N':
break
import csv
fout = open('watch.csv','a',newline='')
W = csv.writer(fout)
W.writerows(L)
fout.close()
print("Records successfully saved")
def Delete():
ClockID = input("Enter Clock ID to be removed = ")
found = False
import csv
fin = open('watch.csv','r')
R = csv.reader(fin)
L = list(R)
fin.close()
for i in L:
If i[0]==ClockID:
found=True
print("Record to be removed is:")
print(i)
Remove(i)
break
if found==False:
print("Record not found")
else:
fout = open('watch.csv','w',newline='')
W = csv.writer(fout)
W.writerows(L)
fout.close()
print("Record Successfully Removed")
Insert() function
½ mark for correct data input and making list
½ mark for correctly opening file
1½ mark for correctly writing
record Delete() function
½ mark for correctly copying data in list
½ mark for correctly identifying record and removing it from the list
½ mark for correctly showing not found message
1 mark for correctly re-writing remaining records
37 a. The most suitable building to house the server is ADMIN building because 1*5=5
it has maximum number of computers and as per 80:20 rule this building
will have the maximum amount of network traffic.
½ mark for correct answer
½ mark for correct justification
b.
1 mark for correct diagram
c. iii. Video Conferencing
1 mark for correct diagram
d.
i. Switch/Hub will be placed in every building to provide network
connectivity to all devices inside the building.
ii. Repeater will not be required as there is not cable running for
more than 100 meters.
½ mark each for each correct reason
e. The device/software that can be installed for data security and to
protect unauthorized access is Firewall.
Or
WAN
1 mark for correct answer
Kendriya Vidyalaya Sangathan, Jaipur Region
Practice paper-3
Class: XII Subject: Computer Science (083)
Maximum Marks: 70 Period: 3 Hours
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 the case of MCQ, the text of the correct answer should also be written.
newt=lshift((1,2,3,4,5,6),13)
print(newt)
(1 mark for each correction)
27 (i) 2
(A) Unique
OR
(B) Default
(ii)
(A) ALTER TABLE STUDENT DROP PRIMARY KEY;
OR
(B) ALTER TABLE STUDENT ADD PRIMARY KEY(RNO);
(1 mark each)
28 Advantage: 2
Hierarchical connection between the nodes.
Disadvantage:
Less reliable than star and mesh.
(1 mark each)
OR
TELNET : Teletype Network Telnet is a network protocol used to virtually access a
computer and provide a two-way, collaborative and text-based communication
channel between two machines. It follows a user command TCP/IP networking
protocol that creates remote sessions.
(1 mark for expansion and 1 mark for use)
def pop_star(StarStudent):
if StarStudent:
return StarStudent.pop()
else:
print("Underflow")
def peek_star(StarStudent):
if StarStudent:
return StarStudent[-1]
else:
print("None")
(1 mark for each correct function definition)
OR
(B)
pos_int=[ ]
def push_positive(N):
for i in N:
if i>0:
pos_int.append(i)
def pop_positive():
if pos_int:
return pos_int.pop()
else:
print("Empty")
def disp_positive():
for i in range(-len(pos_int),0,-1):
print(pos_int[i], end=“ ”)
else:
print("None")
(1 mark for each correct function definition)
31 Shoes10# 3
Gloves20#
Jackets15#
(1 mark for each correct output)
OR
1#
4# 3# 2# 1#
2# 1#
2# 1#
4# 3# 2# 1#
1#
(1/2 mark for each correct output)
OR
(B) Write a Python program to check if a string is a palindrome (reads the same
backward as forward). The string should be entered by the user.
Ans.
def is_palindrome(text):
processed_text = text[::-1]
return processed_text
Ans.
def add_product(RecentlyViewed, new_product):
RecentlyViewed.append(new_product)
def remove_product(RecentlyViewed):
if RecentlyViewed:
return RecentlyViewed.pop()
else:
print("No products recently viewed.")
def show_latest_product(RecentlyViewed):
if RecentlyViewed:
print(RecentlyViewed[-1])
else:
print("No products recently viewed.")
OR
(B)
A hospital is managing patient data using a stack-based system. Patient records
are initially stored in a list. Each record is a tuple containing (patient_id, age,
priority_level). Priority levels are integers, with higher numbers representing
higher priority.
(I) Create a list named patients containing the following patient records:
(101, 65, 2), (102, 32, 4), (103, 78, 1), (104, 45, 3), (105, 52, 5), (106, 28, 2)
(II) Write the definition of a user-defined function push_high_priority(patients,
priority_threshold). It should push only those patient records with a priority level
greater than or equal to the priority_threshold onto a stack called
high_priority_patients.
(III) Write a function get_high_priority() to display all elements of the
high_priority_patients stack while deleting them one by one. If the stack is empty,
the function should display No high-priority patients.
Ans.
# (I) Create the list of patient records
patients = [(101, 65, 2), (102, 32, 4), (103, 78, 1), (104, 45, 3),
(105, 52, 5), (106, 28, 2)]
(ii) Display all data separated by Department and in decreasing order of Salary:
SELECT * FROM Faculty ORDER BY Department, Salary DESC;
OR
(B)
(i) Display Gender wise average salary of those faculties with average salary more
than 90000:
SELECT Gender, AVG(Salary) as AvgSalary FROM Faculty
GROUP BY Gender HAVING AVG(Salary) > 90000;
(ii) Display FName and F_ID of faculties having the string 'ta' in the Fname:
SELECT FName, F_ID FROM Faculty WHERE FName LIKE '%ta%';
(ii) process_data("abc")
Output:
Invalid input: Not an integer.
Data processing complete.
(iii) process_data(50)
Output:
Value is not greater than 100.
Data processing complete.
33 A librarian is managing book inventory using a CSV file named `Inventory.csv`. 4
The file structure is: `[BookID, Title, Author, Available]` where `BookID` is an
integer, `Title` and `Author` are strings, and `Available` is an integer representing
the number of copies available.
The librarian needs to write the following functions:
- add_book(): This function accepts new book details from the user and adds
them to `Inventory.csv`. The file should be created with column headers if it
doesn't exist.
- check_availability(book_id): This function takes a `book_id` as input and
returns the number of copies available for that book. If the book is not
found, it should return -1.
Ans.
import csv
import os
def add_book():
file_exists = os.path.isfile('Inventory.csv')
with open('Inventory.csv', 'a', newline='') as file:
writer = csv.writer(file)
if not file_exists:
writer.writerow(['BookID', 'Title', 'Author', 'Available'])
book_id = input("Enter BookID: ")
title = input("Enter Title: ")
author = input("Enter Author: ")
available = input("Enter number of copies available: ")
writer.writerow([book_id, title, author, available])
print("Book added successfully!")
def check_availability(book_id):
try:
with open('Inventory.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
if row['BookID'] == str(book_id):
return int(row['Available'])
except FileNotFoundError:
print("Inventory file not found.")
return -1
34 Give output of the following queries as per given table(s): 4
WORKER
WID WNAME JOB SALARY DNO
1001 RAHUL SHARMA CLERK 15000 D03
1002 MUKESH VYAS ELECTRICIAN 11000 D01
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
DEPT
DNO DNAME LOC MANAGER
D01 PRODUCTION GROUND FLOOR
D K JAIN
D02 ACCOUNTS 1ST FLOOR
S ARORA
D03 SECURITY 1ST FLOOR
R K SINGH
Ans.
(i) SELECT DISTINCT JOB FROM WORKER;
JOB
----
CLERK
ELECTRICIAN
FITTER
GUARD
(ii) SELECT DNAME, LOC FROM DEPT WHERE DNO IN (SELECT DNO FROM
WORKER WHERE SALARY > 10000);
DNAME LOC
----------- ------------
PRODUCTION GROUND FLOOR
SECURITY 1ST FLOOR
(iii) SELECT W.WNAME, D.MANAGER
FROM WORKER AS W, DEPT AS D
WHERE W.DNO = D.DNO;
WNAME MANAGER
------------- ---------
RAHUL SHARMA R K SINGH
MUKESH VYAS D K JAIN
SURESH S ARORA
ANKUR D K JAIN
(iv) SELECT WNAME FROM WORKER WHERE WNAME LIKE 'R%';
WNAME
-------------
RAHUL SHARMA
35 A table named Products in a database named Inventory stores information about 4
products. The table has the following columns: ProductID (integer, primary key),
ProductName (string), Price (float), and Quantity (integer). Assume the database
username is 'admin' and the password is 'secure123'.
Write a Python code that prompts the user to enter a ProductID and updates the
Quantity of that product by adding 10 to the existing quantity. Handle any potential
errors (e.g., the product ID not existing in the table).
Ans.
import mysql.connector
from mysql.connector import Error
def update_product_quantity(product_id):
try:
connection = mysql.connector.connect(
host="localhost",
database="Inventory",
user="admin",
password="secure123" )
if connection.is_connected():
cursor = connection.cursor()
cursor.execute("SELECT Quantity FROM Products
WHERE ProductID = %s", (product_id,))
result = cursor.fetchone()
if result:
current_quantity = result[0]
new_quantity = current_quantity + 10
update_query = "UPDATE Products SET Quantity = %s
WHERE ProductID = %s"
cursor.execute(update_query, (new_quantity, product_id))
connection.commit()
print(f"updated successfully. New quantity: {new_quantity}")
else:
print("Product not found.")
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
Ans.
import pickle
(i) Write a function `add_order()` to input order details from the user (order_id,
customer_name, order_date, total_amount) and store them in "Orders.dat". The
program should allow adding multiple orders until the user chooses to stop.
def add_order():
orders = []
try:
with open("Orders.dat", "rb") as file:
orders = pickle.load(file)
except FileNotFoundError:
pass
while True:
order_id = input("Enter order ID: ")
customer_name = input("Enter customer name: ")
order_date = input("Enter order date (YYYY-MM-DD): ")
total_amount = float(input("Enter total amount: "))
SECTION-A(1*21=21 MARKS)
QN Answer of Question
1. Ans. True, as continue keyword skips remaining part of an iteration in a 1
loop.
2. Ans. (c) “uter”, as it counts from 4 index to last index 1
3. Ans: (b) True, as firstly “not” performed then “And” performed and at last 1
“Or” performed.
True or not True and False
True or False and False
True or False
True
4. Ans. (d) dict_student.update(dict_marks), as we use update method for 1
dictionary merging with syntax dict1.update(dict2)
5. Ans. (b) tuple, as Elements enclosed in parentheses( ) represents by 1
tuple.
6. Ans: (d) (40,60), as this expression will slice the given tuple starting with 1
index position 3 and selecting every second element till index number 7.
7. Ans. (c) None, as it is empty value. 1
8. Ans. (c) 512, as 2**3**2= 2**9=512 is the answer. 1
9. Ans. (b) Statement 4, as string’s individual element can’t assigned new 1
value so S[0]= '@' # Statement 4 give error.
10. Ans. (c) F=open(‘Notes.txt’) 1
print(F.read(10))
As read method in python is used to read at most n bytes from the file
associated with the given file descriptor. If the end of the file has been
reached while reading bytes from the given file descriptor, os.read( )
method will return an empty bytes object for all bytes left to be read.
11. Ans. (a) Pickling, as pickling is used for object serialization in handling 1
of Binary Files.
12. Ans. (d) n is local and x is global variable 1
As n is defined within function body and x is defined outside the function
body.
13. Alter- Add command is used to add a new column in table in SQL. 1
14. Ans. (b) DISTNICT, as DISTNICT Keyword is used to obtain Non- 1
duplicated values in a SELECT query.
15. Ans. (c) sum( ), as it’s used for summation of numeric values in a 1
column.
16. Ans. (a) Mycur.fetch(), as it’s not a valid method for fetching. 1
17. Ans. (c) Both Modualtion & Demodulation, as MODEM does both 1
tasks.
18. Ans. (c) HomePage, as it is the first page that normally view at a 1
website.
19. Ans: Topology is the way of connecting the networking devices. 1
20. Ans: (a) Both A and R are true and R is the correct explanation for A 1
As global variables are accessed anywhere in the program and local
variables are accessed only within the boundary of loop/ condition/
function.
1|Page
21. Ans: b) Both A and R are true and R is not the correct explanation for A 1
Invalid identifier(s)
(ii) @selute (iii) Que$tion (v) 4th Sem (vii) No#
As identifier(s) name does not have any special character except
underscore. Name should not start with digit and not any space is there
in name.
23 i) Names of any two data types available in python: int, float or any other 1+1
. valid datatype in python. =2
ii) Any 2 operators name used in python: Arithmetic, Logical, Relational
or any other valid operator in python.
24 (i)A) str="PYTHON@LANGUAGE" 2
. print(str[2: : ])
OR
B) d=dict( )
(ii)A) s=”LANGUAGE"
l=list(s)
OR
B) t=tuple( )
25 Lower = r.randint(1,3) means Lower will have value 1,2, or 3 2
. Upper =r.randint(2,4) means Upper will have value 2, 3, or 4
So K will be from (1, 2, 3) to (2, 3, 4)
Means if K=1, then upper limit (2,3,4)
If K=2, then upper limit (2,3,4)
If K=3, then upper limit (2,3,4)
So correct answer (ii) 30#40#50#
Maximum values of variables Lower and Upper are 3 and 4.
26 COUNT(*) returns the count of all rows in the table, 2
. whereas COUNT (COLUMN_NAME) is used with Column_Name
passed as argument and counts the number of non-NULL values in
the particular column that is given as argument.
Example:
A MySQL table, sales have 10 rows with many columns, one column
name is DISCOUNT.
This DISCOUNT column has 6 valid values and 4 empty/ null
values. When we run the Following queries on sales table.
SELECT COUNT(*)
FROM sales;
COUNT(*)
10
SELECT
COUNT(DISCOUNT)
FROM sales;
COUNT( DISCOUNT )
6
As in table, there are 10 rows so count(*) gives 10 and discount
column is having 6 valid values with 4 NULL values so it gives 6.
27 i) 1+1
2|Page
. A) Default constraint should be applied on a table’s column to provide =2
it the default value when column does not have any value.
OR
B) Unique constraint should be applied on a table’s column so that
NULL value is allowed in that column and duplicate values are not
allowed.
ii)
A)
SQL command to add one more column in previously defined table,
named CELL. Column name is CELL_ID with size 10 of integral
type should be added in the table
Alter table CELL
ADD CELL_ID(10) int;
OR
DROP table CELL;
28 (A) VOIP-Voice Over Internet Protocol 2
. Utility-VoIP is used to transfer audio (voice) and video over internet
URL- Uniform Resource Locator
Utility-Place for typing website names in web browser.
OR
(B)
IP Address MAC Address
Internet Protocol Address Media Access Control Address
It is 4 bytes address in IPV4 and It is 6 bytes address.
6 bytes address in IPV6
Or any other valid difference between the two.
(1 mark for ANY ONE difference)
SECTION-C (3*3= 9 Marks)
29 A) 3
. def countlines_et():
f=open("report.txt",'r')
lines=f.readlines()
linee=0
linet=0
for i in lines:
if i[0]=='E':
linee+=1
elif i[0]=='T':
linet+=1
print("No.of Lines with E:",linee)
print("No.of Lines with T:",linet)
countlines_et()
OR
B)
def show_todo():
f=open("abc.txt",'r')
lines=f.readlines()
for i in lines:
if "TO" in i or "DO" in i:
print(i)
show_todo()
30 A) 3
.
3|Page
data = [1,2,3,4,5,6,7,8]
stack = []
def push(stack, data):
for x in data:
if x % 2 == 0:
stack.append(x)
def pop(stack):
if len(stack)==0:
return "stack empty"
else:
return stack.pop()
push(stack,Data)
print(pop(stack)
(½ mark should be deducted for all incorrect syntax. Full marks to
be awarded for any other logic that produces the correct result.)
OR
B)
def push(EventDetails):
BigEvents=[]
count=0
for i in EventDetails:
if EventDetails[i]>200:
BigEvents.append(i)
count+=1
print(“The count of elements in the stack is”,count)
def pop(EventDetails):
if len(EventDetails)==0:
return "Dictionary is empty"
else:
return EventDetails.pop()
push(EventDetails)
print(pop(EventDetails))
(½ mark should be deducted for all incorrect syntax. Full marks to
be awarded for any other logic that produces the correct result.)
31 A) 1*3
(i) SELECT EMP_NAME, BASIC+DA+HRA+NPS AS “GROSS =3
SALARY” FROM EMPLOYEE;
(ii)UPDATE EMPLOYEE SET DA=DA+0.03*BASIC;
(iii)ALTER TABLE EMPLOYEE DROP COLUMN EMP_DESIG;
OR
B)
(i) SELECT COUNT(*) FROM EMPLOYEE;
(ii) SELECT * FROM EMPLOYEE ORDER BY basic desc;
(iii) SELECT SUM(hra) FROM EMPLOYEE;
SECTION-D (4*4= 16 Marks)
32 A) 1+3
. i) When the value passed in the index operator is greater than the actual =4
size of the tuple or list, Index Out of Range is thrown by python.
ii)
value=[1,2,3,4]
data=0
try:
data=value[4]
4|Page
except IndexError:
print(“list index out of range is not allowed”, end=’’)
except:
print(“Some Error occurred”, end=’’)
OR
B)
i) When the division or modulo by zero takes place for all numeric types,
ZeroDivisionError Exception is thrown by python.
ii)
def division(x,y):
try:
div=x/y
print(div, end=’’)
except ZeroDivisionError as e:
print(“ ZeroDivisionError Exception occured”, e, end=’’)
except:
print(“Some Error occurred”, end=’’)
33 import csv 2+2
. def AddNewRec(Country,Capital): =4
f=open(“CAPITAL.CSV”,’a’)
fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
f.close()
def ShowRec():
with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv.reader(NF)
for rec in NewReader:
print(rec[0],rec[1])
AddNewRec(“INDIA”, ”NEW DELHI”)
AddNewRec(“CHINA”, ”BEIJING”)
ShowRec()
Output:
INDIA NEW DELHI
C H I N A B E I J IN G
34 i)SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY 1*4
. SUBJECT ; =4
DEVELOPMENT HUMANRESOURCE
PMENT
LOGISTICS ADM
iii) (a) Switches in all the blocks since the computers need to be
connected to the network.
(b) Repeaters between ADM and HUMANRESOURCE block & ADM
and Logistics block. The reason being the distance is more than 100m.
iv) Modem should be placed in the Server building
v) (c)OFC-Optical Fiber cable, this connection is high-speed wired
communication medium.
OR LAN will be set up among computers connected in Campus.
6|Page
MARKING SCHEME OF 1st PREBOARD ( KVS RO KOLKATA )
2024-25 ( COMPUTER SCIENCE)
Time allowed: 3 Hours Maximum 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 ( No marks should be
provided if student does not write the correct choice )
Ans : True
2. What id the output of following code snippet?
Ans : A ) GL-BALNETW-RK
3. Identify the output of the following code snippet:
text = "The_quick_brown_fox"
index = text.find("quick")
(1)
result = text[:index].replace("_", "") + text[index:].upper()
print(result)
(A) Thequick_brown_fox
(B) TheQUICK_BROWN_FOX
(C) TheQUICKBROWNFOX
(D) TheQUICKBROWN_FOX
Page: 1/21
Ans : (B) TheQUICK_BROWN_FOX
(A) 0
(B) -5
(C) 65
(D) 265
Ans : ( C ) 65
What will be the output of the following code snippet?
5.
(1)
text = "Python Programming"
print(text[1 : :3])
(A) Ph oai
(B) yoPgmn
(C) yhnPormig
(D) Pto rgamn
Ans : (B)
Ans : C )
7. Dictionary my_dict as defined below, identify type of error raised by statement
my_dict['grape']?
my_dict = {'apple': 10, 'banana': 20, 'orange': 30}
ValueError (1)
(B) TypeError
(C) KeyError
(D) ValueError
Ans : (C) KeyError
Page: 2/21
What does the list.pop(x) method do in Python?
8.
Ans : B. Removes the element at index x from the list and returns it.
In a relational database table with one primary key and three unique
9. constraints defined on different columns (not primary), how many candidate
keys can be derived from this configuration?
(1)
(A) 1
(B) 3
(C) 4
(D) 2
Ans : C) 4
10. Fill in the blanks to complete the following code snippet choosing the
correct option:
(A) tell
(B) seek
(C) read
(D) write
Ans : False
Page: 3/21
12. What will be the output of the following code?
x=4
def reset():
global x
x=2
print(x, end='&')
def update(): (1)
x += 3
print(x, end='@')
update()
x=6
reset()
print(x, end='$')
(A) 7@2&6$
(B) 7@6&6$
(C) 7@2&2$
(D) Error
Ans : (D) Error : Unbound local variable x in function update()
Which SQL command can modify the structure of an existing table, such as
13. adding or removing columns? (1)
Page: 4/21
16. Which of the following aggregate functions can be employed to determine
the number of unique entries in a specific column, effectively ignoring
duplicates?
(1)
(A) SUM()
(B) COUNT()
(C) AVG()
(D) COUNT(DISTINCT column_name)
Ans : (D) COUNT(DISTINCT column_name)
Ans : (B) Both A and R are true and R is not the correct explanantion
for A
Assertion (A): A GROUP BY clause in SQL can be used without any
21.
aggregate functions.
Reasoning (R): The GROUP BY clause is used to group rows that have the (1)
same values in specified columns and must always be paired
with aggregate functions.
Page: 5/21
Ans : ( C ) A is True , but R is False
( 1 marks + 1 Marks )
Ans :
Page: 6/21
If L1 = [10, 20, 30, 40, 20, 10, ...] and L2 = [5, 15, 25, ...], then:
24.
(Answer using builtin functions only)
II (A) : L1.extend(L2)
(B) : unique_elements = list(set(L1))
Page: 7/21
26. The code provided below is intended to reverse the order of elements in a
given list. However, there are syntax and logical errors in the code. Rewrite
it after removing all errors. Underline all the corrections made.
def reverse_list(lst)
if not lst:
return lst (2)
reversed_lst = lst[::-1]
return reversed_lst
print("Reversed list: " reverse_list[1,2,3,4] )
27. (I)
A) What constraint should be applied to a table column to ensure that all
values in that column must be unique and not NULL?
OR
B) What constraint should be applied to a table column to ensure that it can
have multiple NULL values but cannot have any duplicate non-NULL (2)
values?
(II)
A) Write an SQL command to drop the unique constraint named
unique_email from a column named email in a table called Users.
OR
B) Write an SQL command to add a unique constraint to the email column
of an existing table named Users, ensuring that all email addresses are
unique.
Ans : (I)(A): Use the UNIQUE constraint along with the NOT NULL OR
PRIMARY KEY constraint.
OR
(B): Use the UNIQUE constraint alone, allowing for multiple NULL
values.
Example: column_name INT UNIQUE NULL
( 1 mark each for correct part for each questions any correct example
as an answer is acceptable )
Page: 8/21
28. A) Explain one advantage and one disadvantage of mesh topology in
computer networks.
OR (2)
B) Expand the term DNS. What role does DNS play in the functioning of the
Internet?
Ans :
(A): Advantage of Mesh Topology: High redundancy; if one connection
fails, data can still be transmitted through other nodes.
Disadvantage of Mesh Topology: Complexity and high cost; requires
more cabling and configuration compared to simpler topologies.
OR
29. A) Write a Python function that extracts and displays all the words present in a
text file “Vocab.txt” that begins with a vowel..
OR (3)
B) Write a Python function that extracts and displays all the words
containing a hyphen ("-") from a text file "HyphenatedWords.txt", which
has a three letter word before hypen and four letter word after hypen.
For example : “for-them” is such a word.
Ans : A)
def display_words_starting_with_vowel():
vowels = 'AEIOUaeiou'
with open('Vocab.txt', 'r') as file:
words = file.read().split()
# Loop through the words and check if the first letter is a vowel
for word in words:
if word[0] in vowels:
print(word)
B)
def display_specific_hyphenated_words():
with open('HyphenatedWords.txt', 'r') as file:
words = file.read().split()
# Loop through the words and check if they match the pattern
for word in words:
parts = word.split('-')
# Check if the word is hyphenated and matches the format "XXX-
XXXX"
if len(parts) == 2 and len(parts[0]) == 3 and len(parts[1]) == 4:
print(word)
Page: 9/21
1/2 mark for file opening + 1/2 mark for correct loop +1/2 mark for
correct use of split( ) + 1 mark for correct condition + 1/2 mark for
output
(A) You have a stack named MovieStack that contains records of movies.
30. Each movie 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:
OR
Write the function pop_odd() to pop the topmost number from the stack and
return it. If the stack is empty, the function should display "Stack is empty".
Write the function disp_odd() to display all elements of the stack without
deleting them. If the stack is empty, the function should display "None".
For example:
If the integers input into the list NUMBERS are: [7, 12, 9, 4, 15]
Ans : (A )
def push_movie(movie_stack, new_movie): # 1 mark
movie_stack.append(new_movie)
def pop_movie(movie_stack):
Page: 10/21
return movie_stack.pop()
def peek_movie(movie_stack):
return "None"
return movie_stack[-1]
OR
if number % 2 != 0:
odd_numbers.append(number)
def pop_odd(odd_numbers):
return odd_numbers.pop()
def disp_odd(odd_numbers):
return "None"
return odd_numbers
Page: 11/21
31. Predict the output of the following code:
data = [3, 5, 7, 2]
result = ""
for num in data:
for i in range(num):
result += str(i) + "*"
result = result[:-1]
print(result)
OR
Ans : 0*1*2*0*1*2*3*4*0*1*2*3*4*5*6*0*1
( 1 mark for predicting correct output sequence of
numbers + 1 mark for predicting correct placement
of * + 1 mark for removing last * )
OR
0 +1 +
0 +1 +2 +
0 +1 +2 +3 +
( 1 MARK For putting output in three lines + 1 mark for
predicting correct sequence of numbers in each line (
1/2 for incorrect partially correct) + 1 mark for
correct placement of + )
Q No. Section-D ( 4 x 4 = 16 Marks) Marks
Note: The table contains many more records than shown here. (4)
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 price in descending order.
(III) To display the distinct customer names from the ORDERS table.
Page: 12/21
(IV) To display the sum of the Price 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;
OR
(B) ( 1 MARK EACH )
(I)
C_Name Total_Quantity
Jitendra 1
Mustafa 2
Dhwani 1
Alice 1
David NULL
(II)
O_Id C_Name Product Quantity Price
1002 Mustafa Smartphone 2 10000
1004 Alice Smartphone 1 9000
Page: 13/21
(III)
Name of a country
Life Expectancy (average number of years a person is expected to
live)
GDP per capita (Gross Domestic Product per person)
Percentage of population with access to healthcare
(4)
For example, a sample record of the file may be: ['Wonderland', 82.5, 40000,
95].
(I) Read all the data from the file in the form of a list and display all those
records for which the life expectancy is greater than 75.
Ans : (I)
import csv
def read_health_data(filename):
records = []
with open(filename, mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row if present
for row in reader:
country = row[0]
life_expectancy = float(row[1])
gdp_per_capita = float(row[2])
access_to_healthcare = float(row[3])
if life_expectancy > 75 :
records.append([country, life_expectancy, gdp_per_capita,
access_to_healthcare])
return records
Page: 14/21
(II)
def count_records( ):
records = read_health_data(“HealthData.csv”)
return len(records)
Alex has been tasked with managing the Student Database for a High
34. School. He needs to access some information from the STUDENTS and
SUBJECTS tables for a performance evaluation. Help him extract the
following information by writing the desired SQL queries as mentioned
below.
Table: STUDENTS
FNam Mark
S_ID LName Enrollment_Date
e s
201 John Doe 15-09-2020 85
202 Jane Smith 10-05-2019 90 (4)
Johnso
203 Alex 22-11-2021 75
n
204 Emily Davis 30-01-2022 60
Micha
205 Brown 17-08-2018 95
el
Table: SUBJECTS
Ans : ( I )
SELECT * FROM STUDENTS S
JOIN SUBJECTS Sub ON S.S_ID = Sub.S_ID
WHERE S.Marks > 70;
Page: 15/21
(II)
SELECT *
FROM SUBJECTS
WHERE Credits BETWEEN 2 AND 4;
(III)
UPDATE SUBJECTS
SET Credits = Credits + 1
WHERE SubName LIKE '%Science%';
(IV) A:
SELECT FName, LName
FROM STUDENTS S
JOIN SUBJECTS Sub ON S.S_ID = Sub.S_ID
WHERE Sub.SubName = 'Mathematics';
OR
B:
SELECT *
FROM STUDENTS, SUBJECTS;
Field Type
productID int(11)
productName varchar(20)
price float
stockQty int(11)
(4)
Write the following Python function to perform the specified operation:
Ans :
import mysql.connector
def AddAndDisplay():
# Connect to the database
conn = mysql.connector.connect(
host='localhost',
user='root',
password='Electro123',
database='PRODUCTDB'
)
cursor = conn.cursor()
productID = int(input("Enter Product ID: "))
Page: 16/21
productName = input("Enter Product Name: ")
price = float(input("Enter Price: "))
stockQty = int(input("Enter Stock Quantity: "))
cursor.execute("INSERT INTO ELECTRONICS
(productID, productName,
price, stockQty) VALUES (%s,
%s, %s, %s)", (productID,
productName, price, stockQty))
conn.commit()
cursor.execute("SELECT * FROM ELECTRONICS
WHERE price > 150")
records = cursor.fetchall()
print("\nRecords with price greater than 150:")
for record in records:
print(record)
cursor.close()
conn.close()|
(1 Mark for Declaration of correct Connection Object
+ 1 Mark for correct input + 1 marks for correctly
using execute( ) method + 1 marks for showing
output using loop )
Ans : (I)
import pickle
def add_employee(filename):
employee_id = int(input("Enter Employee ID: "))
employee_name = input("Enter Employee Name: ")
position = input("Enter Position: ")
salary = float(input("Enter Salary: "))
new_employee = (employee_id, employee_name, position, salary)
with open(filename, 'ab') as file:
pickle.dump(new_employee, file)
(1/2 mark for input + 1 mark for correct use of dump( ) to add new emp
Page: 17/21
data)
(II)
def update_employee(filename):
employees = []
with open(filename, 'rb') as file:
try:
while True:
employees.append(pickle.load(file))
except EOFError:
pass
for i in range(len(employees)):
if employees[i][3] > 50000:
employees[i] = (employees[i][0], employees[i][1], "Team Lead",
employees[i][3])
with open(filename, 'wb') as file:
for employee in employees:
pickle.dump(employee, file)
(1 mark for correct use of load( ) method to retrieve data + 1/2 mark for
correct loop + 1/2 mark for correct condition within loop )
(III)
def display_non_team_leads(filename):
print("\nEmployees who are not Team Leads:")
with open(filename, 'rb') as file:
try:
while True:
employee = pickle.load(file)
if employee[2] != "Team Lead":
print(f"ID: {employee[0]}, Name: {employee[1]}, Position:
{employee[2]}, Salary: {employee[3]}")
except EOFError:
pass
( 1 mark for correct use of Try except block and 1/2 mark for correct
use of while loop )
Page: 18/21
Interstellar Logistics Ltd. is an international shipping company. They are
37. planning to establish a new logistics hub in Chennai, with the head office in
Bangalore. The Chennai hub will have four buildings - OPERATIONS,
WAREHOUSE, CUSTOMER_SUPPORT, and MAINTENANCE. As a
network specialist, your task is to propose the best networking solutions to
address the challenges mentioned in points (I) to (V), considering the
distances between the various buildings and the given requirements.
(5)
Building-to-Building Distances (in meters):
From To Distance
OPERATIONS WAREHOUSE 40 m
OPERATIONS CUSTOMER_SUPPORT 90 m
OPERATIONS MAINTENANCE 50 m
WAREHOUSE CUSTOMER_SUPPORT 60 m
WAREHOUSE MAINTENANCE 45 m
CUSTOMER_SUPPORT MAINTENANCE 55 m
Location Computers
OPERATIONS 40
WAREHOUSE 20
CUSTOMER_SUPPORT 25
MAINTENANCE 22
BANGALORE HEAD OFFICE 15
Page: 19/21
(I) Suggest the most suitable location for the server within the Chennai hub.
Justify your decision.
(II) Recommend the hardware device to connect all computers within each
building efficiently.
(III) Draw a cable layout to interconnect the buildings at the Chennai hub
efficiently. Which type of cable would you recommend for the fastest and
most reliable data transfer?
(IV) Is there a need for a repeater in the proposed cable layout? Justify your
answer.
(V) A) Recommend the best option for live video communication between the
Operations Office in the Chennai hub and the Bangalore Head Office from
the following choices:
a) Video Conferencing
b) Email
c) Telephony
d) Instant Messaging
OR
(V) B) What type of network (PAN, LAN, MAN, or WAN) would be set up
among the computers within the Chennai hub?
Ans :
(I) The server should be placed in the OPERATIONS building.
Justification:
(III) The most efficient cable layout would involve connecting the
buildings as follows:
Page: 20/21
CUSTOMER_SUPPORT
(90 m)
OPERATIONS
/ | \
/ | \
WAREHOUSE MAINTENANCE
(III) There is no need for a repeater in this layout. The maximum distance
between any two buildings is 90 meters, which is well within the 100-meter
limit for Ethernet cable or fiber optics before requiring a repeater.
( 1 mark )
(IV) A) The best option for live communication between the Chennai
Operations Office and the Bangalore Head Office would be Video
Conferencing. This allows real-time face-to-face meetings and visual
communication across long distances, which is ideal for inter-office
collaboration.
OR
(V) B) The network type in the Chennai hub would be a LAN (Local Area
Network), as all computers are located within a confined geographical
area (the logistics hub) and are connected to each other for data
communication within the same campus.
Page: 21/21
KENDRIYA VIDYALAYA SANGATHAN, CHENNAI REGION
CLASS: XII SESSION: 2024-25
PREBOARD
COMPUTER SCIENCE (083)
Time allowed: 3 Hours Maximum 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.
import random
word='Inspiration'
Lot=2*random.randint(2,4)
for i in range(Lot,len(word),3):
print(word[i],end='$')
26 Identify Primary Key and Candidate Key present if any in the below table name 2
Colleges. Justify
Streng
Cid Name Location Year AffiUniv PhoneNumber
th
University
St. Xavier's
1 Mumbai 1869 10000 of 022-12345678
College
Mumbai
Loyola University
2 Chennai 1925 5000 044-87654321
College of Madras
Hansraj Delhi
3 New Delhi 1948 4000 011-23456789
College University
Christ Christ
4 Bengaluru 1969 8000 080-98765432
University University
Lady Shri
Delhi
5 Ram New Delhi 1956 2500 011-34567890
University
College
27 (I) 2
(A) What constraint/s should be applied to the column in a table to make it as
alternate key?
OR
(B) What constraint should be applied on a column of a table so that it becomes
compulsory to insert the value
(II)
(A) Write an SQL command to assign F_id as primary key in the table named flight
OR
(B)Write an SQL command to remove the column remarks from the table name
customer.
28 List one advantage and disadvantage of star and bus topology 2
OR
Define DNS and state the use of Internet Protocol.
OR
(B) Write a function that displays the line number along with no of words in it
from the file Quotes.txt
Example :
None can destroy iron, but its own rust can!
Likewise, none can destroy a person, but their own mindset can
The only way to win is not be afraid of losing.
Output:
Line Number No of words
Line 1: 9
Line 2: 11
Line 3: 11
30 (A) There is a stack named Uniform that contains records of uniforms Each record 3
is represented as a list containing uid, uame, ucolour, usize, uprice.
Write the following user-defined functions in python to perform the specified
operations on the stack Uniform :
(I) Push_Uniform(new_uniform):adds the new uniform record onto the stack
(II) Pop_Uniform(): pops the topmost record from the stack and returns it. If
the stack is already empty, the function should display “underflow”.
(III) Peep(): This function diplay the topmost element of the stack without
deleting it.if the stack is empty,the function should display ‘None’.
OR
(a) Write the definition of a user defined function push_words(N) which accept
list of words as parameter and pushes words starting with A into the stack
named InspireA
(b) Write the function pop_words(N) to pop topmost word from the stack and
return it. if the stack is empty, the function should display “Empty”.
Field Type
EventID int(9)
EventName varchar(25)
EventDate date
Description varchar(30)
Write the following Python function to perform the specified operations:
Input_Disp(): to input details of an event from the user and store into the table Event. The
function should then display all the records organised in the year 2024.
HR ADMIN
London Head
Head Head
Office
Accts Logistics
(a) Both A and R are true and R is the correct explanation for A 4
(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): Default arguments in Python functions must be defined after all 1
required arguments.
Reasoning (R): Default arguments provide a fall back value when no argument is
provided.
21 Assertion (A): An SQL SELECT statement can have both WHERE and ORDER 1
BY clauses.
For example, a sample record in the file might look like: ['Rainford', 32,
75, 120]
Write the following Python functions to perform the specified operations on this
file:
1. Read all the data from the file in the form of a list and display all those
records where the average temperature is above 30 degrees Celsius.
Calculate and display the average rainfall across all records in the file.
34 Consider the following tables STUDENT and ST-HOUSE. 4
Table : STUDENT Table : ST-HOUSE
Class Sec Rno Sname House Hid Hname HMaster
3 A 1 ROHAN H03 H01 GANGA VACHASPATHI
12 C 5 PALLAVI H04 H02 YAMUNA MADHURI
9 D 12 KIRAN H03 H03 NARMADA MURALI
11 A 6 SAMPATH H02 H04 KAVERI SRIHARI
Write SQL Queries for the following.
i) Display class, section and name of all students belong to NARMADA
house.
ii) Display the number of students present in the student table.
iii) Display names of students in the descending order of names.
iv) a) Remove all students of section A
(OR)
b) Write SQL query to add a new column to ST-HOUSE table named Hmember
of
Varchar type with size 20.
35 Raman has created table named NATIONALSPORTS in MYSQL database, 4
SPORTS :
Each record contains the following fields:
∙ GameID(Game number )- integer
∙ Gamename(Name of game) - string
∙ DOG(Date of Game) – Date
∙ Venue(Venue of game) – decimal
Note the following to establish connectivity between Python and MySQL:
∙ Username - root
∙ Password – KVR@321
∙ Host – localhost
Raman , now wants to display all records of venue “Hyderabad”. Help him to
write the python program.
SECTION-E
36 Mayank is a manager working in a retail agency. He needs to manage the records 5
of various customers. For this, he wants the following information of each
candidate to be stored:
- Customer_ID – integer
- Customer_Name – string
- Address – string
- Receipt no-integer
You, as a programmer of the company, have been assigned to do this job for
Mayank.
(i) Write a function to input the data of a customers and append it in a
binary file.
(ii) Write a function to update the data of customers whose receipt no is 101
and change their address to "Secunderabad".
(iii)Write a function to read the data from the binary file and display the data
of all those candidates who are not belong to Secunderabad.
37 CITY CABLE NETWORK has set up its new centre at HYDERABAD for its 5
office and web based activities. It has four buildings as shown in the diagram
below:
A B
C D
Number of Computers
Block A 25
Block B 50
Block C 125
Block D 10
Black A to Block B 50 m
Block C to Block D 25 m
Block A to Block C 90 m
Page 1 of 7
7 If my_dict is a dictionary as defined below, then which of the following statements will 1
raise an exception?
my_dict = {'aman': 10, 'sumit': 20, 'suresh': 30}
(a) my_dict.get('suresh') (b) print(my_dict['aman', 'sumit'])
(c) my_dict['aman']=20 (d) print(str(my_dict))
8 Which of the following can delete an element from a list if the index of the element is 1
given?
(a) pop( ) (b) remove( )
(c) clear( ) (d) all of these
9 Which of the following attributes can be considered as a choice for primary key? 1
(a) Name (b) Street
(c) Roll No (d) Subject
10 Write the missing statement to complete the following code: 1
file = open("abc.txt", "r")
d = file.read(50)
____________________ #Move the file pointer to the beginning of the file
next_data = file.read(75)
file.close()
11 State whether the following statement is True or False: 1
An exception may be raised even if the program is syntactically correct.
12 What will be the output of the following Python code ? 1
v = 50
def Change(n):
global v
v, n = n, v
print(v, n, sep = “#”, end = “@”)
Change(20)
print(v)
(a) 20#50@20 (b) 50@20#50
(c) 50#50#50 (d) 20@50#20
13 Which statement is used to modify data in a table? 1
(a) CHANGE (b) MODIFY (c) UPDATE (d) ALTER
14 How would you return all the rows from a table named "Item" sorted in descending 1
order on the column "IName"?
(a) SELECT * FROM Item SORT 'IName' DESC;
(b) SELECT * FROM Item ORDER BY IName DESC ;
(c) SELECT * FROM Item ORDER IName DESC ;
(d) SELECT * FROM Item SORT BY 'IName' DESC;
15 LIKE clause is used for. 1
(a) For pattern matching (b) For table matching
(c) For inserting similar data in a table (d) For deleting data from a table
16 Count(*) method count 1
(a) NULL values only (b)Empty Values
(c) ALL the values (d) None of these
17 The term HTTP stands for? 1
(a) Hyper terminal tracing program (b) Hypertext tracing protocol
(c) Hypertext transfer protocol (d) Hypertext transfer program
Page 2 of 7
Q20 and Q21 are Assertion(A) and Reason(R) based questions. Mark the correct
choice as:
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is False but R is True
20 Assertion :- A parameter having a default value in the function header is known as a 1
default parameter.
Reason:- The default values for parameters are considered only if no value is
provided for that parameter in the function call statement.
21 Assertion :- Both WHERE and HAVING clauses are used to specify conditions.
Reason :- The WHERE and HAVING clauses are interchangeable.
Page 4 of 7
OR
(B) Predict the output of the Python code given below:
T= [“20”, “50”, “30”, “40”]
Counter=3
Total= 0
for I in [7,5,4,6]:
newT=T[Counter]
Total= float (newT) + I
print(Total)
Counter=Counter-1
Page 5 of 7
COMPANY
CID CNAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE
666 DELL DELHI LAPTOP
CUSTOMER
CUSTID NAME PRICE QTY CID
101 Rohan Sharma 70000 20 222
102 Deepak Kumar 50000 10 666
103 Mohan Kumar 30000 5 111
104 Sahil Bansal 35000 3 333
105 Neha Soni 25000 7 444
106 Sonal Aggarwal 20000 5 333
107 Arjun Singh 50000 15 666
(i) To display those company name along with price which are having price less
than 30000.
(ii) To display the name and price of the companies whose price is between 20000
to 35000.
(iii) To increase the price by 1000 for those customer whose name starts with ‘S’
(iv) To display those product name, city and price which are having product name
as MOBILE.
35 Kabir wants to write a program in Python to insert the following record in the table 4
named Student in MYSQL database, SCHOOL:
- rno(Roll number) – integer
- name(Name) – string
- DOB(Date of Birth) – Date
- Fee – float
Note the following to establish connectivity between Pythonand MySQL:
- Username – root
- Password – tiger
- Host – localhost
The values of fieldsrno, name, DOB and fee has to be accepted from the user.
Help Kabir to write the program in Python.
Page 6 of 7
You, as a programmer of the company, have been assigned to do this job for Amit.
(i) Write a function to input the data of a candidate and append it in a binary file.
(ii) Write a function to update the data of candidates whose experience is more
than 12 years and change their designation to "Sr. Manager".
(iii) Write a function to read the data from the binary file and display the data of all
those candidates who are not "Sr. Manager".
37 PVS Computers decided to open a new office at Ernakulum, the office consist of 5
Five Buildings and each contains number of computers. The details are shown
below.
Page 7 of 7
अनक्र
ु म ांक/ROLL NO सेट/SET : 01
elif Text[i].islower():
L=L+Text[i].upper()
elif Text[i].isdigit():
L=L+(Text[i]*2)
else:
L=L+'#'
print(L)
(A)hAPPY#HOUR1122#33
(B)Happy#hOUR12#3
(C)hAPPY#HOUR112233
(D)Happy Hour11 22 33 #
3 Consider the given expression: 1
17%5==2 and 4%2>0 or 15//2==7.5
Which of the following will be correct output if the given expression is evaluated?
(a)True (b) False (c)None (d)Null
4 Select the correct output of the code: 1
s = "Question paper 2022-23"
s= s.split('2')
print(s)
a. ['Question paper ', '0', '', '-', '3']
b. ('Question paper ', '0', '', '-', '3')
c. ['Question paper ', '0', '2', '', '-', '3']
d. ('Question paper ', '0', '2', '', '-', '3')
5 What will be the output of following code if 1
a = “abcde”
a [1:1 ] == a [1:2]
type (a[1:1]) == type (a[1:2])
6 Select the correct output of the code: 1
a = "foobar"
a = a.partition("o")
print(a)
(a) ["fo","","bar"]
(b) ["f","oo","bar"]
(c) ["f","o","bar"]
(d) ("f","o","obar")
7 State whether the following statement is True or False: 1
An exception may be raised even if the program is syntactically correct.
8 1
Identify the output of the following python code: 1
D={1:"one",2:"two", 3:"three"}
L=[]
for k,v in D.items():
if 'o' in v:
L.append(k)
print(L)
(a) (10,20) (b) (10,) (c) (10) (d) All are tuples.
10 1
Which of the following is the correct usage for tell() of a file
object,………………….?
1
a) It places the file pointer at the desired offset in a file.
b) It returns the byte position of the file pointer as an integer.
c) It returns the entire content of the file.
d) It tells the details about the file.
11 What will be the output of the following Python code snippet? 1
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 > d2
a. True b. False
c. Error d. None
12 Consider the code given below: 1
b=5
def myfun(a):
# missing statement.
b=b*a
myfun(14)
print(b)
Which of the following statements should be given in the blank for #
Missing statement, if the output produced is 70?
a. global a b. global b=70
c. global b d. global a=70
13 Which of the following commands is not a DDL command? 1
1
(a) DROP (b) DELETE (c) CREATE (d) ALTER
14 Which of the following keywords will you use in the following query to 1
display the unique values of the column dept_name?
SELECT --------------------- dept_name FROM Company;
(a)All (b) key (c) Distinct (d) Name
15 What is the maximum width of numeric value in data type int of MySQL. 1
a. 10 digits b. 11 digits
c. 9 digits d. 12 digits
16 SUM(), AVG() and COUNT() are examples of functions. 1
1
a) single row functions
b) aggregate functions
c) math function
d) date function
17 is a standard mail protocol used to receive emails from a remote server 1
to a local email client.
18 Pawan wants to transfer files and photos from laptop to his mobile. He uses 1
Bluetooth Technology to connect two devices. Which type of network will be
formed in this case.
a. PAN b. LAN
c. MAN d. WAN
19 Fill in the blank: 1
In case of switching, message is send in stored and forward manner from
sender to receiver.
Q20 and 21 are ASSERTION AND REASONING based questions. Mark the
correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
20 Assertion (A): The default argument values in Python functions can be mutable 1
types like lists and dictionaries.
Reason (R): Mutable default arguments retain their state across function calls,
which can lead to unexpected behaviour.
21 Assertion (A): The HAVING clause in MySQL is used to filter records after the 1
GROUP BY operation.
Reason (R): The WHERE clause filters records before grouping, while HAVING
allows for conditions on aggregated data.
SECTION
B
22 Write difference between mutable and immutable property, Explain it with 2
its example.
23 Predict the output of the Python 2
code given below:
T = (9,18,27,36,45,54)
L=list(T)
L1 = [ ]
for i in L:
if i%6==0:
L1.append(i)
T1 = tuple(L1)
print(T1)
24 Write the Python statement for each of the following tasks using 2
BUILT-IN functions/methods only:
(i) To insert an element 400 at the fourth position, in the list L1.
(ii) To check whether a string named, message ends with a full stop/
period or not.
OR
OR
(i) Define the term baud with respect to networks.
(ii) How is http different from https?
SECTION C
29 Write a user – defined function countH() in Python that displays the number 3
of lines starting with ‘H’ in the file ‘Para.txt”. Example , if the file contains:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
Output: The line count should be 2.
OR
Write a function countmy() in Python to read the text file “DATA.TXT” and
count the number of times “my” occurs in the file. For example , if the file
“DATA.TXT” contains –
“This is my website. I have displayed my preference in the CHOICE
section.” The countmy( ) function should display the output as:
“my occurs 2 times”
30 3
Aalam has created a list, L containing marks of 10 students. Write a
program, with separate user defined function to perform the following
operation:
3
PUSH()- Traverse the content of the List, L and push all the odd marks into
the stack,S.
31 3
Consider the table ACTIVITY given below:
ACODE ACTIVITYNA PARTICIP PRIZEMONEY SCHEDULED
ME ANTS TE
NUM
1001 Relay Name 16 10000 2004-01-23
1002 High Jump 10 12000 2003-12-12
1003 Shot Put 12 8000 2004-02-14
1005 Long Jump 12 9000 2004-01-01
1008 Discuss Throw 10 15000 2004-03-19
Based on the given table, write SQL queries for the following:
(i) Display the details of all activities in which prize money is more than
9000 (including 9000)
(ii) Increase the prize money by 5% of those activities whose schedule
date is after 1st of March 2023.
(iii) Delete the record of activity where participants are less than 12.
SECTION D
32 You have learnt how to use math module in Class XI. Write a code where you 4
use the wrong number of arguments for a method (say sqrt() or pow()). Use
the exception handling process to catch the ValueError exception.
33 Write a python program to create a csv file dvd.csv and write 10 records in it 4
Dvdid, dvd name, qty, price. Display those dvd details whose dvd price is
more than 25.
34 Consider the following tables and answer the questions a and b: 1*4=4
Table: Garment
GCode GNam e Rate Qty CCode
1 | Page
print(2**3**2)
a) 64 b) 256 c) 512 d) 32
9. Which of the following statement(s) would give an error after executing the 1
following code?
S="Welcome to class XII" #Statement 1
print(S) # Statement 2
S="Thank you" #Statement 3
S[0]= '@' #Statement 4
S=S+"Thank you" #Statement 5
(a) Statement 3 (b) Statement 4
(c) Statement 5 (d) Statement 4 and 5
10. Which of the following option is the correct python statement to read and display 1
the first 10 characters of a text file “Notes.txt”?
(a) F=open(‘Notes.txt’) (b) F=open(‘Notes.txt’)
print(F.load(10)) print(F.dump(10))
def change():
n=10
x=5
print( x)
a) n and x both are local variables b) n and x both are global variables
c) n is global and x is local variable d) n is local and x is global variable
13. Fill in the blank: 1
command is used to add a column in a table in SQL.
14. _______Keyword is used to obtain Non-duplicated values in a SELECT query. 1
(a) ALL (b) DISTINCT (c) SET (d) HAVING
15. Which SQL function returns the sum of values of a column of numeric type? 1
(a)total( ) (b)add( ) (c) sum( ) (d) All of these
16 Which of the following is not valid cursor function while performing database 1
operations using python. Here Mycur is the cursor object?
(a) Mycur.fetch() (b) Mycur.fetchone()
(c) Mycur.fetchmany(n) (d) Mycur.fetchall()
17. What Modem does? 1
a) Modulation (b) Demodulation
c) Both Modualtion & Demodulation (d) Not any
18. Fill in the blank: 1
______is the first page that normally view at a website.
(a) First Page (b) Master Page (c) Home Page (d) Login Page
2 | Page
(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): A variable declared as global inside a function is visible outside 1
the function with changes made to it inside the function.
Reasoning (R): global keyword is used to change the value of a global variable.
21. Assertion (A): COUNT(*) function count the number of rows in a relation. 1
Reasoning (R): DISTINCT ignores the duplicate values.
SECTION-B (7 * 2= 14 Marks)
22. Which of the following can be used as valid identifier(s) in Python? 2
(i) Total (ii) @selute (iii) Que$tion (iv) great
th
(v) 4 Sem (vi) li1 (vii) No# (viii) _Data
23. (i)Write the names of any two data types available in python. 1+1=2
(ii)Write any 2 operators name used in python.
24. Write the Python statement for each of the following tasks using BUILT_IN 1+1=2
functions/ methods only:
i) str="PYTHON@LANGUAGE"
(A) To print the above string from index 2 onwards.
OR
(B) To initialize an empty dictionary named as d.
ii) Write the Python statement for each of the following tasks using BUILT_IN
functions/ methods only:
(A) s=”LANGUAGE"
To convert the above string into list.
OR
(B) To initialize an empty tuple named as t.
25. Find possible o/p (s) at the time of execution of the program from the following code? 2
Also specify the maximum values of variables Lower and Upper.
import random as r
AR=[20, 30, 40, 50, 60, 70];
Lower =r.randint(1,3)
Upper =r.randint(2,4)
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50#
(iii) 50#60#70# (iv) 40#50#70#
26. Differentiate between COUNT(* ) and COUNT(COLUMN_NAME) with example. 2
27. (i) 2
A) What constraint should be applied on a table’s column to provide it the
default value when column does not have any value.
OR
B) What constraint should be applied on a table’s column so that NULL
value is allowed in that column and duplicate values are not allowed.
(ii)
A) Write an SQL command to add one more column in previously defined
table, named CELL. Column name is CELL_ID with size 10 of integer
type should be added in the table.
OR
B) Write an SQL command to permanently remove the table CELL from
database.
3 | Page
28. A) Write the full forms of the URL and VoIP and their utility? 2
OR
B) Mention any two differences between IP and MAC address in networking.
SECTION-C (3*3= 9 Marks)
29. A) Write a method /function countlines_et () in python to read lines from a text file 3
report.txt, and COUNT those lines which are starting either with ‘E’ and starting
with ‘T’ respectively. And display the Total count separately.
For example: if REPORT.TXT consists of
“THE PROGRAMMING IS FUN FOR PROGRAMMER.
ENTRY LEVEL OF PROGRAMMING CAN BE LEARNED FROM USEFUL FOR
VARIETY OF USERS.”
Then,
Output will be: No. of Lines with E: 1 No. of Lines with T: 1
OR
B) Write a method/function show_todo():in python to read contents from a text file
abc.txt and display those lines which have occurrence of the word “ TO” or “DO”
For example:
If the content of the file is
“THIS IS IMPORTANT TO NOTE THAT SUCCESS IS THE RESULT OF HARD WORK.
WE ALL ARE EXPECTED TO DO HARD WORK.
AFTER ALL EXPERIENCE COMES FROM HARDWORK.”
Write the function pop(stack) that removes the top element of the stack on its each
call.
B)
Write a function in Python push(EventDetails) where EventDetails is a dictionary
containing the number of persons attending the events–
{EventName : NumberOfPersons}.
The function should push the names of those events in the stack named ‘BigEvents’
which have number of persons greater than 200. Also display the count of elements
pushed on to the stack.
Write the function pop(EventDetails) that removes the top element of the stack on
its each call.
For example:
4 | Page
Marriage
Graduation Party
OR
B)
(i) To display the total number of employees in Employee table.
(ii) To display the employees records in descending order of
basic_salary respectively.
(iii) To display the total hra of employees in Employee table.
ii) Give an example code to handle IndexError? The code should display the
message “list index out of range is not allowed” in case of IndexError Exception,
and the message “Some Error occured” in case of any other Exception.
OR
B)
i) When is ZeroDivisionError Exception raised in Python?
ii) Write a function division( ) that accepts two arguments. The function should be
able to catch an exception such as ZeroDivisionError Exception, and the message
“Some Error occured” in case of any other Exception.
33 Aman has recently been given a task on CAPITAL.CSV which contains Country and 2+2=4
. Capital as data for records insertion.
5 | Page
34 Write the SQL queries (i) to (iv) based on the relations SCHOOL and ADMIN given 4
. below:
6 | Page
37 Hitech Info Limited wants to set up their computer network in Bangalore 5
based
campus having four buildings. Each block has a number of computers
that are required to be connected for ease of communication, resource sharing and
data security.
You as a network expert have to suggest answers to these parts (a) to (e) raised
by them.
DEVELOPMENT HUMANRESOURCE
KVS
LOGISTICS ADM
RO
Shortest distances between various blocks Jaipur
Block DEVELOPMENT to Block HUMANRESOURCE -- 50 m
Block DEVELOPMENT to Block ADM-- 75 m
Block DEVELOPMENT to Block LOGISTICS-- 80 m
Block HUMANRESOURCE to Block ADM-- 110 m
Block ADM to Block LOGISTICS 140 m
i) Suggest the most suitable block to host the server. Justify your answer.
ii) Suggest the wired medium and Draw the cable layout (Block to Block) to
economically connect various blocks.
iii) Suggest the placement of the following devices with justification:
(a) Hub/Switch (b)Repeater
iv) Suggest the device that should be placed in the Server building so that they
can connect to Internet Service Provider to avail Internet Services.
v) A) What is the Suggestion for the high-speed wired communication medium
between Bangalore Campus and Mysore campus to establish a data network.
(a) TWP Cable (b)CoAxial Cable (c) OFC (d) UTP Cable
OR
B) What type of network (PAN/ LAN/ MAN/ WAN) will be set up among the
computers connected in the Campus?
----------------*------------*------------------
7 | Page
Kendriya Vidyalaya Sangathan, Jaipur Region
PRACTICE PAPER-III
Class: XII Subject: Computer Science (083)
Maximum Marks: 70 Period: 3 Hours
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 the case of MCQ, the text of the correct answer should also be written.
newt=lshift((1,2,3,4,5,6),13)
print(newt)
Sample example :
lshift((6,7,8,9),2) should give the output (8,9,6,7)
27 (i) 2
(A) What constraint should be applied on a column of a table so that there cannot
be NULL value except for only one row
OR
(B) What constraint should be applied on a column of a table so that a predefined
value is assigned if no value is provided by the user.
(ii)
(A) Write an SQL command to remove the Primary Key constraint from a table,
named STUDENT. Adm_No is the primary key of the table.
OR
(B) Write an SQL command to make the column Rno the Primary Key of an
already existing table named STUDENT.
28 A) List one advantage and one disadvantage of Tree topology. 2
OR
B) Expand the term TELNET. What is the use of TELNET?
33 A csv file “Employment.csv” contains the data of a survey. Each record of the file 4
contains the following data:
• Name of a state
• Population of the state
• Sample size (Number of persons who participated in the survey in that
state)
• Employed (Number of persons employed)
Write the following Python functions to perform the specified operations on this file:
(i) Read all the data from the file in the form of a list and display all those records
for which the population is more than 5000000.
(ii) Count the number of records in the file.
34 Manan has been entrusted with the management of ABC School database. He 4
needs to access some information from STUDENT and CLUB tables for a survey
analysis. Help him extract the following information by writing the desired SQL
queries as mentioned below:
Table :STUDENT
Rno Name DateOfBirth Gender Marks ClubId
1 Amit 15-11-2008 M 98 101
2 Divya 27-10-2008 F 78 102
3 Harsh 13-05-2009 M 90 101
4 Manjeet 16-07-2009 M 86 103
5 Aruna 07-08-2009 F 70 102
6 Dinesh 01-03-2009 M 67 103
Table :CLUB
ClubId Cname Fees
101 Eco 300
102 Cyber 500
103 Excursion 700
(i) To display complete details (from both the tables) of those whose marks is
less than 80
(ii) To display the details of those clubs, fees of which is in the range of 400 to
700 (both values included).
(iii) To increase the fees of all clubs by 200 which have ‘o’ in their club name.
(iv) (a) To display Name and Marks of student in Cyber club.
OR
(b) To display the Cartesian Product of these two tables without repeating
ClubId column.
35 A table, named INVENTORY, in SHOP database, has the following structure: 4
Field Type
itemNo int
itemName varchar(15)
price float
qty int
Write the following Python function to perform the specified operation:
addRec(): To input details of an item and store it in the table INVENTORY. The
function should then retrieve and display all records from the INVENTORY table
where the price is greater than 150.
HR
Page 1 of 7
8 Consider the given list L: 1
L = list('All is well in ')
What python code should be written for inserting the word 'Havana' at the end of
the list as separate characters?
a. L.extend('Havana') b. L.append(list('Havana'))
c. both a and b d. None of the above
9 What will be the output of following python code: 1
l2= [1,2,3,'[4,5]']
print(type(l2[-1]))
a. error b. <class ‘list’> c. <class ‘string> d. <class ‘NoneType’>
10 Suppose the content of a text file xyz.txt is as follows: 1
"The best way to Predict the future is to create it."
What will be the output of the following python code?
f = open("xyz.txt")
f.seek(17)
s = f.read(7)
print(s)
f.close()
a. Predict b. The best way to
c. predict the d. to predict the future
11 In Python exception handling, the finally block is executed regardless of whether an 1
exception occurs or not. (True/False)
12 def func(a, b, c=3, d=4): 1
pass
Identify the keyword and positional arguments in the function given above:
a) a and b are positional arguments; c and d are keyword arguments
b) a, b, c, and d are all positional arguments
c) a, b, c, and d are all keyword arguments
d) a, b, and c are positional arguments; d is a keyword argument
13 What is the output of following SQL statement? 1
SELECT Department, COUNT(*) FROM employees
WHERE Salary > 50000 GROUP BY Department;
a. The total number of employees in each department
b. The departments with employees earning over 50,000 and the count of such
employees in each department
c. The departments with average salary over 50,000 and their total number of
employees
d. The number of departments with employees earning over 50,000
14 Consider a table named 'Products' with columns 'product_id', 'product_name', and 1
'category'. Which of the following SQL queries will retrieve all products that are not
in the categories 'Electronics' or 'Furniture'?
a. SELECT product_id, product_name FROM Products
WHERE category NOT IN ('Electronics', 'Furniture');
b. SELECT product_id, product_name FROM Products
WHERE category NOT IN 'Electronics', 'Furniture';
c. SELECT product_id, product_name FROM Products
WHERE category != 'Electronics' AND != 'Furniture';
d. SELECT product_id, product_name FROM Products
WHERE category NOT LIKE ('Electronics', 'Furniture');
15 In MySQL, which command does not change the cardinality of a relation? 1
a. ALTER b. INSERT c. DELETE d. None of these
Page 2 of 7
16 Sita is creating a table for her project. She wants that a particular column always 1
has a unique value. Which constraint should she use?
a. DISTINCT b. UNIQUE c. NOT NULL d. DEFAULT
17 Which of the following is a network protocol? 1
a. Firewall b. HTTP c. Modem d. Switch
18 The Router in a network primarily functions as a __________. 1
a. Converter b. Traffic director c. Amplifier d. Modulato
19 Write the full form of the following: (i) FTP (ii) DNS 1
Q20 and Q21 are Assertion(A) and Reason(R) based questions. Mark the correct
choice as:
(A) Both A and R are true and R is the correct explanation for A
(B) Both A and R are true and R is not the correct explanation for A
(C) A is True but R is False
(D) A is False but R is True
20 Assertion: Assertion: In Python, a function can return multiple values. 1
Reason: Python functions can return tuples, which can be unpacked into multiple
variables.
21 Assertion: The FOREIGN KEY constraint is used to establish links between tables. 1
Reason: A FOREIGN KEY in one table points to a FOREIGN KEY in another table.
Page 4 of 7
Observe the table Students and write query for (i) to (iii): 3
31 Table: Faculty
F_ID FName LName Department Gender Hire_Date Salary
102 Ibomcha Thounaojam Exam M 10/02/2020 75000
103 Shantanu Fernandes Exam M 11/01/2015 120000
104 Tashi Dorjey ICT F 14/03/2023 50000
105 Bhanwar Singh ICT M 13/12/2019 80000
106 Kanta Kumari HOD F 11/01/2024 140000
(A)
(i) Display Gender wise number of faculties who earn more than 85000.
(ii) Display all data separated by Department and in decreasing order of Salary.
(iii) Display FName and F_ID of faculties from ICT department.
OR
(B)
(i) Display Gender wise average salary of those faculties with average salary
more than 90000.
(ii) Display FName and F_ID of faculties having the string ‘ta’ in the Fname.
(iii) Change data of table to award 5% annual increment in salary.
Page 5 of 7
34 Give output of the following queries as per given table(s): 4
WORKER
WID WNAME JOB SALARY DNO
1001 RAHUL SHARMA CLERK 15000 D03
1002 MUKESH VYAS ELECTRICIAN 11000 D01
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
DEPT
DNO DNAME LOC MANAGER
D01 PRODUCTION GROUND FLOOR D K JAIN
D02 ACCOUNTS 1ST FLOOR S ARORA
D03 SECURITY 1ST FLOOR R K SINGH
(i) SELECT DISTINCT JOB FROM WORKER;
(iii) SELECT DNAME, LOC FROM DEPT WHERE SALARY > 10000;
(iv) SELECT W.WNAME, D.MANAGER FROM WORKER AS W, DEPT AS D
WHERE W.DNO = D.DNO;
(v) SELECT WNAME FROM WORKER WHERE WNAME LIKE 'R%';
35 A table named Products in a database named Inventory stores information about 4
products. The table has the following columns: ProductID (integer, primary key),
ProductName (string), Price (float), and Quantity (integer). Assume the database
username is 'admin' and the password is 'secure123'.
Write a Python code that prompts the user to enter a ProductID and updates the
Quantity of that product by adding 10 to the existing quantity. Handle any potential
errors (e.g., the product ID not existing in the table).
Page 6 of 7
37 Kendriya Vidyalaya No 1 Jaipur is setting up the network between its Different Wings 5
of school campus. There are 4 wings named as – SENIOR(S), JUNIOR(J), ADMIN(A)
and HOSTEL(H).
Distance between various wings are given below:
Wing A to Wing S 80m
Wing A to Wing J 200m
Wing A to Wing H 400m
Wing S to Wing J 70m
Wing S to Wing H 120m
Wing J to Wing H 450m
Page 7 of 7
Kendriya Vidyalaya Sangathan, Jaipur Region
PRACTICE PAPER-4
Question Paper
Class: XII Subject: Computer Science (083)
Maximum Marks: 70 Period: 3 Hours
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 the case of MCQ, the text of the correct answer should also be written.
Page 1 of 7
8 Consider the given list L: 1
L = list('All is well in ')
What python code should be written for inserting the word 'Havana' at the end of
the list as separate characters?
a. L.extend('Havana') b. L.append(list('Havana'))
c. both a and b d. None of the above
9 What will be the output of following python code: 1
l2= [1,2,3,'[4,5]']
print(type(l2[-1]))
a. error b. <class ‘list’> c. <class ‘string> d. <class ‘NoneType’>
10 Suppose the content of a text file xyz.txt is as follows: 1
"The best way to Predict the future is to create it."
What will be the output of the following python code?
f = open("xyz.txt")
f.seek(17)
s = f.read(7)
print(s)
f.close()
a. Predict b. The best way to
c. predict the d. to predict the future
11 In Python exception handling, the finally block is executed regardless of whether an 1
exception occurs or not. (True/False)
12 def func(a, b, c=3, d=4): 1
pass
Identify the keyword and positional arguments in the function given above:
a) a and b are positional arguments; c and d are keyword arguments
b) a, b, c, and d are all positional arguments
c) a, b, c, and d are all keyword arguments
d) a, b, and c are positional arguments; d is a keyword argument
13 What is the output of following SQL statement? 1
SELECT Department, COUNT(*) FROM employees
WHERE Salary > 50000 GROUP BY Department;
a. The total number of employees in each department
b. The departments with employees earning over 50,000 and the count of such
employees in each department
c. The departments with average salary over 50,000 and their total number of
employees
d. The number of departments with employees earning over 50,000
14 Consider a table named 'Products' with columns 'product_id', 'product_name', and 1
'category'. Which of the following SQL queries will retrieve all products that are not
in the categories 'Electronics' or 'Furniture'?
a. SELECT product_id, product_name FROM Products
WHERE category NOT IN ('Electronics', 'Furniture');
b. SELECT product_id, product_name FROM Products
WHERE category NOT IN 'Electronics', 'Furniture';
c. SELECT product_id, product_name FROM Products
WHERE category != 'Electronics' AND != 'Furniture';
d. SELECT product_id, product_name FROM Products
WHERE category NOT LIKE ('Electronics', 'Furniture');
15 In MySQL, which command does not change the cardinality of a relation? 1
a. ALTER b. INSERT c. DELETE d. None of these
Page 2 of 7
16 Sita is creating a table for her project. She wants that a particular column always 1
has a unique value. Which constraint should she use?
a. DISTINCT b. UNIQUE c. NOT NULL d. DEFAULT
17 Which of the following is a network protocol? 1
a. Firewall b. HTTP c. Modem d. Switch
18 The Router in a network primarily functions as a __________. 1
a. Converter b. Traffic director c. Amplifier d. Modulato
19 Write the full form of the following: (i) FTP (ii) DNS 1
Q20 and Q21 are Assertion(A) and Reason(R) based questions. Mark the correct
choice as:
(A) Both A and R are true and R is the correct explanation for A
(B) Both A and R are true and R is not the correct explanation for A
(C) A is True but R is False
(D) A is False but R is True
20 Assertion: Assertion: In Python, a function can return multiple values. 1
Reason: Python functions can return tuples, which can be unpacked into multiple
variables.
21 Assertion: The FOREIGN KEY constraint is used to establish links between tables. 1
Reason: A FOREIGN KEY in one table points to a FOREIGN KEY in another table.
Page 4 of 7
Observe the table Students and write query for (i) to (iii): 3
31 Table: Faculty
F_ID FName LName Department Gender Hire_Date Salary
102 Ibomcha Thounaojam Exam M 10/02/2020 75000
103 Shantanu Fernandes Exam M 11/01/2015 120000
104 Tashi Dorjey ICT F 14/03/2023 50000
105 Bhanwar Singh ICT M 13/12/2019 80000
106 Kanta Kumari HOD F 11/01/2024 140000
(A)
(i) Display Gender wise number of faculties who earn more than 85000.
(ii) Display all data separated by Department and in decreasing order of Salary.
(iii) Display FName and F_ID of faculties from ICT department.
OR
(B)
(i) Display Gender wise average salary of those faculties with average salary
more than 90000.
(ii) Display FName and F_ID of faculties having the string ‘ta’ in the Fname.
(iii) Change data of table to award 5% annual increment in salary.
Page 5 of 7
34 Give output of the following queries as per given table(s): 4
WORKER
WID WNAME JOB SALARY DNO
1001 RAHUL SHARMA CLERK 15000 D03
1002 MUKESH VYAS ELECTRICIAN 11000 D01
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
DEPT
DNO DNAME LOC MANAGER
D01 PRODUCTION GROUND FLOOR D K JAIN
D02 ACCOUNTS 1ST FLOOR S ARORA
D03 SECURITY 1ST FLOOR R K SINGH
(i) SELECT DISTINCT JOB FROM WORKER;
(iii) SELECT DNAME, LOC FROM DEPT WHERE SALARY > 10000;
(iv) SELECT W.WNAME, D.MANAGER FROM WORKER AS W, DEPT AS D
WHERE W.DNO = D.DNO;
(v) SELECT WNAME FROM WORKER WHERE WNAME LIKE 'R%';
35 A table named Products in a database named Inventory stores information about 4
products. The table has the following columns: ProductID (integer, primary key),
ProductName (string), Price (float), and Quantity (integer). Assume the database
username is 'admin' and the password is 'secure123'.
Write a Python code that prompts the user to enter a ProductID and updates the
Quantity of that product by adding 10 to the existing quantity. Handle any potential
errors (e.g., the product ID not existing in the table).
Page 6 of 7
37 Kendriya Vidyalaya No 1 Jaipur is setting up the network between its Different Wings 5
of school campus. There are 4 wings named as – SENIOR(S), JUNIOR(J), ADMIN(A)
and HOSTEL(H).
Distance between various wings are given below:
Wing A to Wing S 80m
Wing A to Wing J 200m
Wing A to Wing H 400m
Wing S to Wing J 70m
Wing S to Wing H 120m
Wing J to Wing H 450m
Page 7 of 7
केन्द्रीय विद्यालय संगठन , कोलकाता संभाग
KENDRIYA VIDYALAYA SANGATHAN , KOLKATA REGION
प्री-बोर्ड परीक्षा / PRE BOARD EXAMINATION 2024-25
कक्षा / Class - XII अविकतम अं क / Maximum Marks : 70
विषय / Subject - Computer Science समय / Time : 3 Hrs.
__________________________________________________________________________
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.
text = "The_quick_brown_fox"
index = text.find("quick")
(1)
result = text[:index].replace("_", "") + text[index:].upper()
print(result)
(A) Thequick_brown_fox
(B) TheQUICK_BROWN_FOX
Page: 1/11
(C) TheQUICKBROWNFOX
(D) TheQUICKBROWN_FOX
What will be the output of the following Python expression?
4.
x=5
y = 10
(1)
result = (x ** 2 + y) // x * y - x
print(result)
(A) 0
(B) -5
(C) 65
(D) 265
What will be the output of the following code snippet?
5.
(1)
text = "Python Programming"
print(text[1 : :3])
(A) Ph oai
(B) yoPgmn
(C) yhnPormig
(D) Pto rgamn
6. What will be the output of the following code?
tuple1 = (1, 2, 3)
tuple2 = tuple1 + (4,)
tuple1 += (5,)
print(tuple1, tuple2) (1)
Page: 2/11
In a relational database table with one primary key and three unique constraints
9.
defined on different columns (not primary), how many candidate keys can be
derived from this configuration?
(1)
(A) 1
(B) 3
(C) 4
(D) 2
10. Fill in the blanks to complete the following code snippet choosing the correct
option:
(A) tell
(B) seek
(C) read
(D) write
11. State whether the following statement is 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 (1)
block.
update()
x=6
reset()
print(x, end='$')
(A) 7@2&6$
(B) 7@6&6$
(C) 7@2&2$
(D) Error
Page: 3/11
Which SQL command can modify the structure of an existing table, such as adding or
13. (1)
removing columns?
Page: 4/11
Q20 and Q21 are Assertion(A) and Reason(R) based questions. Mark the correct
choice as:
(A) Both A and R are true and R is the correct explanation for A
(B) Both A and R are true and R is not the correct explanation for A
(C) A is True but R is False
(D) A is False but R is True
Assertion (A): Python functions can accept positional, keyword, and default
20.
parameters.
Page: 5/11
25. Identify the correct output(s) of the following code. Also write the minimum and
the maximum possible values of the variable b.
import random
text = "Adventure"
b = random.randint(1, 5)
for i in range(0, b):
print(text[i], end='*') (2)
26. The code provided below is intended to reverse the order of elements in a given
list. However, there are syntax and logical errors in the code. Rewrite it after
removing all errors. Underline all the corrections made.
def reverse_list(lst)
if not lst:
return lst (2)
reversed_lst = lst[::-1]
return reversed_lst
print("Reversed list: " reverse_list[1,2,3,4] )
27. (I)
A) What constraint should be applied to a table column to ensure that all values in
that column must be unique and not NULL?
OR
B) What constraint should be applied to a table column to ensure that it can have
multiple NULL values but cannot have any duplicate non-NULL values? (2)
(II)
A) Write an SQL command to drop the unique constraint named unique_email
from a column named email in a table called Users.
OR
B) Write an SQL command to add a unique constraint to the email column of an
existing table named Users, ensuring that all email addresses are unique.
28. A) Explain one advantage and one disadvantage of mesh topology in computer
networks.
OR (2)
B) Expand the term DNS. What role does DNS play in the functioning of the
Internet?
Page: 6/11
Q No. Section-C ( 3 x 3 = 9 Marks) Marks
29. A) Write a Python function that extracts and displays all the words present in a
text file “Vocab.txt” that begins with a vowel.
OR (3)
B) Write a Python function that extracts and displays all the words containing a
hyphen ("-") from a text file "HyphenatedWords.txt", which has a three letter
word before hypen and four letter word after hypen. For example : “for-
them” is such a word.
(A) You have a stack named MovieStack that contains records of movies. Each
30.
movie 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:
(II) pop_movie(MovieStack): This function pops the topmost movie record from the
stack and returns it. If the stack is empty, the function should display "Stack is
empty".
(III) peek_movie(MovieStack): This function displays the topmost movie record (3)
from the stack without deleting it. If the stack is empty, the function should display
"None".
OR
(B) Write the definition of a user-defined function push_odd(M) which accepts a list
of integers in a parameter M and pushes all those integers which are odd from the
list M into a Stack named OddNumbers.
Write the function pop_odd() to pop the topmost number from the stack and
return it. If the stack is empty, the function should display "Stack is empty".
Write the function disp_odd() to display all elements of the stack without deleting
them. If the stack is empty, the function should display "None".
For example:
If the integers input into the list NUMBERS are: [7, 12, 9, 4, 15]
Page: 7/11
31. Predict the output of the following code:
data = [3, 5, 7, 2]
result = ""
for num in data:
for i in range(num):
result += str(i) + "*"
result = result[:-1]
print(result)
OR
Note: The table contains many more records than shown here.
(4)
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 price in descending order.
(III) To display the distinct customer names from the ORDERS table.
(IV) To display the sum of the Price 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;
Page: 8/11
A CSV file "HealthData.csv" contains the data of a health survey. Each record of the
33.
file contains the following data:
Name of a country
Life Expectancy (average number of years a person is expected to live)
GDP per capita (Gross Domestic Product per person)
Percentage of population with access to healthcare
For example, a sample record of the file may be: ['Wonderland', 82.5, 40000, 95].
(4)
Write the following Python functions to perform the specified operations on this
file:
(I) Read all the data from the file in the form of a list and display all those records
for which the life expectancy is greater than 75.
Alex has been tasked with managing the Student Database for a High School. He
34.
needs to access some information from the STUDENTS and SUBJECTS tables for a
performance evaluation. Help him extract the following information by writing the
desired SQL queries as mentioned below.
Table: STUDENTS
S_I FNa LNam Enrollment_Dat Mar
D me e e ks
201 John Doe 15-09-2020 85
202 Jane Smith 10-05-2019 90
203 Alex Johns 22-11-2021 75
(4)
on
204 Emily Davis 30-01-2022 60
205 Mich Brown 17-08-2018 95
ael
Table: SUBJECTS
Field Type
productID int(11)
productName varchar(20)
price float
stockQty int(11)
Write the following Python function to perform the specified operation: (4)
Page: 10/11
From To Distance
OPERATIONS WAREHOUSE 40 m
OPERATIONS CUSTOMER_SUPPORT 90 m
OPERATIONS MAINTENANCE 50 m
WAREHOUSE CUSTOMER_SUPPORT 60 m
WAREHOUSE MAINTENANCE 45 m
CUSTOMER_SUPPORT MAINTENANCE 55 m
Location Computers
OPERATIONS 40
WAREHOUSE 20
CUSTOMER_SUPPORT 25
MAINTENANCE 22
BANGALORE HEAD OFFICE 15
(I) Suggest the most suitable location for the server within the Chennai hub. Justify
your decision.
(II) Recommend the hardware device to connect all computers within each building (5)
efficiently.
(III) Draw a cable layout to interconnect the buildings at the Chennai hub efficiently.
Which type of cable would you recommend for the fastest and most reliable data
transfer?
(IV) Is there a need for a repeater in the proposed cable layout? Justify your
answer.
(V) A) Recommend the best option for live video communication between the
Operations Office in the Chennai hub and the Bangalore Head Office from the
following choices:
• a) Video Conferencing
• b) Email
• c) Telephony
• d) Instant Messaging
OR
(V) B) What type of network (PAN, LAN, MAN, or WAN) would be set up among the
computers within the Chennai hub?
Page: 11/11
KENDRIYA VIDYALAYASANGATHAN REGIONAL OFFICE LUCKNOW
1ST PRE-BOARD EXAMINATION 2024-25
CLASS: XII SUBJECT:COMPUTER SCIENCE
TIME: 3 HOURS M. MARKS: 70
General Instructions:
This question paper coñtains 37 questions.
All questions are compulsory. However, internal choices have been provided in some
questions. Attempt only one of the choices in such questions.
Thepaper is divided into 5 Sections -A, B, C, D and E.
Scction A consists of 21 qestions (1 to 21). Each question carries I mark.
Section B consists of 7 questions (22 to 28). Each question carries 2marks.
Section Cconsists of 3questions (29 to 31). Each question carries 3 marks.
Secion Dconsists of4 questicns (32 to 35). Each question carries 4 marks.
Section Econsists of2questions (36 to 37). Each question carries 5 marks.
Allprogramming questions are to be answered using Python langusge only.
In case of MCQ, text of the correct answer should also be written.
Q
No Section-A (21x1 = 21 marks) Marks
3
Which one of the following is False regarding data types in Python?
A. In python, cxplicit data type conversion is possible
B. Mutable data types are those that can be changed.
C. Immutable data types are those that cannot be changed.
D.Nonc of the above
4
The returntypc of string.split() is a
A. string
B. List
C. Tuple
D. Dictionary
5 1
Given the following dictionary
Empl={"salary": 10000,"dept":"sales","age":24,"name"."iohn"}
Emp1.keys() can givc the output as
1|Page
A. ('salary""dept","age""name")
B. (['salary', 'dept', 'age', 'name'])
C. [10000,"sales",24,"john"]
D. (,salary""dept" age""name"}
Select the correct output of the code: a= "Year 2024 at all the best" 1
a = a.split('a')
b=a[0] + "" + a[1] +""+ a[3]
print (b)
a. Year -0- at All the best
b. Ye-r 2024 -11 the best
c. Year -024- at All the best
d. Year-0- at all the best
9 Which SQL command is used to change some values in existing rows?
a) update b) insert c) alter d) order
2| Pag e
Q.12 and 20 is ASSERTION AND REASONING based questions. Mark the correct choice
as
AN Both A and R are l.u3 and R is the corrcct
explanation for A
2) Both A and R arc truc and R is not thc corrcct
cxplanation for
Ais Truc but Ris False
D) A is false but R is True
12 Assertion (A):- The number of actual parameters in a function call may not 1
be equal tothe number of formal parameters of the function.
Reasoning (R):- During a function call, it is optional to pass the values to
default parameters.
13 Thecorrect definition of column 'alias' is
a. A pcrmaFcent new namc of column
EXpis kC A
D.Anew column of atakio
C.A vicy of cxistingcòlumi with diflcrent iname
d: A column which is recently deleted
14 Select the correct statement, with reference to SQL:
A a. Aggrègate functions igrnore NULLt ii a i tt
b. Aggregate functions consider NULLas zero or Falsc
c. Aggregatc functions trcat NULL as a blankstring
d. NULL can bT Written as 'NULL' alsu.
15 In IYSQL databasc, it atable, Alpha has dogreo 5and cardinality 3, -.nd another
tabl:, Betahas dogreu 3 and cardinality 5, wlut wial be tlhe degrcc and cazdinalityof
thc Cartesian prc.t of Alpha and Belu?
a) 5,3 b) &,15.c) ) 5,.shuc itenen iecnae
16 A is a query that itricves iws lrom morc th¡n on: lable or view:
4. Stu.t b. Eud C. Join d. All of l.:
17 ei; communicatiön protocul responsiblc to control tl.
trans1iissioii of data over a network
a. TCP e(b) SMTPc) PPP (d)HTTP
data
19 Identily thc levice on th: ..twork whiuh is responsible for forwarding
from one device to Jothc.
a. NIC Suter c. RJ45 d. Rcpcater
lhat is uscd to
20 Assertion (A): A fiunctic1 is blocl: iorgiulzcd a.N reu_ablc cods
perform a single related action.
3|Pag e
Reason (R): Function provides better modularity for your application and a high
degree of code reusability.
1
21 Which function is used to display the unique values of a column of a table?
a. sum)
b. unique()
C. distinct()
d. return()
Section -B (7x2 =14 marks)
2
22 Predict the output of the Python code given below:
def Swap (a,b):
if a>b:
print(changed ',end= )
return b,a
else:
print(unchanged ',end=)
return a,b
data-[11,22, 16,50,30]
for iin range (4,0,-1):
print(Swap(data[i],data[i-1])
2
23. a) Rishaan has written a code to input anumber and check whether it is even or
odd number. His code is having errors. Obsrve the following code carefully
and rewrite it after removing all syntax. and logical errors. Underline all the
corrections made.
Def checkNumber(N):
status N%2
return
#main-code
4|Page
print(L1)
(a) [9,9,9] (b) [5,5,5] (c) [6,6,6] (d) Allare possible
OR
import random
num1=int(random.random(+0.5)
numl
What will be the minimum and maximum possible values of variable
2
25 Predict the output of the following code: "5"]
TXT = ["10", "20", "30",
CNT = 3
TOTAL = 0
for C in (7, 5,4,6):
T = TXT [CNT]
TOTAL = float (T) +C
print (TOTAL)
CNT-=1
2
argument and checks whether the
26 The code given below accepts a number as an following code carefully and
given number is perfect number or not. Observe the errors. Underline all the
rewrite it after removing all syntax and logical
corrections made.
define perfectNum (num) :
Sum = 0
For i in range (1, num)
IF n i = 0:
Sum = Sum + i
If sum == n:
print ("The number is a Perfect nunber")
else:
number"}
print ("The number is not a Perfect
number")
num =input ("Enter the
perfectNum (aum)
2
27
Anorganization SoftSolutions is considering to maintain their employees records
that :
using SOQL to store the data. As a database administrator, Mårthy has decided
"Name of the table - HRD¶TA
"The attributes of HRDATA are as follows:
ECode - Numeric
5|Page
Desig -Character of size 5
Remn - numeric
City Hospital is considering to maintain their inventory using SQL to store the data.
As a database administer, Ritika has decided that :
Quantity- numeric
Now Ritika wants to remove the column Quantity from the table CHStore . And she
also wants to display the structure of the table CHStore, i.e, name of the attributes
and their respective data types that she has used in the table. Help her to write the
correct commands.
6|Page
Books are referred to as a man's best friend. They are very beneficial for
mankind and have helped it evolve. Books leave a decep impact on us and are
responsible for uplifting our mood.
The output should be 3.
Tyo list Lname and Lage contains names of persons and age of persons 3
30 respectively. A list named Lnameage is empty. Write functions as details given
below
() Push na):- it willpush the tuple containing pair of name and age from
Lname and Lage whose age is above 50
() Pop_na):- it will remove the last pair of name and age and also print name
and age of removed person. It should also print "underflow'" if there is nothing to
remove
For example, the two lists have following data
Lname-[narender", jaya', 'raju",'ramesh', 'amit',
Piyush']
Lage-[45,23,59,34,5 1,43]
After Push na)Lnameage stack shouid contain:
[(raju',59),(amit ,51l)]
The output of first execution of pop na) should be: The name removed is amit
The age of person i_ 51
OR
7|Page
'Sri Lanka']
The output should be: [Columbo',
('Dubai', UAE]
['Naypyidaw', Myanmar']
Stack Empty 3
31 Predict the output of the code given below:
def convert(Old):
I=len(Old)
New="
for iin range(0,l):
if Old[j],isupper():
New=New+Old[|].lower()
elif Old[j].islower():
New=New+Old[].upper()
elif Old[i].isdigit():
New=New+"
else:
New=New+"%"
return New
Older='InDla@2022'
Newer=Convert(Older)
print('New String is:', Newer)
OR
Textl="IND-23"
Text2=""
I=0
while I<len (Text1) :
if Textl [I] >="0" and Textl [I]<="9":
Val = int (Text1 [I])
Val = Val 1
Text2=Text2 + str (Val)
elif Textl [I]>="A" and Text1 [I]<="Z":
Text2=Text2 + (Text1[I+1])
else:
Text2=Text2 + "*"
I+=1
print (Text2)
8|Page
Section -D (4x4 = 16 marks)
4
32 Consider the tables STORE and SUPPLIERS given below:
TABLE: STORE
SCODE QTY RATE LASTBU
ITEM ITEM
Y
NO
60 2009-01-31
2005 Sharpner Classic 23
25 2010-02-01
2003 Ball Pen 0.25 22 50
150 12 201-02-24
2002 Gel Pen Premium 21 2009-03-11
2006 Gel Pen Classic 21 250 20
6 2009-01-19
2001 Eraser Small 22 220
110 2009-12-02
2004 Eraser Big 22
Ball Pen 0.5 180 18 2009-11-03
2009 21
Table :Suppliers
Scode Sname
21 Premium Stationary
23 Soft plastics
22 Tetra Supply
WriteSQL commands for thc following queries (i) to (iv):
with their
i) Todisplay ItemNo, Item Name and Sname from the tables
corresponding natching Scode.
ii)Display the structure of thc tabl storc.
ii) Display the average ralc of Prcmium Stationary and Tetra Supply.
rates
iv)Display thc item,qty, and rate of products in descending order of
OR
Write SQL commands for the following queries ()to (iv) on the basis of relation
Mobile Master and Mobile Stock.
MOBILE STOCK
S Id M Id M Qty MSupplier
S001 MB004 450 NEW VISION
MB003 250 PRAVEENGALLERY
SO02
MB001 300 CLASSIC MOBILE
SO03
MB006 150 A-ONE MOBILE
S004
MB003 150 THE MOBILE
SO05
MB006 50 MOBILE CENTR=
SO06
9|Page
MOBILE MASTER M Mf Dat
Mld MN MPric
M_Company e
ame 2013-02-12
MB001 SAMSUNG GAL 4500
AXY 2012-04-15
MB003 NOKIA NI10 2250
2016-10-17
MB004 MICROMAX UNITE3 4500
2017-11-20
MB005 SONY XPERIA 7500
M
2010-08-21
MB006 OPPO SELFIEE 8500
X
(0) Display the Mobile Company, Name and Price in descending order of their
manufacturing date
ii) List thc details of mobile whose name starts with "S" or ends with "a"
i) Display M ldand sum of Mobile quantity in cach MId.
iv) List the details of Mobile company name whose mobile price is greater than 5000.
33 (a)Write a Program in Python that defines and calls the following user defined
functions:
(i) InsertRow) - To accept and insert data of a student to a CSV file
'class.csv', Each record consists of a list with field elements as
rollno, name and marks to store roll number, student's name and
marks respectively.
(ii) COUNTD () - To count and return the number of students who
scored
marks greater than 75 stored in the CSVfile named 'class.csv'
Ving tables Consumner and Stationary.
Table: Stationery
SID
Stationary
Name
Company Price
BP01 Ball Pen Reynolds 10
PL02 Pencil Natraj 5
EROS
PL01
Eraser Natra) 3
Pencil Apsara 6
GP02 Gel Pen Reynolds 15
Table: Consumer
CID
01
Consumer Name City S ID
Pen House Delhi PL01
06 Writer wcll Mumbai GP02
12
15
Topper Delhi BP01
Good learrer Delhi PL02
16
Motivation Bangalore PL01
Write SQL statements for (i) to (iv)
(() To display the consumer detail in
(i) To display the Name and Price of descending order of thei.name.
15. Stationaries whose Price is in the range 10 to
(ii) To display the ConsumerName, City and
"Reynolds" Company r StationaryName for stationaries of
iv) To incrcasc the Price of all stationary by 2
Rupees
35
4
(i) Kabir wants to write a program in Python to insert the
the table named Student in MYSQL database, SCHOOL:following record in
rno(Roll number )- integer
namc(Name) - string
DOB (Datc of birth)-Date
Fee - float
The values of fielJs rno, name, DOB and fee has to be accepted from the user. Help
Kabir to write the program in Python.
11 |Page
Section -E (2x5 10 marks)
36
() Differentiate between Binary File and CSV File.
(i) Write apython code toperform the following binary file operations with the
help of two user defincd functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing
student information roll number, name and marks (out of 100) of cach
student.
37 "Vidyadhara" an NGO is planning to setup its new campus at Lucknow its web
based activities. The campus has four (04) UNITS as shown below:
ADMIN TRAINING
UNIT UNIT
RESOURCE
FINANCE UNIT
UNIT
12 | Pag e
TRAINING RESOURCE 50
No Of Computers in
UNIT
various UNITs are:
NO OF COMPUTERS
ADMIN 150
FINANCE 25
TRAINING 90
RESOURCE 75
a) Suggest topology and draw the cable layout to efficiently connect various
of buildings within the Lucknow campus for connecting the blocks
b) Which network device will beused to connect digital devices.
local area network? computers in each block to form a
c) Which block, in Lucknow Csmpus ahould be made the
answer.
server? Justify yur
d) Is there arequirement ofa repeater in the given cable layout?
e) NGO is planning to connect its Regional Office at Delhi, Why Why no?
out of the following wired communication, will you Rajasthun.
connectivity?
suggesi tor a very hgh-specd
Twisted Pair cable (b) Ethernet cable (c) Optical Fiber
12PB24CS04
KENDRIYA VIDYALAYA SANGATHAN, ERNAKULAM REGION
PRE-BOARD EXAMINATION
CLASS: XII COMPUTER SCIENCE (083) Time allowed: 3 Hours
Maximum 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
1 State True or False 1
“Dictionaries in Python are mutable but Strings are immutable.”
True
2 str="R and Data Science" 1
z=str.split()
newstr="=".join([z[2].upper(),z[3],z[2]+z[3],z[1].capitalize()])
newstr is equal to
a) 'DATA=Science=DataScience=And' b) 'DATA=DataScience=And'
c) 'DATA=Science=And' d) 'DATA=Science==DataScience=And'
(a) 'DATA=Science=DataScience=And'
3 Consider the given expression: 1
True and not AAA and not True or True
Which of the following will be correct output if the given expression is evaluated
with AAA as False?
(a) True (b) False (c) NONE (d) NULL
(a) True
4 What shall be the output of the following statement? 1
“TEST”.split(‘T’,1)
(a) [ ‘ ‘, ’ ES ’ ,’ ‘ ] (b) [ ‘T’, ’ ES ’ ,’T’] (c) [ ‘ ‘, ‘ EST ’] (d) Error
(c) [ ' ', 'EST' ]
5 What shall be the output for the execution of the following statement? 1
“ANTARTICA”.strip(‘A’)
(a). NTRCTIC (b). [‘ ‘, ‘NT’, ‘RCTIC’, ‘ ‘] (c). NTARTIC (d). Error
(c) NTARTIC
6 Consider The following: t=(12,13,14,16,[2,3]) 1
1
What changes will be made in t after the execution of the following statement?
t.append(4)
(a) t=(12,13,14,16,[2,3],4) (b) t= (12,13,14,16,[2,3,4])
(c) t=(4,12,13,14,16,12,3) (d) It will give an error
(d) It will give an error
7 What will be the output? 1
test = {1:'A', 2:'B', 3:'C'}
del test[1]
test[1] = 'D'
del test[2]
print(len(test))
(a) 0 (b) 1 (c) 2 (d) Error
8 Predict the output of following code snippet: 1
Lst = [10,20,30,40,50,60,70,80,90]
print(Lst[::3])
(iii) Alter
10 Which of the following options is the correct Python statement to read and display 1
the first 10 characters of a text file “poem.txt” ?
(a) F=open(‘poem.txt’) print(F.load(10))
(b) F=open(‘poem.txt’) print(F.reader(10))
(c) F=open(‘poem.txt’) print(F.read(10))
(d) F=open(‘poem.txt’,) print(F.readline(10))
(c) F = open('poem.txt') print(F.read(10))
11 When will the else part of try-except-else be executed? 1
a) always b) when an exception occurs
c) when no exception occurs d) when an exception occurs in to except block
c) when no exception occurs
12 Find and write the output of following python code: 1
a=100
def show():
global a
a=-80 def
invoke(x=5):
global a
a=50+x
show()
invoke(2)
2
invoke()
print(a)
55
13 Fill in the blank: __________command is used for changing value of a column in a 1
table in SQL.
(a) update (b) remove (c) alter (d) drop
(a) update
14 What will be the output of the query? 1
SELECT * FROM products WHERE product_name LIKE 'BABY%';
(a) Details of all products whose names start with 'BABY'
(b) Details of all products whose names end with 'BABY'
(c)Names of all products whose names start with 'BABY'
(d)Names of all products whose names end with 'BABY'
15 To fetch the multiple records from the result set you may use-- method in SQL? 1
a) fetch() b) fetchmany() c) fetchmultiple () d) None of the mentioned
b) fetchmany()
16 Which function is used to display the total no of records from a table in a database? 1
(a) total() (b) total(*) (c) count(*) (d) count()
(c) count(*)
17 Fill in the blank: is a communication medium, classified as long-distance high speed 1
unguided medium.
(a) Optical fiber (b) Microwave (c) Satellite Link (d)WIMAX
(c) Satellite Link
3
read and written without the need the data conversion
(B) Both A and R are true and R is not the correct explanation for A.
Q No Section-B ( 7 x 2=14 Marks) Marks
22 How are list different from dictionaries. Write two points. 2
Access Method: Lists use indices; dictionaries use keys.
Purpose: Lists store ordered collections; dictionaries store data as key-value
pairs for efficient retrieval.
23 Give two examples of each of the following: 2
(I) Membership operators (II) Identity operators
Membership Operators-in , not in
Identity operators-is, is not
25 What possible outputs are expected to be displayed on screen at the time of execution 2
of the program from the following code? Select correct options from below.
import random arr=['10','30','40','50','70','90','100']
L=random.randrange(1,3)
U=random.randrange(3,6)
for i in range(L,U+1):
print(arr[i],"$",end="@")
a)30 $@40 $@50 $@70 $@90
b)30 $@40 $@50 $@70 $@90 $@
c) 30 $@40 $@70 $@90 $@
d) 40 $@50 $@
b,d
26 2
Sona has written the following code to check whether the number is divisible by3.
4
She could not run the code successfully. Rewrite the code and underline each
correction done in the code.
x=10
for i range in (a):
if i%3=0:
print(i)
else: pass
x = 10
for i **in** range(x):
if i % 3 **==** 0:
print(i)
else:
pass
27 (I) A) Differentiate ORDER BY and GROUP BY with an example. 2
The ORDER BY clause is used to sort the result set (the rows returned by a
query) in either ascending (ASC) or descending (DESC) order based on one or
more columns.
The GROUP BY clause is used to group rows that have the same values in
specified columns. It is typically used with aggregate functions like COUNT(),
SUM(), AVG(), etc., to perform operations on each group of rows.
OR
B) Classify the following statements into DDL and DML a)delete b)drop table
c)update d)create table
DDL Commands: DROP TABLE, CREATE TABLE (altering the structure of
database objects).
DML Commands: DELETE, UPDATE (modifying the data within tables)
(II)
A) What do you understand by VARCHAR datatype in a table? Give a suitable
example and differentiate the same with the data type CHAR.
VARCHAR is more flexible and space-efficient for variable-length data, while
CHAR is best suited for fixed-length data where space usage consistency is
important.
OR
B) Categorize the following commands as Group by /Math function: count(),
pow(), round(), avg()
Group by Functions: COUNT(), AVG()
Math Functions: POW(), ROUND()
5
28 A) Expand the following terms: i)MAN ii)HTML 2
MAN: Metropolitan Area Network
HTML: HyperText Markup Language
OR
B) What is URL ?
A URL (Uniform Resource Locator) is the address used to access resources on
the internet. It specifies the location of a web resource (like a webpage, an image,
or a file) and the method to retrieve it. URLs are used by browsers to find and
display the requested resources.
Q No. Section-C ( 3 x 3 = 9 Marks) Marks
29 A) Write a function linecount() in python which read a file ‘data.txt’ and count 3
number of lines starts with character ‘P’.
def linecount():
count = 0
open('data.txt', 'r')
for line in file:
if line.startswith('P'):
count += 1
return count
OR
B) Write a function in python to count number of words ending with ‘n present in a
text file “ABC.txt” If ABC.txt contains “A story of a rich man And his son”, the
output of the function should be Count of words ending with ‘n’ is 2
def count_words_ending_with_n(file_name):
# Open the file in read mode
with open(file_name, 'r') as file:
content = file.read() # Read the content of the file
# Split the content into words
words = content.split()
# Count words that end with 'n' (case insensitive)
count=0
for word in words
if word.lower().endswith('n'))
count=count+1
print(f"Count of words ending with 'n' is “,count)
30 A) A list, items contain the following record as list elements [itemno, itemname, 3
stock]. Each of these records are nested to form a nested list.
Write the following user defined functions to perform the following on a stack
reorder .
i. Push(items)- it takes the nested list as its argument and pushes a list object
containing itemno and itemname where stock is less than 10
6
ii. Popitems() -It pops the objects one by one from the stack reorder and also
displays a message ‘Stack empty’ at the end.
items=[[101,'abc',8],[102,'gg',12],[103,'tt',5],[104,'yy',15]]
reorder=[]
def Push(items):
for i in items:
if i[2]<10:
reorder.append([i[0],i[1]])
Push(items)
reorder [[101, 'abc'], [103, 'tt']]
def Popitems():
while len(reorder):
print(reorder.pop())
else:
print("Stack empty")
Popitems()
OR
(B) Write a function RShift(Arr) in Python, which accepts a list Arr of numbers and
places all even elements of the list shifted to left.
Sample Input Data of the list Arr= [10,21,30,45,12,11],
Output Arr = [10, 30, 12, 21, 45, 11]
def RShift(Arr):
# Separate even and odd elements
even_elements = [num for num in Arr if num % 2 == 0]
odd_elements = [num for num in Arr if num % 2 != 0]
# Combine even elements followed by odd elements
Arr[:] = even_elements + odd_elements
return Arr
str1 = ""
for key in d:
str1 = str1 + str(d[key]) + "@" + “\n”
str2 = str1[:-1]
print(str2)
15@
7@
7
9@
OR
2,2,0,1,2,
8
WHERE Gender = 'Male';
OR
B) Write the output
(I) Select city, sum(basicsalary) as Salary from EMPLOYEE group by city;
city Salary
------------------------------------
Udhamwara 92000
Kupwara Nagar 75000
Bhawani 45000
Ahmed Nagar 50000
Nagar Coolangetta 33000
NewDelhi 40000
max(basicsalary)
----------------------
75000
33 A csv file "furdata.csv" contains the details of furniture. Each record of the file 4
contains the following data:
● Furniture id
● Name of the furniture
● Price of furniture
For example, a sample record of the file may be:
[‘T2340’, ‘Table’, 25000]
Write the following Python functions to perform the specified operations on this
9
file:
a. add() – To accept and add data of a furniture to a CSV file furdata.csv. Each
record consists of a list with field elements as fid, fname, fprice to store furniture
id, furniture name and furniture price respectively
b. search() – To display the records of the furniture whose price is more than
10000.
import csv
# Function to add furniture data to the CSV file
def add():
with open('furdata.csv', 'a', newline='') as file:
writer = csv.writer(file)
fid = input("Enter Furniture ID: ")
fname = input("Enter Furniture Name: ")
fprice = float(input("Enter Furniture Price: "))
record = [fid, fname, fprice]
writer.writerow(record)
print("Furniture record added successfully!")
# Function to search and display furniture with price more than 10000
def search():
with open('furdata.csv', 'r') as file:
reader = csv.reader(file)
34 Write the output of the SQL commands for (i) to (iv) on the basis of 4
tables BOOKS and ISSUES.
Table: BOOKS
Book_id BookName AuthorName Publisher Price Qty
10
L05 Telugu Nannayya DEF 60 25
L02 13
L04 5
L05 21
(I) To display complete details (from both the tables) of those Books whose quantity
issued is more than 5.
Select * from BOOKS, ISSUES where Qty>5 and
BOOKS.Book_id=ISSUES.Book_id;
(II) To display the details of books whose quantity is in the range of 20 to 50 (both
values included).
Select * from BOOKS where Qty between 20 and 50;
(III) To increase the price of all books by 50 which have "DEF” in their PUBLISHER
names.
Update BOOKS set Price=Price+50 where Publisher like '%DEF%';
(IV) (A) To display names (BookName and AuthorName) of all books.
Select BookName, AuthorName from BOOKS;
OR
(B) To display the Cartesian Product of these two tables.
Select * from BOOKS, ISSUES;
35 A table, named STUDENT, in SCHOOL database, has the following structure: 4
Field Type
Rollno integer
Name string
Clas integer
Mark integer
11
import mysql.connector
def AddStudent():
mydb = mysql.connector.connect(host="localhost",user="root",
password="root",database="SCHOOL")
cursor = mydb.cursor()
rollno = int(input("Enter Roll No: "))
name = input("Enter Name: ")
clas = int(input("Enter Class: "))
mark = int(input("Enter Mark: "))
query = "INSERT INTO STUDENT (Rollno, Name, Clas, Mark) VALUES
(%s, %s, %s, %s)"
values = (rollno, name, clas, mark)
cursor.execute(query, values)
mydb.commit()
print("Student record added successfully!")
# Retrieve and display all records where Mark is greater than 80
cursor.execute("SELECT * FROM STUDENT WHERE Mark > 80")
results = cursor.fetchall()
# Display the results
if results:
print("\nStudents with marks greater than 80:")
for row in results:
print(f"Rollno: {row[0]}, Name: {row[1]}, Class: {row[2]}, Mark:
{row[3]}")
else:
print("No students found with marks greater than 80.")
12
book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = float(input("Enter Price: "))
book_record = [book_no, book_name, author, price]
pickle.dump(book_record, file)
cont = input("Do you want to add another record? (yes/no): ").lower()
if cont != 'yes':
break
37 Vidya for all is an NGO. It is setting up its new campus at Jaipur for its web-based 5
activities. The campus has four buildings as shown in the diagram below
13
Resource building to Training building 125m
Resource building 25
Training building 10
Main Finance
Resource Training
14
*************************************
15