Study Material Xii CS
Study Material Xii CS
Study Material Xii CS
ं ाग
KENDRIYA VIDYALAYA SANGATHAN,
MUMBAI REGION
हमारे सरं क्षक
OUR PATRONS
3. Distribution of Marks:
Unit Unit Name Marks Periods
No.
Theory Practical
5. Practical
S.No Marks
Unit Name
. (Total=30)
1 Lab Test:
2 Report file: 7
• Minimum 15 Python programs.
• SQL Queries – Minimum 5 sets using one table /
two tables.
• Minimum 4 programs based on Python - SQL
connectivity
3 Project (using concepts learnt in Classes 11 and 12) 8
4 Viva voce 3
8. Project
The aim of the class project is to create something that is tangible and useful using Python file handling/
Python-SQL connectivity. This should be done in groups of two to three students and should be started
by students at least 6 months before the submission deadline. The aim here is to find a real world problem
that is worthwhile to solve.
Students are encouraged to visit local businesses and ask them about the problems that they are facing.
For example, if a business is finding it hard to create invoices for filing GST claims, then students can do a
project that takes the raw data (list of transactions), groups the transactions by category, accounts for the
GST tax rates, and creates invoices in the appropriate format. Students can be extremely creative here.
They can use a wide variety of Python libraries to create user friendly applications such as games, software
for their school, software for their disabled fellow students, and mobile applications, of course to do some
of these projects, some additional learning is required; this should be encouraged. Students should know
how to teach themselves.
The students should be sensitised to avoid plagiarism and violations of copyright issues while working on
projects. Teachers should take necessary measures for this.
BLUE-PRINT
SAMPLE QUESTION PAPER SESSION 2022-23
CLASS-XII (COMPUTER SCIENCE-083)
(+3 marks
DATABASE
python-
7 MANAGEME 3 2 2 1 20
mysql
NT
interface)
Identifiers
In programming languages, identifiers are names used to identify (Name) a variable, function, or other entities
in a program. The rules for naming an identifier in Python are as follows:
➔ The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
➔ This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_) Thus, an identifier
cannot start with a digit.
➔ It can be of any length. (However, it is preferred to keep it short and meaningful).
➔ It should not be a keyword or reserve word.
➔ We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Variables
A variable in a program is uniquely identified by a name (identifier). Variable in Python refers to an object —
an item or element that is stored in the memory. Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’),
numeric (e.g., 345) or any combination of alphanumeric characters (CD67). In Python we can use an
assignment statement to create new variables and assign specific values to them.
Comments
Comments are used to add a remark or a note in the source code. Comments are not executed by interpreter.
Comments in python can be created as:
➔ for single line comment use # (hash symbol)
➔ for multi line comment use ‘‘‘ text ’’’ (in triple quotes)
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data values a variable
can hold and the operations that can be performed on that data.
Number
Number data type stores numerical values only. It is further classified into three different types: int,
float and complex.
Try the following statements on system in shell mode and observe the output:
num1 = 10 #(integer positive value )
type(num1)
float1 = -1921.9 #(float1 variable contain decimal value so it contains float value)
type(float1)
float2 = -9.8*10**2 #(float2 variable contain decimal value so it contains float value)
print(float2, type(float2))
Boolean
var3= True # (var3 variable contain Boolean Value)
print(type(var3)) # print type Bool
Variables of simple data types like int, float, boolean, etc. hold single values. But such variables are not useful
to hold a long list of information, for example, names of the months in a year, names of students in a class,
names and numbers in a phone book or the list of artefacts in a museum. For this, Python provides data types
like tuples, lists, dictionaries and sets.
Sequences can used as datatype in python
A Python sequence is an ordered collection of items, where each item is indexed by an integer. The three
types of sequence data types available in Python are Strings, Lists and Tuples. A brief introduction to these
data types is as follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special characters including
spaces. String values are enclosed either in single quotation marks (e.g., ‘KV’) or in double quotation marks
(e.g., “Vidyalaya”). The quotes are not a part of the string, they are used to mark the beginning and end of the
string for the interpreter. For example:
Write your examples here:
Prove this statement using proper example: We cannot perform numerical operations on strings, even
when the string contains a numeric value.
(B) List
List is a sequence of items separated by commas and the items are enclosed in square brackets [ ]. In list we
can change the items so we can say it’s a mutable datatype
#To create a list
list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1) # printing the elements of list1
Output: [5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).Once created,
we cannot change the tuple (Records cannot be changed) – i.e. we can say immutable datatype.
Tuple can be defined as
T=5,
T=(5,)
T=5,6,7,8
T= ‘a’,’b’,’c’,5,6,7
T=(5,6,’r’,’s’,’wel’)
(D) Dictionary
Dictionary in Python holds data items in key : value pairs. Items in a dictionary are enclosed in curly braces {
}. Every key is separated from its value using a colon (:) sign. The key : value pairs of a dictionary can be
accessed using the key. The keys are usually strings and their values can be any data type. In order to access
any value in the dictionary, we have to specify its key in square brackets [ ].
#create a dictionary
dict1 = {'Fruit':'Apple', 1:'Monday', 'Price Rs':120}
print(dict1)
output: {'Fruit': 'Apple', 1: ‘Monday’,'Price Rs': 120}
print(dict1['Price Rs'])
output: 120
print(dict1[1])
output:’Monday’
(E) None
None is a special data type with a single value. It is used to signify the absence of value in a situation. None
supports no special operations, and it is neither False nor 0 (zero).
myVar = None
print(type(myVar))
<class 'NoneType'>
print(myVar)
* For operators with equal precedence, the expression is evaluated from left to right except ** which is executed from right to
left.
Flow of Control
Selection
2)
if condition:
statement(s)
else:
statement(s)
3)
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
NOTE
Indentation
Python uses indentation for block as well as for nested block structures. Leading whitespace (spaces and tabs)
at the beginning of a statement is called indentation. In Python, the same level of indentation associates
statements into a single block of code. The interpreter checks indentation levels very strictly and throws up
syntax errors if indentation is not correct. It is a common practice to use a single tab for each level of
indentation.
Repetition
Repetition of a set of statements in a program is made possible using looping constructs.
The ‘for’ Loop
The for statement is used to iterate over a range of values or a sequence. The for loop is executed for each of
the items in the range. These values can be either numeric, or they can be elements of a data type like a string,
list, tuple or even dictionary.
Syntax of the for Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
The ‘while’ Loop
The while statement executes a block of code repeatedly as long as the control condition of the loop is true.
The control condition of the while loop is executed before any statement inside the loop is executed. After
each iteration, the control condition is tested again and the loop continues as long as the condition remains
true. When this condition becomes false, the statements in the body of loop are not executed and the control
is transferred to the statement immediately following the body of while loop. If the condition of the while
loop is initially false, the body is not executed even once.
Syntax of while Loop
while test_condition:
body of while
STRINGS IN PYTHON
Python strings are characters enclosed in quotes of any type – single quotation marks, double quotation marks and
triple quotation marks. An empty string is a string that has 0 characters. Python strings are immutable.
Strings are sequence of characters, where each character has a unique position-id/index. The indexes of a string
begin from 0 to (length -1) in forward direction and -1,-2,-3,….,-length in backward direction.
STRING SLICES
In Python, the term ‘string slice’ refers to a part of the string, where strings are sliced using a range of indices. That
is, for a string say name, if we give name[n:m] where n and m are integers and legal indices, Python will return a
slice of the string by returning the characters falling between indices n and m starting at n, n+1, n+2, … till m-1.
0 1 2 3 4 5 6
word a m a z i n g
-7 -6 -5 -4 -3 -2 -1
Then,
word[0:7] will give ‘amazing’
word[0:3] will give ‘ama’
word[2:5] will give ‘azi’
word[-7:-3] will give ‘amaz’
word[-5:-1] will give ‘azin’
In a string slice, you give the slicing range in the form [<begin-index>:<last>]. If, however, you skip of the begin-
index or last, Python will consider the limits of the string, i.e., for missing begin index, it will consider 0 (the first
index) and for mission last value, it will consider length of the string. Consider the following examples to understand
this:
word[:7] will give ‘amazing’
word[:5] will give ‘amazi’
word[3:] will give ‘zing’
word[5:] will give ‘ng’
Note: Using the same string slicing technique, you will find that for any index n, s[:n]+s[n:] will give you original
string s.
STRING FUNCTIONS AND METHODS
Every string object that you create in Python is actually an instance of String class. The string manipulation methods
that are being discussed below can be applied to string as per following syntax:
<stringObject>.<methodname>()
1. string.capitalize(): Returns a copy of the string with its first character capitalized
Exmple: ‘true’.capitalize() will return ‘True’
‘i love my India’.capitalize() will return ‘I love my India’
2. string.title(): Returns a copy of the string with first character of each work capitalized.
Example: ‘true’.title() will return ‘True’
‘i love my india’.capitalize() will return ‘I Love My India’
3. string.upper(): Returns a copy of the string converted to uppercase. Examples:
string.upper() will return ‘HELLO’
string2.upper() will return ‘THERE’
string3.upper() will return ‘GOLDY’
4. string.lower(): Returns a copy of the string converted to lowercase. Examples:
string.lower() will return ‘hello’
string2.lower() will return ‘there’
string3.lower() will return ‘goldy’
5. string.count(str): Returns the count of an string in the given string. Examples:
‘I love my india’.count(‘i’) will return 2
‘it goes as – ringa ringa roses’.count(‘ringa’) will return 2
6. string.find(sub[,start,end]): Returns the lowest index in the string where the substring sub is found within the
slice range of start and end. Returns -1 if sub is not found. Example:
string = ‘it goes as – ringa ringa roses’
sub = ‘ringa’
string.find(sub) will return 13
string.find(sub,15,22) will return -1
string.find(sub,15,25) will return 19
7. string.index(str): Returns the lowest index in the sting where the substring is found. Example:
‘I love my India’.index(‘o) will return 3
‘I love my India’.index(‘my’) will return 7
8. string.isalnum(): Returns True if the characters in the string are alphanumeric (alphabets or numbers) and
there is at least one character, False otherwise. Example:
string =”abc123”
string2 = ‘hello’
string3 = ‘12345’
string4 = ‘ ’
string.isalnum() will return True
string2.isalnum() will return True
string3.isalnum() will return True
string4.isalnum() will return False
9. string.islower(): Returns True if all cased characters in the string are lowercase. Examples:
string = ‘hello’
string2 = ‘THERE’
string3 = ‘Goldy’
string.islower() will return True
string2.islower() will return False
string3.islower() will return False
10. string.isupper(): Returns True if all cased characters in the string are uppercase. Examples:
string.isupper() will return False
string2.isupper() will return True
string3.isupper() will return False
11. string.isspace(): Returns True if there are only whitespace characters in the string. Examples:
string = “ “
string2 = “”
string.isspace() will return True
string2.isspace() will return False
12. string.isalpha(): Returns True if all characters in the string are alphabetic and there is at least one character,
False otherwise. Example:
string.isalpha() will return False
string2.isalpha() will return True
string3.isalpha() will return False
13. string.isdigit(): Returns True if all the characters in the string are digits. There must be at least one character,
otherwise it returns False. Example:
string.isdigit() will return False
string2.isdigit() will return False
string3.isdigit() will return True
14. string.split([<sep>]): This function splits the string to form a list of strings.
If we do not provide any argument to split then by default it will split the given string considering whitespace as
a separator, e.g.,
“I Love Python”.split() will give [‘I’, ‘Love’, ‘Python’]
If we provide a string or a character as an argument to split(), then the given string is divided into parts
considering the given string/character as separator and separator character is not included in the split strings,
e.g.,
“I Love Python”.split(‘o’) will give [‘I L’, ’ve Pyth’, ’n’]
15. string.partition(<sep>): The partition() method searches for a specified string, and splits the string into a tuple
containing three elements. The first element contains the part before the specified string. The second element
contains the specified string. The third element contains the part after the string.
Example: ‘I Love my India’.partition(‘my’) will give (‘I Love ’, ‘my’, ‘ India’)
16. string.lstrip([chars]): Returns a copy of the string with leading characters removed.
If used without any argument, it removes the leading whitespaces.
One can use optional chars argument to specify a set of characters to be removed.
The chars argument is not a prefix; rather, all combinations of its values (all possible substrings from the given
string argument chars) are stripped when they lead the string.
Examples:
string = “hello”
string.lstrip() will return ‘hello’
string2 = ‘There’
string2.lstrip(‘the’) will return ‘There’
string2.lstrip(‘The’) will return ‘re’
string2.lstrip(‘he’) will return ‘There’
string2.lstirp(‘Te’) will return ‘here’
string2.lstrip(‘Teh’) will return ‘re’
string2.lstrip(‘heT’) will return ‘re’
“saregamapadhanisa”.lstrip(“tears”) will return ‘gamapadhanisa’
“saregamapadhanisa”.lstrip(“races”) will return ‘gamapadhanisa’
17. string.rstrip([chars]): Returns a copy of the string with trailing characters removed.
If used without any argument, it removes the trailing whitespaces.
The chars argument is a string specifying the set of characters to be removed.
The chars argument is not a suffix; rather, all combinations of its values are stripped.
Examples:
string = ‘hello’
string.rstrip() will return ‘hello’
string2 = ‘There’
string2.rstripe(‘ere’) will return ‘Th’
string2.rstrip(‘care’) will return ‘Th’
Dictionary
Dictionaries are mutable unordered collections with elements in the form of a {key:value pairs that associate keys to
values.
Characteristics of a Dictionary
1. Unordered Set: A dictionary is a unordered set of key:value pairs. Its values can contain references to any
type of object.
2. Not a sequence: Unlike a string, list and tuple, a dictionary is not a sequence because it is unordered set of
elements.
3. Indexed by Keys, Not Numbers: Dictionaries are indexed by keys and not by any index like in sequences.
4. Keys must be unique: Each of the keys within a dictionary must be unique. Since keys are used to identify
values in a dictionary, there cannot be duplicate keys in a dictionary. However, two unique keys can have
same values, e.g. consider the BirdCount dictionary here:
BirdCount = {“Finch”:10, “Myna”:13, “Parakeet”:16, “Hornbill”:15, “Peacock”:15}
5. Mutuable: Like lists, dictionaries are also mutable. We can change the value of a certain key “in place” using
the assignment as per syntax:
<dictionary>[<key>] = <value>
For example,
>>>dict1[“3”]
“Yamuna”
>>>dict1[“3”] = “Ganga”
>>>dict1[“3”]
‘Ganga’
6. Internally stored as Mappings: Internally, the key:value pairs of a dictionary are associated with one another
with some internal function (called hash function).this way of linking is called mapping.
Dictionary functions
1. The len() function
This method returns length of the dictionary, i.e., the count of elements (key:value pairs) in the dictionary. The
syntax to use this method is given below:
len(<dictionary>)
For example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(len(Employee))
3
2. The clear() function
This method removes all items from the dictionary and the dictionary becomes empty dictionary. The syntax to
use this method is given below:
<dictionary>.clear()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
Employee.clear()
print(Employee)
{}
3. The get() function
With this method, you can get the item with the given key, similar to dictionary[key], If the key is not present
Python by default gives error, but you can specify your own message through default argument as per following
syntax:
<dictionary>.get(<key>,[default])
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24, ‘dept’:’Sales’}
print(Employee.get(‘dept’))
Sales
print(Employee.get(‘designation’))
NameError:name ‘designation’ is not defined
>>>Employee.get(‘designation’, “Error! Key not found”)
Error! Key not found
4. The items() function
This function returns all of the items in the dictionary as a sequence of (key, value) tuples. Note that these
are returned in no particular order
<dictionary>.items()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
myList = employee.items()
for x in myList:
print(x)
The output of the above code will be like:
(‘salary’, 10000)
(‘age’, 24)
(‘name’, ‘John’)
5. The keys() method
This method returns all of the keys in the dictionary as a sequence of keys in form of a list. Syntax to use this
method is:
<dictionary>.keys()
Example:
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(Employee.keys())
[‘salary’,’age’,’name’]
6. The values() function
This method returns all the values from the dictionary as a list. The syntax to use this method is given below:
<dictionary>.values()
Example
Employee = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
print(Employee.values())
[‘Jhon’,10000,24,]
7. The update() function
This function merges key:value pairs from the new dictionary into the original dictionary, adding or replacing as
needed. The items in the new dictionary are added to the old one and override(overwrite) any item already
there with the same keys. The syntax to use this method is given below:
<dictionary>.update(<other-dictionary>)
Example:
Employee1 = {‘name’:’John’, ‘salary’:10000, ‘age’:24}
Employee2 = {‘name’:’Diya’, ‘salary’:54000, ‘dept’:’Sales’}
Employee1.update(Employee2)
print(Employee1)
{‘salary’:54000, ‘dept’:’Sales’, ‘name’:’Diya’, ‘age’:24}
8. The fromkeys() function
This method creates a dictionary from the given sequence of keys and a value. It assigns same value for all
keys. If value is not given then it assigns None as the value of all keys. Its syntax is:
<dict-var> = dict.fromkeys(<key-sequence> [,<value>])
For example:
month = [‘Jan’, ‘Mar’, ‘May’]
d1 = dict.fromkeys(month, 31)
print(d1)
will give us:
{'Jan': 31, 'Mar': 31, 'May': 31}
and
d2 = dict.fromkeys(month)
print(d2)
will give us:
{'Jan': None, 'Mar': None, 'May': None}
9. The copy() function
This method creates a copy of the dictionary. This method does not make any change in the original dictionary.
It only makes a copy of this dictionary. Its syntax is:
<dict-var> = <original-dict>.copy()
For example:
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
d2 = d1.copy()
print(d2)
will give us:
{‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
10. The pop() function
Like lists pop() method removes an element from a dictionary. This method removes a key:value pair from the
dictionary and returns the value removed. For this a key need to be specified. This method also has an
optional argument for default value if the key is not present in the dictionary. Its syntax is:
<dict>.pop(<key>[,<default-value>])
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
print(d1.pop(‘Jan’))
31
d1.pop(‘Jul’,”Element not present”)
Element not present
11. The popitem() function
In Python 3.7 and higher version this method of dictionary removes the last inserted key:value pair from the
dictionary and return it as a tuple. Its syntax is:
<dict>.popitem()
For example:
d1 = {‘Jan’:31, ‘Feb’:28, ‘Mar’:31}
print(d1.popitem())
(‘Mar’, 31)
12. The setdefault() method
This method of dictionary takes two arguments key and default-value. If key is found in the dictionary then it
returns its corresponding value. If key is not found in the dictionary then it inserts the default-value with key
in the dictionary and returns default-value. If default-value is not given then None is inserted as default-
value of the key and returns nothing. Its syntax is:
<dict>.setdefault(<key>[,<default-value>])
For example:
>>>d1={'Jan':31, 'Feb':28, 'Mar':31}
>>>d1.setdefault('Jan')
31
>>>d1.setdefault('Apr',30)
30
>>>d1.setdefault('May')
>>>d1
{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': None}
13. The max() function
This function when applied with dictionary returns the maximum key value of all keys of dictionary.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
print(max(d1))
‘Mar’
14. The min() function
This function when applied with dictionary returns the smallest key value of all keys of dictionary.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
print(min(d1))
‘Feb’
15. The sorted() function
This function returns the keys of the dictionary in ascending order in the form of a list.
For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
sorted(d1)
['Feb', 'Jan', 'Mar']
For getting result in descending order use reverse=True with sorted() function.
sorted(d1,reverse=True)
['Mar', 'Jan', 'Feb']
Functions
Definition: Function is a named sequence of statements used to perform specific task when it is invoked.
Functions may or may not return value. It contains statements, which are sequentially executed from top to
bottom by python Interpreter. Once defined, a function can be called repeatedly from different places of the
program without writing same code of that function every time, or it can be called from inside another
function, by simply writing the name of the function and passing the required parameters, if any
2) Built –in- These functions are built into Python and can be accessed by a programmer. We don’t have to
import any module (file) to these functions.
Following are some built-in functions in python:-
Name of the function Description Example
abs (x) It always gives positive numeric >>>abs(-4)
4
value in answer.
>>>abs(119L)
119
>>> abs(100)
100
max( x, y, z, .... ) It returns the largest of its >>>max(8, 10, 100)
100
arguments: where x, y and
>>>max(-80, -20, -10)
z are numeric variable -10
min( x, y, z, .... ) It returns the smallest of its >>> min(8, 10, 100)
arguments; where x, y, and 8
z are numeric variable >>> min(-80, -20, -10)
-80
len (s) Return the length (the >>> a= [1,2,3]
number of items) of an >>>len (a)
object. The argument may 3
be a sequence (string, tuple >>> b= „Hello‟
or list) or a mapping >>> len (b)
(dictionary). 5
round( x [, n] ) It returns float x rounded >>>round(80.23456, 2)
to n digits from the 80.23
decimal point, where x and >>>round(-100.000056, 3)
n are numeric expressions. -100.0
If n is not provided then x >>> round (80.23456)
is rounded to 0 decimal 80.0
digits.
range (start, stop[, step]) It generates a list of numbers. It is >>> range(10)
often used in for loops. The [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
arguments must be integers. >>> range(1, 11)
If the step argument is omitted, it [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
defaults to 1. >>> range(0, 30, 5)
If the start argument is omitted, it [0, 5, 10, 15, 20, 25]
defaults to 0. >>> range(0, 10, 3)
If step is positive, the last element [0, 3, 6, 9]
is the largest start + i * step less >>> range(0, -10, -1)
than stop; [0, -1, -2, -3, -4, -5, -6, -7,
if step is negative, the last element -8, -9]
is the smallest start + i * step >>> range(0)
greater than stop. Step must not [ ] empty list
be zero >>> range(1, 0)
[ ] empty list
3) User defined-
User defined functions are those functions which are defined by the programmer for their convenience.
To define a function def keyword is used.
Syntax-
def <Function name> ([parameter 1, parameter 2,…..]) : FUNCTION HEADER
4) Any change made to the global variable will 4) Any change made to the local variable will
impact all the functions in the program where not impact all the functions in the program
that variable can be accessed. where that variable can be accessed.
5) It exists throughout the program 5) It exists only till the function executes.
Example:
x=5 Global variable
def try(): Output is:
x = 10 Local variable local x : 10
print("local x:", x) global x : 5
print("global x:", x)
Default Parameter
A default value is a value that is predefined and assigned to the parameter when the function call does not
have its corresponding argument.
Example:
def simple_interest(p, n, r=2): Here r is default parameter
si = 0.0
si = float(p*n*r)/float(100)
return si
p = float(input("Enter p: "))
n = int(input("Enter n: "))
simple_interest = simple_interest (p,n)
print("Simple interest value: %.2f" % simple_interest)
(A) A
(B) B
(C) a
(D) Error
1) Write a program with a user defined function to count the number of times a character (passed as
argument) occurs in the given string.
Source code:
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)
Output:
Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3
2) Write a program with a user defined function with string as a parameter which replaces all vowels in the
string with '*'.
Source code:
def replaceVowel(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:",st)
print("The modified String is:",st1)
Output:
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld
3) Write a program which reverses a string passed as parameter and stores the reversed string in a new
string. Use a user defined function for reversing the string.
Source code:
def reverseString(st):
newstr = '' #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr
Output:
Enter a String: Hello World
The original String is: Hello World
The reversed String is: dlroW olleH
4) Write a program using a user defined function to check if a string is a palindrome or not. (A string is called
palindrome if it reads same backwards as forward.
For example, Kanak is a palindrome.)
def checkPalin(st):
i=0
j = len(st) - 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
print("The given string",st,"is a palindrome")
else:
print("The given string",st,"is not a palindrome")
Output 1:
Enter a String: kanak
The given string kanak is a palindrome
Output 2:
Enter a String: computer
The given string computer is not a palindrome
Output is:
Enter string:applee
2
UNIT-I
FILE HANDLING IN PYTHON
ABOUT FILE:
A file is a sequence of bytes contain data and store it on some storage device. File handling is an
important part of any computer application.
➔ Sometime the output generated by a program is large thus file help to store that huge data.
TYPES OF FILES
Text Files:
A file whose contents can be viewed using a text editor is called a text file. A text file is simply a
sequence of ASCII or Unicode characters. In text file, translation will take place after the EOL or delimiter
is encountered. Thus, it is slower than binary file.
Binary Files:
A binary file stores the data in the same way as stored in the memory. In Binary file there is no
delimiter for a line. The file contents returned by a binary file is raw i.e. with no translation, thus Binary
files are faster than text files.
CSV Files:
CSV stands for Comma Separated Values. CSV is just like a text file, in a human readable format
which is extensively used to store tabular data, in a spreadsheet or database. The separator character of
CSV files is called a delimiter. Default delimiter is comma (,). Other delimiters are tab (\t), colon (:), pipe (|),
semicolon (;) characters.
In Python, any type of File Handling consists the following three steps:
1. Opening of a file with specific mode. Using open () method / with statement of python.
The first step of file handling is to open the file by specifying file-path and file-mode. If no file-mode is
specified by default file will be open in reading mode.
Example: f = open(“demo.txt”,”r”)
2) Using Python ‘with’ statement: -
Absolute Path:
• Absolute file paths are notated by a leading forward slash or drive label.
Example C:\\KVSROMUMBAI\\demo.txt
• An absolute path, which always begins with the root folder.
Relative Path:
A relative path, is relative to the program’s current working directory.
CLOSING A FILE: -
close() method is use to close the opened file. In python files are automatically close at the end of the
program but it is advisable to close a file after the end of the program.
S yntax: <fileObject>.close()
Example : f.close()
Moreover, if file has opened using ‘with’ statement of python then it will automatically close after
the nested block of code.
1. read() - The read() method returns the whole text in the form of string. You can also specify how
many characters you want to return by passing the size as argument.
Syntax: <file_object>.read([n]) where n is the No. of bytes that we want to read from the file.
b) <file_object>.read(n) – It will read exactly n bytes from the beginning of the file.
Example:
f = open("demo.txt", "r")
Syntax: <file_object>.readline()
Example
f = open("demo.txt", "r")
3. readlines() – This method will return a list of strings, each separated by \n. readlines() can be used to read
the entire content of the file.
Syntax: <file_object>.readlines()
# Program to print the first and last line of the text file abcd.txt
myf=open("abcd.txt","r")
lst=myf.readlines()
print(lst[0]) # Used to print the first line
print(lst[-1]) # Used to print the last line
myf.close()
myf=open("abcd.txt","r")
lst=myf.readlines()
n =int(input('Enter how many lines you wish to print from last'))
for i in range(-1,-n-1,-1):
print(lst[i])
myf.close()
myf=open("myfile.txt","r")
x=myf.read()
c=0
for i in x:
if(i.isdigit()):
c=c+1
print('Total digits=',c)
myf.close()
The read() method reads data from a text file, and store its contents in a string type variable. It
can either read the whole content from the file if any parameter is not passed inside read method,
otherwise if n is passed inside read() the method will read n number of characters.
The readline() function reads data line by line from the text file. At a time it will return one line
of data in the form of string.
The readlines() function reads all lines and return them in a list.
Now, carefully watch the given code and then identify the data type of record1 and record2?
file = open("portfolio.txt")
record1 = file.readlines()
file.close()
file = open("portfolio.txt")
record2 = file.read()
file.close()
FILE = open("quotes.txt")
LC = 0
DATA = FILE.readlines()
for L in DATA:
if L[0] == 'B':
LC += 1
print("No. of lines starts with B =",LC)
FILE.close()
Output:
FILE = open("quotes.txt")
AC = 0
DATA = FILE.read()
for L in DATA:
if L=='B':
AC+=1
print("Total No. of alphabet B in the file =",AC)
FILE.close()
Output:
A Program can also write strings into a text file. Followings are the methods to write a data to the
file:
write ()
writelines()
Note: - To write into a text file, we must add parameter as ‘w’ or ‘a’ in the open() function which specifies the
"w" – for overwrite any existing content and then write the new data
Difference between ‘a’ and ‘w’ modes i.e. append and write modes: -
If you open a file in “w” means write mode, Python overwrites an existing file or creates a new
file. For an existing file, the earlier data gets removed.
If you want to write into a file with retaining the previous data, the file must be opened in “a”
means append mode.
1) write() – This method takes a string ( as parameter ) and writes it in the file. For storing data with end of line
character, we will have to add \n character to the end of the string.
Example:
f = open("demo.txt", "w")
f.close()
print(f.read())
# Open the previous file "demo.txt" and add more content to the file:
f = open("demo.txt", "a")
f.close()
# Now again open the file in read mode and see the result …. (Check by yourself)
2) writelines() - Drawback of write() function is it will write a string in a text file at a time, and it can't be
used for writing a list, tuple etc. into a file. writelines() method will help to write a sequence of strings to the
file. The sequence can be any object producing strings, typically a list of strings. So, whenever we have to
write a sequence of string / data type, we will use writelines(), instead of write().
f = open("demo.txt", "w")
f.writelines(["Python is just amazing!", "\nWe love python"]) # here we used list data
f.close()
f = open("demo.txt", "r")
print(f.read())
flush() function: - The flush() function forces the writing of data on disc which was still pending in the
output buffer.
Syntax : <file_object>.flush()
f = open("demo_flush.txt","w+")
f.write("India is my country.\n")
f.flush()
x=”Jai Hind”
f.write(x)
f.seek(0) # Here seek() will move the file pointer(handle) at the beginning of the file.
print(f.read())
f.close()
seek() function: – The seek() function changes the position of the file-pointer by placing the file-pointer at
the specified position in the open file.
Offset will be 0 or 1 or 2
0 for beginning of the file (to move file pointer w.r.t. beginning of file) it is default mode.
1 for current position of file pointer (to move file pointer w.r.t current position of it.)
2 for end of file (to move file-pointer w.e.t. end of file)
Example:
f=open("demo_seek.txt","r")
print(f.read()) # after reading all the bytes file pointer reaches to the end of the file.
f.seek(6) # Now the file pointer will move to the 6th Byte from beginning.
print(f.read()) # It will print the remaining number of bytes after 6th Byte.
tell() function: – This function returns the current position of file pointer in the file.
Syntax: <file_object>.tell()
Example:
f=open("d:\\pooja\\demo_seek.txt","r")
print(f.read(5)) # This will read 5 bytes from the beginning
print(f.tell()) # This will show 5 as file pointer is at 5th character from beginning
BINARY FILES:
A Binary file stores the information in the form of a stream of bytes. A binary file stores the data
in the same way as stored in the memory. In Binary file there is no delimiter for a line. The file contents
returned by a binary file is raw i.e. with no translation, thus Binary files are faster than text files.
Python objects (list, dictionary etc) have a specific structure which must be maintained
while storing or accessing them. Python provides a special module called pickle module for this.
PICKLING refers to the process of converting the structure(list/dictionary) to a byte of stream before
writing it to a file. The process to converts any kind of python objects (list, dict etc.) into byte streams (0s
and 1s).
UNPICKLING is used to convert the byte stream back to the original structure while reading the
contents of the file.
pickle Module: -
Before reading or writing to a file, we have to import the pickle module.
import pickle
pickle.dump() – This method is used to write the object in the file which is opened in ‘wb’ or ‘ab’
i.e. write binary or append binary access mode respectively.
Syntax : pickle.dump(<structure>,<FileObject>)
import pickle
fo = open("binary_file1.dat","wb")
Laptop = ["Dell","HP","ACER"]
pickle.dump(Laptop,fo)
fo.close()
pickle.load() – This method is used to read data from a file and return back into the structure (list/dictionary).
Structure can be any sequence in Python such as list, dictionary etc. FileObject is the file handle of file in
which we have to write.
fbin = open("binary_file1.dat","rb")
x=pickle.load(fbin)
print(x)
fbin.close()
# Simple program to write a dictionary data into a binary file
import pickle
f=open("my_bin1.bin","wb")
D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}
pickle.dump(D1,f)
f.close()
f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()
# Write a User defined function bdict() to store customer data into a binary file customer.dat using a
dictionary and print them on screen after reading them. The customer data contains
customer_ID(c1,c2,c3) as key, and name, city as values.
import pickle
def bdict():
f = open("customer.dat","wb")
d = {'C1':['Siman Raheja','Haryana'],
'C2':['Praharsh Kumar','Pune'],
'C3':['Vinita Minj','Indore']}
pickle.dump(d,f)
f.close()
f = open("customer.dat","rb")
d = pickle.load(f)
print(d)
f.close()
# Sample program to insert any number of records (as per user’s choice) of employee (employee number,
name, salary and allowance) and then display all the records.
import pickle
bfile=open("empfile.dat","ab")
recno=1
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
# Write a program that have a binary file “Book.dat”. The file has structure [BookNo, Book_Name, Author,
Price]. Now do as directed: -
1) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
2) Write the definition of show_all_books() UDF to display the details of all the books.
3) Write a User Defined function CountRec(Author) in Python which accepts the Author name as
parameter, display the details of the book of the same author also return the number of books of the
given Author are stored in the binary file “Book.dat"
import pickle
def createfile():
fobj=open("Book.dat","ab")
def show_all_books():
fobj=open("Book.dat","rb")
L1=[]
try:
while True:
L1=pickle.load(fobj)
print(L1)
except EOFError:
print('All Record displayed')
pass
fobj.close()
def countrec(Author):
fobj=open("Book.dat", "rb")
cnt = 0
print("Book No Book Name Author Price")
try:
while True:
r=pickle.load(fobj)
if Author==r[2]:
cnt = cnt + 1
print(r[0],"\t",r[1],"\t",r[2],'\t',r[3])
except:
print()
fobj.close()
return cnt
# Write a program that uses a binary file “STUDENT.DAT” has structure [roll_number, Name, Percentage].
Write a User defined function countrec() that would read contents of the file
“STUDENT.DAT” and display the details of those students whose percentage is above 75%.
import pickle
def createfile():
fobj=open("student.dat","ab")
rec=[rno, nm , p]
pickle.dump(rec, fobj)
print("Record saved")
fobj.close()
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>375:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
createfile()
countrec()
CSV FILES: -
CSV stands for Comma Separated Values. It is a type of plain text file that uses specific structure to
arrange tabular data i.e. data stored in rows and columns such as a spreadsheet or database.
CSV is like a text file, It is in human readable format and extensively used to store tabular data, in a
spreadsheet or database.
Each line of the csv file is a data record. Each record consists of one or more fields, separated by
commas. The separator character of CSV files is called a delimiter.
Default delimiter is (,). Other delimiters are tab(\t), colon (:), pipe(|), semicolon (;) characters.
To read data from csv files, reader() method of csv module is used.
csv.reader() returns a reader object.
STEPS TO READ
import csv
f = open("emp.csv","r")
emp_reader=csv.reader(f)
for row in emp_reader:
print(row[0],row[1],row[2]) # print(row) : As a list
f.close()
To write data into csv files, writer() function of csv module is used.
csv.writer(): This function returns a writer object which writes data into writer object.
Significance of writer object
The csv.writer() returns a writer object that converts the data into a delimited string.The string
can be later converted into csv files using the writerow() or writerows() method.
Syntax:
<writer_object>.writerow() :
<writer_object>.writerows()
# Program to write data into a CSV File and to read data stored in csv file
import csv
f=open("mycsv.csv","w",newline='')
w=csv.writer(f)
lst=["RNO","NAME","MARKS"]
w.writerow(lst)
f=open("mycsv.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()
# Program to write Employee Name, EmpID and Dept for some employees in a csv file then display
records of all the employees.
import csv
f=open("emp.csv","w",newline='')
emp_writer = csv.writer(f)
emp_writer.writerow(["EmpName","EmpID","Dept"])
emp_rec = []
while True:
print("Enter Employee details: ")
empname = input("EmpName : ")
eid = int(input("EmpID : "))
dept = input("Department : ")
emp_rec.append([empname,eid,dept])
if ch == "N" or ch =="n":
break
emp_writer.writerows(emp_rec)
f.close()
f=open("emp.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()
Madhwan, is doing internship in “SQUARE Solutions Pvt. Ltd.”. He wrote the following python code to store
student’s data in csv file (Student.csv) handling. Unfortunately, he forgot some steps of the python code.
Please help him to create a CSV File 'Student.csv' by completing the code.
CSV File
1,SAKSHAM,XII,A
2,ARNAV,XI,A
3,SHREEVALI,XII,A
4,BHOOMI,XI,A
5,SWARIT,XII,A
import_____ #Statement-1
data = []
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(rec)
stuwriter. _____ (data) #Statement-5
csvfh.close()
a) csv file
b) CSV
c) csv
d) Csv
a) "School.csv","w"
b) "Student.csv","w"
c) "Student.csv","r"
d) "School.csv","r"
a) reader(csvfh)
b) reader(MyFile)
c) writer(csvfh)
d) writer(MyFile)
e) Choose the function name that should be used for Statement-5 to create the desired CSV File.
a) dump()
b) load()
c) writerows()
d) writerow()
In Data Structure w e a r e collecting and organizing data in such a way that we can perform
operations on these data in an effective way.
Stack
A stack is a data structure whose elements are accessed according to the Last- In First-
Out (LIFO) mechanism. This is because in a stack, insertion and deletion of elements can
only take place at one end, which is called top of the stack.
Similarly, If we want to remove any coin from the stack, the coin on the top of the stack has to
be removed first. That means, the coin that was kept last (i.e. at the top) in the stack has
to be taken out first.
The two operations performed on the stack are:
• Push operation: It means inserting element at the top of the stack. This can be
done with the help of append() method of the list as: st.append(element) where ‘st’ is
a list.
• Pop operation: It means removing the topmost element from the stack. This can be
performed using pop() method of the list as: st.pop() where ‘st’is a list. This method
returns the removed element that can be displayed.
Applications of Stack
• Recursion
• Postfix notations(Evaluation of expressions)
• Tower of Hanoi
def stkpop():
if len(st) ==0:
print("Underflow")
else:
print(st.pop()," removed")
def display():
if st==[ ]:
print("Underflow")
else:
print("stack is: ")
L=len(st)-1
for i in range(L,-1,-1): print(st[i])
char=True
while(char):
print("1.Push")
print("2.Pop")
print("3.display")
ch=int(input("Enter choice: "))
if ch==1:
stkpush()
elif ch==2:
stkpop()
elif ch==3:
display()
else:
char=False
Output: -
# A Menu Driven Program to store Name and marks out of 100 for some students in a stack
and implementation of stack operations.
stk=[]
ui='y'
while(ui=='y'):
print('Menu')
print('1.Push a student record’)
print(‘2.Pop a student record’)
print(‘3.Show all students record')
print('4.Search student record scored above 90')
if(ans==1):
n=input('Enter Name')
m=int(input('Enter Total marks obtained out of 100'))
stk.append((n,m))
if(ans==2):
if(stk==[]):
print('Stack is empty')
else:
y=stk.pop()
print(y,' is removed from stack')
if (ans==3):
s=len(stk)
for i in range(s-1,-1,-1):
print('============')
print(stk[i])
if(ans==4):
s=len(stk)
for i in range(s-1,-1,-1):
if (stk[i][1]>=90):
print('************')
print(stk[i])
***
UNIT-II-COMPUTER NETWORK
EVOLUTION OF NETWORK
TRANSMISSION MEDIA
NETWORKING DEVICES
NETWORKING TOPOLOGIES
NETWORKING PROTOCOLS
SWITCHING TECHNIQUES
WEB SERVICES
ARPANET
INTERNET
EVOLUTION OF
NETWORKING
CIRCUIT
INTERSPACE
SWITCHING
SWITCHING MESSAGE
TECHNOLOGIES SWITCHING
PACKET
SWITCHING
TRANSMISSION
MEDIA
UNGUIDED
GUIDED MEDIA
MEDIA
RJ-45
SWITCH/HUB
CONNECTOR
REPEATER SWITCH
NETWORK
DEVICES
ETHERNET
ROUTER
CARD
NETWORK NETWORK
TOPOLOGIES TYPES
BUS LAN
STAR MAN
TREE WAN
PAN
NETWORK PROTOCOLS
WIRELESS
TCP/IP FTP PPP HTTP SMTP TELNET VOIP POP3 HTTPS
PROTOCOLS
WEB SERVICES
Q. Define internet?
Ans Internet is a network of networks.
Q. Name the protocol that is used to transfer file from one computer to another.
Ans:FTP
Q.Name the transmission media best suitable for connecting to desert areas.
Ans: Microwave
Q.Rearrange the following terms in increasing order of speedy medium of data transfer:
Telephone line, Fiber Optics, Coaxial Cable, Twisted Paired Cable.
Ans: Telephone line, Twisted Pair Cable, Coaxial Cable, Fiber Optics.
Q. Name the protocol that is used to upload and download files on internet.
Ans: FTP or HTTP
Q.Name the transmission media best suitable for connecting to hilly areas.
Ans: Microwave / Radio wave.
Q.Which type of network (out of LAN, PAN and MAN) is formed, when you connect two mobiles using
Bluetooth to transfer a video?
Ans:PAN
Q. Ravi has purchased a new Smart TV and wants to cast a video from his mobile to his new Smart TV.
Identify the type of network he is using and explain it.
Ans: Ravi is using PAN-Personal Area Network. It is a private network which is setup by an individual to
transfer data among his personal devices of home.
Q.Your friend Rakesh complaints that somebody accessed his mobile device remotely and deleted the
important files. Also he claims that the password of his social media accounts were changed. Write a the
name of crime?
Ans:The gaining of unauthorized access to data in a system or computer is termed as hacking. It can be
classified in two ways: (i) Ethical Hacking (ii)Cracking
Ans:
Q. What is the difference between hub and switch? Which is more preferable in a large network of
computers and why?
Ans: Hub forwards the message to every node connected and create a huge traffic in the network hence
reduces efficiency whereas a Switch (also called intelligent hub) redirects the received information/ packet
to the intended node(s).
In a large network a switch is preferred to reduce the unwanted traffic in the network. It makes the network
much more efficient.
Q.Differentiate between web server and web browser. Write any two popular web browsers.
Ans: Web Browser : A web browser is a software application for accessing information on the World Wide
Web. When a user requests a web page from a particular website, the web browser retrieves the necessary
content from a web server and then displays the page on the user‟s device.
Web Server : A web server is a computer that runs websites. The basic objective of the webserver is to
store, process and deliver web pages to the users. This intercommunication is done using Hypertext
Transfer Protocol (HTTP).
Popular web browsers: Google Chrome, Mozila Firefox, Internet Explorer etc.
In-circuit switching, each data unit knows In Packet switching, each data unit just knows the
the entire path address which is provided by final destination address intermediate path is
the source. decided by the routers.
In-Circuit switching, data is processed at the In Packet switching, data is processed at all
source system only intermediate nodes including the source system.
The delay between data units in circuit The delay between data units in packet switching
switching is uniform. is not uniform.
Q. What is communication channel? Name the basic types of communication channels available
Ans: Communication channel mean the connecting cables that link various workstations. Following are
three basic types of communication channels available:
a) Twisted-Pair Cables
b) Coaxial Cables
c) Fiber-optic Cables.
Q.. Which of the following communication medium requires line of sight communication?
Microwave, radio wave , infrared, Bluetooth
Ans: Microwave, infrared
Q. . What are the similarities and differences between bus and tree topologies?
Ans: Similarities: In both Bus and Tree topologies transmission can be done in both the directions, and
can be received by all other stations. In both cases, there is no need to remove packets from the medium.
Differences: Bus topology is slower as compared to tree topology of network. Tree topology is
expensive as compared to Bus Topology
Q.. When do you think, ring topology becomes the best choice for a network?
Ans: Ring topology becomes the best choice for a network when, short amount of cable is required.
No wiring closet space requires.
Q.. Write the two advantages and two disadvantages of Bus Topology in network.
Ans. ADVANTAGE: Easy to connect a computer or peripheral to a linear bus. Requires less cable
length than a star topology
.
DISADVANTAGE: Slower as compared to tree and star topologies of network. Breakage of wire at
any point disturbs the entire
Q.. Define the following:
Example of Web browser – Google Chrome, Fire Fox, Internet Explorer, Safari, Opera, etc.
Web Server: A Web Server is software which fulfills the request(s) done by web browser. Web server
have different ports to handle different request from web browser like generally FTP request is handle
at Port 110 and HTTP request is handle at Port 80. Example of Web server are – Apache, IIS
Q: Uplifting Skills Hub India is a knowledge and skill community which has an aim to
uplift the standard of knowledge and skills in society. It is planning to set up its
training centres in multiple towns and villages pan India with its head offices in the nearest cities. They
have created a model of their network with a city, a town, and 3 villages as follows.
As a network consultant, you have to suggest the best network related solutions for their issues/ problems
raised in (i) to (iv) keeping in mind the distance between various locations and given parameters.
Note:
In Villages, there are community centers, in which one room has been given as a
training center for this organization to install computers. The organization has got financial support
from the government and top IT companies.
i. Suggest the most appropriate location of the SERVER in the B_HUB (out of the 4 locations), to get
the best and effective connectivity. Justify your answer.
ii. Suggest the best-wired medium and draw the cable layout (location to location) to efficiently
connect various locations within the B_HUB.
iii. Which hardware device will you suggest to connect all the computers within each location of
B_HUB?
iv. Which service/protocol will be most helpful to conduct live interactions of Experts from Head
Office and people at all locations of B_HUB?
v. What kind of network will be formed between city head office and town?
Ans:
i. B-TOWN can house the server as it has the maximum no. of computers.
ii. The optical fiber cable is the best for this star topology.
iii. Switch device - connecting all the computers within each location of B_HUB
iv. VoIP- Voice Over Internet Protocol
v. MAN
Q: Rehaana Medicos Centre has set up its new centre in Dubai. It has four buildings as shown in the
diagram given below:
Distances between various buildings are as follows:
Accounts to Research Lab 55 m
No of Computers
Accounts 25
Store 15
Packaging Unit 60
As a network expert, provide the best possible answer for the following
queries:
i) Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place (i.e. buildings) to house the server of
this organization.
iii) Suggest the placement of the Repeater device with justification.
iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the network.
(v) Suggest the placement of the Hub/ Switch with justification.
Ans:
(i)
(ii) Research Lab
(iii) With respect to above topology repeater is not needed, as none of the distance is above 100m
(iv) Firewall
(v) Switch is better than hub being unicast, secure and fast device. It is needed in all buildings
Q: PVS Computers decided to open a new office at Ernakulum, the office consist of Five Buildings
and each contains number of computers. The details are shown below.
building 1 building 2
Computers in each building are networked but buildings are not networked so far. The Company has
now decided to connect building also.
(i) Suggest a cable layout for connecting the buildings
(ii) Do you think anywhere Repeaters required in the campus? Why?
(iii) The company wants to link this office to their head office at Delhi
(a) Which type of transmission medium is appropriate for such a link?
(b) What type of network would this connection result into?
(iv) Where server is to be installed? Why?
(v) Suggest the wired Transmission Media used to connect all buildings efficiently.
Q: “VidyaDaan” an NGO is planning to setup its new campus at Nagpur for its
web-based activities. The campus has four (04) UNITS as shown below:
(ii) Suggest the most suitable place i.e. UNIT to install the server for the above
NGO.
(iii) Which network device is used to connect the computers in all UNITs?
(a) Twisted Pair cable (b) Ethernet cable (c) Optical Fibre
Ans:
(ii)ADMIN
(iii) Switch
(iv)
Q ‘SmartEdu’ is an educational organization is planning to setup its new campus at Cochin for its web
based activities. The campus has four compounds as shown in the diagram.
Computers in each building are networked but buildings are not networked. The company has now decided
to connect the buildings.
i) Suggest a most suitable cable layout for the above connection
ii) Suggest most suitable topology of the connection between the building.
iii) Suggest the most suitable building to place the server by giving suitable reason.
iv) Suggest the placement of the following devices
a) Repeater b) Hub/Switch
v) Organization is planning to link its head office in Chennai. Suggest an efficient medium for efficient
data communication.
Ans:- (i)
(ii) Star topology
(iii) Training Compound, as per 80:20 rule maximum computers mean maximum internal traffic
(iv) between Main to Training, resource to Training and Training to Finance as distance is greater than
100m
(v) Optical Fibre
RDBMS: Relational Database Management System
TYPES OF COMMAND
DATA
TYPES OF CONSTRAINTS
DATA DEFINITION MANIPULATION TRANSACTION
LANGUAGE (DDL) LANGUAGE (DML) CONTROL
COMMANDS LANGUAGE (TCL)
COMMANDS PRIMARY KEY
INSERT COMMAND
CREATE TABLE
CHECK
COMMAND
SAVEPOINT
COMMAND FOREIGN KEY
SELECT COMMAND
ALTER TABLE
COMMAND
COMMIT COMMAND NOT NULL
UPDATE
COMMAND
step1 :
• import pymysql or mysql.connector
step2
• mydb=mysql.connector.connect(host="____",user="____",passwd="______")
step3
• mycursor=mydb.cursor()
step4
• mycursor.execute("______SQL QUERY__________")
Database Management System
DATABASE:
Dept:
Deptno dname Loc
10 Accounting New York
20 Research Dallas
30 Sales Chicago
40 Operations Bostan
Component of a table:
➢ Byte: group of 8 bits and is used to store a character.
➢ Data Item: smallest unit of named data. It represent one type of information and
oftenreferred to as a field or column information
➢ Record : collection of data items which represent a complete unit of information
➢ Table: collection of all Rows and Columns.
Common RDBMS:
➢ Oracle, MS SQL Server, MySQL, IBM DB2, IBM Informix, SAP Sybase, Adaptive
Server Enterprise, SAP Sybase IQ, Teradata, PostgreSQL, SQLite, etc.
➢ Out of these MySQL, PostgreSQL and SQLite are Open source implementation.
MySQL
➢ Runs on virtually all platforms including Linux, Unix and Windows. Popular for web
based application and online publishing. It is a part of LAMP (Linux, Apache, MySQL,
PHP) stack
SQLite
➢ Relational DBMS but it is not client-server database engine rather, it is embedded into
end program. Arguably the most widely deployed database engine as it is used by
severalbrowsers, OS and embedded systems (Mobiles).
PostgreSQL
➢ General purpose object-relational DBMS.
➢ It is the most advanced open source database system. It is free and open source
i.e.source code is available under PostgreSQL license, a liberal open source
license.
Common DBMS Tools for Mobile Devices:
➢ SQL Anywhere, DB2 Everywhere, IBM Mobile Database, SQL Server Compact, SQL
Server Express, Oracle DatabaseLite, SQLite, SQLBase etc.
➢ Out of these SQLite is public domain open source implementation.
Relational Data Model:-
Data is organized in two-dimensional tables called relations. The tables or relations are relatedto
each other.
Various Terms Used in Relational Model: - A relational database is a type of database that
stores and provides access to data points that are related to one another.
Basic Terminologies related to a Relational Database:-
➢ Entity: An entity is something that exists and an object which can be distinctly
identified. For example, student entity, employee entity,
➢ Attribute: The term attribute is also used to represent a column.
➢ Tuple: Each row in a table is known as tuple.
➢ Cardinality of Relation: It is the number of records or tuples in the relation.
➢ Degree of Relation: Number of columns or attributes is known as degree of a relation.
➢ Domain of Relation: It defines the kind of data represented by the attribute.
➢ Body of the Relation: It consists of an unordered set of 0 or more tuples.
Concept of Keys
➢ In relation each record must be unique i.e. no two identical records are allowed in
theDatabase.
➢ A key attribute identifies the record and must have unique values. There are
varioustypes of Keys:
Primary key:
➢ A set of one or more attribute that can identify a record uniquely in the relation is
calledPrimary Key.
➢ There can be only 1 primary key in a table
➢ Allows only distinct (no duplicate) values and also forces mandatory entry (NOT NULL)
i.e. we cannot left it blank.
Candidate Key
➢ In a table there can be more than one attribute which contains unique values.
Thesecolumns are known as candidate key as they are the candidate for primary
key.
➢ Among these database analyst select one as a primary key based on requirement like
must contain unique value, compulsory entry and where maximum searching is done
etc.
Alternate Key
➢ In case of multiple candidate keys, one of them will be selected as Primary Key and
restof the column will serve as Alternate Key
➢ A Candidate Key which is not a primary key is an Alternate Key.
Foreign key
From the Above table definition we can observe that the DEPTNO column of EMPLOYEE tableis
deriving its value from DEPTNO of table DEPARTMENT. So we can say that the DEPTNO of
EMPLOYEE table is a foreign key whose value is dependent upon the Primary key columnDEPTNO
of table DEPARTMENT.
REFERENTIAL INTEGRITY:
➢ Used to ensure relationship between records in related tables is valid and user
don’taccidentally delete or change the related data.
➢ Referential integrity can be applied when:
➢ The master table’s column is a Primary Key or has a unique index
➢ The related fields have the same data type
➢ Both tables must belong to same database.
➢ When referential integrity is enforced using Foreign Key you must observe the following
rules:
➢ You cannot enter a value in Child Table which is not available in Master Table’s Primary
key column. However you can enter NULL values in foreign key
➢ You cannot delete a record from Master Table if matching record exists in related table.
➢ You cannot modify or change the Primary Key value in Master table if its matching record
is present in related table.
Structured Query Language
➢ It is a language that enables you to create and operate on relational databases
➢ It is the standard language used by almost all the database s/w vendors.
➢ Pronounced as SEQUEL
➢ It is portable i.e. it is compatible with most of the database.
➢ It is not a case sensitive language.
➢ It is very easy to learn.
SQL – features
➢ Allows creating/modifying a database’s structure
➢ Changing security settings for system
➢ Permitting users for working on databases or tables
➢ Querying database
➢ Inserting/modifying/deleting the database contents
Classification of SQL
➢ DDL (Data Definition Language)
➢ DML (Data Manipulation Language)
➢ DCL (Data Control Language)
➢ TCL (Transaction Control Language)
Data Definition Language:
➢ It allows to create database objects like creating a table, view or any other
databaseobjects.
➢ The information about created objects are stored in special file called DATA
DICTIONARY
➢ DATA DICTIONARY contains metadata i.e. data about data.
➢ The commands of DDL are –
o CREATE – To create a new database object
o ALTER – To modify existing database object
o DROP – To permanently remove existing database object.
Data Manipulation Language:
➢ It allows to perform following operation on data in the table
➢ Retrieval of information stored in table
➢ Insertion of new data in table
➢ Modification of existing data in table
➢ Deletion of existing data from table
➢ DML is of 2 type
➢ Procedural DML (in this we specify what data is needed and how to get it)
➢ Non-Procedural DML (in this we specifywhat data is needed
withoutspecifying how to get it)
➢ The commands of DML are
o SELECT – To retrieve data from the table
o INSERT – To insert new tuple/row in the table
o UPDATE – To update existing tuple/row from the table
o DELETE – To delete existing tuple/row from the table
Exercise
:
➢ MySQL database system refers to the combination of a MySQL server instance and
MySQL database.
➢ It operates using Client/Server architecture in which the server runs on the
machinecontaining the database and client connects to server over a network
➢ MySQL is a multiuser database system, meaning several users can access the
databasesimultaneously.
The Server
➢ Listens for client requests coming in over the network and access the database as per
therequirements and provide the requested information to the Client.
The Client
➢ Are the programs that connect to MySQL server and sends requests to the server and
receives the response of Server. Client may be the MySQL prompt or it may be Front-end
programming which connect to server programmatically like connecting to MySQL using
Python Language or Java or any other language.
FEATURES OF MYSQL:
STARTING MYSQL:
Click on Start →All Programs →MySQL → MySQL Server→ MySQL →Command LineClient
Char varchar
Fixed length string Variable length string
Fast, no memory allocation every time Slow, as it take size according to data so every
time memory allocation is done
It takes more memory It takes less space
Simple Queries in SQL
➢ Show Databases- This command is used to list all databases on MySql Server
➢ Use <databasename>- This command is used to change/select/open given database
e.g. To open a database named ‘test’
>>> use test
➢ Show tables – This command will list all the tables from current database. If no database
isselected it will generate error.
➢ Select database () – This command will display the name of current database.
➢ Desc <tablename> or Describe <tablename> - This command will be used to display the
structure of the table.
➢ Create table <tablename> - This command / statement is used to create a new table in
adatabase. The syntax the is
➢ Drop table <tablename> - This command is used to permanently delete the table from
database.
For example, drop table pet; will delete pet table from database
➢ Alter table <tablename> - This command is used to modify the structure of existing table
such as adding new column, removing existing column, rename or changing data type, size
and constraints.
o Adding new column to exiting
tableSyntax :
tableSyntax :
➢ Performing calculation on
columnSyntax:
SELECT column1 operator value, column2…. FROM Tablename
Syntax:
ifnull(column, value_to_replace’)
Here, comm column contains null value which is replaced by ‘N/A’.
Relational Operator
> greater than
< less than
>= greater than equal to
<= less than equal to
= equal
! = or <> not equal to
Logical Operator
And – evaluated true if all the logical expression is true otherwise
false.Or - evaluated true if any the logical expression is true otherwise
false. Logical operator is used to combine two or more logical
expression,
Membership Operator
in – Not
in
The IN operator allows you to specify multiple values in a WHERE clause.The
IN operator is a shorthand for multiple OR conditions.
Comparing NULL
is null – is
not null
NULL (Absence of value) value cannot be compared using Relational operator. The
above statement is used to check whether column contains NULL or not.
Range Operator
Between
Pattern Matching
Like
Not Like
Like clause is used to match pattern using two wild card characters
_ (underscore) – single unknown character
% (modulo) - Zero or more unknown characters
e.g.
words staring with ‘t’ ‘t%’
words ending with ‘t’ ‘%t’
words containing ‘t’ - ‘%t%’
word with ‘t’ as second letter - ‘_t%’
words with ‘t’ as third last character – ‘%t_ _’
words containing four letter and ‘t’ as second letter – ‘_ t_ _’
Syntax:
SELECT */col_list
FROM tablename
ORDER BY col1 asc/desc, col2 asc/desc;
Aggregate Functions
➢ An aggregate function performs a calculation on multiple values and returns a
singlevalue.
➢ These function work on multiple rows collectively return single value.
➢ List of Aggregate functions are
o max() : return maximum value in set of value
In above example there are 14 row in the EMP table, but distinct clause
only consider unique value.
➢ Group By Clause
o It is used in a SELECT statement to collect data across multiple records and group
the results by one or more columns.
Syntax:
SELECT column_name, aggregate_function
FROM table_name
GROUP BY column_name
In above example salary is grouped on job and maximum salary from each job isdisplayed.
o Select clause involving group by clause can contain column present in group by
clause, aggregate function or no column. Otherwise it will return random data
fromother column as given below.
➢ Having clause –
o Having clause is used to place condition on aggregate function in conjunction
withgroup by clause.
o Having clause in placed after where clause in select statement.
Syntax:
SELECT columm_name, aggregate_function(col_name)
FROM table
WHERE condition GROUP BY
column_name
HAVING aggregate_function(column_name) operator expression;
The above query will display deptno, maximum salary and number of employees from
each department.
The query given below display deptno, maximum salary and number of employees
from those department which have maximum salary greater than equal to 3000.
As condition is on aggregate function max(), where clause can’t be used in this case.
Exercise Questions:
1. What is MySQL used for? Abhay wants to start learning MySQL. From where can he obtain the
MySQL software ?
2. In the table “Student”, Priya wanted to increase the Marks(Column Name:Marks) of those students
by 5 who have got Marks below 33. She has entered the following statement:
3. SELECT Marks+5 FROM Student WHERE Marks<33;
Identify errors(if any) in the above statement. Rewrite the correct SQL statement.
4. Write SQL statement to add a column ‘‘COUNTRY’’ with data type and size as VARCHAR(70) to the
existing table named ‘‘PLAYER’’. Is it a DDL or DML or TCL command ?
5. Table Student has the columns RNO and SCORE. It has 3 rows in it. Following two SQL statements
were entered that produced the output (AVG(SCORE) as 45 and COUNT(SCORE) as 2) :
(i) AVG(SCORE)
(ii) Count(score)
6. ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee resides. Write
SQL query to display details of all rows except those rows that have CITY as ‘DELHI’ or ‘MUMBAI’ or
‘CHANDIGARH’.
7. How is a database related to a table ?
Write SQL query to create the above table with appropriate data types and sizes of columns.
8. Ms. Rajshri is the Class Teacher of Class XII. She wants to create a table named ‘Student’ to store
marks in different subjects of her class. Identify any 4 columns for the table along with their suitable
data types.
9. “XYZ” Company conducts workshops for employees of organizations. The company requires
data of workshops that are organized. Write SQL query to create a table ‘Workshop’ with the
following structure:
10. Ariya wants to add another column ‘Gender’ in the already existing table ‘CUSTOMERS’. She
has written the following statement. However, it errors. Rewrite the correct statement.
MODIFY TABLE CUSTOMERS GENDER char(1);
(i) To display names of drivers and destination city where TELEVISION is being transported.
(ii) To display driver names and destinations where destination is not MUMBAI.
(iii) To display the names of destination cities where items are being transported. There
should be no duplicate values.
(iv) To display details of rows that have some value in DRIVERGRADE column.
(v) To display names of drivers, names of items and travel dates for those items that are
being transported on or before 1st April 2019.
(vi) To display the number of drivers who have ‘MOHAN’ anywhere in their names.
(vii) To display the names of drivers, item names and travel dates in alphabetic (ascending)
order of driver names.
(viii) To display names of drivers whose names are three characters long.
18. ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee resides. Write
SQL query to display details of all rows except those rows that have CITY as ‘DELHI’ or ‘MUMBAI’ or
‘CHANDIGARH’.
19.Consider the table given below. Write SQL queries for (i) to (vii).
Table : Gym
REGID NAME PREWEIGHT CURRWEIGHT DOJ GENDER BRANCH
Columns REGID stores Registration Id, PREWEIGHT stores weight of the person before joining Gym,
CURRWEIGHT stores current weight, DOJ stores Date of Joining, BRANCH stores the branch of Gym
where the person has enrolled.
(i) To display names of members along with their previous and current weights who are in
Model Town branch.
(ii) To display all names of members, previous weight, current weight, Change in weight (i.e.
how much increase from previous weight or decrease from previous weight, Decrease will
be displayed with negative sign)
(iii) To display BRANCH wise count of members in the Gym. (i.e. display the BRANCH and
number of members in each BRANCH)
(iv) To display names and date of joining of all the members who joined in the year 2018.
(v) To display Names and Current weight of all the members in descending order of Current
Weight.
(vi) To display the names and date of joining of male members who have joined after 27 th
September 2018.
(vii) To display names and date of joining of members who have their names starting with ‘S’
and ending with ‘a’.
20. Consider the table Flight given below, write command in SQL for (i) to (iv) and output for (v) to (viii)
Table : FLIGHT
EMP Table
DEPT Table
Ven Diagram
Syntax:
SELECT * FROM table1, table2;Or
Output:
+ + + + + + + + + + + +
| empno | ename | job | mgr | hiredate | sal | comm | deptno | deptno | dname | loc |
+ + + + + + + + + + + +
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 | 10 | ACCOUNTING | NEW YORK |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 | 10 | ACCOUNTING | NEW YORK |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 | 10 | ACCOUNTING | NEW YORK |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 | 10 | ACCOUNTING | NEW YORK |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 | 10 | ACCOUNTING | NEW YORK |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 | 10 | ACCOUNTING | NEW YORK |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
+ + + + + + + + + + + +
➢ Equi Join-
❖ It performs a JOIN against equality or matching column(s) values of the
associatedtables.
Ven Diagram
Syntax
SELECT * /Column_list
FROM Table1, Table 2
WHERE table1.column=Table2.column;Or
SELECT * /Column_list
FROM Table1 join Table2 on Table1.Column=Table2.Column;
Example: SELECT * FROM emp JOIN dept ON emp.deptno=dept.deptno;Or
+ + + + + + + + + + + +
| empno | ename | job | mgr | hiredate | sal | comm | deptno | deptno | dname | loc |
+ + + + + + + + + + + +
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 | 10 | ACCOUNTING | NEW YORK |
+ + + + + + + + + + + +
Example 1: Display the employee name, sal and name of department name
Ans: In the above query ename and sal belong to emp table whereas dname belongs
toDEPT table. So, to retrieve data in this we will use join
SELECT emp.ename, emp.sal, dept.dname
FROM emp, dept WHERE emp.deptno=dept.deptno;
Output:
+ + + +
| ename | sal | dname |
+ + + +
| SMITH | 800.00 | RESEARCH |
| ALLEN | 1600.00 | SALES |
| WARD | 1250.00 | SALES |
| JONES | 2975.00 | RESEARCH |
| MARTIN | 1250.00 | SALES |
| BLAKE | 2850.00 | SALES |
| CLARK | 2450.00 | ACCOUNTING |
| SCOTT | 3000.00 | RESEARCH |
| KING | 5000.00 | ACCOUNTING |
| TURNER | 1500.00 | SALES |
| ADAMS | 1100.00 | RESEARCH |
| JAMES | 950.00 | SALES |
| FORD | 3000.00 | RESEARCH |
| MILLER | 1300.00 | ACCOUNTING |
+ + + +Note:
❖ Here ‘e’ & ‘d’ are table alias for EMP & DEPT table respectively.
Example: Display the employee name, salary and grade of each employee.
Ans: In the above query the involved table are EMP and SALGRADE.
SELECT e.ename, e.sal, s.grade
FROM emp e, salgarde s
WHERE e.sal BETWEEN s.losal AND s.hisal;Output:
+ + + +
| ename | sal | grade |
+ + + +
| SMITH | 800.00 | 1|
| ALLEN | 1600.00 | 3|
| WARD | 1250.00 | 2|
| JONES | 2975.00 | 4|
| MARTIN | 1250.00 | 2|
| BLAKE | 2850.00 | 4|
| CLARK | 2450.00 | 4|
| SCOTT | 3000.00 | 4|
| KING | 5000.00 | 5|
| TURNER | 1500.00 | 3|
| ADAMS | 1100.00 | 1|
| JAMES | 950.00 | 1|
| FORD | 3000.00 | 4|
| MILLER | 1300.00 | 2|
+ + + +
➢ Natural Join
❖ A natural join is a type of join operation that creates an implicit join by
combiningtables based on columns with the same name and data type.
❖ It makes the SELECT query simpler with minimal use of conditions.
❖ There is no need to specify the name of common column in the SELECT statement.
❖ Common column is present only once in the output.
Syntax:
SELECT */column_list
FROM Table1 NATURAL JOIN TABLE2;
Or
SELECT */column_list
FROM TABLE1 join on common_column_name;
Example :
SELECT * FROM emp JOIN dept USING(deptno);Or
SELECT * FROM emp NATURAL JOIN DEPT;
Output:
+ + + + + + + + + + +
| deptno | empno | ename | job | mgr | hiredate | sal | comm | dname | loc |
+ + + + + + + + + + +
| 20 | 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | RESEARCH | DALLAS |
| 30 | 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | SALES | CHICAGO |
| 30 | 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | SALES | CHICAGO |
| 20 | 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | RESEARCH | DALLAS |
| 30 | 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | SALES | CHICAGO |
| 30 | 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | SALES | CHICAGO |
| 10 | 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | ACCOUNTING | NEW YORK |
| 20 | 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | RESEARCH | DALLAS |
| 10 | 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | ACCOUNTING | NEW YORK |
| 30 | 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | SALES | CHICAGO |
| 20 | 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | RESEARCH | DALLAS |
| 30 | 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | SALES | CHICAGO |
| 20 | 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | RESEARCH | DALLAS |
| 10 | 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | ACCOUNTING | NEW YORK |
+ + + + + + + + + + +
Customer Table:
Q1. Write a SQL query to display Salesman, cust_name and city from above table where the
salesperson and customer belongs to same city.
Ans:
SELECT s.name AS "Salesman",
c.cust_name, c.city
WHERE s.city=c.city;
Or
SELECT salesman.name AS "Salesman",
customer.cust_name, customer.city
FROM salesman,customer
WHERE salesman.city=customer.city;
Q2. write a SQL query to display ord_no, purch_amt, cust_name, city of those orders whereorder
amount exists between 500 and 2000.
Ans:
SELECT o.ord_no,o.purch_amt,
c.cust_name,c.city
FROM orders o,customer c
WHERE o.customer_id=c.customer_id
AND o.purch_amt BETWEEN 500 AND 2000;
Q3. Write a SQL query to display Customer Name, city, Salesman, commission the all
salesperson(s) and their respective the customer(s).
Ans:
SELECT c.cust_name AS "Customer Name",c.city,
customer c, salesman s
WHERE c.salesman_id=s.salesman_id;
Ans. Joins in SQL are the statements or clauses using which we can combine two or more tables,
based on some common fields present among the tables.
Q5.Explain the different types of Joins in SQL?Ans:
❖ Equi Join – Inner join is used to return the records which are having matching
valuesin both the tables.
❖ Left Join – Left join is used to concatenate all the rows of the left table and
thematching rows in the right table.
❖ Right Join-Right join is used to concatenate all the rows of the right table and
thematching rows in the left table.
❖ Full Join-Full join is used to return all the records of both the tables as long as there
isa matching record in either table.
❖ Self Join-Self join is a join that is used to join a table to itself. In a self-join, a table is
considered as if it were two tables.
❖ Cartesian Join-Cartesian join is used to return the number of rows in the first table
multiplied by the number of rows in the second table. It is also referred to as cross
join.
Q6. What is Natural Join?
Ans: Natural join is used to create an implicit join clause based on the value of common attributesin
the two tables. Common attributes are the attributes that have the same name in both tables.
Natural join does not need any comparison operator as in the case of equi join.
63 | P a g e
Ans: An Equi Join is a type of join that combines tables based on matching values in the
specified columns.
❖ The column names do not need to be the same.
❖ The resultant table can contain repeated columns.
❖ It is possible to perform an equi join on more than two
tables.Q 8. What is the difference between cross join and natural join?
Ans: A cross join produces a cross product or cartesian product of two tables whereas the natural
join is based on all the columns having the same name and data types in both the tables.
Unsolved Exercise:
1. Consider the following tables PARTICIPANT and ACTIVITY and answer the questions that follow :
(i) When the table ‘‘PARTICIPANT’’ was first created, the column ‘NAME’ was planned as
the Primary key by the Programmer. Later a field ADMNO had to be set up as Primary
key. Explain the reason.
OR
Identify data type and size to be used for column ACTIVITYCODE in table ACTIVITY.
(ii) To display Names of Participants, Activity Code, Activity Name in alphabetic ascending
order of names of participants.
(iii) To display Names of Participants along with Activity Codes and Activity Names for only
those participants who are taking part in Activities that have ‘bag’ in their Activity
Names and Points of activity are above 250.
2. In a database there are two tables ‘LOAN’ and ‘BORROWER’ as shown below:
Table: LOAN
Customer_Name Loan_no
Jones K-170
Smith K-230
Hayes K-155
❖ Establish connection using mysql.connector connect() method. This method will generated
ER_ACCESS_DENIED_ERROR is password is wrong.
mycon=mysql.connector.connect((host=”localhost”,user=”root”,password=””,
database=’test’)
host : - server name on which MySQL is running, default is localhost (127.0.0.1) for local
machine
❖ Result_set object holds all the record (rows) returned by execute() method
❖ Perform required operations using various cursor method
❖ Close Cursor using close() method of Cursor object
mycursor.close()
Output:
('information_schema',)
('mydb',)
('mysql',)
('newdb',)
('performance_schema',)
('school',)
('sys',)
('test',)
('xiicomm',)
Code:
Output:
Enter name of the person to update Address Rohit
Enter New Address Patna
1 records updated
Code:
Exercise:
1. What is the role of execute() method?
2. What is the significance of using connect()?
3. Explain the following method of cursor object
a. fetchone()
b. rowcount
c. fetchall()
4. What is Python’s database interface known as?
Class: XII Session: 2022-23 Computer
Science (083)
General Instructions:
SECTION
A
1. Which of the following is an invalid statement? 1
a. abc=1,000,000 c. a b c=100 200 300
b. a, b, c= 100,200,300 d. a=b=c=100
2. Which of the following operators has the highest precedence? 1
(a) << (b) ** (c)% (d)and
3. 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
4. What will be the value of the given expression? 1
3+3.00, 3**3.0
(a) (6.0, 27.0)
(b) (6.0, 9.00)
(c) (6,27)
(d) [6.0,27.0]
(e) [6,27]
5. Select the correct output of the code: 1
a = "foobar"
a = a.partition("o")
(a) ["fo","","bar"]
(b) ["f","oo","bar"]
(c) ["f","o","bar"]
(d) ("f","o","obar")
6. If a text file is opened in w+ mode, then what is the initial position of file 1
pointer/cursor?
18 Assertion (A): Local Variables are accessible only within a function or block 1
. in which it is declared
Reason (R): Global variables are accessible in the whole program.
SECTION B
(b) Sum = 0 1
25 2
.
(a) Find the Degree and Cardinality of the Cartesian product of the
Supplier and Product relations.
(b) Identify the foreign key in the given tables, also mention in which table
it is appearing as a foreign key?
OR
Find output:
(a) select *from product p, supplier s where p.supcode=s.supcode;
(b) select *from product natural join supplier;
SECTION C
26 (a) Create the connection of Python with MYSQL, in which (1) 1+2
User=Admin Password= Admin2123 Database Name=System
(b) Write the output of the queries (a) to (d) based on the table, Staff given
below:
Table: Staff
27 Assume that a text file named TEXT1.TXT already contains some text written 3
. into it, write a program with a function named vowelwords(), that reads the
file TEXT1.TXT and create a new file named TEXT2.TXT , which shall
contain only those words from the
file TEXT1.TXT which don’t start with an uppercase vowel(i.e. with
‘A’,’E’,’I’,’O’,’U’)
OR
Write a Python program to count all the line having 'a' as last character.
28 Dileep has to create a database named Company in MYSQL. 3
.
He now needs to create a table named Employee in the database to store the
records of employees in the company. The table Employee has the following
structure:
Table: Employee
For example:
T1=(1,2,3,4)
T2=(5,6,7,8)
Then function should return
(6,8,10,12)
And if
T1=(1,2,3)
T2=(5,6,7,8)
Then function should return
-1
30. Rajiv has created a dictionary containing employee names and their salaries as 3
key value pairs of 6 employees.
Write a program, with separate user defined functions to perform the following
operations:
● Push the keys (employee name) of the dictionary into a stack, where the
corresponding value (salary) is less than 85000.
● Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
OR
Aruna has a list containing temperatures of 10 cities. You need to help her
create a program with separate user defined functions to perform the following
operations based on this list.
● Traverse the content of the list and push the negative temperatures into a stack.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
T=[-9, 3, 31, -6, 12, 19, -2, 15, -5, 38]
Sample Output of the code should be:
-5 -2 -6 -9
SECTIO
ND
31 Excel Public School, Coimbatore is setting up the network between its 5
. different
wings of school campus. There are 4 wings namely SENIOR(S),
JUNIOR (J),
ADMIN (A) and HOSTEL (H).
Distances between various wings are given below:
Wing A to Wing S 100m
Wing A to Wing J 200m
Wing A to Wing H 400m
Wing S to Wing J 300m
Wing S to Wing H 100m
Wing J to Wing H 450m
Number of Computers installed at various wings are as follows:
Wings Number of Computers
Wing A 20
Wing S 150
Wing J 50
Wing H 25
(a) Suggest the best-wired medium and mention the topology or
layout to connect various wings of Excel Public School,
Coimbatore.
(b) Name the most suitable wing to house the server. Justify your
answer.
(c) Suggest placement of HUB/SWITCH in the network of the
School.
(d) Suggest a device that can provide wireless Internet access to all
smartphone/laptop users in the campus of Excel Public School,
Coimbatore.
(e) Draw suitable layout to connect all four wings of Excel Public
School
____________________ #statement 1
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
BRANCH VARCHAR(50),
ROLL INT NOT NULL,
SECTION VARCHAR(5),
AGE INT
)"""
# table created
cursorObject.________________________ #statement 3
O
R
I.Write a user defined function CreateEmp() to input data for a record and add
to emp.dat.
(a) what will be the degree and cardinality of the resulting relation after
Cartesian product of above relations?
(b) what will be the degree and cardinality of the resulting flight after addition
of two rows and deletion of one column?
(c) (i) Write a query to display the NAME, corresponding FARE and F_DATE
of all PASSENGERS who have a flight to START from DELHI.
(ii) Write a query to delete the records of flights which end at Mumbai.
OR
(c) create a new table traveller having same fields and tuples as passenger.
3 Sudev, a student of class 12th, is learning CSV File Module in Python. During 5
5. examination, he has been assigned an incomplete python code to create a CSV
file ‘customer.csv’. Help him in completing the code which creates the desired
CSV file.
I. Identify suitable code for the blank space in line marked as Statement-
a) include
b) add
c) Import
d) import
II. Identify the missing code for the blank space in line marked as Statement-2.
a) Customer
b) reader
c) csvwriter
d) writer
III. Identify the argument name for the blank space in line marked as Statement-
3?
a) Row
b) Rec
c) row
d) rec
IV. Identify the missing file name for the blank space in line marked as
Statement-4?
a) customer
b) customer.csv
c) customer.txt
d) customer.dat
V. Identify the object name for the blank space in line marked as Statement-5?
a) i
b) Rec
c) row
d) rec
Class: XII Session: 2022-23 Computer
Science (083)
Marking Scheme
SECTION
A
1. c. a b c=100 200 300 1
2. (b) ** 1
3. c) Error 1
5. (d) ("f","o","obar") 1
7. (c) references 1
9. (c) start(10) 1
11 (d) ‘rb+’ 1
.
12 (d) having 1
.
13 b. Optical fiber 1
.
14 (c) 241212 1
.
15 c) total 1
.
16 (d) fetchone 1
.
17 e. A is false but R is True 1
.
18. b. Both A and R are true and R is not the correct explanation for A 1
SECTION B
20 2
. Any two point of difference
. OR
21 (a) typeerror 1+1
.
(b) 30
22 Referential integrity refers to the relationship between tables. Because each 1+1
. table in a database must have a primary key, this primary key can appear in
other tables because of its relationship to data within those tables. When a
primary key from one table appears in another table, it is called a foreign key .
25 2
.
Find output:
(a)
PID PNAME QTY PRIC COMPANY SUPCO SUPCO SNAM CITY
E DE DE E
101 DIGITAL 120 1200 RENBIX S01 S01 GET KOLKA
CAMER 0 ALL IN TA
A 14X
102 DIGITAL 100 2200 DIGI POP S02 S02 DIGI CHENN
PAD 11I 0 BUSY AI
GROU
P
104 PENDRI 500 1100 STOREKIN S01 S01 GET KOLKA
VE G ALL IN TA
16GB
106 LED 70 2800 DISPEXPE S02 S02 DIGI CHENN
SCREEN 0 RTS BUSY AI
32 GROU
P
105 CAR 60 1200 MOVEON SO3 SO3 EASY DELHI
GPS 0 MARK
SYSTEM ET
CORP
(b)
PID PNAME QTY PRICE COMPANY SUPCOD SNAME CITY
E
101 DIGITAL 120 12000 RENBIX S01 GET KOLKAT
CAMERA ALL IN A
14X
102 DIGITAL 100 22000 DIGI POP S02 DIGI CHENNA
PAD 11I BUSY I
GROUP
104 PENDRIV 500 1100 STOREKING S01 GET KOLKAT
E 16GB ALL IN A
106 LED 70 28000 DISPEXPERT S02 DIGI CHENNA
SCREEN S BUSY I
32 GROUP
105 CAR GPS 60 12000 MOVEON SO3 EASY DELHI
SYSTEM MARKE
T CORP
SECTION C
26 (a) import mysqlconnector as myc 1
mycon=myc.connect(host=”localhost” user=”Admin” passwd=”Admin123”
databse=”System”)
0.5
X4
(b) Write the output of the queries (a) to (d) based on the table, Staff given
below:
Table: Staff
(a) 5.66
(b) 12-01-2006
(c) 3 Christina 15-11-2009 Sales F 12
7 habeena 16-08-2011 Sales F 10
(d) Dima 03-05-2016
Danish 11-09-2013
27 f1=open(“TEXT1.TXT”) 3
.
f2=open(“TEXT2.TXT”,”w”)
data=f1.read().split()
for word in data:
if word[0] not in “AEIOU”:
f2.write(word, “ “)
f1.close()
f2.close()
OR
f1=open(“TEXT1.TXT”)
data=f1.readlines()
for line in data:
if line.strip()[-1]==”a”:
print(line)
f1.close()
28 Create table Employee(Empid int(5) primary key, Empname char(25) not null, 3
. Design char(15) unique , Salary float, DOB date);
29. def merge_tuple(t1,t2): 3
t3=( )
if len(t1)==len(t2):
for i in range(len(t1)):
t3[i]=t1[i]+t2[i]
return t3
return -1
30. def push(d, stack): 3
for key in d:
if d[key]<85000:
stack.append(key)
def pop(stack):
if stack==[ ]:
print(“underflow”)
else:
print(stack.pop())
OR
def push(l, stack):
for ele in l:
if ele<0:
stack.append(ele)
def pop(stack):
if stack==[ ]:
print(“underflow”)
else:
print(stack.pop())
SECTIO
ND
31 (a) Star topology , optical fibre or coaxial
.
32 (a) 15 20 15 2+3
.
(b) Statement 1 – import mysql.connector
Statement 2 – database.cursor()
Statement 3- execute(studentRecord)
33 (any 2) 1+2+
. • CSV is human readable and easy to edit manually. 2
• CSV is simple to implement and parse. OR
• CSV is processed by almost all existing applications.
• CSV provides a straightforward information schema. 2+3
• CSV is faster to handle.
• CSV is smaller in size.
• CSV is considered to be standard format.
Write a program to
(a)
(b) f=open(“data.csv”,”r”)
data=csv.reader()
print(row)
OR
I.
import pickle
def CreateEmp():
f1=open("emp.dat",'wb')
eid=input("Enter E. Id")
ename=input("Enter Name")
designation=input("Enter Designation")
salary=int(input("Enter Salary"))
l=[eid,ename,designation,salary]
pickle.dump(l,f1)
f1.close()
II.
import pickle
def display():
f2=open("emp.dat","rb")
while True:
try:
rec=pickle.load(f2)
print(rec['eid'],rec['ename'],rec['designation'],rec['salary'])
except EOFError:
break
f2.close()
SECTION
E
3 (a) degree = 9 cardinality = 20 1+1+2
4
(b) degree = 8 cardinality = 28
(c) (i) Select Name, fare, f_date from passenger p, flight f where p.fno=f.fno
and start=”DELHI”;
3 I. d) import 5
5. II. c) csvwriter
III. d) rec
IV. b) customer.csv
V. d) rec
KENDRIYA VIDYALAYA SANGATHAN – MUMBAI REGION
Sample Question Paper
Class: XII Time: 3 Hours
Subject: Computer Science Max. Marks: 70
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A has 18 questions carrying 1 mark each.
4. Section B has 7 very short answer type questions carrying 2 marks each.
5. Section C has 5 short answer type questions carrying 3 marks each.
6. Section D has 3 long answer type questions carrying 5 marks each.
7. Section E has 2 long answer type questions carrying 4 marks each.
8. Internal choices are given in few questions.
9. All programming questions are to be answered using PYTHON language only.
SECTION – A
1 Identify the name(s) from the following that cannot be used as identifiers in 1
Python:
asaword22, 22ndyear, date26-10-2022, _my_file_2
2 Name the datatype for the following: 1
a. ‘True’
b. 2.46E-2
3 Consider the following dictionary: 1
machine = {‘id’:1001, ‘name’:’UPS’, ‘capacity’:5000, ‘rate’:15000.00}
Write a statement to change the capacity to 4500.
4 What will be the result of following expression: 1
10>12 and “a”+1<55
a. True
b. False
c. Error
d. None
5 What will be the output of the following: 1
str = “Cricket World Cup in Australia”
str2 = str[:7] + ” “ + str[18:] + “.”
print(str2)
6 Which of the file opening mode will not create a new file if file does not exist: 1
a. r
b. w
c. a
d. There is not such file opening mode
7 Fill in the blank: 1
Command used to remove a column/attribute from the table/relation is _________.
a. Update
b. Drop
c. Alter
d. Remove
8 Shridharan created a database namely work. Now he wants to create a table in 1
it. For this he needs to open the database he created. Write command to open
the database that is created by Shridharan.
9 What will be the output of the following code: 1
address = ‘42/B/III, Van-Vihar Colony, Nagpur’
str = address.replace(‘/’,’@’)
print(address)
10 Fill in the blank: 1
The attribute which is a candidate key but not a primary key is known as
_______________________.
11 Which of the following gives the result as string when applied to text file in 1
Python:
a. read()
b. readline()
c. readlines()
d. get()
12 When following command is run the result yielded 20 rows: 1
SELECT * FROM Clock;
But when following command is run; it yielded 17 rows only:
SELECT name FROM Clock;
Can you state the reason for the difference?
13 Which of the following is used for remote login: 1
a. VoIP
b. HTTP
c. IMAP
d. TELNET
14 What will be the output of the following statement: 1
print(30/5+(16+6))
15 Rajiv ran following two commands: 1
SELECT count(commission) FROM Employee;
SELECT count(*) FROM Employee;
Output of first command is 8 where output of second command is 14. What is
the reason for the difference?
16 After executing any DML command from Python in Python-Mysql connectivity, 1
following is necessary to execute in order to make the changes permanent in
MySQL:
a. save()
b. store()
c. commit()
d. update()
Questions 17 and 18 are ASSERTION (A) and REASONING ® based questions. Mark the
correct choice as
a. Both A and R are true and R is the correct explanation of A.
b. Both A and R are true and R is not the correct explanation of A.
c. A is true but R is false.
d. A is false but R is true.
17 Assertion (A): Inside a function if we make changes in a string it will reflect 1
back to the original string.
Reason (R): String is an immutable datatype and it is called by value.
18 Assertion (A): In CSV file there is a blank line after every record. 1
Reason (R): Default value of newline is ‘\n’ in open() statement used with
csv file.
SECTION – B
19 Following code is having some errors. Rewrite the code after correcting and 2
underlining each correction:
x == 20
def printme():
y = x + 10
sum = 0
for i in range(x,y)
if i%3=0:
sum=sum+i+1
Elseif:
sum += 2
return(sum)
20 Write one advantage and one disadvantage of using Fiber Optic Cable. 2
OR
Write two differences between Circuit Switching and Packet Switching.
21 What will be the output of the following code: 2
sub = “083 Comp. Sc. & 065 Info. Prac.”
n = len(sub)
s=’’
for i in range(n):
if sub[i].isupper():
s = s + sub[i].lower()
elif sub[i].islower():
s = s + sub[i]
elif sub[i].isdigit():
s = s + ‘x’
elif sub[i].isspace():
pass
else:
s = s + ‘!’
print(s)
22 Define Foreign Key. Identify foreign key from the following tables: 2
Table: Bank_Account
Acctno Name BCode Type
1001 Amrita A2 Savings
1002 Parthodas A3 Current
1005 Miraben A2 Current
Table: Branch
Code City
A1 Delhi
A2 Mumbai
A3 Nagpur
23 a. What is the full form of SMTP and HTTP? 1
b. What is the use of POP3? 1
24 What will be the output of the following code: 2
def Call4Change():
for i in range(len(lst)):
if lst[i]%2==0:
lst[i]+=1
elif lst[i]%3==0:
lst[i]+=2
elif lst[i]%5==0:
lst[i]+=4
else:
lst[i]=0
lst = [1, 2, 9, 5, 12, 6, 7, 3, 10, 8, 11, 4]
Call4Change()
print(lst)
OR
What will be the output of the following code:
def Value2New(M, N=10):
M = M + N
N = N*2
if N%10==0:
N=N/5
return(M,N)
P,Q = Value2New(100,20)
print(P,’#’,Q)
P,Q = Value2New(50)
print(P,’#’,Q)
25 Name the SQL function that will be used in following situations:
a. To find the average salary paid to employees. ½
b. To find the month in which an employee is hired. ½
c. To find position of a substring in customer name. ½
d. To find 40% of totalmarks rounded to 2 decimal places. ½
OR
Consider the following tables and write queries for a and b:
Table: Bank_Account
Acctno Name BCode Type
1001 Amrita A2 Savings
1002 Parthodas A3 Current
1005 Miraben A2 Current
Table: Branch
Code City
A1 Delhi
A2 Mumbai
A3 Nagpur
a. To list Acctno, Name and City of those accounts whose Account Type is 1
Current. 1
b. To display Acctno and Name of those accounts whose Code is A2.
SECTION – C
26 Consider the following tables and answer the questions a and b:
Table: Garment
GCode GName Rate Qty CCode
G101 Saree 1250 100 C03
G102 Lehanga 2000 100 C02
G103 Plazzo 750 105 C02
G104 Suit 2000 250 C01
G105 Patiala 1850 105 C01
Table: Cloth
CCode CName
C01 Polyester
C02 Cotton
C03 Silk
C04 Cotton-
Polyester
a. What will be output of the following command:
1
SELECT * FROM GARMENT NATURAL JOIN CLOTH;
b. What will be the output of following commands:
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;
27 Write a function countbb() in Python, which reads the contents from a text file 3
‘article.txt’ and displays number of occurrences of words ‘bat’ and ‘ball’ (in all
possible cases) to the screen.
Example:
If the content of file article.txt is as follows:
Bat and ball games are field games played by two opposing teams. Action starts
when the defending team throws a ball at a dedicated player of the attacking
team, who tries to hit it with a bat and run between various safe areas in the
field to score runs (points). The defending team can use the ball in various
ways against the attacking team's players to force them off the field when they
are not in safe zones, and thus prevent them from further scoring. The best
known modern bat and ball games are cricket and baseball, with common roots
in the 18th-century games played in England.
The countbb() function should display as:
Number of times bat occurs is 3
Number of times ball occurs is 5
OR
Write a function SOnly() in Python, which reads the contents from a text file
‘news.txt’ and creates another file ‘modnews.txt’. New file contains only those
lines that starts with an alphabet.
Example:
If the content of file news.txt is as follows:
This is Peter from California.
24th street is where I live.
__name__ is used in Python functions.
User defined functions is what I am presently reading.
Upon execution of function Sonly() file modnews.txt should contain:
This is Peter from California.
User defined functions is what I am presently reading.
28 Consider following tables and write queries for situation a and b. Find the output
of c and d:
Table: CLUB
CoachID CoachNam Ag Sports Dateofapp Pay Sex
e e
1 KUKREJA 35 KARATE 1996-03-27 1000 M
2 RAVINA 34 KARATE 1998-01-20 1200 F
3 KARAN 34 SQUASH 1998-02-19 2000 M
4 TARUN 33 BASKETBALL 1998-01-01 1500 M
5 ZUBIN 36 SWIMMING 1998-01-12 750 M
6 KETAKI 36 SWIMMING 1998-02-24 800 F
7 ANKITA 39 SQUASH 1998-02-20 2200 F
8 ZAREEN 37 KARATE 1998-02-22 1100 F
9 KUSH 41 SWIMMING 1998-01-13 900 M
10 SHAILYA 37 BASKETBALL 1998-02-19 1700 M
Table: COACHES
Sportsperson Sex Coach_No
AJAY M 1
SEEMA F 2
VINOD M 1
TANEJA F 3
a. To list names of all coaches with their date of appointment in descending
order.
b. To display total pay given to coaches in each sport. 1
c. SELECT Sportsperson, Coachname FROM Club, Coaches WHERE Coachid 1
= Coach_no;
d. SELECT Sex, MAX(Dateofapp), MIN(Dateofapp) FROM Club GROUP ½
BY Sex; ½
SECTION D
31 Superior Education Society is an educational Organization. It is planning to setup
its Campus at Nagpur with its head office at Mumbai. The Nagpur Campus has
4 main buildings – ADMIN, COMMERCE, ARTS and SCIENCE.
You as a network expert have to suggest the best network related solutions for
their problems raised in a to e, keeping in mind the distances between the
buildings and other given parameters:
1
c. Which of the following will you suggest to establish the online face-to-
face communication between the people in the ADMIN office of Nagpur
Campus and Mumbai Head office?
i. Cable TV
ii. E-mail
iii. Video Conferencing 1
iv. Text Chat
d. Suggest the placement of following devices with appropriate reasons:
i. Switch/Hub 1
ii. Repeater
e. Suggest the device/software to be installed in Nagpur Campus to take
care of data security and unauthorized access.
32 a. Write the output of the Code given below: 2
x = 15
def add(p=2, q=5):
global x
x = p+q+p*q
print(x,end=’@’)
m = 20
n = 5
add(m,n)
add(q=10, p = -3)
b. The code given below inserts the following record in table Garment: 3
GCode – integer
GName – string
Rate – decimal
Qty – integer
CCode = integer
Write missing Statements (Statement 1, Statement 2 and Statement 3) to
complete the code:
import mysql.connector as mycon
cn = mycon.connect(host=’localhost’, user=’test’, password=’None’,
database=’cloth’)
cur = ______________________ #Statement 1
while True:
GCode = int(input(“Enter Garment Code = “))
GName = input(“Enter Garment Name = “)
Rate = float(input(“Enter Rate = “))
Qty = int(input(“Enter Quantity = “))
CCode = int(input(“Enter Cloth Code = “))
q = “insert into Garment Values ({}, ‘{}’, {}, {}, {}”.format(GCode,
GName, Rate, Qty, CCode)
cur._______________(q) #Staatement 2
____________________ #Statement 3
ans = input(“Do you have more records (Y/N)=”)
if ans.upper()==’N’:
break
print(“Records Successfully Saved”)
cn.close()
OR
a. Write the output of the Code given below:
def Timing(T, m=0): 2
print(“Present Time is”,end=’:’)
if m>10 and m<=20:
print(“Quarter Past”,T)
elif m<=40:
print(“Half Past”,T)
elif m<=59:
print(“Quarter to”,T+1)
else:
print(“Incorrect Minutes”)
Timing(5,18)
Timing(11)
Timing(12,60)
b. The code given below reads those records from table Garment which has Qty 3
less than 50. Records in table Garments are stored with following attributes:
GCode – integer
GName – string
Rate – decimal
Qty – integer
CCode = integer
Write missing Statements (Statement 1, Statement 2 and Statement 3) to
complete the code:
import mysql.connector as mycon
cn = mycon.connect(host=’localhost’, user=’test’, password=’None’,
database=’cloth’)
cur = ______________________ #Statement 1
cur._________________________ #Staatement 2 (Create & Execute Query)
G = ____________________ #Statement 3Read complete result of query
print(“Required records are:”)
for i in G:
print(i)
cn.close()
33 What is the difference between CSV file and Text File? Write a program in 5
Python that defines and calls the following functions:
Insert() – To accept details of clock from the user and stores it in a csv file
‘watch.csv’. Each record of clock contains following fields – ClockID, ClockName,
YearofManf, Price. Function takes details of all clocks and stores them in file in
one go.
Delete() – To accept a ClockID and removes the record with given ClockID
from the file ‘watch.csv’. If ClockID not found then it should show a relevant
message. Before removing the record it should print the record getting removed.
OR
Give one advantage of using CSV file over Binary file. Write a program in Python 5
that defines and calls the following functions:
saving() – To accepts details of equipments from the user in following format
(ID, Name, Make, Price) and save it in a csv file ‘parts.csv’. Function saves
one record at a time.
search() – To accept two prices and displays details of those equipments which
has price between these two values.
SECTION E
34 Mayanti just started to work for a sports academy having several branches across
India. The sports academy appoints various trainers to train various sports. She
has been given the task to maintain the data of the trainers. She has made a
table called TRAINERS in the database which has following records:
Table: TRAINER
TrainerNo Name City HireDate Salary
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000
Based on the data given above answer the following questions:
a. Can City be used as Primary key for table TRAINER? Justify your answer. 1
b. What is the degree and cardinality of the table TRAINER? If we add two 1
rows and remove three rows from table TRAINER. Also if we add another
attribute in the table, what will be the degree and cardinality of the table
TRAINER will become?
c. Write statements for:
i. Insert a new record in table TRAINER with values, TrainerNo = 1
107, Name = Swastik, HireDate = 1999-01-22, Salary = 90000.
ii. Increase the salary of those Trainer having city as DELHI by 5000. 1
OR
c. Write Statements for:
i. Removes those records from table TRAINER who were hired after 1
year 2000.
ii. Add a new column Grade with datatype as Varchar and maximum 1
size as 2.
35 Tarun Nair is working under XYZ Incorporation which deals with exporting of goods
to foreign countries. To keep track of inventory he is creating a Python program
to store the information of item number and quantity in a binary file inventory.dat.
For that he has written the following code. Go through the code given and solve
problems given below:
def write(ino,qty):
F = open(____________) #Mark 2
L= _______________ #Mark 3
L.append([ino,qty])
F.close()
F=open('inventory.dat','wb')
pickle.dump(L,F)
F.close()
def Receive(ino,qty):
F=open(“inventory.dat”,”rb”)
L=pickle.load(F)
F.close()
for i in range(len(L)):
if L[i][0] == ino:
L[i][1] += qty
F=open("inventory.dat",'wb')
pickle.dump(L,F)
________________ #Mark 4
def Sent(ino,qty):
with open(“inventory.dat”,”rb”) as F:
L=pickle.load(F)
for i in range(len(L)):
if L[i][0] == ino:
L[i][1] -= qty
with open("inventory.dat",'wb') as F:
pickle.dump(L,F)
a. Write statement to open the file at Mark 2 to read records from the file. 1
b. Write statement at Mark 3 to read the content of binary file in list L. 1
c. Write statement at Mark 4 to close the file. 1
d. Why there is no need to close the file in function Sent()? 1
**************************************************************
KENDRIYA VIDYALAYA SANGATHAN – MUMBAI REGION
Marking Scheme
Class: XII Time: 3 Hours
Subject: Computer Science Max. Marks: 70
1 Identify the name(s) from the following that cannot be used as identifiers in Python:
asaword22, 22ndyear, date26-10-2022, _my_file_2
Answer:
22ndyear, date26-10-2022
½ mark for each correct answer
2 Name the datatype for the following:
a. ‘True’
b. 2.46E-2
Answer:
a. String or str
b. Float or Number
½ mark for each correct answer
3 Consider the following dictionary:
machine = {‘id’:1001, ‘name’:’UPS’, ‘capacity’:5000, ‘rate’:15000.00}
Write a statement to change the capacity to 4500.
Answer:
machine[‘capacity’] = 4500
1 mark for the correct answer
4 What will be the result of following expression:
10>12 and “a”+1<55
a. True
b. False
c. Error
d. None
Answer:
b. False
1 mark for the correct answer
5 What will be the output of the following:
str = “Cricket World Cup in Australia”
str2 = str[:7] + ” “ + str[18:] + “.”
print(str2)
Answer:
Cricket in Australia.
1 mark for the correct answer
6 Which of the file opening mode will not create a new file if file does not exist:
a. r
b. w
c. a
d. There is not such file opening mode
Answer:
a. R
1 mark for the correct answer
7 Fill in the blank:
Command used to remove a column/attribute from the table/relation is _________.
a. Update
b. Drop
c. Alter
d. Remove
Answer:
c. Alter
1 mark for the correct answer
8 Shridharan created a database namely work. Now he wants to create a table in it.
For this he needs to open the database he created. Write command to open the
database that is created by Shridharan.
Answer:
Use work;
1 mark for the correct answer
½ mark if only Use is written.
9 What will be the output of the following code:
address = ‘42/B/III, Van-Vihar Colony, Nagpur’
str = address.replace(‘/’,’@’)
print(address)
Answer:
42/B/III, Van-Vihar Colony, Nagpur
1 mark for the correct answer
10 Fill in the blank:
The attribute which is a candidate key but not a primary key is known as
_______________________.
Answer:
Alternate Key
1 mark for the correct answer
11 Which of the following gives the result as string when applied to text file in Python:
a. read()
b. readline()
c. readlines()
d. get()
Answer:
a. read() and b. readline()
½ mark each for each correct answer
12 When following command is run the result yielded 20 rows:
SELECT * FROM Clock;
But when following command is run; it yielded 17 rows only:
SELECT name FROM Clock;
Can you state the reason for the difference?
Answer:
First command displays all columns from the table Clock but second command shows only
name column. Difference between output rows is because three rows have NULL values for
name column.
1 mark for the correct answer
13 Which of the following is used for remote login:
a. VoIP
b. HTTP
c. IMAP
d. TELNET
Answer:
d. TELNET
1 mark for the correct answer
14 What will be the output of the following statement:
print(30/5+(16+6))
Answer:
28.0
1 mark for the correct answer
15 Rajiv ran following two commands:
SELECT count(commission) FROM Employee;
SELECT count(*) FROM Employee;
Output of first command is 8 where output of second command is 14. What is the
reason for the difference?
Answer:
First command counts commission column whereas second command counts rows present
in the table. Reason for difference is that there are 6 rows in tables having NULL for column
commission.
1 mark for the correct answer
16 After executing any DML command from Python in Python-Mysql connectivity, following
is necessary to execute in order to make the changes permanent in MySQL:
a. save()
b. store()
c. commit()
d. update()
Answer:
c. commit()
1 mark for the correct answer
17 Assertion (A): Inside a function if we make changes in a string it will reflect back
to the original string.
Reason (R): String is an immutable datatype and it is called by value.
Answer:
d. A is false but R is true
1 mark for the correct answer
18 Assertion (A): In CSV file there is a blank line after every record.
Reason (R): Default value of newline is ‘\n’ in open() statement used with csv
file.
Answer:
a. Both A and R are true and R is the correct explanation of A.
1 mark for the correct answer
19 Following code is having some errors. Rewrite the code after correcting and underlining
each correction:
x == 20
def printme():
y = x + 10
sum = 0
for i in range(x,y)
if i%3=0:
sum=sum+i+1
Elseif:
sum += 2
return(sum)
Answer:
x = 20
def printme():
y = x + 10
sum = 0
for i in range(x,y):
if i%3==0:
sum=sum+i+1
elif:
sum += 2
return(sum)
½ mark each for each correct correction
20 Write one advantage and one disadvantage of using Fiber Optic Cable.
OR
Write two differences between Circuit Switching and Packet Switching.
Answer:
Advantages (any one):
1. Fiber Optic Cable has very fast speed.
2. Fiber Optic Cables are immune to noise or attenuation.
Disadvantages (any one):
1. Fiber Optic Cables are very costly.
2. Fiber Optic Cables are difficult to maintain
½ mark for correct advantage and ½ mark for correct disadvantage
OR
1. In circuit switching a dedicated path is established between sender and receiver,
whereas, in packet switching no dedicated path is established between sender and
receiver.
2. In circuit switching there is no delay in data transmission, whereas, packet switching
experiences delay in data transmission.
3. In circuit switching there is no issue of congestion or garbled messages, whereas,
in packet switching congestion and garbled messages is a common issue.
4. Circuit switching required long setup time, whereas, packet switching requires no
setup time.
1 mark each for each correct difference (maximum 2 marks)
21 What will be the output of the following code:
sub = “083 Comp. Sc. & 065 Info. Prac.”
n = len(sub)
s=’’
for i in range(n):
if sub[i].isupper():
s = s + sub[i].lower()
elif sub[i].islower():
s = s + sub[i]
elif sub[i].isdigit():
s = s + ‘x’
elif sub[i].isspace():
pass
else:
s = s + ‘!’
print(s)
Answer:
xxxcomp!sc!!xxxinfo!prac!
½ mark for correct display of x
½ mark for correct display of !
½ mark for correct conversion of uppercase to lowercase
½ mark for not converting lowercase too uppercase
22 Define Foreign Key. Identify foreign key from the following tables:
Table: Bank_Account
Acctno Name BCode Type
1001 Amrita A2 Savings
1002 Parthodas A3 Current
1005 Miraben A2 Current
Table: Branch
Code City
A1 Delhi
A2 Mumbai
A3 Nagpur
Answer:
A non-key attribute in a relation which is a primary key in another table can be used to
establish relationship between these tables. Such an attribute is known as foreign key in
table where it is not a primary key.
BCode attribute in table Bank_Account is a foreign key for Code attribute of table Branch.
1 mark for correct definition of Foreign Key
1 mark for correct identification of Foreign Key in example
23 a. What is the full form of SMTP and HTTP?
b. What is the use of POP3?
Answer:
a. SMTP → Simple Mail Transfer Protocol
HTTP → HyperText Transfer Protocol
½ mark each for each correct expansion.
b. POP3 or Post Office Protocol version 3 is used to access mailbox and download e-
mail messages to the local computer.
1 mark for correct answer
24 What will be the output of the following code:
def Call4Change():
for i in range(len(lst)):
if lst[i]%2==0:
lst[i]+=1
elif lst[i]%3==0:
lst[i]+=2
elif lst[i]%5==0:
lst[i]+=4
else:
lst[i]=0
lst = [1, 2, 9, 5, 12, 6, 7, 3, 10, 8, 11, 4]
Call4Change()
print(lst)
OR
What will be the output of the following code:
def Value2New(M, N=10):
M = M + N
N = N*2
if N%10==0:
N=N/5
return(M,N)
P,Q = Value2New(100,20)
print(P,’#’,Q)
P,Q = Value2New(50)
print(P,’#’,Q)
Answer:
[0, 3, 11, 9, 13, 7, 0, 5, 11, 9, 0, 5]
½ mark for correct conversion to 0
½ mark for correct addition of 1
½ mark for correct addition of 2
½ mark for correct addition of 4
OR
120 # 8.0
60 # 4.0
1 mark each for each correct output
25 Name the SQL function that will be used in following situations:
a. To find the average salary paid to employees.
b. To find the month in which an employee is hired.
c. To find position of a substring in customer name.
d. To find 40% of totalmarks rounded to 2 decimal places.
OR
Consider the following tables and write queries for a and b:
Table: Bank_Account
Acctno Name BCode Type
1001 Amrita A2 Savings
1002 Parthodas A3 Current
1005 Miraben A2 Current
Table: Branch
Code City
A1 Delhi
A2 Mumbai
A3 Nagpur
a. To list Acctno, Name and City of those accounts whose Account Type is
Current.
b. To display Acctno and Name of those accounts whose Code is A2.
Answer:
a. AVG()
b. MONTH()
c. INSTR()
d. ROUND()
½ mark each for each correct answer
OR
a. SELECT ACCTNO, NAME, CITY FROM BANK_ACCOUNT, BRANCH WHERE
BCODE = CODE AND TYPE = ‘Current’;
b. SELECT ACCTNO, NAME FROM BANK_ACCOUNT WHERE BCODE = ‘A2’;
1 mark each for each correct answer
26 Consider the following tables and answer the questions a and b:
Table: Garment
GCode GName Rate Qty CCode
G101 Saree 1250 100 C03
G102 Lehanga 2000 100 C02
G103 Plazzo 750 105 C02
G104 Suit 2000 250 C01
G105 Patiala 1850 105 C01
Table: Cloth
CCode CName
C01 Polyester
C02 Cotton
C03 Silk
C04 Cotton-Polyester
a. What will be output of the following command:
SELECT * FROM GARMENT NATURAL JOIN CLOTH;
b. What will be the output of following commands:
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;
Answer:
a. +-------+-------+---------+------+------+-----------+
| ccode | gcode | gname | rate | qty | cname |
+-------+-------+---------+------+------+-----------+
| C03 | G101 | Saree | 1250 | 100 | Silk |
| C02 | G102 | Lehanga | 2000 | 100 | Cotton |
| C02 | G103 | Plazzo | 750 | 105 | Cotton |
| C01 | G104 | Suit | 2000 | 250 | Polyester |
| C01 | G105 | Patiala | 1850 | 105 | Polyester |
+-------+-------+---------+------+------+-----------+
1 mark for complete correct output
½ mark for partially correct output
b.
i. +------+
| qty |
+------+
| 100 |
| 105 |
| 250 |
+------+
ii. +----------+
| SUM(QTY) |
+----------+
| 355 |
| 205 |
+----------+
iii. +---------+-----------+------+
| GNAME | CNAME | RATE |
+---------+-----------+------+
| Plazzo | Cotton | 750 |
| Suit | Polyester | 2000 |
| Patiala | Polyester | 1850 |
+---------+-----------+------+
iv. +-----------+
| AVG(RATE) |
+-----------+
| 1775.0000 |
+-----------+
½ mark each for each correct output
27 Write a function countbb() in Python, which reads the contents from a text file
‘article.txt’ and displays number of occurrences of words ‘bat’ and ‘ball’ (in all possible
cases) to the screen.
Example:
If the content of file article.txt is as follows:
Bat and ball games are field games played by two opposing teams. Action starts when
the defending team throws a ball at a dedicated player of the attacking team, who
tries to hit it with a bat and run between various safe areas in the field to score runs
(points). The defending team can use the ball in various ways against the attacking
team's players to force them off the field when they are not in safe zones, and thus
prevent them from further scoring. The best known modern bat and ball games
are cricket and baseball, with common roots in the 18th-century games played
in England.
The countbb() function should display as:
Number of times bat occurs is 3
Number of times ball occurs is 5
OR
Write a function SOnly() in Python, which reads the contents from a text file ‘news.txt’
and creates another file ‘modnews.txt’. New file contains only those lines that starts
with an alphabet.
Example:
If the content of file news.txt is as follows:
This is Peter from California.
24th street is where I live.
__name__ is used in Python functions.
User defined functions is what I am presently reading.
Upon execution of function Sonly() file modnews.txt should contain:
This is Peter from California.
User defined functions is what I am presently reading.
Answer:
def countbb():
fin = open('article.txt', 'r')
data = fin.read()
fin.close()
L = data.split()
bat=ball=0
for i in L:
i = i.rstrip(".,;-'")
if i.upper() == 'BAT':
bat += 1
elif i.upper() == 'BALL':
ball += 1
print("Number of times bat occurs",bat)
print("Number of times ball occurs",ball)
½ mark for correct function header
½ mark for correct opening of file
½ mark for correct closing of file
½ mark for correct reading of data
½ mark for correct loop and correct condition
½ mark for correct printing of output
OR
def SOnly():
fin = open('news.txt','r')
L = fin.readlines()
fin.close()
for i in L:
if i[0].isalpha()==False:
L.remove(i)
fout = open('modnews.txt','w')
fout.writelines(L)
fout.close()
½ mark for correct function header
½ mark for correct opening of files
½ mark for correct closing of files
½ mark for correct reading of data
½ mark for correct preparation of data for second file
½ mark for correct writing data in second file
28 Consider following tables and write queries for situation a and b. Find the output of c
and d:
Table: CLUB
CoachID CoachName Ag Sports Dateofapp Pay Sex
e
1 KUKREJA 35 KARATE 1996-03-27 1000 M
2 RAVINA 34 KARATE 1998-01-20 1200 F
3 KARAN 34 SQUASH 1998-02-19 2000 M
4 TARUN 33 BASKETBALL 1998-01-01 1500 M
5 ZUBIN 36 SWIMMING 1998-01-12 750 M
6 KETAKI 36 SWIMMING 1998-02-24 800 F
7 ANKITA 39 SQUASH 1998-02-20 2200 F
8 ZAREEN 37 KARATE 1998-02-22 1100 F
9 KUSH 41 SWIMMING 1998-01-13 900 M
10 SHAILYA 37 BASKETBALL 1998-02-19 1700 M
Table: COACHES
Sportsperson Sex Coach_No
AJAY M 1
SEEMA F 2
VINOD M 1
TANEJA F 3
a. To list names of all coaches with their date of appointment in descending order.
b. To display total pay given to coaches in each sport.
c. SELECT Sportsperson, Coachname FROM Club, Coaches WHERE Coachid =
Coach_no;
d. SELECT Sex, MAX(Dateofapp), MIN(Dateofapp) FROM Club GROUP BY Sex;
Answer:
a. SELECT COACHNAME, DATEOFAPP FROM CLUB ORDER BY DATEOFAPP
DESC;
b. SELECT SUM(PAY) FROM CLUB GROUP BY SPORT;
c. +--------------+-----------+
| Sportsperson | Coachname |
+--------------+-----------+
| AJAY | KUKREJA |
| VINOD | KUKREJA |
| SEEMA | RAVINA |
| TANEJA | KARAN |
+--------------+-----------+
d. +------+----------------+----------------+
| sex | MAX(Dateorapp) | MIN(Dateorapp) |
+------+----------------+----------------+
| F | 1998-02-24 | 1998-01-20 |
| M | 1998-02-19 | 1996-03-27 |
+------+----------------+----------------+
½ mark for partially correct query (a and b)
1 mark for completely correct query (a and b)
½ mark each for each correct output (c and d)
29 Write a function SumDiv(L,x), where L is a list of integers and x is an integer;
passed as arguments to the function. The function returns the sum of elements of L
which are divisible by x or x+1.
For example,
If L Contains [10, 27, 12, 20, 22] and x is 5
Then function returns 42 (10+12+20)
Answer:
def Sumdiv(L,x):
sum = 0
for i in L:
if i%x==0 or i%(x+1)==0:
sum += i
return(sum)
½ mark for correct function header
½ mark for correct initialization of sum variable
½ mark for correct loop
½ mark for correct condition
½ mark for correct increment
½ mark for correct return statement
30 A nested list contains the records of Mobiles in the following format:
[[modelno, name, price], [modelno, name, price], [modelno, name, price],….]
Write the following user defined functions to perform given operations on the stack
named Mobile:
a. Push operation – To push details (modelno, name, price) of those mobiles
which has price lower than 10000. Make a note that there cannot be more
than 20 elements in stack Mobile.
b. Pop operation – To pop elements from stack one by one and display them.
Also, display “Underflow” when stack becomes empty.
For example,
If the list contains
[[‘V20’, ‘Vivo 20 SE’, 18000], [‘S11’, ‘Lava S11’, 8900], [‘i88’, ‘IPro 88 SE’,
6500], [‘ip13’, ‘iPhone 13’, 125000]]
The stack should contain:
[‘i88’, ‘IPro 88 SE’, 6500]
[‘S11’, ‘Lava S11’, 8900]
The Output should be:
[‘i88’, ‘IPro 88 SE’, 6500]
[‘S11’, ‘Lava S11’, 8900]
Underflow
OR
A Dictionary Medal contains the details of schools and medals won by them in following
format {school_name:medals_won}.
Write a function Push(Medal) in Python that pushes those school names in stack
named SCHOOL which has won more than 3 medals. Maximum capacity of stack
SCHOOL is 15. Function also shows number of items pushed in stack. If number of
items exceeds 15 then it shows OVERFLOW.
For example:
If dictionary Medal contains
{‘KV1’:5, ‘KV2’:2, ‘KV3’:4, ‘KV4’:1, ‘KV5’:7}
Then stack should contain
KV5
KV3
KV1
The output should be:
Number of item pushed in stack Medal are 3
Answer:
def Push(L, mobile):
for i in L:
if i[2]<10000 and len(mobile)<20:
mobile.append(i)
elif len(mobile)>=20:
print("OVERFLOW")
break
def Pop(mobile):
while len(mobile)>0:
print(mobile.pop())
print("Underflow")
½ mark for correct function headers
½ mark for correct loop and condition in Push
½ mark for correct push using append
½ mark for correct condition for Overflow
½ mark for correct pop statement and loop
½ mark for correct printing of overflow
OR
def Push(Medal):
x=0
for sc in Medal:
if Medal[sc]>3 and len(SCHOOL)<15:
SCHOOL.append(sc)
x+=1
elif len(SCHOOL)>=15:
print("OVERFLOW")
break
print("Number of item pushed in stack Medal are",x)
½ mark for correct function header
½ mark for correct loop
½ mark for correct condition
½ mark for correct append statement
½ mark for correct overflow condition
½ mark for correct printing of output
31 Superior Education Society is an educational Organization. It is planning to setup its
Campus at Nagpur with its head office at Mumbai. The Nagpur Campus has 4 main
buildings – ADMIN, COMMERCE, ARTS and SCIENCE.
You as a network expert have to suggest the best network related solutions for their
problems raised in a to e, keeping in mind the distances between the buildings and
other given parameters:
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.
1 mark for correct answer
32 a. Write the output of the Code given below:
x = 15
def add(p=2, q=5):
global x
x = p+q+p*q
print(x,end=’@’)
m = 20
n = 5
add(m,n)
add(q=10, p = -3)
b. The code given below inserts the following record in table Garment:
GCode – integer
GName – string
Rate – decimal
Qty – integer
CCode = integer
Write missing Statements (Statement 1, Statement 2 and Statement 3) to complete
the code:
import mysql.connector as mycon
cn = mycon.connect(host=’localhost’, user=’test’, password=’None’, database=’cloth’)
cur = ______________________ #Statement 1
while True:
GCode = int(input(“Enter Garment Code = “))
GName = input(“Enter Garment Name = “)
Rate = float(input(“Enter Rate = “))
Qty = int(input(“Enter Quantity = “))
CCode = int(input(“Enter Cloth Code = “))
q = “insert into Garment Values ({}, ‘{}’, {}, {}, {}”.format(GCode, GName,
Rate, Qty, CCode)
cur._______________(q) #Staatement 2
____________________ #Statement 3
ans = input(“Do you have more records (Y/N)=”)
if ans.upper()==’N’:
break
print(“Records Successfully Saved”)
cn.close()
OR
a. Write the output of the Code given below:
def Timing(T, m=0):
print(“Present Time is”,end=’:’)
if m>10 and m<=20:
print(“Quarter Past”,T)
elif m<=40:
print(“Half Past”,T)
elif m<=59:
print(“Quarter to”,T+1)
else:
print(“Incorrect Minutes”)
Timing(5,18)
Timing(11)
Timing(12,60)
b. The code given below reads those records from table Garment which has Qty less
than 50. Records in table Garments are stored with following attributes:
GCode – integer
GName – string
Rate – decimal
Qty – integer
CCode = integer
Write missing Statements (Statement 1, Statement 2 and Statement 3) to complete
the code:
import mysql.connector as mycon
cn = mycon.connect(host=’localhost’, user=’test’, password=’None’, database=’cloth’)
cur = ______________________ #Statement 1
cur._________________________ #Staatement 2 (Create & Execute Query)
G = ____________________ #Statement 3 Read complete result of query
print(“Required records are:”)
for i in G:
print(i)
cn.close()
Answer:
a. 125@-23@
1 mark each for each correct output
b. Statement 1: cur = cn.cursor()
Statement 2: cur.execute(q)
Statement 3: cn.commit()
1 mark each for each correct answer
OR
a. Present Time is:Quarter Past 5
Present Time is:Half Past 11
Present Time is:Incorrect Minutes
½ mark for 1 correct output
1 mark for 2 correct outputs
2 marks for all correct outputs
b. Statement 1: cn.cursor()
Statement 2: cur.execute(“Select * from Garment where Qty<50”)
Statement 3: cur.fetchall()
1 mark each for each correct answer
33 What is the difference between CSV file and Text File? Write a program in Python
that defines and calls the following functions:
Insert() – To accept details of clock from the user and stores it in a csv file
‘watch.csv’. Each record of clock contains following fields – ClockID, ClockName,
YearofManf, Price. Function takes details of all clocks and stores them in file in one
go.
Delete() – To accept a ClockID and removes the record with given ClockID from the
file ‘watch.csv’. If ClockID not found then it should show a relevant message. Before
removing the record it should print the record getting removed.
OR
Give one advantage of using CSV file over Binary file. Write a program in Python that
defines and calls the following functions:
saving() – To accepts details of equipments from the user in following format (ID,
Name, Make, Price) and save it in a csv file ‘parts.csv’. Function saves one record
at a time.
search() – To accept two prices and displays details of those equipments which has
price between these two values.
Answer:
Text files are plain text files which are used to store any kind of text which has no fixed
format. whereas, CSV files are also text files but they can store information in a specific
format only.
def Insert():
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)
L.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")
while True:
print("1. Add Clock Details")
print("2. Remove Clock Details")
print("3. Exit")
ch = int(input("Enter your choice(1-3)="))
if ch==1:
Insert()
elif ch==2:
Delete()
elif ch==3:
print("Thanks for using this program")
break
else:
print("Incorrect Choice. Please re-enter")
1 mark for correct difference between csv and text files.
Insert() function
½ mark for correct data input and making list
½ mark for correctly opening file
½ 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
½ mark for correctly re-writing remaining records
Main
½ mark for correct main program
OR
CSV files stores records in text format that can be read and manipulated by other
spreadsheet software like excel. However, binary files stores records in raw format and can
only be read and managed by programs only.
def saving():
L=[]
ID = input("Enter ID = ")
name = input("Enter Name = ")
Make = input("Enter Make = ")
price = int(input("Enter Price = "))
R = [ID, name, Make, price]
L.append(R)
import csv
fout = open('parts.csv','a',newline='')
W = csv.writer(fout)
W.writerows(L)
fout.close()
print("Record successfully saved")
def search():
price1 = int(input("Enter Starting Price Range = "))
price2 = int(input("Enter Ending Price Range = "))
found = False
import csv
fin = open('watch.csv','r')
R = csv.reader(fin)
L = list(R)
fin.close()
for i in L:
if int(i[3])>=price1 and int(i[3])<=price2:
found=True
print(i)
if found==False:
print("Record not found")
while True:
print("1. Add Equipment Details")
print("2. Search Equipments based on Price Range")
print("3. Exit")
ch = int(input("Enter your choice(1-3)="))
if ch==1:
saving()
elif ch==2:
search()
elif ch==3:
print("Thanks for using this program")
break
else:
print("Incorrect Choice. Please re-enter")
1 mark for correct advantage of CSV file.
saving() function
½ mark for correct data input and making list
½ mark for correctly opening file
½ mark for correctly writing record
search() function
½ mark for correctly copying data in list
½ mark for correctly identifying record
½ mark for correctly displaying record
½ mark for correctly showing not found message
Main
½ mark for correct main program
34 Mayanti just started to work for a sports academy having several branches across India.
The sports academy appoints various trainers to train various sports. She has been
given the task to maintain the data of the trainers. She has made a table called
TRAINERS in the database which has following records:
Table: TRAINER
TrainerNo Name City HireDate Salary
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000
Based on the data given above answer the following questions:
a. Can City be used as Primary key for table TRAINER? Justify your answer.
b. What is the degree and cardinality of the table TRAINER? If we add two rows
and remove three rows from table TRAINER. Also if we add another attribute
in the table, what will be the degree and cardinality of the table TRAINER will
become?
c. Write statements for:
iii. Insert a new record in table TRAINER with values, TrainerNo = 107,
Name = Swastik, HireDate = 1999-01-22, Salary = 90000.
iv. Increase the salary of those Trainer having city as DELHI by 5000.
OR
c. Write Statements for:
iii. Removes those records from table TRAINER who were hired after year
2000.
iv. Add a new column Grade with datatype as Varchar and maximum size
as 2.
Answer:
a. No. City cannot be used as Primary key for table TRAINER because it has duplicate
values in it.
½ mark for correct identification
½ mark for correct justification
b. Before Changes: Degree = 5, Cardinality = 6
After Changes: Degree = 6, Cardinality = 5
½ mark for correct Degree and Cardinality before changes
½ mark for correct Degree and Cardinality after changes
c.
i. INSERT INTO Trainer (TrainerNo, Name, HireDate, Salary) VALUES (107,
‘Swastik’, ‘1999-01-22’, 90000);
ii. UPDATE Trainer SET Salary = Salary + 5000 WHERE City = ‘DELHI’;
OR
i. DELETE FROM Trainer WHERE Year(HireDate)>2000;
ii. ALTER TABLE Trainer ADD (Grade Varchar(2));
1 mark each for each correct query
½ mark each for partially correct query
35 Tarun Nair is working under XYZ Incorporation which deals with exporting of goods to
foreign countries. To keep track of inventory he is creating a Python program to store
the information of item number and quantity in a binary file inventory.dat. For that he
has written the following code. Go through the code given and solve problems given
below:
def write(ino,qty):
F = open(____________) #Mark 2
L= _______________ #Mark 3
L.append([ino,qty])
F.close()
F=open('inventory.dat','wb')
pickle.dump(L,F)
F.close()
def Receive(ino,qty):
F=open(“inventory.dat”,”rb”)
L=pickle.load(F)
F.close()
for i in range(len(L)):
if L[i][0] == ino:
L[i][1] += qty
F=open("inventory.dat",'wb')
pickle.dump(L,F)
________________ #Mark 4
def Sent(ino,qty):
with open(“inventory.dat”,”rb”) as F:
L=pickle.load(F)
for i in range(len(L)):
if L[i][0] == ino:
L[i][1] -= qty
with open("inventory.dat",'wb') as F:
pickle.dump(L,F)
a. Write statement to open the file at Mark 2 to read records from the file.
b. Write statement at Mark 3 to read the content of binary file in list L.
c. Write statement at Mark 4 to close the file.
d. Why there is no need to close the file in function Sent()?
Answer:
a. F=open(‘inventory.dat’,’rb)
b. L=pickle.load(F)
c. F.close()
d. In function Sent() file is opened using with statement which implicitly closes the file
and hence there is no need to separately close the file.
1 mark each for each correct answer
***************************************
***
SECTION A
1. Python loops can also have else caluse(True/False) 1
2. Which of the following is not a keyword? 1
a) eval b) assert c) nonlocal d) pass
3 What will be the output of the following code snippet ? 1
rec={“Name”:”Python”,”Age”:”20”,”Addr”:”NJ”,”Country”:”USA”}
id1=id(rec)
del rec
rec={“Name”:”Python”,”Age”:”20”,”Addr”:”NJ”,”Country”:”USA”}
id2=id(rec)
print(id1==id2)
a) True b) False c)1 d) Exception
20. Write two points of difference between Twisted Pair Cables and Coaxial Cables 2
OR
Write two points of difference between SMTP and POP3
21. a) Given is a Python string declaration: 2
cbseexam=”BoardExamination2022-23”
22. Explain the use of constraints in Relational Database Management System. Give Example 2
to support your answer
23 a) Write the full form of the following 2
(i) NFS (ii) FTP
b) What is Modem ? What is its function ?
24 Predict the output of the following code given below: 2
def func(message,num=1):
print(message*num)
func(‘Python’)
func(‘Easy’,3)
OR
Predict the output of the following code given below:
tuple1=(‘Jayesh’,’Ramya’,’Taruna’,’Suraj’)
list1=list(tuple1)
for Name in list1:
if Name[0]==’T’:
break
else:
print(“Finished”)
print(“Got it!”)
25 Differentiate between CHAR and VARCHAR datatypes 2
OR
Categorized the following command as TCL and DDL
ALTER,COMMIT,DROP,ROLLBACK
SECTION C
26. a) Consider the table Hotel given below 1+2
EMPID CATEGORY SALARY
E101 MANAGER 60000
E102 EXECUTIVE 65000
E103 CLERK 40000
E104 MANAGER 62000
E105 EXECUTIVE 50000
E106 CLERK 35000
b) Write the output of the queries (i) to (iv) based on the table
TABLE-ACTIVITY
ACODE ACTIVITYNAME PARTICIPANTS NUM PRIZEMONEY SCHEDULEDATE
OR
Write a function in Python, Push(Client) where , Client is a dictionary containing the
details of clients– {Cname:age}. The function should push the names of those client in
the stack who have age greater than 50. Also display the count of elements pushed into
the stack. For example: If the dictionary contains the following data:
Cname={"Robert":55,"Jhon":35,"Smith":75,"Reyan":25} The stack should contain Robert
Smith The output should be: The count of elements in the stack is 2
SECTION D
31. Hi Standard Tech Training Ltd. is a Mumbai based organization which is expanding 5
its office set-up to Chennai. At Chennai office compound, they are planning to
have 3 different blocks for Admin, Training and Accounts related activities. Each
block has a number of computers, which are required to be connected in a network
for communication, data and resource sharing.
As a network consultant, you have to suggest the best network related solutions
for them for issues/problems raised by them in (i) to (v), as per the distances
between various blocks/locations and other given Parameters
Shortest distances between various blocks/locations:
Admin Block to Accounts Block 300 Metres
Number of Computers-
Training Block=150
Admin Block=50
i) Suggest the most appropriate place for the server in the Chennai Office
to get the best effective connectivity. Justify your answer
ii) Suggest the best wired medium for connection of computers in the
Chennai office
iv) Suggest a device /software and its placement that would provide data
security for the entire network of the Chennai office
v) Suggest a device and the protocol that shall be needed to provide
wireless Internet access to all smartphones /laptop users in the
Chennai office
32 a). Write the output of the code given below: 2+3
a=10
y=5
def myfunc():
global a
y=a
a=2
print(“y=”,y, ”a=”,a)
print(“a+y=”,a+y)
return a+y
print(“y=”,y,”a=”,a)
print(myfunc())
print(“y=”,y, “a=”,a)
(b) The code given below inserts the following record in the table Books:
Title – String
AuthorName – string
ISBN_No – String
Price – 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 Library.
• The details (Title, AuthorName, ISBN_No and Price) are to be accepted from the
user. Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def Library_data():
con1=mysql.connect(host="localhost",user="root",password="tiger",
database="Library")
mycursor=_________________ #Statement 1
Title=input("Enter Book Title :: ")
AuthorName=input("Enter Book Author Name :: ")
ISBN_No=input("Enter Book ISBN Number:: ")
Price=int(input("Enter Price of Book :: "))
querry="insert into Books values({},'{}',{},{})".format(Title,AuthorName ,
ISBN_No,Price)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")
OR
(i) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’.
Each record consists of a list with field elements as empid, name and
mobile to store employee id, employee name and employee salary
respectively.
(ii) (ii) COUNTR() – To count the number of records present in the CSV file
named ‘record.csv’.
OR
Give any one point of difference between a binary file and a csv file. Write a
Program in Python that defines and calls the following user defined functions:
SECTION E
TABLE-BOOKS
TABLE-ISSUED
Book_id Quantity_Issued
T0001 4
C0001 5
F0001 2
i) To Show Book name,Author name and Price of books of First Publ Publishers
ii) To display the names and price from books in ascending order of their price,
iii) Write the statement to
a) To insert a new row in the table issued having the following data:’F0003”,1
b) To increase the price of all books of EPB Publishers by 50
OR
import___________ # Fill_Line1
sqlist=list()
for k in range(10):
sqlist.append(k*k)
fout=________________ #Fill_Line 2
_______________________ #Fill_Line 3
fout.close()
fin=_____________________ #Fill_Line 4
________________________ #Fill_Line 5
fin.close()
(a) Complete Fill_Line1 so that the required library becomes available to the
program
(b) Complete Fill_Line 2 so the above mentioned binary file is opened for writing
in the file object fout
(c) Complete Fill_Line 3 so that list created in nthe code , namely Sqlist, is
written in the open file.
(d) Complete Fill_Line 4 which will open the same binary file for reading in the
file object fin.
(e) Complete Fill_Line 5 so that the contents of the open file in the file handle
fin are read in a list namely mylist.
Class: XII Session: 2022-23Computer Science (083)
(Theory)
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
9. This question paper contains five sections, Section A to E.
10. All questions are compulsory.
11. Section A have 18 questions carrying 01 mark each.
12. Section B has 07 Very Short Answer type questions carrying 02 marks each.
13. Section C has 05 Short Answer type questions carrying 03 marks each.
14. Section D has 03 Long Answer type questions carrying 05 marks each.
15. Section E has 02 questions carrying 04 marks each. One internal choice is
given in Q35 against part c only.
16. All programming questions are to be answered using Python Language only.
SECTION A
1. Python loops can also have else caluse(True/False) 1
Ans True
2. Which of the following is not a keyword? 1
b) eval b) assert c) nonlocal d) pass
Ans Eval
3 What will be the output of the following code snippet ? 1
rec={“Name”:”Python”,”Age”:”20”,”Addr”:”NJ”,”Country”:”USA”}
id1=id(rec)
del rec
rec={“Name”:”Python”,”Age”:”20”,”Addr”:”NJ”,”Country”:”USA”}
id2=id(rec)
print(id1==id2)
b) True b) False c)1 d) Exception
Ans True
4 What is the output of this code? 1
>>>int(“3”+”4”)
b) “7” b)”34” c) 34 d) 24
Ans 34
5 Select the correct output of the code 1
x=”apple,pear,peach”
y=x.split(“ , “)
for z in y:
print(z)
e) apple,pear,peach
f) pear,apple,peach
g) peach,apple,pear
h) Error
Ans apple,pear,peach
6 To read the next line of the file from a file object infi,we use 1
b) infi.read(all) b)infi.read() c)infi.readline() d) infi.readlines()
Ans infi.readline()
7 Fill in the Blank: 1
___________is not a legal constraint for a CREATE TABLE command ?
cbseexam=”BoardExamination2022-23”
Ans a) Bor
b) 6
22. Explain the use of constraints in Relational Database Management System. Give Example 2
to support your answer
23 a) Write the full form of the following 2
(ii) NFS (ii) FTP
b) What is Modem ? What is its function ?
Ans i) Network File System
ii) File Transfer Protocol
b) A modem is a computer peripheral that connects a workstation to other work stations
via telephone lines and facilitates communications
Modem converts digital signals to A/F(Audio Frequency) tones which are in the frequency
range that the telephone lines can transmit and also it can convert transmitted tones
back to digital information
OR
Predict the output of the following code given below:
tuple1=(‘Jayesh’,’Ramya’,’Taruna’,’Suraj’)
list1=list(tuple1)
for Name in list1:
if Name[0]==’T’:
break
else:
print(“Finished”)
print(“Got it!”)
Ans Python
EasyEasyEasy
OR
Finished
Finished
Got it!
25 Differentiate between CHAR and VARCHAR datatypes 2
OR
Categorized the following command as TCL and DDL
ALTER,COMMIT,DROP,ROLLBACK
Ans The difference between CHAR and VARCHAR is that of fixed length and variable length.
The CHAR datatype specifies a fixed length character string. When a column is given
CHAR(n), then MySql ensures that all values stored in that column have this length i.e. n
bytes. If a value is shorter than this length n then blanks are added, byt the size of value
remains n bytes
OR
TCL-ROLLBACK,COMMIT
DDL-ALTER,DROP
SECTION C
26. a) Consider the table Hotel given below 1+2
EMPID CATEGORY SALARY
E101 MANAGER 60000
E102 EXECUTIVE 65000
E103 CLERK 40000
E104 MANAGER 62000
E105 EXECUTIVE 50000
E106 CLERK 35000
b) Write the output of the queries (i) to (iv) based on the table
TABLE-ACTIVITY
ACODE ACTIVITYNAME PARTICIPANTNUM PRIZEMONEY SCHEDULEDATE
Ans b
27. Write a method in Python to read lines from a text file DIARY.TXT and display those lines 3
which start with the alphabet ‘P’
OR
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 40000(both values inclusive)
28. a) Write the outputs of the SQL queries (i) to (iv) based on the relations DEPT and WORKER 3
TABLE-DEPT
DCODE DEPARTMENT CITY
D01 MEDIA DELHI
D02 MARKETING DELHI
D03 INFRASTRUCTURE MUMBAI
D05 FINANCE KOLKATA
D04 HUMAN RESOURCE MUMBAI
TABLE-WORKER
WNO NAME DOJ DOB GENDER DCODE
1001 GEORGE K 2013-09-02 1991-09-01 MALE D01
1002 RYMA SEN 2012-12-11 1990-12-15 FEMALE D03
1003 MOHITESH 2013-02-03 1987-09-04 MALE D05
1007 ANIL JHA 2014-01-17 1984-10-19 MALE D04
1004 MANILA SAHAI 2012-12-09 1986-11-14 FEMALE D01
1005 R SAHAY 2013-11-18 1987-03-31 MALE D02
1006 JAYA PRIYA 2014-06-09 1985-06-23 FEMALE D05
OR
Write a function in Python, Push(Client) where , Client is a dictionary containing the
details of clients– {Cname:age}. The function should push the names of those client in
the stack who have age greater than 50. Also display the count of elements pushed into
the stack. For example: If the dictionary contains the following data:
Cname={"Robert":55,"Jhon":35,"Smith":75,"Reyan":25} The stack should contain Robert
Smith The output should be: The count of elements in the stack is 2
Ans def MakePush(Package):
a=int(input(“Enter Package Title”))
Package.append(a)
def MakePop(package):
if(Package==[]):
print(“Stack empty”)
else:
print(“Deleted element:”,Package.pop())
OR
SECTION D
31. Hi Standard Tech Training Ltd. is a Mumbai based organization which is expanding 5
its office set-up to Chennai. At Chennai office compound, they are planning to
have 3 different blocks for Admin, Training and Accounts related activities. Each
block has a number of computers, which are required to be connected in a network
for communication, data and resource sharing.
As a network consultant, you have to suggest the best network related solutions
for them for issues/problems raised by them in (i) to (v), as per the distances
between various blocks/locations and other given Parameters
Training Block=150
Admin Block=50
vi) Suggest the most appropriate place for the server in the Chennai Office
to get the best effective connectivity. Justify your answer
vii) Suggest the best wired medium for connection of computers in the
Chennai office
ix) Suggest a device /software and its placement that would provide data
security for the entire network of the Chennai office
x) Suggest a device and the protocol that shall be needed to provide
wireless Internet access to all smartphones /laptop users in the
Chennai office
Ans. 1 mark for each correct answer
(b) The code given below inserts the following record in the table Books:
Title – String
AuthorName – string
ISBN_No – String
Price – 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 Library.
• The details (Title, AuthorName, ISBN_No and Price) are to be accepted from the
user. Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def Library_data():
con1=mysql.connect(host="localhost",user="root",password="tiger",
database="Library")
mycursor=_________________ #Statement 1
Title=input("Enter Book Title :: ")
AuthorName=input("Enter Book Author Name :: ")
ISBN_No=input("Enter Book ISBN Number:: ")
Price=int(input("Enter Price of Book :: "))
querry="insert into Books values({},'{}',{},{})".format(Title,AuthorName ,
ISBN_No,Price)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")
OR
y= 10 a= 2
a+y= 12
12
y= 5 a= 2
b)
Statement 1: con1.cursor()
Statement 2: mycursor.execute(querry)
Statement 3: con1.commit()
OR
a) SCHOOLbbbbCOM
b)
Statement 1: con1.cursor()
Statement 2: mycursor.execute("select * from books where Price>=200")
Statement 3: mycursor.fetchall()
33. What is the advantage of using a csv file for permanent storage? Write a Program
in Python that defines and calls the following user defined functions:
(iii) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’.
Each record consists of a list with field elements as empid, name and
mobile to store employee id, employee name and employee salary
respectively.
(iv) (ii) COUNTR() – To count the number of records present in the CSV file
named ‘record.csv’.
OR
Give any one point of difference between a binary file and a csv file. Write a
Program in Python that defines and calls the following user defined functions:
Ans Difference between binary file and csv file: (Any one difference may be given)
Binary file:
• Extension is .dat
CSV file:
• Extension is .csv
• Human readable
Program:
import csv
def add():
fout=open("furdata.csv","a",newline='\n')
wr=csv.writer(fout)
FD=[fid,fname,fprice]
wr.writerow(FD)
fout.close()
def search():
fin=open("furdata.csv","r",newline='\n')
data=csv.reader(fin)
found=False
for i in data:
if int(i[2])>10000:
found=True
print(i[0],i[1],i[2])
if found==False:
fin.close()
add()
print("Now displaying")
search()
SECTION E
TABLE-BOOKS
TABLE-ISSUED
Book_id Quantity_Issued
T0001 4
C0001 5
F0001 2
iv) To Show Book name,Author name and Price of books of First Publ Publishers
v) To display the names and price from books in ascending order of their price,
vi) Write the statement to
c) To insert a new row in the table issued having the following data:’F0003”,1
d) To increase the price of all books of EPB Publishers by 50
OR
OR
35. Aaruni Shah is learning to work with Binary files in Python using a process known 5
as pickling/de-pickling. Her teacher has given her the following incomplete code
which is creating a binary file namely Mydata.dat and then opens, reads and
displays the content of this created file
import___________ # Fill_Line1
sqlist=list()
for k in range(10):
sqlist.append(k*k)
fout=________________ #Fill_Line 2
_______________________ #Fill_Line 3
fout.close()
fin=_____________________ #Fill_Line 4
________________________ #Fill_Line 5
fin.close()
(f) Complete Fill_Line1 so that the required library becomes available to the
program
(g) Complete Fill_Line 2 so the above mentioned binary file is opened for writing
in the file object fout
(h) Complete Fill_Line 3 so that list created in nthe code , namely Sqlist, is
written in the open file.
(i) Complete Fill_Line 4 which will open the same binary file for reading in the
file object fin.
(j) Complete Fill_Line 5 so that the contents of the open file in the file handle
fin are read in a list namely mylist.
15 Aman store 5 five in table ‘student’ and for attribute fee Rs. 1
1500,2500,3000,1000,NULL stored respectively. Aman executed the below
command in SQL :
Select average(fee) from student;
After executing the above command for NULL fee record Rs. 4500 updated in
the table student .
on the basis of above select command what will be the average of fee will come
as output:
a. 1600 b. 2000 c. 2500 d. None of the above
Answer:
b. 2000
1 mark for correct answer
SECTION – B
19 Rewrite the following code in Python after removing all syntax error(s). Underline 2
each correction done in the code:
Value=30
Def Display(Value): #
Function Define
for VAL in range(0,Value)
if(val%4==0):
print(VAL*4)
elif(VAL%5==0):
Print(VAL+3)
Else:
print(VAL+10)
Display(30) #
Function call
Answer:
Value=30
def Display(Value): #
Function Define
for VAL in range(0,Value):
if(VAL%4==0):
print(VAL*4)
elif(VAL%5==0):
print(VAL+3)
else:
print(VAL+10)
Display(30) #
Function call
½ mark for each correction , 2 marks all correction and proper syntax
1 mark for difference and 1 mark for writing correct web browsers name
Answer:
fUNnpYTHONn3.7.
2 marks for correct output
OR
Predict the output of the python code given below:
T=25,26,27,28,29
L=list(T)
NL=[ ]
for I in L:
if(i%2==0):
NL.append(i)
else:
NL.append(i-1)
NP=tuple(NL)
print(NP)
Answer :
(25,26,26,28,28)
2 marks for correct output
25 Mohan facing problem to apply SQL functions help him as per below circumstances
and suggest correct function with column name if any as per given statement:-
e. Want to count total number of record of a table(relation) ½
f. Want to find the average of fees received in the vidyalaya ½
g. Want to count for a column city how many city entered in the
column(attribute) except null values ½
h. Want to find the maximum fee paid by a student in the Vidyalaya ½
Answer:
a. Count(*) b. avg(fee) c. Count(city) d. Max(fee)
½ mark for each correct answer
OR
Categorize the following commands as DDL or DML:
CREATE, DELETE, ALTER, UPDATE 2
Answer:
DDL : CREATE , ALTER
DML: DELETE, UPDATE
½ mark each for categorizing the command, total 2 marks
SECTION – C
26 Consider the following tables and answer the questions a and b:
Table: School
SID SName Fee Class CCode
S101 JATIN 2000 11 C1101
S102 PARTH 1500 11 C1102
S103 SNEHA 1800 12 C1202
S104 PRADEEP 2750 11 C1101
S105 ABHINAV 2400 12 C1201
Table: TEACHER
CCode TName
C1101 PRAMOD
C1102 SMARAT
c. What will be output of the following command: 1
SELECT * FROM SCHOOL NATURAL JOIN TEACHER;
d. What will be the output of following commands:
v. SELECT DISTINCT CLASS FROM SCHOOL; ½
vi. SELECT CCODE, SUM(FEE) FROM SCHOOL GROUP BY CCODE ½
HAVING COUNT(*)>1;
vii. SELECT SNAME, TNAME, FROM SCHOOL S, TEACHER T ½
WHERE S.CCODE = T.CCODE AND FEE>2000;
viii. SELECT AVG(FEE) AS AVGFEE FROM SCHOOL WHERE FEE ½
BETWEEN 1500 AND 1800;
Answer:
a. SELECT * FROM SCHOOL NATURAL JOIN TEACHER;
SID SName Fee Class CCode TNAME
S101 JATIN 2000 11 C1101 PRAMOD
S102 PARTH 1500 11 C1102 SMARAT
S104 PRADEEP 2750 11 C1101 PRAMOD
b(i).
SID
S101
S102
b(ii)
CCODE FEE
C1101 4750
C1102 1500
C1202 1800
C1201 2400
b(iii)
SNAME TNAME
PRADEEP PRAMOD
b(iv)
AVGFEE
1650
3 marks for correct output of sub parts of a (1 mark) , b(I to iv) ( ½ mark each)
Answer:
def displayMyMe():
num=0
f=open(“STORY.txt,’r’)
N=f.read()
M=N.split()
for X in M:
if (X==”Me” or “My”):
num=num+1
f.close()
print(“Count of My/Me in file : “, num)
OR
Write a function vowelcount() in Python , which should read each character of
a text file POEM.txt, should count and display the occurrence of vowels (including
both cases)
Example
If the file content is as follows :
You are good student of class
Total Vowels : 10
Answer:
def vowelcount():
f=open(“POEM.txt,’r’) # r mode if not mention then it default take read mode
vowel=[‘a’,’e’,’i’,’o’,’u’,’A’,’E’,’I’,’O’,’U’]
count=0
data=f.read()
for i in data:
if i in vowel:
count=count+1
print(“ Total Vowels : “,count)
f.close()
28 Consider the relations(tables) Games and Player and write the output of the
query for a (i) to (iv) ( ½ mark each= 2 marks) ,(b) write the command
as per statement
Table: GAMES
GCode GName Number Gametype Prize Sdate
G101 Carom 2 Indoor 15000 2022-07-02
G102 Badminton 2 Outdoor 12000 2021-09-15
G103 Table Tennis 4 Indoor 8000 2022-07-25
G104 Chess 2 Indoor 7000 2020-10-01
G105 Lawn Tennis 4 Outdoor 20000 2022-11-01
Table: PLAYER
PCOD PNAME GCode
E
P1 PRAMOD G101
P2 SMARAT G102
P3 DIPAK G103
½
P4 NILESH G105
½
(a) Write the output of all statements (Queries)
e. SELECT Gametype, avg(Prize) from GAMES group by Gametype;
f. SELECT max(Sdate), min (Sdate) from GAMES;
½
g. SELECT Gname, Gametype, G.GCode, , Pname FROM Games G, Player
P WHERE G.GCode=P.GCode and Prize>10000;
½
h. SELECT Gname, Pname from Games G, Player P where Number>=4 and
G.GCode=P.GCode;
1
(b) Write a Query to insert a record in to table GAMES :
GCode GName Number Gametype Prize Sdate
G106 Chess 2 Indoor 12000 2022-10-11
29 Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and 3
n is a numeric value by which all elements of the list are shifted to left.
Sample Input date of the list
Arr=[10,20,30,40,12,11] , n=2
Output
Arr=[30,40,12,11,10,20]
Answer :
def LShift(Arr,n):
L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)
student=[]
def Push(student):
stud_name=input(“ enter the name of student”)
S=[stud_name]
Student.append(S)
print(“student record added into the stack”)
OR
Write a function in Python Pop(student) , where student is a stack
implemented by a list of student name . The function returns the value deleted
from the stack.
student list containing student record
ANSWER:
def Pop(student):
if (student==[]):
print(“stack is empty”)
else:
n=student.pop()
print(n, “student record deleted from the stack”)
SECTION D
31 Three student of KV started a business company Alumni University and setting up
its academic block in Mumbai and is planning to set up of a network. The
University has 3 academic block (BUSINESS, TECHNOLOGY, LAW) and one
Human Resources Centre as shown in the diagram below:
Centre and blocks distances is as follows:
LAW Block to Business Block 40 m
LAW Block to Technology Block 80 m
LAW Block to HR Centre 105 m
Business Block to Technology Block 30 m
Business Block to HR Centre 35 m
Technology Block to HR Centre 15 m
Numbers of computer in each of the blocks/ Centre is as follows:
LAW Block 18
Technology Block 45
HR Center 105
Business Block 30
f. Suggest the most suitable palce (i.e. Block/ Center) to install the server 1
of this University with a suitable reason.
g. Suggest an proper layout for connecting these blocks /center for wired 1
connectivity
h. Which device will your suggest to be placed / installed in each of these 1
blocks/center to efficiently connect all the computers with in these
blocks/center.
i. Suggest the place to fix repeater in the network with justification 1
j. The university is planning to connect its admission office in all states, 1
which is more than approx. 1000 km from University , which type of
network out of LAN, MAN, WAN will be established ? Justify your answer.
ANSWER:
(i) Server will be installed in HR Center because of having maximum number
of computer in the area
(ii) Make a layout That connect all blocks with HR center (or any proper best
layout)
(iii) Switch will be installed in all blocks/center to connect all the computers in
a network
(iv) Repeater may be placed when the distance between two blocks is more
than 70-80 meter
(v) WAN, because the given distance is more than the range of LAN and WAN
32 c. Write the output of the Code given below: 2
m = 5
def product(p=2, q=5):
global m
m = p*q+q*p
print(m,end=’#’)
a = 20
b = 5
product(a,b)
product(q=3, p = 2)
Answer
200#12#
1 mark for each correct output
d. The code given below used to insert the record in table Games of database
STATEGAME: 3
GCode – integer
GName – string
Number – integer
Prize – integer
Write missing Statements (Statement 1, Statement 2 and Statement 3) to complete the code
for executing the program in python using myconnector:
Answer
Statement 1: cur = connection.cursor()
Statement 2: cur.execute(row)
Statement 3: connection.commit()
1 mark each for each correct answer
33 What is the use of CSV file in Python Programming? how its helps to store 5
data in it.? Write a program in Python that defines and call the following user
define functions:-
add() – To accept and add data of an student in to a CSV file “school.csv”.
Each record consists of a list with field elements as sid, sname and class to add
student id, student name and class respectively.
Count() – To count the number of records present in the CSV file named
‘school.csv’
ANSWER
CSV file in python programming helps to store data like a text file in a format COMMA
SEPERATED VALUE. The extension of CSV file is .csv , it’s a Human Redable format.
This file can be open in Excel and Notepad also
import csv
def add():
fout=open(“school.csv”,’a’, “newline=’\n’)
wrow=csv.writer(fout)
sid=int(input( “enter the student id”))
sname=input(“enter the student name”)
class=int(input(“enter class in number in which student studying”))
row=[sid,sname,class]
wrow.writerow(row)
fout.close()
def Count():
fin=open((“school.csv”,’a’, “newline=’\n’)
data=csv.reader(fin)
record=list(data)
print(len(record))
fin.close()
add()
Count()
1 mark for explaining the use of CSV file, ½ mark for importing csv module
1½ mark for making add() correct storing the data and 1 ½ counting the total number
of records from a CSV file
½ mark function calling
SECTION E
34 Rohan just started to work for a sports academy having several branches across
India. The sports academy appoints various trainers to train various sports. She
has been given the task to maintain the data of the trainers. She has made a
table called TRAINERS in the database which has following records:
Table: TRAINER
TNo TName City HireDate Salary
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000
Based on the data given above answer the following questions:
d. Which column will be the primary key in this table justify your answer?
e. What is the degree and cardinality of the table TRAINER? If we add
three rows and after that remove two rows from table TRAINER. Also if 1
we add two another attribute in the table, what will be the degree and 1
cardinality of the table TRAINER will become?
f. Write statements for:
v. Insert a new record in table TRAINER with values, TN = 107,
TName = ‘Pramod’, City=’ DELHI’ HireDate = ‘1999-01-22’,
Salary = 90000. 1
vi. Increase the salary of those Trainer having city as DELHI by 5000.
OR (option for part C only) 1
d. Write Statements for:
v. Removes those records from table TRAINER who were hired after
year 2000. 1
vi. Add a new column Game with datatype as Varchar and maximum
size as 20. 1
Answer:
d. Tno column in the table (relation) can be declare as Primary key because of
having unique value.
1 mark for correct justification or any correct justification
e. Before Changes: Degree = 5, Cardinality = 6
After Changes: Degree = 7, Cardinality = 7
½ mark for correct Degree and Cardinality before changes
½ mark for correct Degree and Cardinality after changes
f.
iii. INSERT INTO Trainer (TNo, TName, City, HireDate, Salary) VALUES
(107, ‘Pramod’,’Delhi’, ‘1999-01-22’, 90000);
iv. UPDATE Trainer SET Salary = Salary + 5000 WHERE City = ‘DELHI’;
OR (option for part (c) only
iii. DELETE FROM Trainer WHERE Year(HireDate)>2000;
iv. ALTER TABLE Trainer ADD (Game Varchar(20));
1 mark each for each correct query
½ mark each for partially correct query
35 SMARAT is working under KVS, which deals with student record and want to
store data in to file with the information of STUDENT id and student name in
a binary student.dat. student will go aboard , if id of the student will match .
For that he has written the following code. Go through the code given and solve
problems given below:
def write(id,name):
F = open(____________) #Statement 1
L= _______________ # Statement 2
L.append([id,name])
F.close()
F=open('inventory.dat','wb')
pickle.dump(L,F)
F.close()
def Receive(id,name):
F=open(“inventory.dat”,”rb”)
L=pickle.load(F)
F.close()
for i in range(len(L)):
if L[i][0] == id:
L[i][1] += qty
F=open("student.dat",'wb')
pickle.dump(L,F)
________________ #Statement 3
def Sent(id,name):
with open(“student.dat”,”rb”) as F:
L=pickle.load(F)
for i in range(len(L)):
if L[i][0] == id:
L[i][1] -= name
with open("student.dat",'wb') as F:
pickle.dump(L,F)
e. Write python code to open the file at Statement 1 to read records from the file. 1
f. Write python code at Statement 2 to read the content of binary file in list L. 1
g. Write python code at Statement 3 to close the file. 1
h. Why binary file is more accurate to store the data for future use? 1
Answer:
e. F=open(‘student.dat’,’rb)
f. L=pickle.load(F)
g. F.close()
h. Binary file in python store the data in machine understandable format, user can not read the
data from a file. It is a portable file to transfer the data from one computer to another like a
python program is also portable. In this file security of data is easily maintainable because it
is not understandable for individual user.
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q34 against part(d) only.
8. All programming questions are to be answered using Python Language only.
Section :- A
1. State True or False 1
“A list of character is similar to a string type ”
2. Which of the following is not a tuple function ? 1
(a) min ( ) (b) max( ) (c) update( ) (d) count( )
3. Write the output of the following code :- 1
a= {‘a’: “Apple”, ‘b’: “Banana” , ‘c’: “Cat”}
a[‘a’]= “Anar”
print (a)
def functions1(a) :
a= a+ ‘1’
a=a*2
function1 (“hello”)
10. What kind of transmission medium is most appropriate to carry data in a computer network that 1
is exposed to electrical interferences?
(a) Unshielded twisted pair (c) Microwave
(b) Coaxial cable (d) Optical Fiber
11. Which of the following keywords will you use in the following query to display all the values of 1
the column dept_name ?
12. Which operator tests column for the absence of data (i.e. NULL value) ? 1
(a) EXISTS operator (b) NOT operator (c) IS operator (d) None of these
13. Mandatory argument required to connect any database from python 1
(a) Username, Password, Hostname, Database name, Port
(b) Username, Password, Hostname
(c) Username, Password, Hostname, Database name
(d) Username, Password, Hostname, Port
14. When iterating over an object returned from csv.reader(), what is returned with each iteration? 1
For example, given the following code block that assumes csv_reader is an object returned
from csv.reader(), what would be printed to the console with each iteration?
15. Read the following statement about feature of CSV file and select which statement is TRUE ? 1
Statement 1: Only database can support import/export to CSV format
Statement 2: CSV file can be created and edited using any text editor
Statement 3:All the columns of CSV file can be separated by comma ‘ ,’ only
16. In order to open a connection with MySQL database from within Python using mysql.connector 1
package _________ function is used .
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both (A) and (R) are correct and (R) is correct explanation of (A).
(b) Both (A) and (R) are correct and (R) is not the correct explanation of (A).
(c) (A) is True but (R) is False.
(d) (A) is False but (R) is True.
17. Assertion (A) : Data Integrity means that data is accurate and consistent in the database. 1
Reason (R) :- Data integrity also ensures that your data is safe from any outside forces.
18. Assertion (A) : A database can have only one table 1
Reason (R) :- if a piece of data is stored in two places in the database, then storage space is
wasted.
SECTION B
19. Rewrite the following code in python after removing all syntax error(s) . Underline each 2
correction done in the code :-
def sum(c)
s=0
for i in Range (1, c+1)
s=s+i
return s
print(sum(5)
20. Write an advantage and a disadvantage of using Optical fiber cable ? 2
OR
What is the basic difference between functioning of a hub and switch when both precisely
connect computers into a network?
21. What is output of following codes :-
(a) s= ‘My’ 1
s1= ‘Blog’
s2=s[:1] +s1[len (s1)-1:]
print (s2)
22. What is the difference between primary key and unique constraints ? 2
23. (a) Expand the following terms :- 1
(i) SMTP (ii) POP
(b) What is the uses of microwave signals? 1
24. Determine the output of the following :- 2
Table :- LAB
No Itemname CostPerItem Quantity DateofPurchase Warranty Operational
1 Computer 60000 9 21/05/1996 2 7
2 Printer 15000 3 21/05/1997 4 2
3 Scanner 18000 1 29/08/1998 3 1
4 Camera 21000 2 13/06/1996 1 2
5 Hub 8000 1 31/10/1999 2 1
6 UPS 5000 5 21/05/1996 1 4
7 Plotter 25000 2 11/01/2000 2 2
27. Write a function LShift (Arr, n) in Python , which accepts a list Arr of numbers and n is a 3
numeric value by which all elements of the list are shifted to left .
OR
Write a function in Python that counts the number of “Me” or “My” word present in a text file
“STORY.TXT” , if the “STORY.TXT ” contents are as follows :-
Mt first book
was Me and
My family .It
gave me
chance to be
known to the
world.
30. Write a function in Python , MakePush (Package) and MakePop (Package) to add a new package 3
and delete a package from a List of Package Descriptions , considering them to act as push and
pop operations of the Stack data structure .
OR
Write Addnew(Book) and Remove( Book) functions in Python to Add a new Book and Remove
a Book from a List of Books , considering them to act as PUSH and POP operations of the data
structure Stack .
SECTION D
31. (a) Ravya Industries has set up its new center at Kaka Nagar for its office and web based 4
activities . The company compound has 4 buildings as shown in the diagram below :
Raj Fazz
Building Building
Harsh Jazz
Building Building
import random
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 = “# ”)
(i) 10 #40#70 # (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#
(b) Differentiate between fetchone ( ) and fetchcall ( ) method with suitable example for each .
3
OR
(a) Which names are local and which are global in the following code fragment ?
invader= “Big names ” 2
pos = 200
level=1
def play ( ):
max_level= level+10
print(len(invanders) == 0
returnmax_level
res =play ( )
print (res)
33. Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv” which will 5
contain user name and password for some entries . He has written the following code . As a
programmer, help him to successfully mexecute the given task :
Table :- STORE
(d) Abhay want to remove that table STORE from the database MyStore . Which command will
he use from the following :
OR
(d) Now Abhay wants to display the structure of the table STORE ,i.e. name of the attributes and
their respective data types that he has used in the table . Write the query to display the same .
35. Ariba Malik has been given following incomplete code , which takes a student’s details 4
(rollnumber, name and marks ) and writes into a binary file stu.dat using pickling .
import pickle
sturno = int (input (“Enter roll number:=” ))
stuname= input (“Enter name :”)
stumarks= float (input (“Enter marks : ”))
Stu1= {“RollNo. ” : sturno , “Name ” : stuname, “Marks ” : stumarks }
with __________________ as fh : # Fill_Line 1
___________________ # Fill_Line 2
_________________________ as fin : # Fill_Line 3
____________________ # Fill_Line 4
print (Rstu )
if Rstu [“Marks”] >=85:
print (“Eligible for merit certificate ”)
else :
print (“Not eligible for merit certificate ”)
(a) Complete Fill_Line 1 so that the mentioned binary file is opened for writing in fh object
using a with statement.
(b) Complete Fill_Line 2 so that the dictionary Stu’s contents are written on the file opened in
step (a)
(c) Complete Fill_Line 3 so the the earlier created binary file is opened for reading in a file
object namely fin using a with statement.
(d) Complete Fill_Line 4 so that the contents of open file in fin are read into a dictionary namely
Rstu.
************************************
Kendriya Vidyalaya Sangathan
Mumbai Region
Class XII ( Session 2022-23) Subject :- Computer Science (083)
Sample Question Paper (Theory)
Marking Scheme
Time :- 3:00 hr M.M. :- 70
General Instructions:
9. This question paper contains five sections, Section A to E.
10. All questions are compulsory.
11. Section A have 18 questions carrying 01 mark each.
12. Section B has 07 Very Short Answer type questions carrying 02 marks each.
13. Section C has 05 Short Answer type questions carrying 03 marks each.
14. Section D has 03 Long Answer type questions carrying 05 marks each.
15. Section E has 02 questions carrying 04 marks each. One internal choice is given in Q34 against part(d) only.
16. All programming questions are to be answered using Python Language only.
Section :- ( A)
Ans 1:- False 1
Ans 2:- (c) 1
Ans 3:- (a) 1
Ans 4:- (a) 1
Ans 5:- (b) 1
Ans 6 :- Immutable 1
Ans 7:- (b) 1
Ans 8:- (d) 1
Ans 9 :- False ½ +½
True
Ans10 :- (d) 1
Ans 11:- (a) 1
Ans 12:- (c) 1
Ans13 :- (c) 1
Ans 14:- (a) 1
Ans 15:- (c) 1
Ans 16 :- (c) 1
Ans 17: (a) 1
Ans 18:- (d) 1
SECTION ( B )
Ans 19:- def sum(c) : 2
s=0 (½
for i in range (1, c+1): +½+½
s=s+i +½)
return s
print(sum(5))
OR
A hub shares and distributes bandwidth among all connected computers whereas a switch does
not share bandwidth , rather each computer gets full bandwidth.
Ans 22:- Primary key cannot have NULL value , the unique constraints can have NULL values . There is
only one primary key in a table , but there can be multiple unique constraints . The primary key
creates the cluster index automatically but the Unique key does not.
(b) Microwave signals are used to transmit data without the use of cables . The microwave 1
signals are similar to radio and television signals and are used for long distance communication.
(1 mark for find wrong statement and 1 mark for correct code )
SECTION ( C)
Ans 26 :- (a) (i) 1 (ii) 1 (iii) 80000 (iv) 23800 2
(½ mark for each)
(b) An Equijoin is a special type of join where two tables are joined on the basis of common
column having equal values i.e it is based upon we use only an equality operator . The EQUI 1
join shows the common columns from all the participating tables .
(½ mark for correct function header , 1 mark for correct outer loop ,1 mark for correct inner
loop statement , ½ mark for print statement)
OR
def displayMeMy ( ) :
num= 0
f=open (“story.txt” , “rt”)
N= f.read ( )
M=N.split ( )
for x in M:
if x== “Me” or x== “My”:
print (x)
num =num+1
f.close( )
print (“Count of Me/My in file ”, num)
OR
Book [ ]
def Addnew (s):
Name = input (“Enter Book Name ”)
Book.append (Name)
SECTION ( D)
Ans 31 :- (i) 4=
Raj Fazz
Building Building
Harsh Jazz
Building Building
1
(ii) The most suitable place /block to house the server of this organization would be Raj Building
, as this block contains the maximum number of computer , thus decreasing the cabling cost for
most of the computers as well as increasing the efficiency of the maximum computers in the ½ +½
network.
(½ mark for naming the server block and ½ mark for correct reason.)
(iv) The type of network that shall be formed to link the sale counters situated in various parts of
the same city would be a MAN, because MAN (Metropolitan Area Networks) are the 1
networks that link computer facilities within a city.
For example , if the SQL query returned two records in the resultset such as :
101 Rushil 97.5
106 Anya 98.0
then fetchall ( ) will get all the recorsd (i.e both records shown ) in one go. And fetchone ( ) will
first get the fist record and after using fetchone( ) again , it will get the second record.
( 1 mark for each correct answer and ½ mark for each example )
OR
(a) Global names : invaders, pos , level ,res
Local names : max_level
1
1
( 1 mark for each correct answer )
(b)
(i) A database cusror is a special control structure that facilities the row by row processing of the
records of the resultset .
The resultset refers to a logical set of records that are fetched from the database by
executing an SQL query and made avaliable to the application program.
OR
(d) Des or Describe Store ( 1 mark for correct answer )
Ans :- 35 import pickle
sturno = int (input (“Enter roll number:=” ))
stuname= input (“Enter name :”)
stumarks= float (input (“Enter marks : ”))
Stu1= {“RollNo. ” : sturno , “Name ” : stuname, “Marks ” : stumarks }
**************************************************************************
KENDRIYA VIDYALAYA SANGATHAN MUMBAI REGION
Sample Question Paper 2022-23
Class- XII
Computer Science (083)
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each.
8. All programming questions are to be answered using Python Language only.
SECTION – A
Q.No. QUESTIONS Marks
6. The file mode to open a binary file for writing as well as reading is --------------- 1
(a) wb (b) wr (c) wb+ (d) wr+
7. Which of the following is not a legal constraint for create table command? 1
(a)primary key (b) unique (c) check (d) distinct
8. Consider the following Sql statement . What type of statement is this? 1
SELECT* FROM Employee;
(a) DML (b) DDL (c) TCL (d) DCL
9. Which of the following statements would give an error after executing the 1
following code?
T= ‘green’ # ---- Statement 1
T[0]= ‘G’ #---- Statement 2
T=[1 , ‘B’ ,14.5 ] #---- Statement 3
T[3]=15 #---- Statement 4
Options:-
(a) Statement 2 and 4
(b) Statement 1 and 2
(c) Statement 3 and 4
(d) Statement 1 and 3
10 Fill in the blank: - 1
A---------------------------------- is a property of the entire relation , which ensures
through its value that each tuple is unique in a relation.
(a)Rows (b) key (c) Attribute (d) Field
11 What will be the output of the following statement in python? (fh is a file handle) 1
fh.seek(-30,2)
Options:-
It will place the file pointer:-
(a) at 30th byte ahead of current current file pointer position
(b) at 30 bytes behind from end-of file
(c) at 30th byte from the beginning of the file
(d) at 5 bytes behind from end-of file
12 Which of the following keywords will you use in the following query to display 1
the unique values of the column dept_name?
SELECT --------------------- dept_name FROM Company;
(a)All (b) key (c) Distinct (d) Name
13 The physical address assigned by NIC manufacturer is called--------------address. 1
(a)IP (b) MAC (c) TCP (d) URL
14 What will the following expression be evaluated to in Python? 1
(Given values :- A=16 , B=15)
print((14+13%15) +A%B//A)
a) 10#20# b) 10#20#30#40#50#
c) 10#20#30# d) 50#60#
OR
def ChangeLst():
L=[]
L1=[]
L2=[]
for i in range(1,10):
L.append(i)
for i in range(10,1,-2):
L1.append(i)
for i in range(len(L1)):
L2.append(L1[i]+L[i])
L2.append(len(L)-len(L1)
print(L2)
25. Differentiate between DELETE and DROP table commands with example. 2
OR
Categorize the following commands as DDL or DML:
INSERT, DESC, ALTER, DELETE
SECTION – C
26. (a) Based on the tables CAR and CUSTOMER write the output of the 1+2
following query:
Table : Car
Ccode CarName Make
501 A-Star Suzuki
503 Indigo Tata
502 Innova Toyota
509 SX4 Suzuki
510 C Class Mercedes
511 I-20 Tata
Table: Customer
Ccode Address
502 Kolkata
509 Jaipur
502 Beas
(b) Write the output of the queries (i) to (iv) based on the table, TRAVEL
given below:
Table: TRAVEL
TNO TNAME TDATE KM TCODE NOP
101 Janish 2015-02-18 100 101 32
102 Vedika 2014-06-06 65 101 45
103 Tarun 2012-10-09 32 104 42
104 John 2015-10-30 55 105 40
105 Ahmed 2015-12-15 47 101 16
106 Raveena 2016-02-26 82 103 9
27. Write a function countwords( ) that read a file ‘python.txt’ and display the total 3
number of words which begins by uppercase character.
Example:
OR
Write a python function ALCount(), which should read each character of text
file “STORY.TXT” and then count and display the number of lines which begins
from character ’a’ and ‘l’ individually (including upper cases ‘A’ and ‘L’ too)
Example:
A python is a powerful
Language is user friendly
It is platform independent Language
Output of function should be :
A or a: 1
L or l : 1
28. (a) Write the output of SQL queries (i) to (iv) based on table SCHOOLADMIN 3
and ROADMIN, given below:
Table: SCHOOLADMIN
ANO NAME STREAM DOB PHONE FEE
101 Srishti B Business 2005-05- 1234322 2000
Admin 12 4
102 Aman Sciences 2005-11- 6713432 4000
02 4
103 Shivam Sciences 2006-01- 5113432 3500
23 4
104 Banita Business 2005-10- 1324193 2500
Admin 12 4
105 Myra Fine Arts 2005-07- 1244593 1500
01 1
106 Raghav Humanities 2005-06- 4215593 5000
05 1
107 Medini Fine Arts 2005-09- 5121593 1000
05 1
108 Udai Veer Sciences 2006-11-25 5513432 4500
4
Table: ROADMIN
R_NO STREAM PLACE
1 Sciences Agra
2 Fine Arts Jaipur
3 Humanities Tinsukia
(b) Write the command to view the structure of the table ‘ROADMIN’
29. Define a function add( a , b ) where a and b are lists of same length. 3
1. If length of the lists is not equal, function should display a message
‘Length not equal’
2. If length is equal then elements of both the lists should be added together
and form a new list.
For example :
A = [ 1, 2, 3, 4 ]
B= [8,11,27, 14]
C= [ 9, 13, 30, 18 ]
Write the following user defined functions to perform given operations on the
stack named STUD:
(ii) Pop_student( ) – To Pop the objects from the stack and display them.
Also display ‘Stack empty’ when there is no element in the stack.
OR
SECTION – D
31. Bright training institute is planning to set up its centre in Amritsar with four 5
specialised blocks for Medicine, Management, Law courses along with an
Admission block in separate buildings. The physical distance between these
blocks and the number of computers to be installed in these blocks are given
below. You as a network expert have to answer the queries raised by their board
of directors as given in (I) to (IV)
(i) Suggest the most suitable place to install the main server of this institution
to get efficient connectivity.
(ii) Suggest the best wired medium and draw the best cable layout for effective
network connectivity of the blocks having server with all the other blocks.
(iii) Suggest the devices to be installed in each of these buildings for connecting
computers installed within the building out of the following:
● Modem
● Switch
● Gateway
● Router
(iv) Suggest the most suitable wired medium for efficiently connecting
computers installed in every building out of the following network cables.
● Coaxial cable
● Ethernet cable
● Single pair
● Telephone cable.
(v) Mr X works in the admin block and he usually connects his projector to his
mobile phone for presentation purpose. Identify the type of network he
creates
● PAN
● LAN
● MAN
● WAN
32. (a) Find and write the output of the following Python code: 2+3
def Show(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2 != 0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Show('CBSE kvs')
(b) The code given below inserts the following record in the table “Library”:
BID – integer
BTitle – string
Pages – Integer
Price – Integer
import mysql.connector as mc
def sql_data( ):
con1=mc.connect(host=”localhost”, user=’root’,
password=’kvs’, database=’LIB’)
mycur= ________________________________ # Statement-1
BID=int(input(‘Enter book ID=’))
BTitle=input(‘Enter book title=’)
Pages = int(input(“Enter no. of pages=”))
Price = int(input(“Enter book price=”))
Qry=”insert into library values ( { }, ‘{ }’, { }, { })”. format(BID,
BTitle, Pages, Price)
________________________ # Statement-2
________________________ # Statement-3
print(‘Data added in the table”)
OR
(a) Find and write the output of the following python code:
def changer(p,q=10):
p=p/q
q=p%q
print(p,’#’,q)
return p
a=200
b=20
a=changer(a,b)
print(a,’$’,b)
b=changer(b)
print(a,’$’,b)
(b) The code given below reads the following record from the table
“Library” and display only those records who have price less than 500:
BID – integer
BTitle – string
Pages – Integer
Price – Integer
import mysql.connector as mc
def sql_data( ):
con1=mc.connect(host=”localhost”, user=’root’,
password=’kvs’, database=’LIB’)
mycur= ________________________________ # Statement-1
print(“Books with price less than 500 are: ”)
________________________ # Statement-2
Write a program in Python that defines and calls the following user defined
functions:
OR
Write a program in Python that defines and calls the following user defined
functions:
SECTION – E
Each question carries 4 marks
Q.No. QUESTIONS Marks
34. A Multinational Company XYZ is considering to maintain the records of 4
their employee using SQL to store the data. As a database administer,
Abhinay has decided that :
• Name of the database - db
• Name of the table – EMPLOYEE
(a) Identify the attribute best suitable to be declared as a primary key as well
as foreign key.
(b) Write the degree and cardinality of the table EMPLOYEE.
(c) Insert the following data into the attributes EMPID, FIRSTNAME,
LASTNAME, Hire_Date ADDRESS and CITY respectively in the given table
EMPLOYEE.
EMPID=1201, FIRSTNAME=Amit, LASTNAME=Singh, Hire_Date=01-
Aug-2020 ADDRESS=222E South City and CITY= Kolkata.
(d) Abhinay want to remove the table EMPLOYEE from the database db.
Which command will he use.
35. Ratnesh of class 12 is writing a program to create a CSV file “student.csv” which will 4
contain Name, Date of Birth and place. He has written the following code. As a
programmer, help him to successfully execute the given task.
import _______ #Line 1
with open('E:/student.csv',________) as f: #Line 2
w = csv. _______(f) #Line 3
ans= 'y'
while (ans== 'y'):
name= input("Name?: ")
date = input("Date of birth: ")
place = input("Place: ")
w.writerow([name, date, place])
ans=input("Do you want to enter more y/n?: ")
F=open("E:/student.csv", 'r')
reader = csv.________(F) #Line 4
for row in reader:
print(row)
F._______( ) #Line 5
(a) Name the module he should import in Line 1.
(b) In which mode, Ratnesh should open the file to add data into the file.
(c) Fill in the blank in Line 3 to write the data to the csv file.
(d) Fill in the blank in Line 4 to read the data from a csv file.
KENDRIYA VIDYALAYA SANGATHAN MUMBAI REGION
Sample Question Paper 2022-23
Marking Scheme
Class- XII
Computer Science (083)
Maximum Marks : 70 Time: 3 Hrs.
SECTION – A
Q.No. Answers Marks
1. State True or False 1
“In Python, a variable is a place holder for data”
Ans:- False
2. Which value type does input() return? 1
(a) Boolean (b) String (c) int (d)float
Ans:- (b) String
3. Which is the correct form of declaration of dictionary? 1
(a) D={1:’M’ , 2: ‘T’ , 3:’W’}
(b) D= {1;’M’ , 2; ‘T’ , 3;’W’}
(c) D= {1:’M’ 2: ‘T’ 3:’W’ }
(d) D= {1:’M’ ; 2: ‘T’ ; 3:’W’}
Ans:- (a) D={1:’M’ , 2: ‘T’ , 3:’W’}
4. How would you write AY in Python as an expression? 1
(a) A*Y (b) A**Y (c) A^Y (d) A^^Y
Ans:- (b) A**Y
5. What is the length of the tuple shown below: - 1
SECTION-B
Each question carries 2 marks
19. The following Python code is supposed to print the largest word in a sentence but there are 2
few errors. Rewrite the code after removing errors and underline each corrections made.
Str=input("Enter a sentence")
word=split()
print(word)
maxlen=0
largest=""
for i in word:
l=len(i)
if(l>maxlen):
largest=l
print(largest)
Ans
Str=input("Enter a sentence")
word=Str.split()
print(word)
maxlen=0
largest=""
for i in word:
l=len(i)
if(l>maxlen):
largest=i
maxlen=l
print(largest)
20. Write any two differences between telnet and ftp. 2
Ans:-
Key TELNET FTP
Port Number In general, TELNET uses the port FTP uses port numbers 20
Used number 23 for its command and 21 to establish a
operations. connection and perform file
transfer operations.
Or
Write short notes on URLs and domain names.
Ans:-
A URL (Universal Resource Locator) is a complete web address used to find a particular
web page. While the domain is the name of the website, a URL will lead to any one of the
pages within the website. Every URL contains a domain name, as well as other
components needed to locate the specific page or piece of content.
A domain is the name of a website, a URL is how to find a website, and a website is what
people see and interact with when they get there.
21. 1. A List is declared in Python as below 2
mylist=[34,65,-77,12,0,113,31]
Find the output of the command
mylist[:5]
Ans. [34, 65, -77, 12, 0]
a) 10#20# b) 10#20#30#40#50#
c) 10#20#30# d) 50#60#
Ans:-
Minimum value of c is 0
Maximum value of c is 4
Possible Answers : 1,2,3
OR
def ChangeLst():
L=[]
L1=[]
L2=[]
for i in range(1,10):
L.append(i)
for i in range(10,1,-2):
L1.append(i)
for i in range(len(L1)):
L2.append(L1[i]+L[i])
L2.append(len(L)-len(L1))
print(L2)
Ans:-
[11, 10, 9, 8, 7, 4]
25. Differentiate between DELETE and DROP table commands with example. 2
Ans:-
Parameter DELETE DROP
OR
Table : Car
Ccode CarName Make
501 A-Star Suzuki
503 Indigo Tata
502 Innova Toyota
509 SX4 Suzuki
510 C Class Mercedes
511 I-20 Tata
Table: Customer
Ccode Address
502 Kolkata
509 Jaipur
502 Beas
Ans:-
Ccode CarName Make Address
502 Innova Toyota Beas
502 Innova Toyota Kolkata
509 SX4 Suzuki Jaipur
(b) Write the output of the queries (i) to (iv) based on the table, TRAVEL 2
given below:
Table: TRAVEL
TNO TNAME TDATE KM TCODE NOP
101 Janish 2015-02-18 100 101 32
102 Vedika 2014-06-06 65 101 45
103 Tarun 2012-10-09 32 104 42
104 John 2015-10-30 55 105 40
105 Ahmed 2015-12-15 47 101 16
106 Raveena 2016-02-26 82 103 9
Ans:-
Count(Distinct Tcode)
Ans:-
TCODE MAX(NOP) COUNT(*)
101 45 3
3. Select Tname from TRAVEL where NOP < 20 order by Tname desc;
Ans.
TNAME
Raveena
Ahmed
MIN(KM)
65
Ans.
def COUNTWORDS( ):
fin=open(‘PYTHON.TXT’, ‘r’)
count=0
for line in fin:
for i in line.split( ):
if i[0].isupper( ):
count+=1
print(count)
fin.close( )
COUNTWORDS( )
OR
Write a python function ALCount(), which should read each character of text
file “STORY.TXT” and then count and display the number of lines which begins
from character ’a’ and ‘l’ individually (including upper cases ‘A’ and ‘L’ too)
Ans.
def ALCount( ):
f = open('STORY.TXT' , 'r' )
countA = 0
countL = 0
for line in f:
if line[0] == 'A' or line[0] == 'a' :
countA+=1
if line[0] == 'L' or line[0] == 'l' :
countL+=1
print('A or a : ', countA)
print('L or l : ', countL)
f.close()
ALCount( )
28. (a) Write the output of SQL queries (i) to (iv) based on table SCHOOLADMIN 3
and ROADMIN, given below:
Table: SCHOOLADMIN
ANO NAME STREAM DOB PHONE FEE
101 Srishti B Business 2005-05- 1234322 2000
Admin 12 4
102 Aman Sciences 2005-11- 6713432 4000
02 4
103 Shivam Sciences 2006-01- 5113432 3500
23 4
104 Banita Business 2005-10- 1324193 2500
Admin 12 4
105 Myra Fine Arts 2005-07- 1244593 1500
01 1
106 Raghav Humanities 2005-06- 4215593 5000
05 1
107 Medini Fine Arts 2005-09- 5121593 1000
05 1
108 Udai Sciences 2006-11-25 5513432 4500
Veer 4
Table: ROADMIN
R_NO STREAM PLACE
1 Sciences Agra
2 Fine Arts Jaipur
3 Humanities Tinsukia
Ans.
Stream Max(FEE)
Business Admin 2500
Sciences 4500
Fine Arts 1500
Humanities 5000
( ½ mark for the correct output)
Ans.
Name Place
Myra Jaipur
Medini Jaipur
(b) Write the command to view the structure of the table ‘ROADMIN’.
29. Define a function add( a , b ) where a and b are lists of same length. 3
1. If length of the lists is not equal, function should display a message
‘Length not equal’
2. If length is equal then elements of both the lists should be added together
and form a new list.
For example :
A = [ 1, 2, 3, 4 ]
B= [8,11,27, 14]
C= [ 9, 13, 30, 18 ]
Ans.
def add ( a , b ):
c=[ ]
if len(a) != len(b):
print('Length not equal')
else:
for i in range(len(a)):
c.append(a[i] + b[i] )
print(c)
Write the following user defined functions to perform given operations on the
stack named STUD:
Ans.
STUD= [ ]
def Push_Student(s):
if s[2] > 75:
L1 = [s[0],s[1]]
STUD.append(L1)
def Pop_student( ):
num=len(STUD)
while len(STUD) ! = 0:
d=STUD.pop()
print(d)
num=num-1
else:
print(“Stack empty”)
(1½ marks for correct push element and 1½ marks for correct pop
element)
OR
Write a function Push(STUD) in python, where STUD is a dictionary containing
The details of stationary items- {Sname : marks}.
The function should push the names of those students in the stack who have
marks less than 33. Also display the count of elements pushed into the stack.
Ans.
Stack= [ ]
def Push(STUD):
cnt= 0
for k in STUD:
if (STUD[k] < 33):
Stack.aappend(k)
Cnt = cnt + 1
print(“ The count of elements =”,cnt)
SECTION – D
31. Bright training institute is planning to set up its centre in Amritsar with four 5
specialised blocks for Medicine, Management, Law courses along with an
Admission block in separate buildings. The physical distance between these
blocks and the number of computers to be installed in these blocks are given
below. You as a network expert have to answer the queries raised by their board
of directors as given in (I) to (IV)
(i) Suggest the most suitable place to install the main server of this
institution to get efficient connectivity.
Ans: Admin Block is the most appropriate place to install the main
server as it has the maximum number of computers.
(ii) Suggest the best wired medium and draw the best cable layout for
effective network connectivity of the blocks having server with all the
other blocks.
Ans. Fibre cable
( ½ mark for the correct wired medium , ½ mark for correct layout)
Ans. Switch
(1 mark for the correct answer)
(iv) Suggest the most suitable wired medium for efficiently connecting
computers installed in every building out of the following network cables.
● Coaxial cable
● Ethernet cable
● Single pair
● Telephone cable.
(v) Mr X works in the admin block and he usually connects his projector to
his mobile phone for presentation purpose. Identify the type of network
he creates
● PAN
● LAN
● MAN
● WAN
Ans. PAN
(1 mark for the correct answer)
32. (a) Find and write the output of the following Python code: 2
def Show(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2!=0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Show('CBSE kvs')
Ans. cbse#KVS
(b) The code given below inserts the following record in the table “Library”: 3
BID – integer
BTitle – string
Pages – Integer
Price – Integer
import mysql.connector as mc
def sql_data( ):
con1=mc.connect(host=”localhost”, user=’root’,
password=’kvs’, database=’LIB’)
mycur= ________________________________ # Statement-1
BID=int(input(‘Enter book ID=’))
BTitle=input(‘Enter book title=’)
Pages = int(input(“Enter no. of pages=”))
Price = int(input(“Enter book price=”))
Qry=”insert into library values ( { }, ‘{ }’, { }, { })”. format(BID,
BTitle, Pages, Price)
________________________ # Statement-2
________________________ # Statement-3
print(‘Data added in the table”)
Ans:
Statement-1: con1.cursor()
Statement-2: mycur.execute(Qry)
Statement-3: con1.commit()
OR
(a) Find and write the output of the following python code: 2
def changer(p,q=10):
p=p/q
q=p%q
print(p, '#',q)
return p
a=200
b=20
a=changer(a,b)
print(a,'$',b)
b=changer(b)
print(a,'$',b)
Ans:
10.0 # 10.0
10.0 $ 20
2.0 # 2.0
10.0 $ 2.0
(b) The code given below reads the following record from the table 3
“Library” and display only those records who have price less than 500:
BID – integer
BTitle – string
Pages – Integer
Price – Integer
Note the following to establish connectivity between Python and MySQL:
- Username is root
- Password is kvs
- The table exists in MySQL database name LIB.
import mysql.connector as mc
def sql_data( ):
con1=mc.connect(host=”localhost”, user=’root’,
password=’kvs’, database=’LIB’)
mycur= ________________________________ # Statement-1
print(“Books with price less than 500 are: ”)
________________________ # Statement-2
Ans:
Statement-1: con1.cursor()
Statement-2: mycur.execute(“select * from library where price <
500”)
Statement-3: mycur.fetchall( )
33. Give any one point of difference between ‘writerow ( ) ’ and ‘writerows ( )’ 5
functions.
Write a program in Python that defines and calls the following user defined
functions:
Program:
import csv
def ADD( ):
fout = open("shop.csv", 'a', newline= '\n')
wr=csv.writer(fout)
shopno=int(input("Enter Shop No.= "))
name=input("Enter Shop name = ")
address=input("Enter Address= "))
lst=[shopno,name,address] --------- ½ mark
wr.writerow(lst) --------- ½ mark
fout.close()
def COUNTS ():
fin=open("shop.csv","r",newline="\n")
data=csv.reader(fin)
d=list(data)
print(len(d))
fin.close()
ADD()
COUNTS()
OR
How rb+ is different from ab+ mode of file handling? 5
Write a program in Python that defines and calls the following user defined
functions:
Program:
import pickle
def createfile( ):
f = open ( 'record.dat' , 'wb' )
while True:
rno = int ( input ('Enter the roll number : ' ) )
name = input ( 'Enter the name : ' )
clas = int (input ('Enter Class : ') )
section = input ( 'Enter Section : ' )
per = float (input ( ‘Enter percentage : ‘ ) )
record = [rno,name,clas,section,per]
pickle.dump ( record,f )
choice = input ( 'Do you have more records (y/n) : ' )
if choice == 'n' or choice == 'N':
break
f.close( )
def searchRecord(num):
f=open('record.dat','rb+')
found=0
try:
while True:
record = pickle.load ( f )
if record[0] == num:
print(record)
found=1
break
except EOFError:
pass
if found==0:
print('Record not found')
f.close( )
createfile()
rn=int(input(‘Enter roll no. to search=’);
searchRecord(rn)
(1 mark for difference
½ mark for importing pickle module
1½ marks each for correct definition of createfile() and
searchRecord()
½ mark for function call statements)
SECTION -E
Each question carries 4 marks
34. A Multinational Company XYZ is considering to maintain the records of 4
their employee using SQL to store the data. As a database administer,
Abhinay has decided that :
• Name of the database - db
• Name of the table – EMPLOYEE
(a) Identify the attribute best suitable to be declared as a primary key as well
as foreign key.
Ans. empid
(b) Write the degree and cardinality of the table EMPLOYEE.
Ans. Degree – 6
Cardinality - 6
(c) Insert the following data into the attributes EMPID, FIRSTNAME,
LASTNAME, Hire_Date ADDRESS and CITY respectively in the given table
EMPLOYEE.
EMPID=1201, FIRSTNAME=Amit, LASTNAME=Singh, Hire_Date=01-
Aug-2020 ADDRESS=222E South City and CITY= Kolkata.
Ans. INSERT INTO EMPLOYEE values(1201,”Amit”,”Singh”,”2020-08-01”,” 222E South
City”,”Kolkata”)
(d) Abhinay want to remove the table EMPLOYEE from the database db. Which command will
he use.
Ans. Drop table employee;
35. Ratnesh of class 12 is writing a program to create a CSV file “student.csv” which will contain 4
Name, Date of Birth and place. He has written the following code. As a programmer, help him
to successfully execute the given task.
import _______ #Line 1
with open('E:/student.csv',________) as f: #Line 2
w = csv. _______(f) #Line 3
ans= 'y'
while (ans== 'y'):
name= input("Name?: ")
date = input("Date of birth: ")
place = input("Place: ")
w.writerow([name, date, place])
ans=input("Do you want to enter more y/n?: ")
F=open("E:/student.csv", 'r')
reader = csv.________(F) #Line 4
for row in reader:
print(row)
F._______( ) #Line 5
(a) Name the module he should import in Line 1.
Ans. CSV
(b) In which mode, Ratnesh should open the file to add data into the file.
Ans. a or a+
(c) Fill in the blank in Line 3 to write the data to the csv file.
Ans. writer
(d) Fill in the blank in Line 4 to read the data from a csv file.
Ans. reader
Class: XII Session: 2022-23
Computer Science (083)
Sample Question Paper (Theory)
----------------------------------------------------------------------------------------------------------------------------------------------
-----
SECTION A
1 In a Python program, a control structure: 1
(A) Defines program-specific data structre
(B) Directs the order of Execution of statements in the program
(C) Dictates what happens before the program starts and after it terminates
(D) None of above
2 Find the invalid Identifier from the following: 1
(A) Myname
(B) 1Myname
(C) My_name
(D) Myname2
3 Which of the following is invalid method for fetching the records from database 1
within Python ?
(A) fetchone()
(B) fetchmany()
(C) fetchall()
(D) fetchmulti()
13 which of the following is the correct output for executing the following python 1
statement?
print(5 + 3**2 / 2)
(A) 32 (B) 8.0 (C) 9.5 (D) 32.0
1
14 Which topology is based on a central node which acts as a hub ?
(A) Bus topology (B) Star topology
(C) Tree topology (D) Hybrid Topology
1
15 To establish a connection between Python and SQL database, what of the
following statement is connecting database server?
(A) importMySQLdb
(B) MySQLdb.connect
(C) db.cursor
(D) None of the above
16 _______function place the pointer at the specified position of the file pointer by 1
in an opening file.
(A) 10#40#70#
(B) 30#40#50#
(C) 50#60#70#
(D) 40#50#70#
20 (a) Write the full form of the following 2
i) ARPANET ii) WiMax
table : games
gameno gname
10 Football
11 Lawn Tennis
b) write the output of queries i) to iv) based on the table, LOANS given below:
Table : LOANS
27 Write a user – defined function countH() in Python that displays the number of 3
. 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”
28 Write the output of the SQL queries i) to iv) based on the relations SHOP and 2+1
. ACCESSORIES given below:
Table: SHOP
Id SName Area
S01 ABC Computronics CP
S02 All Infotech Media GK II
S03 Tech Shopee CP
S04 Geek Tenco Soft Nehru Place
S05 Hitech Tech Store Nehru Place
Table : ACCESSORIES
No Name Price Id
A01 Motherboard 12000 S01
A02 Hard Disk 5000 S01
A03 Keyboard 500 S02
A04 Mouse 300 S01
A05 Motherboard 13000 S02
A06 Keyboard 400 S03
A07 LCD 6000 S04
T08 LCD 5500 S05
T09 Mouse 350 S05
T010 Hard Disk 450 S03
Expected Result:[2,4,6,8]
OR
Write a function in Python MakePush(Package) and MakePop(Package) to add a
new Package and delete a Package from a List of package description,
considering them to act as puch and pop operations of the Stack data structure.
SECTION D
31 “Vidya for All” is an educational NGO. It is setting up its new campus at Jaipur 5
. for its web-based activities. The campus has four building as shown in diagram
below:
Main Resource
Building Building
Training Accounts
Building Building
Main Building 15
Resource Building 25
Training Building 250
Accounts Building 10
b.) study the database ‘company’ that has a table ‘Emp’ that stores IDs of
employees. Code contain the connectivity to retrieve data, one record at a time,
for employees with IDs less than 10.
Write the missing statements
i)Statement1 .
ii)Statement2
iii)Statement3
OR
a)Predict the output of the following code given below:
def fun(s):
k=len(s)
m=” “
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower( )
elif s[i].isalpha( ):
m=m+s[i].upper( )
else:
m = m + ‘bb’
print(m)
fun(‘school2@com’)
b)Consider the following code which is doing following ,
updating the records of employees by increasing the salary by Rs.1000 of all
those employees who are getting less than Rs. 80000.
Write the following missing statements:
i)statement1
ii)statement2
iii)statement3
try:
cursor._______________ #statement3
bd1.commit( )
except:
db1.rollback( )
bd1.close( )
33 Write a user defined function to perform read and write operations onto a 5
. ‘student.csv’ file having fields roll number, name, stream and marks.
Or
Based on the above STOR Table and data in it answer the following questions:
35 Vishal has been given following incomplete code which takes a students details 1+1+1+
. (rollnumber, name and marks) and writes into binary file stu.dat using pickling. 1
Print(Rstu)
if Rstu[“Marks”] >= 85:
print(“Eligible for merit certificate”)
else:
print(“Not Eligible for merit certificate”)
Class: XII Session: 2022-23
Computer Science (083)
Sample Question Paper (Theory)
----------------------------------------------------------------------------------------------------------------------------------------------
SECTION A
1 In a Python program, a control structure: 1marks
(E) Defines program-specific data structre each
(F) Directs the order of Execution of statements in the program
(G) Dictates what happens before the program starts and after it terminates
(H) None of above
ANS : B
2 Find the invalid Identifier from the following: 1marks
(E) Myname each
(F) 1Myname
(G) My_name
(H) Myname2
ANS : B
3 Which of the following is invalid method for fetching the records from 1marks
database within Python ? each
(E) fetchone()
(F) fetchmany()
(G) fetchall()
(H) fetchmulti()
ANS : D
4 What is the default EOL Character in python ? 1marks
(B) \n (B) \t (C) \l (D) \h each
ANS : A
5 This method is used to load (unpickling) data from binary file 1marks
(B) load() (B) dump() (C) seek() (D) tell() each
ANS : A
ANS : C
11 State true or false 1marks
“ Immutable data type are those that can never change their values “ each
ANS TRUE
12 Which of the following statement(s) would give an error after executing the 1marks
following code? each
x=50 # Statement 1
Def func(x) # Statement 2
x=2 # Statement 3
func(x) # Statement 4
print(x) # Statement 5
ANS : D
13 which of the following is the correct output for executing the following 1marks
python statement? each
print(5 + 3**2 / 2)
(B) 32 (B) 8.0 (C) 9.5 (D) 32.0
ANS : C
1marks
14 Which topology is based on a central node which acts as a hub ? each
(B) Bus topology (B) Star topology
(C) Tree topology (D) Hybrid Topology
ANS : B
1marks
15 To establish a connection between Python and SQL database, what of the each
following statement is connecting database server?
(E) importMySQLdb
(F) MySQLdb.connect
(G) db.cursor
(H) None of the above
ANS : B
16 _______function place the pointer at the specified position of the file pointer 1marks
by in an opening file. each
18 Assertion (A): CSV (Comma Separated Values) is a file format for data 1marks
storage each
which looks like a text file.
Reason (R): The information is organized with one record on each line and
each
field is separated by comma.
ANS : (A) Both A and R are true and R is the correct explanation for A
SECTION B
19 What possible outputs(s) are expected to be displayed on screen at the time of 1marks
execution of the program from the following code? Also specify the for each
maximum values that can be assigned to each of the variables Lower and correct
Upper. answer
import random
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="#")
(A) 10#40#70#
(B) 30#40#50#
(C) 50#60#70#
(D) 40#50#70#
ans : (B)
Maximum value that assigned to Lower and Upper is 3 and 4 respectively
Ans :
300 @ 200
300 # 100
150 @ 100
300 @ 150
22 Rewrite the following code in Python after removing all syntax error(s). 2
Underline each correction done in the code.
30= Value ½ marks
for VAL in range(0,Value) for each
If val%4=0: correct
print (VAL*4) row
Else val%5==0:
print (VAL+3)
Ans :
Value=30
for VAL in range(0,Value) :
if val%4 = = 0:
print (VAL*4)
else val%5==0:
print (VAL+3)
Ans: (a) @@2202 puC’W 02T ## 1 marks for each correct row
(b) Ans: dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])
Name gname
Rohan Football
Rohan Lawn Tennis
Jaya Football
Jaya Lawn Tennis
Teena Football
Teena Lawn Tennis
B. i) 1200000
ii) 4500
iii) 2
iv) All given table data will display.
27 def countH( ):
f = open(“Para.txt”, “r”)
lines = 0
l = f.readlines( )
for i in l:
if[0] ==’H’:
lines+=1
print(“No of lines are”, lines)
f.close( )
or
def countmy( ):
f = open(“DATA.txt”, “r”)
count= 0
x = f.read( )
word = x.split( )
for i in word:
if( i== “my”)
count = count + 1
print(“my occurs”, count, “Times”)
f.close( )
28. a) i) Name
Motherboard
Hard Disk
LCD
ii) Area Count
CP 2
GK II 1
Nehru Place 2
iii) Count(Distinct Area)
3
iv) Name Price
Motherboard 12000
Motherboard 13000
def Display(stk):
if isEmpty(stk):
print(“Stack Empty”)
else:
top = len(stk) – 1
print(stk[top],”top”]
for a in range (top -1, -l,-1):
print(stk[a])
or
def MakePush(Package):
a = int(input(“Enter package title:”))
Package.append(a)
def MakePop(Package):
if (Package===[]):
print(“Stack Empty”)
else:
print(“Deleted element:”, Package.pop( ))
SECTION D
31 i) Bus Topology
Resource
Main
Building Building
Training Accounts
Building Building
b) i)mycon
ii)db.cursor()
iii)db.close()
or
a) SCHOOLbbbbCOM
b) i)statement1 – import mysql.connector
ii) cursor = db.cursor() #statement2
iii) cursor.execute(sql) #statement3
def writecsv():
with open(“student.csv”, ‘w’, newline=’’) as fobj;
csv_w=csv.writer(fobj), deliniter=’,’)
csv_w.writerow(row)
or
difference between text and csv file (1marks)
def addCsvFile(Username, Password):
f= open(‘user.csv’,’a’)
newFileWriter=csv.writer(f)
newFileWriter.writerow([username,password])
f.close( )
def readCvsFile():
with open(‘user.csv’,’r’) as newFile:
for row in newFileReader:
print(row[0],row[1])
newFile.close( )
SECTION E
34. a. primary key – ItemNo
b. Degree – 4, Cardinality – 6
c. i) insert into STORE values(2010,”Note Book”,25,50);
ii)update store set quantity = quantity + 10;
or
c. i) delete * from STORE WHERE ItemNo=2005;
ii) alter table STORE add(price float(5));