SlideShare a Scribd company logo
1
KENDRIYA VIDYALAYA SANGATHAN
CHENNAI REGION
Session 2022-23
Class XII
Computer Science (083)
Based on Latest CBSE Exam Pattern
2
KENDRIYA VIDYALAYA SANGATHAN
CHENNAI REGION
OUR PATRONS
Smt. T RUKMANI
Offg. DEPUTY COMMISIONER
KVS RO CHENNAI
Sh. P.I.T. RAJA
ASSISTANT COMMISSIONER
KVS RO CHENNAI
3
MEMBERS AND DETAILS OF TOPICS ALLOTTED
Name of the co-ordinator – Smt. Sangeetha S, KV Sulur
S.No. Name of the
Teacher
Name of the
KV
Name of the Chapter
allotted
1 Sh. Renju Leopold KV Aruvankadu
Python Revision Tour,
Functions and Text File
Handling
2 Smt. R Srikeerthy KV HVF
Binary files, CSV and
Data Structures
3
Sh. Prem Kumar
Singh
KV DGQA Computer Networks
4 Smt. Merina Paul NO.2 Madurai Database Management
5 Smt. Meera G KV Gill Nagar
Interfacing Python with
MySQL
With support of other contractual PGT CS of different KVs of Chennai
Region
COURSE DIRECTOR
Sh. N. RAKHESH
PRINCIPAL
KV VIJAYANARAYANAM, CHENNAI
4
INDEX
Sl.No Contents Page
No.
1 Curriculum 2022-23 5
2 CBSE Sample Question Paper 9
4 Revision of Python topics covered in Class XI 23
5 Functions 45
6 File handling -Introduction and Text file 69
7 Binay files 82
8 CSV files 100
9 Data structures - Stacks 118
10 Computer Networks 127
11 Database Management 144
12 Interface Python with MySQL 166
13 Sample Papers 189
5
CURRICULUM
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Unit-I Computational Thinking and Programming – 2
Revision of Python topics covered in class XI
PYTHON BASICS
Python is a simple, general purpose, high level, and object-oriented programming
language.Python is an interpreted scripting language also. Guido Van Rossum is the founder of
Python programming language.Guido was a fan of the popular BBC comedy show of that time,
"Monty Python's Flying Circus". So he decided to pick the name Python for his newly created
programming language.
Features of Python
• Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple
and easy to learn and provides lots of high-level data structures.
• Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an ideal language
for scripting and rapid application development.
• Python supports multiple programming pattern, including object-oriented, imperative, and
functional or procedural programming styles.
• Python is not intended to work in a particular area, such as web programming. That is why
it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.
• We don't need to use data types to declare variable because it is dynamically typed so we
can write a=10 to assign an integer value in an integer variable.
• Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.
Applications of Python Programming Language
• Data Science
• Date Mining
• Desktop Applications
• Console-based Applications
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Enterprise Applications
• 3D CAD Applications
• Machine Learning
24
• Computer Vision or Image Processing Applications.
• Speech Recognitions
How To Use Python?
Python can be downloaded from www.python.org. (Standard Installation)
It is available in two versions-
• Python 2.x
• Python 3.x (It is in Syllabus)
Apart from above standard Python. We have various Python IDEs and Code Editors. Some of them
are as under:
(i) Anaconda Distribution: free and open-source distribution of the Python, having various inbuilt
libraries and tools like Jupyter Notebook, Spyder etc
(ii) PyCharm (iii) Canopy (iv) Thonny (v) Visual Studio Code (vi) Eclipse + PyDev
(vii) Sublime Text (viii) Atom (ix) GNU Emacs (x) Vim (xi) Spyder and many
more . .
Python Interpreter - Interactive And Script Mode:
We can work in Python in Two Ways:
(i) Interactive Mode: It works like a command interpreter as shell prompt works in DOS Prompt or
Linux. On each (>>>) symbol we can execute one by one command.
(ii) Script Mode: It used to execute the multiple instruction (complete program) at once.
Python Character Set:
Character Set is a group of letters or signs which are specific to a language. Character set includes
letter, sign, number and symbol.
• Letters: A-Z, a-z
• Digits: 0-9
• Special Symbols: _, +, -, *, /, (, #,@, {, } etc.
• White Spaces: blank space, tab, carriage return, newline, form feed etc.
• Other characters: Python can process all characters of ASCII and UNICODE.
Tokens
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens.It is also known as Lexical Unit.
Types of token are
• Keywords
• Identifiers (Names)
• Literals
• Operators
• Punctuators
25
Keywords
Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions.Python contains thirty-five keywords in the version, Python 3.9.
Identifiers
In programming languages, identifiers are names used to identify 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 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 reserved word.
• We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Legal Identifier Names Example:
Myvar my_var _my_var myVar myvar2
Illegal Identifier Names Example:-
2myvar my-var my var= 9salary
Literals or Values:
Literals are the fixed values or data items used in a source code. Python supports different types
of literals such as:
a. String literals - “Rishaan”
b. Numeric literals – 10, 13.5, 3+5i
c. Boolean literals – True or False
d. Special Literal None
e. Literal collections
Literal collections
Literals collections in python includes list, tuple, dictionary, and sets.
• List: It is a list of elements represented in square brackets with commas in between. These
variables can be of any data type and can be changed as well.
• Tuple: It is also a list of comma-separated elements or values in round brackets. The values
can be of any data type but can’t be changed.
• Dictionary: It is the unordered set of key-value pairs.
• Set: It is the unordered collection of elements in curly braces ‘{}’.
Operators
An operator is used to perform specific mathematical or logical operation on values. The values
that the operator works on are called operands.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
26
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic operators: used with numeric values to perform common mathematical operations.
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Assignment operators: used to assign values to variables
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Comparison Operators: Comparison operators are used to compare two values.
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Logical Operators: Logical operators are used to combine conditional statements
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Identity Operators: used to compare the objects, not if they are equal, but if they are actually the
27
same object, with the same memory location.
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
Membership operators: used to test if a sequence is present in an object.
in Returns True if a sequence with the specified x in y
value is present in the object
not in Returns True if a sequence with the specified x not in y
value is not present in the object
Punctuators
Punctuators are symbols that are used in programming languages to organize sentence
structure, and indicate the rhythm and emphasis of expressions, statements, and program
structure. Common punctuators are: „ “ # $ @ []{}=:;(),
Python Variables
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you
can store integers, decimals or characters in these variables.
• Variables are containers for storing data values.
• Unlike other programming languages, Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
Example:
x = 5
y = "John"
print(x)
print(y)
• Variables do not need to be declared with any particular type and can even change type
after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
• String variables can be declared either by using single or double quotes:
x = "John"
# is the same as
x = 'John'
Output Variable:
The Python print statement is often used to output variables. To combine both text and a variable,
Python uses the, character:
x = "awesome"
28
print("Python is " , x)
Display Multiple variable:-
x = "awesome“
y=56
print(“Value of x and y is=" , x, y)
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables. Also Python allows you to assign a single value to several variables
simultaneously.
The operand to the left of the = operator is the name of the variable and the operand to the right of the
= operator is the value stored in the variable
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)
a = b = c = 1
a,b,c = 1,2,"john"
Data Types
The data stored in memory can be of many types, i.e., Every value belongs to a specific data type
in Python. Data type identifies the type of data which a variable can hold and the operations that
can be performed on those data.Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
The different standard data types −
• Numbers
29
• String
• List
• Tuple
• Dictionary
• Boolean
• Set
Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −
var1 = 1
var2 = 10
Python supports four different numerical types
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e -36j
080 0xDEFABCECBDAE 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
You can also delete the reference to a number object by using the del statement. The syntax of
the del statement is −
del var1[,var2[,var3[....,varN]]]]
e.g. del var
del var_a, var_b
Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ).
str = 'Hello World!'
print str # Prints complete string Hello World!
print str[0] # Prints first character of the string H
30
print str[2:5] # Prints characters starting from 3rd to 5th
llo
print str[2:] # Prints string starting from 3rd character llo World!
print str * 2 # Prints string two times Hello World!Hello World!
print str + "TEST" # Prints concatenated string Hello World!TEST
Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]).
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at
0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list ['abcd', 786, 2.23, 'john', 70.2]
print list[0] # Prints first element of the list- abcd
print list[1:3] # Prints elements starting from 2nd till 3rd
- [786, 2.23]
print list[2:] # Prints elements starting from 3rd element -[2.23, 'john', 70.2]
print tinylist * 2 # Prints list two times-[123, 'john', 123, 'john']
print list + tinylist # Prints concatenated lists-['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Lists are enclosed in brackets ( [ ] ) and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints the complete tuple--('abcd', 786, 2.23, 'john', 70.2)
print tuple[0] # Prints first element of the tuple-- abcd
print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd
--(786, 2.23)
print tuple[2:] # Prints elements of the tuple starting from 3rd element--(2.23, 'john', 70.2)
print tinytuple * 2 # Prints the contents of the tuple twice--(123, 'john', 123, 'john')
print tuple + tinytuple # Prints concatenated tuples-- ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Dictionary
Python's dictionaries are kind of hash table type. They consist of key-value pairs. A dictionary key
can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can
be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example −
dict = {}
31
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key This is one
print dict[2] # Prints value for 2 key This is two
print tinydict # Prints complete dictionary {'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys ['dept', 'code', 'name']
print tinydict.values() # Prints all the values ['sales', 6734, 'john']
Boolean
Boolean represent one of two values: True or False. When you compare two values, the expression
is evaluated and Python returns the Boolean answer.Also, almost any value is evaluated to True if
it has some sort of content.
print(10 > 9) True
print(10 == 9) False
print(10 < 9) False
bool("abc") True
bool(123) True
bool(["apple", "cherry"])True
bool(False) False
bool(None) False
bool(0) False
bool("") False
bool(()) False
bool([]) False
bool({}) False
Mutable and Immutable Objects in Python
Everything in Python is an object. So, every variable holds an object instance. All objects in Python
can be either mutable or immutable. When an object is initiated, it is assigned a unique object id.
Its type is defined at runtime and once set can never change, however its state can be changed if it
is mutable. Generally, a mutable object can be changed after it is created, and an immutable object
can’t.
Mutable objects
Mutability means the ability to modify or edit a value. Mutable objects in Python enable the
programmers to have objects that can change their values. They generally are utilized to store
a collection of data. It can be regarded as something that has mutated, and the internal state applicable
within an object has changed.
32
In mutable data types, we can modify the already existing values of the data types (such as lists,
dictionaries, etc.). Or, we may add new values or remove the existing values from our data types.
Basically, we may perform any operation with our data without having to create a new copy of our
data type. Hence, the value assigned to any variable can be changed.
e.g.color = ["red", "blue", "green"]
print(color)
color[0] = "pink"
color[-1] = "orange"
print(color)
Output:
['red', 'blue', 'green']
['pink', 'blue', 'orange']
Immutable Objects
Immutable objects in Python are objects wherein the instances do not change over the period.
Immutable instances of a specific type, once created, do not change, and this can be verified using
the id method of Python
e.g.message = "Welcome to GeeksforGeeks"
message[0] = 'p'
print(message)
Output
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment
❖ Exception: However, there is an exception in immutability as well.Tuple in python is
immutable. But the tuple consists of a sequence of names with unchangeable bindings to
objects.
33
Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the
contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable.
Expression in python:
A combination of constants, operands and operators is called an expression. The expression in
Python produces some value or result after being interpreted by the Python interpreter. The
expression in Python can be considered as a logical line of code that is evaluated to obtain some
result. If there are various operators in an expression then the operators are resolved based on their
precedence.
E.g. Expression 6-3*2+7-1 evaluated as 6
Types of Expression in Python
Constant Expressions x = 10 + 15
Arithmetic Expressions y=x**3+x-2+5/2
Integral Expressions x=10 y=5.00 result = x + int(y)
Floating Expressions result = float(x) + y
Relational Expressions 10+15>20
Logical Expressions r=x and y
Combinational Expressions result = x + (y << 1)
Type Casting in Python
Type Casting is the method to convert the variable data type into a certain data type in order to the
operation required to be performed by users.
There can be two types of Type Casting in Python –
• Implicit Type Casting
• Explicit Type Casting
Implicit Type Conversion
In this, methods, Python converts data type into another data type automatically, where users don’t
have to involve.
34
# Python automatically converts
# a to int
a = 7
print(type(a))
# Python automatically converts
# b to float
b = 3.0
print(type(b))
# Python automatically converts
# c to float as it is a float addition
c = a + b
print(c)
print(type(c))
# Python automatically converts
# d to float as it is a float multiplication
d = a * b
print(d)
print(type(d))
Explicit Type Casting
In this method, Python need user involvement to convert the variable data type into certain data type
in order to the operation required.Mainly in type casting can be done with these data type function:
int() : int() function take float or string as an argument and return int type object.
float() : float() function take int or string as an argument and return float type object.
str() : str() function take float or int as an argument and return string type object.
E,g, # int variable
a = 5
# typecast to float
n = float(a)
print(n)
print(type(n))
Precedence and Associativity of Operators
Operator Precedence: This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
35
Operator Associativity: If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.
Comments in python:
Comments are non-executable statements of python. It increases the readability and understandability
of code.
Types of comment:
i. Single line comment (#) – comments only single line.
e.g. a=7 # 7 is assigned to variable ‘a’
print(a) # displaying the value stored in ‘a’
ii. Multi-line comment (‘‘‘………..’’’) – Comments multiple line.
e.g. ‘‘‘Program -1
A program in python to store a value invariable ‘a’ and display the value stored in it.’’’
a=7
print(a)
Python Input and Output
Python executes code top to bottom, when written in the correct syntax.Once the interpreter is running
you can start typing in commands to get the result.
Input using the input( ) function
input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <type ‘str’>. It does not evaluate the expression it just returns the
complete statement as String. Python provides a built-in function called input which takes the input
from the user. When the input function is called it stops the program and waits for the user’s input.
When the user presses enter, the program resumes and returns what the user typed.
name = input('What is your name?n')
What is your name?
Ram
Taking multiple inputs from user
36
Using split() method
Using List comprehension
split() method :
This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided then any white space is a separator. Generally, users use a
split() method to split a Python string but one can use it in taking multiple inputs.
input().split(separator, maxsplit)
List comprehension is an elegant way to define and create list in Python. We can create lists just like
mathematical statements in one line only. It is also used in getting multiple inputs from a user.
x, y, z = [int(x) for x in input("Enter three values: ").split()]
Output using print() function
print() : function prints the message on the screen or any other standard output device.
print(value(s), sep= ' ', end = 'n', file=file, flush=flush)
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Debugging:-
Debugging is a process of locating and removing errors from program.
Errors in a program
An error or exception refers to an interruption in the execution of code due to which we cannot attain
the expected outcome to the end-users. These errors are classified on the basis of the event when the
program generate the error. The two types of errors are Compile Time Errors and Runtime Errors
and Logical errors
Compile Time Errors
These errors occur when we violate the rules present in a syntax. The compile-time error indicates
something that we need to fix before compiling the code. A compiler can easily detect these errors.
Eg Syntax error and Semantic Error.
Logic errors
These errors are not always easy to recognize immediately. This is due to the fact that such errors,
unlike that of syntax errors, are valid when considered in the language, but do not produce the
intended behavior. These can occur in both interpreted and compiled languages. It may occur due to
the logic of the program.
37
Runtime Errors
These errors occur during the run-time program execution after a successful compilation. Division
error is one of the most common errors (runtime). It occurs due to the division by zero. It is very
difficult for a compiler to find out a runtime error because it cannot point out the exact line at which
this particular error occurs.
---------------------------------------------------------------------------------------------------------------------
Control flow statements
The control flow of a Python program is regulated by conditional statements, loops, and function
calls. In order to control the flow of execution of a program there are three categories of statements
in python. They are:
1. Selection statements
2. Iteration statements
3. Jump statements / Transfer statements
Selection Statements
Decision making is valuable when something we want to do depends on some user input or some
other value that is not known when we write our program. This is quite often the case and Python,
along with all interesting programming languages, has the ability to compare values and then take
one action or another depending on that outcome.
Python have following types of selection statements
1. if statement
2. if else statement
3. Ladder if else statement (if-elif-else)
4. Nested if statement
if statements
This construct of python program consist of one if condition with one block of statements. When
condition becomes true then executes the block.
Syntax:
38
if ( condition):
Statement(s)
Example:
age=int(input(“Enter Age: “))
if ( age>=18):
print(“You are eligible for vote”)
if(age<0):
print(“You entered Negative Number”)
if - else statements
This construct of python program consist of one if condition with two blocks. When condition
becomes true then executes the block given below
Syntax:
if ( condition):
Statement(s)
else:
Statement(s)
Example
x = int(input("Please enter an integer: "))
y = int(input("Please enter another integer: "))
i f x > y:
print(x,"is greater than",y)
e l s e :
print(y,"is greater than or equal to",x)
Ladder if else statements (if-elif-else)
The Python compound statement if, which uses if, elif, and else clauses, lets you conditionally
execute blocks of statements. Here’s the syntax for the if statement:
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
Example
i = 20
if (i == 10):
39
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Nested-if
Nested if statements mean an if statement inside another if statement.
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example
num=int(input(“Enter Number: “))
if ( num<=0):
if ( num<0):
print(“You entered Negative number”)
else:
print(“You entered Zero ”)
else:
print(“You entered Positive number”)
Python Iteration Statements
The iteration (Looping) constructs mean to execute the block of statements again and again
depending upon the result of condition. This repetition of statements continues till condition meets
True result. As soon as condition meets false result, the iteration stops.
Python supports following types of iteration statements
1. while
2. for
Four Essential parts of Looping:
i. Initialization of control variable
ii. Condition testing with control variable
iii. Body of loop Construct
iv. Increment / decrement in control variable
40
for loop
For loops are useful when you need to do something for every element of a sequence
<statements before for loop>
for <variable> in <sequence>:
<body of for loop>
<statements after for loop>
Example
s = input("Please type some characters and press enter:")
for c in s:
print(c)
print("Done")
while Loop
Python's while statement is its most general iteration construct. In simple terms, it repeatedly
executes a block of indented statements, as long as a test at the top keeps evaluating to a true value.
When the test becomes false, control continues after all the statements in the while, and the body
never runs if the test is false to begin with.
while <test>: # loop test
<statements1> # loop body
else: # optional else
<statements2> # run if didn't exit loop with b
Example
count = 0
while (count < 9):
print ('The count is:', count )
count = count + 1
print ("Good bye!" )
Python supports to have an else statement associated with a loop statement. If the else statement is
used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If
the else statement is used with a while loop, the else statement is executed when the condition
becomes false
Example:
count = 0
while count < 5:
print (count, " is less than 5" )
count = count + 1
else:
print( count, " is not less than 5”)
Single Statement Suites: If there is only one executable statement in while loop, then we can use this
41
format.
Example:
flag = 1
while (flag): print ('Given flag is really true!' )
print( "Good bye!" )
Jump Statements
Now that we‘ve seen a few Python loops in action, it‘s time to take a look at two simple statements that
have a purpose only when nested inside loops—the break and continue statements.
In Python:
pass
Does nothing at all: it‘s an empty statement placeholder
break
Jumps out of the closest enclosing loop (past the entire loop statement)
continue
Jumps to the top of the closest enclosing loop (to the loop‘s header line)
---------------------------------------------------------------------------------------------------------------------
Python range( ) Function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
Syntax:
range( start value, stop value, step value )
Where all 3 parameters are of integer type
● Start value is Lower Limit
● Stop value is Upper Limit
● Step value is Increment / Decrement
Note: The Lower Limit is included but Upper Limit is not included in result.
Example
range(5) => sequence of 0,1,2,3,4
range(2,5) => sequence of 2,3,4
range(1,10,2) => sequence of 1,3,5,7,9
range(5,0,-1) => sequence of 5,4,3,2,1
range(0,-5) => sequence of [ ] blank list
(default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
42
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0
43
WORK SHEET
LEVEL-1
Q.No
Questions
Marks
1
Which of the following is not a Tuple in Python ?
(a) (1,2,3) (b) (‘one’,two’,’three’) (c) (10,) (d) (‘one’)
Ans: (‘one’)
(1)
2
What will be output of the following code snippet:
A=[1.2.3.4,5]
print(a[3:0:-1])
Ans : [4,3,2]
(1)
3
Write the output of the code given below:
my_dict = {"name": "Kuhan",'Door No.': 100}
my_dict["Door No."] = 128
my_dict['address'] = "Karnataka"
print(my_dict.items())
Ans: dict_items([('name', 'Kuhan'), ('Door No.', 128), ('address', 'Karnataka')])
(2)
4
Find and write the output of the following python code:
Msg="CompuTer"
Msg1=''
for i in range(0, len(Msg)):
if Msg[i].isupper():
Msg1=Msg1+Msg[i].lower()
elif i%2==0:
Msg1=Msg1+'*'
else:
Msg1=Msg1+Msg[i].upper()
print(Msg1)
Ans: cO*P*t*R
(4)
44
LEVEL-2
1 D={“AMIT”:90,”RESHMA”:96,”SUMAN”:92}
Print(“SUMAN” in D, 90 in D, sep=”#”)
(a) True#False (b) True#True (c) False#True (d) False#False
Ans : (a) True#False
(1)
2 Find and write the output of the following python code:
x = "Welcome"
i = "e"
while i in x:
print(i, end = "$")
Ans :e$e$e$e$e$......
(1)
3. What is the output of the following Python statement : print(5+3**2/2)
Ans : 9.5
(1)
4. The return type of the input() function is Ans:String (1)
5. Consider the given expression :
not True and True or False
Ans : False
(1)
6. Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-3])
Ans: @2 ina B@
(2)
7. What will be the output if entered number n is 1 and n is 4 :
i=2
n=int(input("enter the value of n"))
while i<n:
if n % i==0:
break
print(i)
i=i+1
(3)
45
else:
print("done")
Ans : n=1 ------ done
n=4 ------- no output
8. What is the output of the following code snippet?
def ChangeVal(M,N):
for i in range(N):
if M[i]%5 == 0:
M[i]//=5
if M[i]%3 == 0:
M[i]//=3
L = [25,8,75,12]
ChangeVal(L,4)
for i in L:
print(i,end="#")
Ans : 5#8#5#4#
(4)
LEVEL-3
1 State True or False:
The # symbol used for inserting comments in python is a token
Ans : True
(1)
2 Which of the following invalid identifier in Python?
(a) name (b) section (c) true (d) break
Ans: (d) break
(1)
3 Evaluate the following expressions :
a) 8 // 4 + 18 * 6 / 3– 3
(2)
46
b) 35/5 or 5.0 + 30/10
Ans: a) 35.0
b)7.0
4 Concatenation operator in list is :
(a) * (b) , (c) + (d) =
Ans : +
(1)
5
Find error in the following code(if any) and correct code by rewriting code and underline
the correction;‐
x= int(input(“Enter value of x:”) )
for I in range [0,10]:
if x=y:
print( x + y)
else:
print( x‐y)
(2)
WORKING WITH FUNCTIONS
Function Definition:
A function is a programming block of codes which is used to perform a single, related,
specific task. It only works when it is called. We can pass data, known as parameters, into a function.
A function can return data as a result.
Python treats functions like a first-class member. It implies that in Python, functions and other
objects are of same significance.Functions can be assigned to variables, stored in collections, or
passed as arguments. This brings additional flexibility to the language.
Advantages of Functions
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding
Python function types
There are three categories of functions:
• Built-in functions
47
• Function defined in modules
• User defined functions.
Built-in functions
The functions whose functionality is predefined in Python are referred to as built-in functions.
The python interpreter has several such functions that are always available for use.
E.g. len(), type(), int(), input()
Function defined in modules
These functions are pre-defined in particular modules and can only be used after the specific
module is imported.
E.g. All mathematical functions are defined in the module math.
User-defined functions
Python User Defined Functions allow users to write unique logic that the user defines. It is
the most important feature in Python that consists of custom-defined logics with a set of rules and
regulations that can be passed over the data frame and used for specific purposes.
Structure of functions in Python
Internally Python names the segment with top-level statements (no indentation) as
_main_ Python begins execution of a program from top-level statements.
Defining a Function
A function in Python is defined as given below:
def< function name >(parameters):
[“ ” ”<function’s docstring>” “ “]
<statements>
[<statements>]
……………………..
48
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the function does.
• One or more valid python statements that make up the function body. Statements must have
the same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.
Function header:
The Header of a function specifies the name of the function and the name of each
of its parameters. It begins with the keyword def.
Parameters:
Variables that are listed within the parenthesis of a function header.
Function Body:
The block of statements to be carried out, ie the action performed by the function.
Indentation:
The blank space needed for the python statements. (four spaces convention)
Flow of execution in a function call
The flow refers to the order in which statements are executed during a program run. The
function body is a block of statements and python executes every block in an execution frame.
An execution frame contains:
• Some internal information (used for debugging)
• Name of the function
• Values passed to the function
• Variables created within the function
49
• Information about the next instruction to be executed
Whenever a function call statement is encountered, an execution frame for the function is created
and the control is transferred to it. The statements are then executed and if there is return
statement in the program, it will be executed and returns to the function call statement block.
def message():
print('Hello I am learning how to create function in python.')
def sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))
# main program
# calling the function message()
message()
# calling the function sum()
sum(10,20)
In the above program, two functions message() and sum() is declared. The message() function
does not accept any argument but displays a text on the screen whenever we call it. On the other
hand, the sum() function accept two arguments and display their sum on the screen. when the main
program calls the function message(), the program flow goes to the body of the function message()
and execute its codes. After that, it returns to the main program and then calls the second function
sum() by sending it two arguments (10,20), the program flow goes to the body of the function sum(),
and execute its code and again returns to the main program. At last, the main programs end.
The function calling another function is called the caller and the functions being called
is the called function or callee.
Parameters and Arguments
The parameters are the variables that we can define in the function declaration. In fact, we
utilized these variables within the function. Also, the programming language in the function
description determines the data type specification. These variables facilitate the function’s entire
execution. In addition, they are known as local variables because they are only available within the
function.
The arguments are the variables given to the function for execution. Besides, the local
variables of the function take the values of the arguments and therefore can process these parameters
for the final output.
50
Passing parameters:-
Python support three types of formal arguments/parameters:
1. Positional argument (required arguments):-
When the functions call statement must match the number and order of arguments as define
in the functions definition this is called the positional arguments.
Example:-
def check(a,b,c):
:
Then possible functions call for this can be:-
check(x,y,z)#3values(allvariables)passed
check(2,x,y)#3values(literal+variables)passed
check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed.
Thus through such function calls-
• The argument must be provided for all parameters (required)
• The values of argument are matched with parameters, position(order)wise(positional)
2. Default arguments:-
A parameter having defined value in the function header is known as a default parameter.
Example:-
def interest(principal,time,rate=10):
si=interest(5400,2) #third argument missing
So the parameter principal get value 5400,time get 2 and since the third argument rate is missing, so
default value 0.10 is used for rate.
• Default argument are useful in situations where some parameters always have same
value.
Some advantages of the default parameters are listed below:-
51
• They can be used to add new parameters to the existing functions.
• They can be used to combine similar function in to one.
3. Keyword(or named)arguments:-
Keyword arguments are the named arguments with assigned values being passed in the function
call statement.
Example:-
def interest(prin,time,rate):
return prin * time * rate
print (interest ( prin = 2000 , time = 2 , rate 0.10 ))
print (interest ( time = 4 , prin = 2600 , rate = 0.09 ))
print(interest(time=2,rate=0.12,prin=2000))
All the above functions call are valid now, even if the order of arguments does not match.
4. Using multiple argument type together:-
Python allows you to combine multiple argument types in a function call.
Rules for combining all three types of arguments:-
• And argument list must first contain positional(required) arguments followed by any
keyword argument.
• Keyword arguments should be taken from the required arguments preferably.
• You cannot specify a value for an argument more than once.
Example:-
def interest(prin,cc,time=2,rate=0.09):
return prin * time * rate
Types of user defined function
1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return
1. No Argument No return
def Add():
a= int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
print (“The Sum of inputted Numbers is:”, c)
Add()
print(“ Executed”)
2. With Argument No return
def Add(a,b):
c=a+b
52
print(“The Sum of inputted Numbers is:”, c)
num1=int (input(“Enter First Number”))
num2= int (input(“Enter Second Number”))
add(num1,num2)
Remember: The variable in main program are differ from the variable in function definition i.e. a
and b should be x and y. In this scenario the variable passed (num1,num2)will be called argument,
and when it replace with the variable defined in the function will be called as parameter.
3. No Argument with return
def Add():
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
x= add()
print (“The Sum of inputted Numbers is:”, x)
Note: { As return does not show the result we have to store the returned value on another
variable x}
4. With Argument with return
def Add (a,b):
c=a+b
return c
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
x= add(a,b)
print (“The Sum of inputted Numbers is:”, x)
Calling function and Called function:
• Function which is called by another Function is called Called Function. The called
function contains the definition of the function and formal parameters are associated
with them.
• The Function which calls another Function is called Calling Function and actual
Paramaters are associated with them.
• In python, a function must be defined before the function call otherwise
python interpreter gives an error.
Difference between Arguments and parameters
These two terms are very interchangeable, so it is not so important to know the difference.
The terms they refer to are almost identical. However, in order to sound more professional, correct
terminology is important.
Function Parameters: Variables that are in brackets when defining the function. When a method is
called, the arguments are the data passed to the method’s parameters.
53
Function arguments : Arguments are used to pass information from the rest of the program to the
function. This information return a result. There is no limit to the number of arguments that can be
written. Depending on the type of function you’re performing, there might even be no argument.
Use commas to separate the arguments in a function. Take into account the number of
arguments you put in a function call. The number of arguments must be exactly the same as the
number of parameters.
In the example below, the variable name is the input parameter, where as the value, “Arnav”, passed
in the function call is the argument.
def welcome(name):
print("Hello! " + name + " Good Morning!!")
welcome("Arnav")
Output:
Hello! Arnav Good Morning!!
Returning a Function
If you wish to return some values from the function to the rest of the program, you can use
the return statement. As the name suggests, it returns a value without printing it. Executing this
statement will cause the Python function to end immediately and store the value being returned into
a variable.
Scope of variables
Scope means in which part(s) of the program, a particular piece of code or data is accessible
or known.
In python there are broadly 2 kinds of Scopes:
• Global Scope
• Local Scope
Global Scope:
• A name declared in top level segment(_main_) of a program is said to have global scope
and can be used in entire program.
• Variable defined outside of the all functions are global variables.
Local Scope :
• A name declared in a function body is said to have local scope i.e. it can be used only
within this function and the other block inside the function.
• The formal parameters are also having local scope.
When dealing with Python functions, you should also consider the scope of the variables. The
code in a function is in its own little world, separate from the rest of the program. Any variable
declared in the function is ignored by the rest of the function. This means that two variables with the
same name can exist, one inside the function and the other outside the function. However, this is not
a good practice. All variable names must be unique regardless of their scope.
54
Local variable: A variable that is defined within a function and can only be used within that
particular function. With respect to the local variable, the area in a function is called “local area”.
Global variable: A variable that is defined in the main part of the programming and, unlike local
variables, can be accessed via local and global areas.
Example:
Lifetime of Variables:
Lifetime is the time for which a variable lives in memory. For global variables the lifetime is
entire program run i.e. as long as program is executing. For local variable, lifetime is their function’s
run i.e. as long as function is executing.
Name Resolution(Scope Resolution)
For every name used within program, python follows name resolution rules known as
LEGB rule.
• Local Environment : first check whether name is in local environment, if yes Python uses
its value otherwise moves to (ii)
• Enclosing Environment:if not in local,Python checks whether name is in Enclosing
Environment, if yes Python uses its value otherwise moves to (iii)
• Global Environment:if not in above scope Python checks it in Global environment, if
yes Python uses it otherwise moves to (iv)
• Built-In Environment:if not in above scope, Python checks it in built-in environment, if
yes, Python uses its value otherwise Python would report the error: name <variable>
notdefined.
WORKSHEET
LEVEL I
I. Questions (1 mark)
55
1. Which of the following is the use of function in python?
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned
2. What is the output of the below program?
def printMax(a, b):
if a > b:
print(a, ‘is maximum’)
elif a == b:
print(a, ‘is equal to’, b)
else:
print(b, ‘is maximum’)
printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned
3. What is the output of the below program?
x = 50
def func():
global x
print('x is', x)
x = 2
print('Changed global x to', x)
func()
print('Value of x is', x)
a) x is 50
Changed global x to 2
Value of x is 50
b) x is 50
Changed global x to 2
Value of x is 2
c) x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned
4. What is the output of the below program?
def C2F(c):
return c * 9/5 + 32
print (C2F(100))
print (C2F(0))
a) 212.0
32.0
56
b) 314.0
24.0
c) 567.0
98.0
d) None of the mentioned
5. The default value for a parameter is defined in function ………..
6. Python names the top level segment as…………..
7. Variable declared inside functions may have global scope (True/False)
8. Which arguments given below is skipped from function call?
a)Positional b)Default c)Keyword d)named
9. What is the order of resolving scope in Python?
a)BGEL b)LEGB c)GEBL d)LBEG
10.Complete the function body.
def f(num):
…………..
print (f(8))
a)return 0 b)print(num) c)print(“num”) d)return num
11. The function pow(x,y,z) is evaluated as:
a) (x**y)**z b) (x**y) / z c) (x**y) % z d) (x**y)*z
12. The function seed is a function which is present in the ……………..module
13. What are the outcomes of the functions shown below?
sum(2,4,6)
sum([1,2,3])
14. What is the output of the functions shown below?
min(max(False,-3,-4), 2,7)
a) 2 b) False c) -3 d)0
15. What is the output of the programgiven below?
a = 100
def func (a) :
a = 20
func (a)
print (' a is now ', a)
A. a is now 50
B. a is now 100
C. a is now 2
D. error
16. What will be the output of the following python code:
val = 100
def display(N):
global val
val = 50
if N%14==0:
57
val = val + N
else:
val = val - N
print(val, end="@")
display(40)
print(val)
A. 100@10
B. 50@5
C. 5@50
D. 100@10@
17. What will be the output of the following python code:
def A_func (x=10, y=20):
x =x+1
y=y-2
return (x+y)
print(A_func(5),A_func())
A. 24,29
B. 15,20
C. 20,30
D. 25,30
18. Consider the following code and choose correct answer
def nameage(name=”kishan”, age=20):
return age,name
t=nameage(20,”kishan”)
print(t[1])
A. kishan
B. 20
C. (kishan, 20)
D. (20,kishan)
II. Questions (2 marks)
1. Write the output of the pseudocode
def absolute_value(num):
if num>= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
III.Questions (3 marks)
1. Differentiate ceil() and floor() function?
IV.Questions (5 marks)
58
1. What are the arguments supported by python? Explain each of them with a suitable example.
2. What is the difference between the formal parameters and actual parameters? What are their
alternative names? Also, give a suitable Python code to illustrate both.
ANSWERS
I Answer the following 1 mark
1 A
2 C
3 B
4 A
5 Header
6 _main_
7 False
8 B
9 B
10 B
11 C
12 Random
13 The first function will result in an error because the function sum() is used to
find the sum of iterablenumbers. Hence the outcomes will be Error and
6respectively.
14 The function max() is being used to find themaximum value from among -3,
-4 and false. Since falseamounts to the value zero, hence we are left with
min(0, 2, 7)Hence the output is 0 (false)
15 B
16 A
17 A
18 B
II Answer the following 2 marks
1 2
59
4
III Answer the following 3 marks
1 Floor Function Ceil Function
floor function returns the integer
value just lesser than the given
rational value.
ceil function returns the integer
value just greater than the given
rational value
represented as floor(x). represented as ceil(x)
The floor of negative fractional
numbers is represented using the
floor function
The ceil of negative fractional
numbers are represented using ceil
function.
It returns the value which is just
less than or equal to the given
value.
It returns the value which is just
greater than or equal to the given
value.
Eg. the floor of 78.38 is 78 and the
floor of -39.78 is -40.
Eg. ceil of 78.38 is 79 and ceil of -
39.78 is -39.
IV Answer the following 5 marks
1 Python supports four argument types:
Positional Arguments: Arguments passed to a function in correct positional
order, no. of arguments must match with no. of parameters required.
Default Arguments: Assign a default value to a certain parameter, it is used
when the user knows the value of the parameter, default values are specified
in the function header. It is optional in the function call statement. If not
provided in the function call statement then the default value is considered.
Default arguments must be provided from right to left.
Key Word Arguments: Keyword arguments are the named arguments with
assigned values being passed in the function call statement, the user can
combine any type of argument.
Variable Length Arguments: It allows the user to pass as many arguments
as required in the program. Variable-length arguments are defined with the *
symbol.
60
2 Actual Parameter is a parameter, which is used in function call statement to
send the value from calling function to the called function. It is also known
as Argument.
Formal Parameter is a parameter, which is used in function header of the
called function to receive the value from actual parameter. It is also known
as Parameter. For example,
def addEm(x, y, z):
print(x + y + z)
addEm (6, 16, 26)
In the above code, actual parameters are 6, 16 and 26; and formal parameters
are x, y and z.
LEVEL II
IV. Questions (1 mark)
1. Name the Python Library modules which need to be imported to invoke the following
functions :
load ()
pow ()
2. What is the output of the below program ?
x = 50
def func(x):
#print(‘x is’, x)
x = 2
#print(‘Changed local x to’, x)
func(x)
print(‘x is now’, x)
a) x is now 50
b) x is now 2
c) x is now 100
d) None of the mentioned
3. What is the output of the below program?
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
61
a)
a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and c is 50
b)
a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c)
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d) None of the mentioned
4. What is the output of below program?
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
a) 2
b) 3
c) The numbers are equal
d) None of the mentioned
5. A function is executed in an execution frame. True / False
6. Function returning values are also known as ………. Functions
7. Default return value for a function that does not return any value is …..
8. Where is the function call and parameters stored in the system?
a.Heap b.Queue c.Array d.Stack
9. What is the output of the function shown below?all([2,4,0,6])
a) Error b) True c) False d)0
10. What is the output of the following function?any([2>8, 4>2, 1>2])
a) Error b) True c) False d) 4>2
11. What is the output of the function shown below?
import math.abs(math.sqrt(25))
a) Error b) -5 c) 5 d) 5.0
12. What is the output of the function: all(3,0,4.2)
a) True b) False c) Error d)0
13. What is the output of the function complex() ?
a) 0j b) 0+0j c) 0 d) Error
62
14. Predict the output of the following code
def fun3(num1,num2):
for x in range(num1,num2):
if x%4==0:
print(x,end=’ ‘)
fun3(10,20)
A. 10 12 16 20
B. 12 16
C. 12 16 20
15. Identify correct output (K)
def fun3(a,b,c):
return a+1,b+2,c+3
t=fun3(10,20,30)
print(t)
A. 11,22,33
B. 11 22 33
C. (11, 22, 33)
D. (11 22 33)
16. The correct way to call a function is:
A. A_func()
B. def A_func()
C. return A_func()
D. call A_func()
Questions (2 marks)
1. What is the output of the below program?
def sayHello():
print('Hello World!')
sayHello()
sayHello()
2. From the program code given below, identify the parts mentioned below:
def processNumber(x):
x = 72
return x + 3
y = 54
res processNumber(y)
Identify these parts: function header, function call, arguments, parameters
Questions (3 marks)
1. What is a function? Why is it needful?
2. Compute the code. Write the output of the pseudocode.
r=30
t=15
63
def swap(f,g):
f = r+t
g= f - g
g = f - g
print("f=", f,"g=", g)
swap(r,t)
swap(11,3)
swap(t,10)
swap(r,t)
3. Trace the following code and predict output produced by it.
(a)
1. def power (b, p):
2. y = b **p
3 return y
4.
5 def calcSquare(x) :
6. a = power (x, 2)
7. return a
8.
9. n=5
10. result = calcSquare (n) + power (3, 3)
11. print(result)
(b)
1.def power (b, p):
2 .r = b ** p
3. return r
4
5. def calcSquare(a):
6. a = power (a, 2)
7. return a
9.n = 5
10. result = calcSquare(n)
11. print (result)
(c)
1. def increment(X):
2. X = X + 1
3.
4. # main program
5. X = 3
6. print(x)
7. increment(x)
8. print(x)
64
Questions (5 marks)
1. Differentiate between parameters and arguments.
2. Differentiate between actual parameter(s) and a formal parameter(s) with a suitable example
for each.
ANSWERS
I Answer the following 1 mark
1 pickle
math
2 A
3 C
4 B
5 True
6 Fruitful functions
7 None
8 D
9 C
10 True
11 5.0
12 The function all() returns ‘True’ if any one
or more of the elements of the iterable are non zero. In theabove case, the
values are not iterable, hence an error isthrown.
13 A
14 B
15. C
16 A
II Answer the following 2 marks
65
1 Hello World!
Hello World!
2 Function header-- def processNumber(x):
Function call--- processNumber (y)
Arguments----- y
Parameters ----- x
Function body-------x = 72
return x + 3
Main program-------- y = 54
res processNumber(y)
III Answer the following 3 marks
1 A function is a set of instructions or subprograms that are used to perform a
specific task. It divides the large program into smaller blocks of a program that
processes the data and often returns a value. Functions are needful
-To make the program easy
-Divide the large program into a small block of codes
-Reduce the lines of code
-Easy to update
-Reuse of the code is possible
-Error correction is easier
2 f= {45} g= {15}
f= {45} g= {3}
f= {45} g= {10}
f= {45} g= {15}
3 (a)1→5→9→10→5→6→1→2→36→7→10→1→2→3→10→11
(b) 1-59→10→56→1→2→36→710→11
(c) 1-5-6-7→1→2→8
66
IV Answer the following 5 marks
1 Parameters Arguments
These are specified during the
function definition.
Values passed during the function
call.
They are also known as formal
parameters.
They are also known as actual
parameters.
The values passed as parameters are
local variables and are assigned
values of the arguments during the
function call.
Every argument is assigned to a
parameter when the function is
defined.
These variables help in the
complete execution of the function.
These variables are passed to the
function for execution.
The values contained by these
parameters can only be accessed
from function return statements or
if the scope of these parameters is
made global.
The arguments are accessible
throughout the program depending
upon the scope of the variable
assigned.
2 Actual Parameter is a parameter, which is used in function call statement to
send the value from calling function to the called function. It is also known as
Argument.
Formal Parameter is a parameter, which is used in function header of the called
function to receive the value from actual parameter. It is also known as
Parameter. For example,
def addEm(x, y, z):
print(x + y + z)
addEm (6, 16, 26)
In the above code, actual parameters are 6, 16 and 26; and formal parameters
are x, y and z.
LEVEL III
I Questions (1 mark)
67
1. Which keyword is used for function?
a) fun
b) define
c) def
d) function
2. What are the two main types of functions?
a) Custom function & User defined function
b) Built-in function & User defined function
c) User defined function & System function
d) System function & Built-in functions
3. What is the output of below program?
def cube(x):
return x * x * x
x = cube(3)
print( x)
a) 9
b) 3
c) 27
d) 30
4. Which of the following functions is a built-in function in python?
a) seed() b) sqrt() c) factorial() d) print()
5. What is the output of the expression?round(4.5676,2)?
a) 4.5 b) 4.6 c) 4.57 d) 4.56
6. What is the output of the following function?complex(1+2j)
a) Error b) 1 c) 2j d) 1+2j
7. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as:
a) (a%b, a//b) b) (a//b, a%b) c) (a//b, a*b) d) (a/b, a%b)
8. What is the output of the function shown below?
list(enumerate([2, 3]))
9. What is the result of the code?
def p(x):
print(2**x)
p(3)
a)8 b)64 c)6 d)x
10. The default value of the parameter is defined in the ………….
11. Choose correct answer for the following code
def abc(X,Y):
print(X,Y)
abc(10,20)
A. X and Y are called actual parameter
B. X and Y are default argument
C. 10 and 20 are formal parameter
D. None of above
12. Predict the output of the following code
def fun2(list1):
for x in list1:
print(x.upper(),end=”#”)
68
fun2([‘Rajesh’,’Kumar’)
13. What will be the result of thefollowing code:
def func1(a):
a= a + '1'
a = a * 2
func1("good")
A. good
B. good2good
C. goodgood
D. indentation error
14. Which of the following functions acceptsinteger as argument:
A. chr()
B. ord()
C. sum()
D. mul()
15. The function header contains:
A. Function name only
B. Parameter list only
C. Both function name & Parameter list
D. Return valu
16. A variable defined outside of all functions is known as :
A. Local variable
B. Global variable
C. Static variable
D. Unknown variable
II. Questions (2 marks)
1. What is the local variable and global variable?
2. Write the output of the code
def res():
eng = 56
math = 40
sci = 60
if eng<=35 || math<=35 || sci=35:
print(‘Not Qualified’)
else:
print(“Qualified”)
res()
3. Write the output of the code
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
69
print("Value outside function:",x)
4. What are default arguments? What are the advantages of keyword arguments?
III. Questions (3 marks)
1. What is a function? Why do we need functions in python programming?
2. Write and explain the types of functions supported by python.
3. What are keyword arguments?
4.
IV.Questions (5 marks)
1. Explain the following built-in functions.
(a) id ()
(b) chr ()
(c) round ()
(d) type ()
(e) pow ()
ANSWERS
I Answer the following 1 mark
1 C
2 B
3 C
4 D
5 C
6 D
7 B
8 The built-in function enumerate() accepts an iterable as an argument. The
function shown in the above case returns containing pairs of the numbers
given, starting from 0.Hence the output will be: [(0, 2), (1,3)].
9 A
10 Header
11 D
12 B
13 D
14 A
15 C
16 B
70
II Answer the following 2 marks
1 Global Variable: A variable that is declared in top-level statements is called
a global variable. To access the value of a global variable user need to write
a global keyword in front of the variable in a function.
Local Variable: A name declared in a specific function body is called a
local variable
2 Qualified
3 Value inside function: 10
Value outside function: 20
4 Python allows function arguments to have default values; if the function is
called without the argument, the argument gets its default value
III Answer the following 3 marks
2 Built in Functions: Pre-defined functions of python such as len(), type(),
input() etc.
Functions defined in modules: Functions defined in particular modules, can
be used when the module is imported. A module is a container of functions,
variables, constants, classes in a separate file which can be reused.
User Defined Functions: Function created by the programmer
4 If there is a function with many parameters and we want to specify only
some of them in function call,
then value for such parameters can be provided by using their names instead
of the positions. These are called keyword argument.
(eg) def simpleinterest(p, n=2, r=0.6)
def simpleinterest(p, r=0.2, n=3)
It is easier to use since we need not remember the order of the arguments.
We can specify the values for only those parameters which we want, and
others have default values.
IV Answer the following 5 marks
71
a)id():
Return the “identity” of an object. This is an integer which is guaranteed to
be unique and constant for this object during its lifetime. Two objects with
non-overlapping lifetimes may have the same id() value. This is the address
of the object in memory.
(b) chr ():
Return the string representing a character whose Unicode code point is the integer
i. For example, chr(97) returns the string 'a', while chr(8364) returns the string
'€'. This is the inverse of ord().
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base
16). ValueError will be raised if i is outside that range.
(c) round ()
Return number rounded to ndigits precision after the decimal point. If ndigits is
omitted or is None, it returns the nearest integer to its input.
For the built-in types supporting round(), values are rounded to the closest
multiple of 10 to the power minus ndigits; if two multiples are equally close,
rounding is done toward the even choice (so, for example, both round(0.5) and
round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits
(positive, zero, or negative). The return value is an integer if ndigits is omitted
or None. Otherwise, the return value has the same type as number
(d) type ()
With one argument, return the type of an object. The return value is a type object
and generally the same object as returned by object.__class__.
(e) pow ()
Return base to the power exp; if mod is present, return base to the power
exp, modulo mod (computed more efficiently than pow(base, exp) % mod).
The two-argument form pow(base, exp) is equivalent to using the power
operator: base**exp.
The arguments must have numeric types. With mixed operand types, the
coercion rules for binary arithmetic operators apply. For int operands, the
result has the same type as the operands (after coercion) unless the second
argument is negative; in that case, all arguments are converted to float and a
float result is delivered. For example, pow(10, 2) returns 100, but pow(10, -
2) returns 0.01. For a negative base of type int or float and a non-integral
72
exponent, a complex result is delivered. For example, pow(-9, 0.5) returns a
value close to 3j.
FILE HANDLING
Files are of bytes stored on storage devices such as hard-disks. Files help in storing
information permanently on a computer.
Data Files:
Data files are files that store data pertaining to a specific application. The data files
can be stored in following ways:
• Text files: These files store information in the form of a stream of ASCII or UNICODE
characters. Each line is terminated by an EOL character. Python programs, contents written
in text editors are some of the example of text files.
• Binary files: These files store information in the form of a stream of bytes. No EOL character
is used and binary files hold information in the same format in which it is held in the memory.
The .exe files, mp3 file, image files, word documents are some of the examples of binary
files.We can’t read a binary file using a text editor.
Difference Between Text File And Binary File
Text File Binary File
Stores information in ASCII characters. Stores information in the same format which
the information is held in memory.
Less prone to get corrupt as change reflects as
soon as made and can be undone.
Can easily get corrupted, corrupt on even single
bit change.
Store only plain text in a file. Can store different types of data.
Widely used file format and can be opened in
any text editor.
Developed for an application and can be
opened in that only.
Slower than binary files. Binary files are faster and easier for a
program to read and write the text files.
Opened in any text editor. Mostly .txt and .rtf
are used as extensions of text files.
Can have any application defined extensions.
In Python, File Handling consists of following three steps:
• Open the file.
• Process file i.e.perform read or write operation.
• Close the file.
73
Opening Files :
To perform file operation, it must be opened first then after reading, writing,editing
operation can be performed.To create any new file then too it must be opened. On opening
of any file, a file relevant structure is created in memory as well as memory space is created
to store contents. Once we are done working with the file, we should close the file.
Itisdoneusing open() function as per one of the following syntax:
<fileobjectname>=open(<filename>)
<fileobjectname>=open(<filename>,<mode>)
For example:
stu=open("students.txt")
The above statement open file"students.txt" in file mode as read mode(defaultmode) and attaches it to
file object namely stu.
Consider one more file open statement: - stu=open
("e:mainstudents.txt","w")
The above statement open file"students.txt"(storedinfoldere:main)in write mode(because
of"w"givenasmode)and attaches it to file object namely stu.
• Please note that when you open a file in read mode,the given file must exist in folder,
otherwise Python will raise error.
File Object/File Handle:-A file object is a reference to a file on disk.It opens and makes it
available for a number of different tasks.
FileAccessModes:-
Text
file
mode
Binary
File
Mode
Description
‘r’ ‘rb’ Read-Default value. Opens a file for reading, error if the file
does not exist.
‘w’ ‘wb’ Write- Opens a file for writing, creates the file if it does not
exist
‘a’ ‘ab’ Append- Opens a file for appending, creates the file if it does
not exist
‘r+’ ‘rb+’ Read and Write- File must exist, otherwise error is raised.
74
‘w+’ ‘wb+’ Read and Write-File is created if does not exist.
‘a+’ ‘ab+’ Read and write – Append new data
A file-mode governs the type of operations(e.g.,read/write/append) possible in the opened file i.e., it
refers to how the file will be used once it's opened.
Closing Files :
One must always close a file when the file is no longer required for any more
operations.The file can be closed by using the close( ) function which can be used w ith the
file pointer as follows:
<file_handle>.close()
Working with Text Files:
1. Read the data from a file
2. Write the data to a file
3. Append the data to a file
Reading from Text Files
Python provides three types of read functions to read from a data file.
• Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file.
• Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read
bytes in the form of string ending with line character or blank string if no more bytes are left
for reading.
• Filehandle.readlines(): reads all lines and returns them in a list
Examples:
Let a text file “Book.txt” has the following text:
Example-1:Programusingread()function:
fin=open("D:pythonprogramsBoo
k.txt",'r')
str=fin.read( )
OUTPUT:
Python is interactive language. It is case sensitive
language.
It makes the difference between uppercase and
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters. It is official language of
google.”
75
print(str)
fin.close()
lowercase letters. It is official language of google.
Example-2:Programusingread()function:
fin=open("D:python programsBook.txt",'r')
str=fin.read(10)
print(str)
fin.close()
OUTPUT:
Python is
Example-3:usingreadline()function:
fin=open("D:python programsBook.txt",'r')
str=fin.readline( )
print(str) fin.close( )
OUTPUT:
Python is interactive language. It is case sensitive
language.
Example-4:usingreadlines()function:
fin=open("D:python programsBook.txt",'r')
str=fin.readline( )
print(str)
fin.close( )
OUTPUT:
['Python is interactive language. It is case
sensitive language.n', 'It makes the difference
between uppercase and lowercase letters.n', 'It
is official language of google.']
Writing onto Text Files:
Like reading functions , the writing functions also work on open files.
• <filehandle>.write(str1): Wrties string str1 to file referenced by <file handle>.
• <filehandle>.writelines(L): Wrties all strings in list L as lines to file referenced by
<file handle>.
Myfile
Example-1:Program using write()function:
f=open(r’MyFile.txt’,’w’)
data = ‘My name is Aarav.’
f.write(data)
f.close( )
f=open(r’MyFile.txt’,’r’)
data = f.read( )
OUTPUT:
My name is Aarav.
I am Peter.
How are you?
76
print(data)
f.close( )
Example-2:Program using writelines()function:
f=open(r’Myfile.txt’,’a’)
data=[‘I have a dog., ‘nI love my cat.’]
f.writelines(data)
f.close( )
f=open(r’Myfile.txt’,’r’)
data = f.read( )
print(data)
f.close( )
OUTPUT:
#It will append the content.
My name is Aarav.I have a dog.
I love my cat.
flush( ) function:
•When we write any data to file, python hold everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to force Python to write the content of buffer onto
storage, you can use flush() function.
•Python automatically flushes the files when closing them i.e. it will be implicitly called by the
close(), but if you want to flush before closing any file you can use flush()
seek( ) function:
The seek( ) function allows us to change the position of the file pointer in the opened
file as follows:
f.seek(offset,mode)
where
offset - is a number specifying number of bytes.
mode - specifies the reference point from where the offset will be calculated to place
the file pointer. The mode argument is optional and has three possible values namely 0, 1
and 2. The default value of mode is 0.
0 - beginning of file
1 - current position in file
2 - end of file
tell( ) function:
The tell() method returns the current position of the file pointer in the opened file. It is used as
follows:
f.tell()
77
Example-1: tell()function:
Example: fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )
OUTPUT:
14
WORKSHEET
LEVEL-I
1 To open a file "c:marks.txt" for reading, we use
(a) file_read = open("c:marks.txt", "r")
(b) file_read = open("c:marks.txt", "r")
(c) file_read = open(file = "c:marks.txt", "r")
(d) file_read = open(file = "c:marks.txt", "r")
1
2 What is the use of tell() method in Python?
(a) returns the current position of record pointer within the file
(b) returns the end position of record pointer within the file
(c) returns the current position of record pointer within the line
(d) none of the above
1
3 Which of the following commands can be used to read "n" number of characters from
a file using the file object <File>?
(a) File.read(n) (b) N = file.read() (c) File.readline(n) (d) File.readlines()
1
4 What is the correct syntax of open() function?
(a) File = open(file_name[, access_mode][, buffering])
(b) File object = open(file_name [, access_mode][,buffering])
(c) File object = open(file_name)
(d) None of the above
1
5 Write the coding to display the content of file "welcome.txt". 1
6 Write the output of the given program:
1
7 Write a python program to accept a line from the user and store that in a file
“story.txt”.
2
8 Write a function to copy all the upper case words to another file. 2
9 Write the function to read the content from the file display the word which are having
the length of exactly 4 characters.
3
10 Krishna is confused in Python code given below. Please help him to answer the
following questions.
5
78
(a) Which line in the above code check for capital letter?
(b) Which line in the above code read the file “story. txt”?
(c) Which line in the above code does not affect the execution of program?
(d) Which line is the above code coverts capital letter to small letter?
(e) Which line is the above code opens the file in write mode?
(f) Which line is the above code saves the data?
(g) Which line(s) is/are the part of selection statement.
(h) Which line(s) is/are used to close story1.txt?
ANSWERS
1 (b) file_read = open("c:marks.txt", "r")
2 (a) returns the current position of record pointer within the file
3 (a) File.read(n)
4 (b) File object = open(file_name [, access_mode][,buffering])
5
6 22
7
79
8
9
10
(a) Line 6 (b) Line 4 (c) Line 10 (d) Line 7 (e) Line 2 (f) Line 13 (g) Line 6, Line 8
and Line 11 (h) Line 15
LEVEL-2
1 To read two characters from a file object "file_read"
(a) file_read.read(2)
(b) file_read(2)
(c) file_read(read,2)
(d) file_read.readlines(2)
1
2 seek() method in files used for 1
3 What does the <readlines()> method returns? (a) Str (b) A list of lines(c) List of single
characters(d) List of integers
1
4 Differentiate the following:
(a) f = open('diary.txt', 'r')
(b) f = open('diary.txt', 'w')
1
80
5 Assume that file “tear.txt”, already contain “I love my India” in the file. What will be
the output of the given program:
1
6 Write a function to count the Upper case vowel in file “All.txt”. 2
7 Write a function to read the content from the file “Story.txt”. The function will take a
string as parameter
and search the string into the file.
2
8 Aarti is new in python data-handling. Please help her to count the number of lines
which begins with ‘W’ or ‘w’ in poem.txt.
(a) # Line 1 : To open file POEM.txt in read mode
(b) # Line 2 : To check first character of every line is ‘W’ or ‘w’.
(c) # Line 3 : To increase the value of count by 1.
(d) # Line 4 : To call the function count_poem.
4
ANSWERS
1 (a) file_read.read(2)
2 Sets the file's current position at the offset
3 (b) A list of lines
4
(a) It opens the file in reading mode only in text format.
(b) It opens the file in writing mode only in text format. If the file exists, then it erases
the previous data.
81
5 13
6
7
8 (a) file1 = open("POEM.TXT","r")
(b) r1[0]=='W' or r1[0]=='w':
(c) count=count+1
(d) count_Poem()
LEVEL-3
1 To read the content of the file as a string via a file object "f"
(a) f.read(2) (b) f.read()(c) f=file.readline() (d) f.readlines()
1
2 The readlines() returns
(a) only first line from the file
(b) only last line from the file
(c) all lines from the file
(d) none of the above
1
3 Observe the following code and answer the questions that follow:
(i) What type (Text/Binary) of file is Mydata?
(ii) Fill the Blank 1 with statement to write “ABC” in the file “Mydata”.
1
82
4 A text file “Quotes.Txt” has the following data written in it:
Write the output of the given program.
1
5 Write a method in Python to read lines from a text file INDIA.TXT, to find and
display the occurrence of the word "India".
2
6
Write a function to read the content from the file “India.txt”, and store the frequency
of each word in dictionary and display the dictionary in the screen.
Content of the file is:
‘‘India is the fastest growing economy.
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is capable of reaching.’’
Output of the file:
{‘India’: 4, ‘is’: 4, ‘the’: 4, ‘fastest’: 1, ‘growing’: 1, ‘economy.’: 1, ‘looking’: 2,
‘for’: 1, ‘more’: 1, ‘investments’: 1, ‘around’: 1, ‘globe.’: 1, ‘The’: 1, ‘whole’: 1,
‘world’: 1, ‘at’: 1, ‘as’: 1, ‘a’: 1, ‘great’: 1, ‘market.’: 1, ‘Most’: 1, ‘of’: 2, ‘Indians’:
1, ‘can’: 1, ‘foresee’: 1, ‘heights’: 1, ‘that’: 1, ‘capable’: 1, ‘reaching.’: 1}
4
7 Mohan has written the following code:
4
Living a life you can be proud of
Doing your best
Spending your time with people and activities that are important to you
Standing up for things that are right even when it’s hard
Becoming the best version of you.
83
(a) What will be the output?
(i) It will display first 20 characters. (ii) It will display 20th character and
onwards.
(iii) It will display first 20 bytes. (iv) It will display content at 20th
byte.
(b) Meenu, Mohan's friend has written the following Python code.
What will be the output?
(i) True (ii) False (iii) None (iv) Error
(c) The read() method returns____________.
(i) str (ii) list (iii) tuple (iv) None of these
(d) The readline() method returns ______________.
(e) The readlines() method returns _______________.
ANSWERS
1 (b) f.read()
2 (c) all lines from the file
3
(i) Text File (default mode)
(ii) File.write(“ABC”)
4 ife y
5
84
6
7 (a) (iii) It will display first 20 bytes.
(b) (i) True
(c) (i) str
(d) str (e) list
85
BINARY FILES
Topics Covered :
o Binary file: basic operations on a binary file:
o Open using file open modes (rb, rb+,wb,wb+, ab, ab+),
o Close a binary file,
o import pickle module, dump() and load() method,
o read, write/create, search, append and update operations in a binary file.
Binary files store data in the binary format (0’s and 1’s) which is understandable by the
machine. So when we open the binary file in our machine, it decodes the data and displays
in a human-readable format.
There are three basic modes of a binary file:
• read: This mode is written as rb
• write: This mode is written as wb
• append: This mode is written as ab
The plus symbol followed by file mode is used to perform multiple operations together. For
example, rb+ is used for reading the opening file for reading and writing. The cursor position is
at the beginning when + symbol is written with file mode.
To open a binary file follow this syntax:
file = open(<filepath>, mode)
For example: f = open(“one.dat”,”rb”)
Binary File Modes: File mode governs the type of operations read/write/append possible in the
opened file. It refers to how the file will be used once its opened.
File
Mode
Description
rb Read Only: Opens existing file for read operation
wb Write Only: Opens file for write operation. If file does not exist, file is created. If
file exists, it overwrites data.
ab Append: Opens file in write mode. If file exist, data will be appended at the end.
rb+ Read and Write: File should exist, Both read and write operations can be
performed.
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
ab+ Write and Read: File created if does not exist, If file exist data is truncated.
86
Pickle Module: Python pickle is used to serialize and deserialize a python object structure.
Any object on python can be pickled so that it can be saved on disk.
Pickling: Pickling is the process whereby a Python object hierarchy is converted into
a byte stream. It is also known as serialization
Unpickling: A byte stream is converted into object hierarchy.
To use the pickling methods in a program, we have to import pickle module using
import keyword.
Example:
import pickle
In this module,we shall discuss two functions of pickle module, which are:
i) dump():To store/write the object data to the file.
ii) load():To read the object data from a file and returns the object data.
Syntax:
Write the object to the file:
pickle.dump(objname, file-object )
Read the object from a file:
pickle.load(file-object)
Write data to a Binary File:
Example:
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname=input("Enter student Name:")
student={"roll":roll,"name":sname} # create a dictionary
list.append(student) #add the dictionary as an element in the list
choice=input("Want to add more record(y/n):")
if(choice=='n'):
break
file=open("student.dat","wb") # open file in binary and write mode
pickle.dump(list, file)
file.close()
OUTPUT:
Enter student Roll No: 1201
Enter student Name: Anil
Want to add more record(y/n): y
87
Enter student Roll No: 1202
Enter student Name: Sunil
Want to add more record(y/n): n
Read data from a Binary File:
To read the data from a binary file, we have to use load() function
Example:
import pickle
file = open("student.dat", "rb")
list =pickle.load(file)
print(list)
file.close()
OUTPUT:
[{'roll':'1201','name':'Anil'},{'roll':'1202','name':'Sunil'}]
Update a record in Binary File:
def update():
name=input("Enter the name to be updated ")
newstu=[]
while True:
try:
stu=p.load(f)
for i in stu:
if i[1].lower()==name.lower():
rno=int(input("Enter the updated Roll number"))
s=[rno,name]
newstu.append(s)
else:
newstu.append(i)
except:
break
f.close()
f=open("student.dat","rb+")
update()
p.dump(newstu,f)
print(“Record updated”)
f.close()
OUTPUT:
Enter the name to be updated Sunil
Enter the updated Roll number 1204
Record updated
88
Delete a record from binary file:
import pickle
def deletestudent():
roll=input('Enter roll number whose record you want to delete:')
list = pickle.load(fw)
found=0
lst= []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found=1
fw=open(“student.dat”,”rb+”)
delestudent()
pickle.dump(lst,fw)
fw.close()
if found==1:
print(“Record Deleted”)
else:
print(“Record not found”)
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
WORKSHEET
LEVEL – 1
I Answer the following questions Marks
1 Which type of file does not have delimiters? 1
2 The process of converting the structure to a byte stream before writing
to the file is known as _________.
1
3 The process of converting byte stream back to the original structure is
known as _______
1
4 Raman open a file in readmode, but the file doesn’t exist in the folder.
Python raised an error for the code. What type of error will be shown?
1
5 The prefix ______ in front of a string makes it raw string that is no
special meaning attached to any character.
1
89
6 Pickling is otherwise known as ________________ 1
7 CSV files are opened with __________argument to supress EOL
translation.
1
8 Which of the following statement is incorrect in the context of binary
files?
a. Information is stored in the same format in which the information is
held in memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing
1
II Answer the following
1 What is EOFError? How can we handle EOFError in python? 2
2 How text files and binary files are stored inside computer memory? 2
3 Name any two exceptions that occur while working with pickle module. 2
4 What is the difference between writer object’s writerow() and
writerows() function?
2
III Answer the following
1 Binary files are the best way to store program information. Discuss 3
2 The code given below reads from a file “sales.dat” which has following
information [itemcode, amount] Read from the file and find the sum of
the amount.
import pickle
F1 = open ("sales.dat", "rb")
sum = 0
while True:
try:
________________
3
90
________________
except EOFError:
break
print (sum)
F1.close()
IV Answer the following
1 What are the different file access modes? Explain 5
2 Write the differences between read(), readline(), readlines(). Explain it with
this example
a) Consider the following lines.
The Dowry system is evil in society. It has reduced the sacred affair of
marriage to a business deal. Brides are treated as a marketable
commodity. The parents of the brides are often put under inhuman
pressure for a handsome dowry.
5
3 Arun, during Practical Examination of Computer Science, has been assigned
an incomplete search() function to search in a pickled file student.dat.
The Filestudent.dat is created by his Teacher and the following
information is known about the file.
• File contains details of students in [roll_no,name,marks] format.
• File contains details of 10 students (i.e. from roll_no 1 to 10) and
separate list of each student is written in the binary file using dump().
Arun has been assigned the task to complete the code and print details of roll
number 1.
def search():
f = open("student.dat",____)#Statement-1
____: #Statement-2
while True:
rec = pickle.____#Statement-3
if(____): #Statement-4
print(rec)
except:
pass
____ #Statement-5
I. In which mode Arun should open the file in Statement-1?
a) r
b) r+
c) rb
d) wb
5
91
II. Identify the suitable code to be used at blank space in line marked as
Statement2
a) if(rec[0]==1)
b) for i in range(10)
c) try
d) pass
III. Identify the function (with argument), to be used at blank space in line
marked
as Statement-3.
a) load()
b) load(student.dat)
c) load(f)
d) load(fin)
IV. What will be the suitable code for blank space in line marked as
Statement-4.
a) rec[0]==2
b) rec[1]==2
c) rec[2]==2
d) rec[0]==1
V. Which statement Arun should use at blank space in line marked as
Statement4 to close the file.
a) file.close()
b) close(file)
c) f.close()
d) close()
Answers
I 1. Binary files
2. Pickling
3. Unpickling
4. FileNotFoundError
5. r
6. Serialization.
7. Newline
8. Every line ends with a new line character
II 1.EOFError is raised when one of the built-in functions input() or
raw_input() hits an end-of-file condition (EOF) without reading any
data. We can overcome this issue by using try and except keywords in
Python, called Exception Handling.
2.A text file stores information in the form of a stream of ASCII or
Unicode characters based on the default state of programming
languages.
Binary file store information as stream of bytes .
3. Pickle.PicklingError and pickle.Unpickling Error
92
4.writer.writerow(row): Write the row parameter to the writer’s file
object, formatted according to delimiter defined in writer function.
writerows(rows): Writes multiple rows (sequence) to the writer’s file
object
III 1.Binary files store the information in the form of a stream of bytes
similar to the format a computer memory holds data. Also there is no
delimiter for a line and no translations occur in binary files. Thus binary
files are faster and easier for a program to read and write. So the best
method for a data or program information is to store it as binary files.
1. Program
L = pickle.load(F1)
1. sum = sum + L[1]
IV
1. Mode & Description
a) r - reading only. Sets file pointer at beginning of the file. This is
the default
a. mode.
b) rb – same as r mode but with binary file.
c) r+ - both reading and writing. The file pointer placed at the
a. beginning of the file.
d) rb+ - same as r+ mode but with binary file.
e) w - writing only. Overwrites the file if the file exists. If not,
a. creates a new file for writing.
f) wb – same as w mode but with binary file.
g) w+ - both writing and reading. Overwrites. If no file exists,
a. creates a new file for R & W.
h) wb+ - same as w+ mode but with binary file.
i) a -for appending. Move file pointer at end of the file.Creates
a. new file for writing,if not exist.
j) ab – same as a but with binary file
2. a) read() – Reads at most n bytes. If no n is specified it will read the
entire file
e.g. f1=open(“E:mydatainfo.txt”)
info=f1.read(15)
output:
The Dowry syste
b) readline() – Reads a line of input. If n is specified it reads at most n bytes.
93
It returns read bytes in the form of a string ending with line character or
returns a blank string if no more bytes are left for reading in the file.
e.g. f1=open(“E:mydatainfo.txt”)
info=f1.readlines()
output:
The Dowry system is evil in society
c) readlines() – Read all lines and returns them in a list
output:
[“The Dowry system is evil in society.n”” It has reduced the sacred affair
of marriage to a business deal.n”“Brides are treated as a marketable
commodity. n””The parents of the brides are often put under inhuman
pressure for a handsome dowry.n“]
3.c,c,c,d,c
LEVEL – 2
Answer the following questions Marks
1 A collection of bytes stored in computer’s secondary memory is known
as ______
1
2 Default EOL character in Python is the _______ 1
3 The _________ files are used to store large data such as images, video
files, audio files etc
1
4 ______ module is used to store data into a python objects with their
structure.
1
5 ______ function of pickle module is used to write data into binary 1
6 _______ function of pickle module is used to read data from binary file. 1
7 Ms. Suman is working on a binary file and wants to write data from a
list to a binary file. Consider list object as L1, binary file suman_list.dat,
and file object as f. Which of the following can be the correct statement
for her?
a) f = open(‘sum_list’,’wb’); pickle. dump(L1,f)
b) f = open(‘sum_list’,’rb’); L1=pickle.dump(f)
c) f = open(‘sum_list’,’wb’); pickle.load(L1,f)
1
94
d) f = open(‘sum_list’,’rb’); L1=pickle.load(f)
8 Ranjani is working on the sports.dat file but she is confused about how
to read data from the binary file. Suggest a suitable line for her to fulfil
her wish.
import pickle
def sports_read():
f1 = open("sports.dat","rb")
_________________
print(data)
f1.close()
sports_read()
1
9 Which of the following statement is incorrect in the context of binary
files?
a. Information is stored in the same format in which the information is
held in memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing
1
10 Which of the following statement opens a binary file record.bin in write
mode and writes data from a list L = [1,2,3,4] on the binary file?
a. with open('record.bin','wb') as myfile:
pickle.dump(L,myfile)
b. with open('record.bin','wb') as myfile:
pickle.dump(myfile,L)
c. with open('record.bin','wb+') as myfile:
1
95
pickle.dump(myfile,L)
d. with open('record.bin','ab') as myfile:
pickle.dump(myfile,L)
II Answer the following questions
1 What are delimited text files? Give examples 2
2 What is a file object? 2
3 What is the difference between write() and writelines()? 2
4 The code given below writes Name and Roll Nos into a binary file. Fill
in the blanks to complete the code.
import pickle
with open ("file.dat", "wb") as F1:
while True:
op = int (input ("Enter 1 to add data, 0 to quit"))
if (op == 1):
__________________________
__________________________
pickle.dump([name,rollno],F1)
elif op == 0:
break
2
5 Write a code to include list of items Apple, Mango, Banana to a Binary
File.
2
6 Read the following Python code carefully and answers the question
given after the code
import pickle
#open file in binary mode for writing.
2
96
with open('emp.dat', '____') as outfile: #Line 1
#Store data in list
employee = [101,'Simran',20000]
_________________ #Line 2
a) Fill in the blank in line 1 to open file in binary mode for append
data to the file
b) Fill in the blank in line 2 to pickle the list and write to file
7 What will be displayed by the following code ?
import pickle
Names = ['First', 'second', 'third', 'fourth', 'Fifth']
for i in range(-1, -5, -1):
lst.append(Names[i])
with open('test.dat', 'wb') as fout:
pickle.dump(1st, fout)
with open('test.dat', 'rb') as fin:
nlist = pickle.load(fin)
print(nlist)
2
III
1 What is pickle module? Why we use pickle module? 3
2 Write a code to show how a dictionary is stored as binary file. 3
3 A binary file “salary.DAT” has structure [employee id, employee name,
salary]. Write a function countrec() in Python that would read contents
of the file “salary.DAT” and display the details of those employee
whose salary is above 20000.
3
97
4 A file sports.dat contains information in following format [event,
participant].
Write a program that would read the contents from file and copy only
those records from sports.dat where the event name is “Athletics” in
new file named Athletics.dat
3
5 A binary file “STUDENT.DAT” has structure [admission_number,
Name, Percentage]. Write a function countrec() in Python that would
read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also display number of
students scoring above 75%
3
6 What is pickle.dump()?What is pickle.load()? 3
7 Write a function in to search and display details of all trains, whose
destination is "Delhi" from a binary file "'TRAIN .DAT'" Assuming the
binary file is containing the objects of the following dictionary type:
Train = {'Tho' :_______ , 'From': _____, " To': ________}
3
ANSWERS
I 1.Files
2. Newline (n)
3. Binary
4. PICKLE
5.dump()
6.load()
7.option d
8.data = f1.load(f).
9. c
10. with open('record.bin','wb') as myfile:
pickle.dump(L,myfile)
II 1.Text files where a particular character is stored to separate the data in
it are known as delimited text files. In these files. there will be a tab (→)
, comma(,) , pipe(│) or tilde(~ ) placed after each value.
98
E.g.: CSV files – Comma Separated Files
TSV files – Tab separated files
2. Python file object provides methods and attributes to access and
manipulate files. Using file objects, we can read or write any files.
Whenever we open a file to perform any operations on it, Python returns
a file object.
3.The difference between Write() and WriteLine() method is based on
new line character.
Write() method displays the output but do not provide a new line
character.
WriteLine() method displays the output and also provides a new line
character it the end of the string, This would set a new line for the next
output.
4.rollno=int(input("Enter the Roll Number: "))
name=input("Enter the name: ")
5.
import pickle
def writefile():
f=open("datafile.dat", "wb")
list=["Apple","Mango", "Banana"]
pickle.dump(list,f)
f.close
writefile()
print("Writing done")
6. a) ab
b)pickle.dump(employee, outfile)
7. ['Fifth', 'fourth', 'third', 'second"]
III 1. Pickle module provides us the ability to serialise and deserialize objects
that is, it helps to convertobjects into bitstreams that can be stored in
files and later utilised to recreate the original objects.
99
For us, writing different kinds of objects into the binary file and later,
reading the file's content is really challenging.The fact that some of the
objects may have changing lengths makes this a tedious task. So we use
the pickle module to solve this issue since it can handle dictionaries,
sets, lists, tuples, classes, and more.It can store lists, Tuples,
dictionaries, sets, classes etc.
2.
import pickle
F1 = open ("file.dat", "wb")
Icode = input ("Enter code : ")
quantity = int (input ("Quantity : "))
d = {Icode:quantity},
pickle.dump(d, F1)
F1.close()
3.
def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp idtEmp NametEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"tt",rec[1],"tt",rec[2])
except:
fobj.close()
countrec()
4.
import pickle
100
F1 = open ("sports.dat", "rb")
F2 = open ("athletics.dat", "wb")
sum = 0
while True:
try:
l = pickle.load(F1)
if (l[0].lower() == "athletics"):
print (l)
pickle.dump(l,F2)
except EOFError:
break
F1.close()
F2.close()
5.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
101
6. dump() function is used to store the object data to the file.
dump( object, filehandle )
It takes 3 arguments.
First argument is the object that we want to store.
The second argument is the file object we get by opening the desired
file in write-binary (wb) mode.
the third defines the protocol.
load() function is used to retrieve pickled data.
mylist = pickle.load(filehandle)
Arguments
The primary argument is the filehandle that you get by opening the file
in read-binary (rb) mode.
7. The code includes following steps,
Import of pickle module.Opens the TRAIN.DAT file as read-only in
binary format and starts reading from the beginning of the file.using
while loop searches the "Delhi".if the "Delhi" does not exits its results
a string " Not found ! ! ! "
import pickle
def search():
file open("TRAIN.DAT","rb")
found = 0
try:
while True :
Train = pickle.load(file)
if Train [ "To" ] ¡ 'Delhi':
print(Train)
found=1
except EOFError :
if found == 0:
102
print("Not found !!!")
file.close()
search()
LEVEL – 3
Answer the following questions Marks
1. Write Python statements to open a binary file "student.dat" in both read &
write mode.
1
2. Which of the following statement is true?
a. pickling creates an object from a sequence of bytes
b. pickling is used for object serialization
c. pickling is used for object deserialization
d. pickling is used to manage all types of files in Python
1
3. Read the following Python code carefully and answers the question given after
the code
import pickle
#open file in binary mode for writing.
with open('emp.dat', '____') as outfile: #Line 1
#Store data in list
employee = [101,'Simran',20000]
_________________ #Line 2
Fill in the blank in line 1 to open file in binary mode for append data to the
file.
Fill in the blank in line 2 to pickle the list and write to file
1
1
4. Raghav is trying to write a tuple t = (1,2,3,4,5) on a binary file test.bin.
Consider the following code written by him.
import pickle
t = (1,2,3,4,5)
1
103
myfile = open("test.bin",'wb')
pickle._________ #Statement 1
myfile.close()
Identify the missing code in Statement 1.
a. dump(myfile,t)
b. dump(t, myfile)
c. write(t,myfile)
d. load(myfile,t)
5. Computers store every file as a collection of ………
a)strings b)Bytes c)characters d)object e)none of the
above
1
6. The default file-open mode is ………..
a)r b)a c)w d)w+ e)none of the above
1
7. Which of the following file mode open a file for reading and writing both in the
binary file?
a) rb) rb c) rb+ d) rwb
1
8. The _____ file mode is used to handle binary file for reading.
a)rb b)wb c)r+ d)wb+ e)None of the above
1
9. Which of the following file mode opens a file for reading and writing both as
well as overwrite the existing file if the file exists otherwise creates a new
file?
a) w b) wb+ c) wb d) rwb
1
10. ______ module is used to store data into an python objects with their structure.
a)csv b)pickle c)os d)numpy
1
11. A _________ is a file format which stores records separated by comma.
a)numpy b)tsv c)csv d)dat
1
II Answer the following
12. What are the two types of data files? Give examples for each. 2
13. What is pickling and unpickling of data? 2
14. What is aBinary File? Give examples 2
104
15. How can you delete a file? Write a pseudocode to delete a file 2
16. Write a function to read name and roll no from a binary file. 3
III Answer the following
1 Amritya Seth is a programmer, who has recently been given a task to write a
python code to perform the following binary file operations with the help of
two user defined functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing
student information – roll number, name and marks (out of 100) of each
student.
b. GetStudents() to display the name and percentage of those students who
have a percentage greater than 75. In case there is no student having percentage
> 75 the function displays an appropriate message. The function should also
display the average percent.
He has succeeded in writing partial code and has missed out certain statements,
so he has left certain queries in comment lines. You as an expert of Python
have to provide the missing statements and other related queries based on the
following code of Amritya
Answer any four questions (out of five) from the below mentioned questions.
import pickle
def AddStudents():
____________ #1 statement to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
____________ #2 statement to write the list Linto the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
5
105
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
____________ #3 statement to readfrom the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who has percentage more than 75")
average=Total/Countrec print("average percent of class = ",average)
AddStudents()
GetStudents()
I. Which of the following commands is used to open the file
“STUDENT.DAT”
for writing only in binary format? (marked as #1 in the Python code)
a. F= open("STUDENT.DAT",'wb')
b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+')
d. F= open("STUDENT.DAT",'w+')
106
II. Which of the following commands is used to write the list L into the
binary file,
STUDENT.DAT? (marked as #2 in the Python code)
a. pickle.write(L,f)
b. pickle.write(f, L)
c. pickle.dump(L,F)
d. f=pickle.dump(L)
III. Which of the following commands is used to read each record from the
binary
file STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F)
b. pickle.read(r,f)
c. r= pickle.read(f)
d. pickle.load(r,f)
IV. Which of the following statement(s) are correct regarding the file
access modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its
beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing
file if it exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the
file if it exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the
file exists
V. Which of the following statements correctly explain the function of
seek() method?
a. tells the current position within the file.
b. determines if you can move the file position or not.
c. indicates that the next read or write occurs from that position in a file.
107
d. moves the current file position to a given specified position
2 Compare Text files, Binary Files and CSV files 5
ANSWERS
I 1.file = open("student.dat", "rb+")
2.pickling is used for object serialization
3.a) ab
b)pickle.dump(employee,outfile)
4. dump(t, myfile)
5. b
6.a
7.c
8.c
9.b
10 b
11. c
II 12.
There are two types of files:
Text Files- A file whose contents can be viewed using a text editor is called
atext file. A text file is simply a sequence of ASCII or Unicode
characters.Python programs, contents written in text editors are some of the
example oftext files.
Binary Files-A binary file stores the data in the same way as as stored in
thememory. The .exe files, mp3 file, image files, word documents are some of
theexamples of binary files. We can’t read a binary file using a text editor
13.
Pickling is the process of transforming data or an object in memory (RAM) to
a stream of bytes called byte streams. These byte streams in a binary file can
then be stored in a disk or in a database or sent through a network.
Unpickling is the inverse of pickling process where a byte stream is converted
back to Python object
108
14.
A binary file is a file whose content is in a binary format consisting of a series
of sequential bytes, each of which is eight bits in length.Binary Files contain
raw data so are not in human readable format. It can be read by using some
special tool or program.
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc
15.
To delete a file, import the OS module, and run its os.remove() function.
import os
os.remove("demofile.txt")
16.
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("n-------DISPALY STUDENTS DETAILS--------")
print("nRoll No.",' ','Name','t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'t ' ,rec['SNAME'])
except EOFError:
break
109
III 1.
I. a)
II.c)
III. a)
IV. a)
V.d)
2.
Text Files Binary Files CSV Files
1 It is capable to
handle textual data.
It is capable to
handle large file.
It is very common
format and
platform
independent.
2 It consists of series
of lines of a set of
letters, numbers or
symbols (String)
It consists of data
with a specific
pattern without
any delimiter.
It consists of plain
text with a list of
data with a
delimiter.
3 Any text editors
like notepad can be
used to read them.
No specific
programs can be
used to read them,
python provides
functions to read
data.
It can be read
using text editors
like notepads and
spreadsheet
software.
4 Every line ends
with EOL.
There is no
specific EOL
character.
It terminates a line
automatically
when the delimiter
is not used after
data.
CSV Files
The CSV (Comma Separated Values) is a special text file format in which rows of data are present
and the individual data elements are separated by commas. The CSV format is the most common
import and export format for spreadsheets and databases. The csv files have the extension .csv
Example for data contained in csv file
Raghu,23,100
110
Tisha,45,230
Yatin,67,90
Advantages of csv files:
• CSV is human readable and easy to edit manually.
• CSV is simple to implement and parse.
• CSV is processed by almost all existing applications.
• CSV is smaller in size
• CSV is considered to be standard format
• CSV is compact. For XML you start tag and end tag for each column in each row. In CSV
you write the column headers only once.
• CSV can handle large unstructured data generated by social media effectively
Examples of some valid formats of CSV files are:
1. Each record is located on a separate line, delimited by a line break (CRLF). For example:
One,two,three CRLF
four,five,six CRLF
2. The last record in the file may or may not have an ending line break. For example:
One,two,three CRLF
four,five,six
3. There maybe an optional header line appearing as the first line of the file with the same
format as normal record lines. For example:
Name,Rollno,Marks CRLF  Header line
Raghu,1011,56 CRLF
Swara,1012,78 CRLF
4. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
"one","two","three" CRLF
Eight,nine,ten
[Note:
1. CR stands for the character 'Carriage Return' with Integer ASCII code - 13 and
C++/Python notation r or 'r'.
2. LF stands for the character 'Line Feed' with Integer ASCII code - 10 and C++/Python
notation n or 'n'.
111
3. In Windows platform the Enter Key / End of Line(EOL) / newline character is represented
by the character combination CRLF i.e. 'rn' in python.
4. In Unix/Linux platforms the Enter Key /End of Line (EOL) / newline character is
represented by the character LF only i.e. 'n' in python.
5. In Macintosh platforms the Enter Key / End of Line (EOL) / newline character is
represented by the character CR only i.e. 'r' in python.
6. When opening a file for reading CSV file add the parameter, newline='EOL_character' to
process the End of Line correctly.
While opening a CSV file for reading on Windows platform, add the parameter, newline='rn' in
the open() method to avoid adding an extra blank line while processing/displaying output on the
screen ]
In CSV files there can be delimiters other than comma(,)
Tab separated values
Raghu 23 100
Tisha 45 230
Yatin 67 90
Semicolon separated values
Raghu ;23;100
Tisha;45;230
Yatin;67;90
Using CSV module to handle csv files
What is csv module?
The csv module implements classes to read and write tabular data in CSV format. The csv module
handles the different types of delimiters and quoting characters in CSV files and efficiently
manipulate such data, hiding the details of reading and writing the data from the programmer.
The module has to be imported in python program to handle csv files.
import csv as c
or
import csv
READING FROM A CSV FILE-READER OBJECT
Reading from a csv file is done using a reader object. The CSV file is opened as a text
file with Python’s built-in open() function, which returns a file object. This creates a
special type of object to access the CSV file (reader object), using the reader()
function.
112
The reader object is an iterable that gives us access to each line of the CSV file as a
list of fields. You can also use next() directly on it to read the next line of the CSV file,
or you can treat it like a list in a for loop to read all the lines of the file (as lists of the
file’s fields).
Syntax:
csv.reader(fileobject,delimiter=“ “)-> it returns a reader object
PROGRAM TO READ AND DISPLAY CONTENTS OF CSV FILE
#reading and displaying contents from a csv file
import csv as c
with open(‘12ACS.csv’,"r") as mycsv:
csvreader=c.reader(mycsv,delimiter=",")
for row in csvreader:
print (row)
CREATING A CSV FILE THROUGH A PYTHON PROGRAM FOR WRITING DATA
To write to a CSV file in Python, we can use the csv.writer() function. The
csv.writer() function returns a writer object that converts the user's data into a
delimited string.
This string can later be used to write into CSV files using the writerow() function.
In order to write to a CSV file, we create a special type of object to write to the CSV
file "writer object", which is defined in the CSV module, and which we create using
the writer() function.
The writerow() method allows us to write a list of fields to the file. The fields
can be strings or numbers or both. Also, while using writerow(), you do not need to
add a new line character (or other EOL indicator) to indicate the end of the line,
writerow() does it for you as necessary.
PROGRAM TO CREATE A CSV FILE AND WRITE DATA IN IT
def createcsv():
f=open("cricket.csv","w",newline='')
s=csv.writer(f,delimiter="-")
s.writerow(["playername","runsscored","Matchsplayed"])
while True:
c=eval(input("Enter the name ,runs, matches"))
s.writerow(c)
ch=input("Do you want to continue (Y/N)")
if ch.upper()!="Y":
break
f.close()
writerow() Vs writerows()
writerow() is used to write a single row to a csv file.
113
writerows() is used to write multiple rows/lines to csv file
To demonstrate writerow() and writerows()
import csv
f=open("one.csv","w",newline='')
csvwriter=csv.writer(f,delimiter=',')
csvwriter.writerow(['one','two','three'])
l=[(23,45,67),(34,56,78),(45,67,78)]
csvwriter.writerows(l)
f.close()
OUTPUT:
one,two,three
23,45,67
34,56,78
45,67,78
WORKSHEET
LEVEL – 1
I Questions (1 mark)
1 CSV files are opened with __________argument to supress EOL translation.
2 The _________ parameter of csv.reader() function is used to set a specific delimiter like a single
quote or double quote or space or any other character.
3 When you read csv file using csv.reader() function it returns the values in _______ object.
4 If you want to change a default delimiter of csv file, you can specify ________ parameter.
5 Which of the following is not a function of csv module?
a. readline()
b. writerow()
c. reader()
d. writer()
6 Anshuman wants to separate the values by a $ sign. Suggest to him a pair of function and
parameter to use it.
A open,quotechar
B writer,quotechar
C open,delimiter
D writer, delimiter
7 Which of the following is tasks cannot be done or difficult with CSV module?
A Data in tabular form
B Uniqueness of data
C Saving data permanently
D All of these
8 Observe the following code and fill the blank in statement1
import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
114
print(_____) #statement4
a) open(“data.csv”)
b) f=open(“data.csv”)
c) Both A & B are Correct
d) Both A & B are incorrect
9 A CSV file is also known as a ….
A. Flat File
B. 3D File
C. String File
D. Random File
10 The command used to skip a row in a CSV file is
A. next()
B. skip()
C. omit()
D. bounce()
11 Which of the following is a string used to terminate lines produced by writer()method of csv
module?
A. Line Terminator
B. Enter key
C. Form feed
D. Data Terminator
12 Making some changes in the data of the existing file or adding more data is called
A. Editing
B. Appending
C. Modification
D. Alteration
13 Observe the following code and fill the blank in statement4
import csv
with _________ as f: #statement1
r = csv.______(f) #statement2
for row in ______: #statement3
print(_____) #statement4
a) r
b) row
c) f
d) csv
14 One row of CSV file can be considered as _______ in terms of database
15 What is the output of the following program?
import csv
d=csv.reader(open('c:PYPRGch13city.csv'))
next(d)
for row in d: print(row)
if the file called “city.csv” contain the following details
chennai,mylapore
115
mumbai,andheri
A. chennai,mylapore
B. mumbai,andheri
C. Chennai, mumbai
D. chennai,mylapore
mumbai, andheri
II Questions (2 marks)
1 What is the difference between writer object’s writerow() and writerows() function?
2 How will you sort more than one column from a csv file?Give an example statement.
3 What Is CSV File”
4 Syntax for opening Student.csv file in write mode is
myfile = open("Student.csv","w",newline='').
What is the importance of newline=''?
5 What is the output of the following program if the student.csv file contains following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row)
III Questions (3 marks)
1 Write a note on open() function of python. What is the difference between the two methods?
2 Write a Python program to modify an existing file
3 Write a Python program to read a CSV file with default delimiter comma (,).
4 What is the difference between reader() and DictReader() function?
5 Observe the following code and fill in the given blanks:
import csv
with _________ as f: #1
r = csv.______(f) #2
for row in ______: #3
print(_____) #4
IV Questions (5 marks)
1 Vijay Kumar of class 12 is writing a program to create a CSV file "user.csv" which will contain
user name and password for some entries. He has written the following code. As a
programmer, help him to successfully execute the given task.
import ____________ # Line 1
# to write / add data into the CSV file
def addRecord(user,password):
file=open('users.csv','___',newline='') # Line 2
cwriter = csv.writer(file)
cwriter.writerow([user,password])
file.close()
116
#csv file reading code
def readRecord(): # to read data from CSV file
f=open('users.csv','r')
creader = csv._________(f) # Line 3
for row in creader:
print (row[0],row[1])
__________ # Line 4
addRecord("Neil", "123@456")
addRecord("Swati","sw@tee")
addRecord("Farida","myname@FRD")
readRecord() #Line 5
1a Name the module he should import in Line 1.
1b In which mode, Vijay should open the file to append data into the file.
1c Fill in the blank in Line 3 to read the data from a csv file.
1d Fill in the blank in Line 4 to close the file
1e Write the output he will obtain while executing Line 5.
2 What are the different file access modes? Explain
3 Puneeta is storing the data of her gift store in a csv file named gift.csv which will store Gift_code
and Gift_name of items of her gift store. She has written the following code .As a
programmer help her to successfully execute her program in python:
import ___________ # Line 1
def writeFile(Gift_code,Gift_name):
F=open(“gift.csv”,‟___‟) #Line 2
FW=csv.________(F) #Line 3
FW.writerow([Gift_code,Gift_name)
F.close()
#CSV file for reading
def readFile():
with ________(„gift.csv‟,‟r‟) as newF #Line 4
FR=csv.reader(newF)
for row in FR:
if row[0]==101:
print(row)
writeFile(101,”Photoframe”)
writeFile(102,”Soft Toys”)
writeFile(103,”Flower Pot”)
readFile() #Line 5
3a Name the module she should import in line 1.
3b In which mode Puneeta should open the file to add data in it?
3c Fill in the blanks in Line 3 to write data to csv file gift.csv
3d Fill in the blank in Line 4 to open the csv file from the disk
3e Which user defined function is used here for reading data?
4 Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he
117
has been assigned an incomplete python code (shown below) to create a CSV File
'Student.csv' (content shown below). Help him in completing the code which creates the
desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code
import_____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
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
fh.close()
I.Identify the suitable code for blank space in line marked as Statement-1.
a) csv file
b) CSV
c) csv
d) Csv
II.Identify the missing code for blank space in line marked as Statement-2?
a) "School.csv","w"
b) "Student.csv","w"
c) "Student.csv","r"
d) "School.csv","r"
III.Choose the function name (with argument) that should be used in the blankspace of line
marked as Statement-3
a) reader(fh)
b) reader(MyFile)
c) writer(fh)
d) writer(MyFile)
IV.Identify the suitable code for blank space in line marked as Statement-4.
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section'
d) roll_no,name,Class,sectionc) co.connect()
118
V.Choose the function name that should be used in the blank space of line markedas Statement-
5 to create the desired CSV File?
a) dump()
b) load()
c) writerows()
d) writerow()
LEVEL – 2
I Answer the following Marks
1 The expansion of CRLF is
(A) Control Return and Line Feed
(B) Carriage Return and Form Feed
(C) Control Router and Line Feed
(D) Carriage Return and Line Feed
1
ans (D) Carriage Return and Line Feed
2 Importing CSV files can be much faster, and it also consumes less memory
while comparing with .xls files(True/False)
1
an True
3 A ________ parameter is used to quote all fields of csv files.
ans Quoting
4 Read following statement about features of CSV file and select which
statement is TRUE?
Statement1: Only database can support import/export to CSV format
Statement2: CSV file can be created and edited using any text editor
Statement3: All the columns of CSV file can be separated by comma only
a. Statement 1 and statement 2
b. Statement 2 and statement 3
c. Statement 2
d. Statement 3
ans c. Statement 2
119
5 Which of the following file types can be opened with notepad as well as
ms excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of thes
ans CSV Files
6 What is the output of the following program if the student.csv file contains
following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row);
1
ans Akshaj, 400
II Answer the following Marks
1 Write a program to copy the data from “data.csv” to “temp.csv” 2
ans import csv
f=open("data.csv","r")
f1=open("temp.csv",'w')
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close( )
f1.close( )
120
2 When is a CSV file ? When do we use CSV? 2
A CSV (Comma Separated Values) file is a form of plain text document
which uses a particular format to organize tabular information. CSV file
format is a bounded text document that uses a comma to distinguish the
values. Every row in the document is a data log. Each log is composed of
one or more fields, divided by commas. It is the most popular file format
for importing and exporting spreadsheets and databases.
3 Write a Python program to modify an existing file.
ans import csv
row = [‘3’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each row of data as a list
lines [3] = row
with open( student.csv’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = csv.writer(writeFile) #writerows()method writes multiple rows
to a csv file
writer.writerows(lines)
III Answer the following Marks
1 a) Write a Python program to read each row from a given csv file and
print a list of strings
department_id,department_name,manager_id,location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
70,Public Relations,204,2700
80,Sales,145,2500
2+1
121
90,Executive,100,1700
b) What does tell() method do?
Ans
a
b
import csv
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in data:
print(', '.join(row))
It tells you the current position of cursor within the file
Syntax: file_object.tell()
2 What is difference between tell() and seek() methods? 3
ans tell() seek()
It returns the current position of
cursor in file.
Change the cursor position by
bytes as specified by the offset
Example:
fout=open(“story.txt”,”w”)
fout.write(“Welcome Python”)
print(fout.tell( ))
fout.close( )
Example:
fout=open(“story.txt”,”w”)
fout.write(“Welcome Python”)
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output : 4 Output : 5
IV Answer the following Marks
1 Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv”
which will contain user name and password for some entries. He has
written the following code. As a programmer, help him to successfully
execute the given task.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV
file
f=open(' user.csv','________') # Line 2
5
122
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
readCsvFile() #Line 5
(a) Name the module he should import in Line 1.
(b) In which mode, Ranjan should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.
ans a) Line 1 : csv
b) Line 2 : a
c) Line 3 : reader
d) Line 4 : close()
e) . Line 5 : Arjun 123@456
Arunimaaru@nima
Frieda myname@FRD
2 Ronit has a CSV file “marks.csv” which has name, class and marks
separated by comma. He is writing a Python program to copy only the
5
123
name and class to another CSV file “class.csv”. He has written the
following code. As a programmer, help him to successfully execute the
given task.
import csv
file = open('class.csv', ---------a--------- , newline="");
writer = csv.writer(file)
file.close()
----- b ----- open('marks.csv') as csvfile:
data = csv. ----- c------- (csvfile)
for row in data:
writer.writerow([----d ------ ,-----e --------- ])
a. In which mode should Ronit open the file to make a new file?
b. Which Python keyword should be used to manage the file stream?
c. Fill in the blank in Line 3 to read the data from a csv file.
d. Fill in the blank to write name into marks.csv
e. Fill in the blank to write class into marks.csv.
ans import csv
file = open('class.csv', 'w', newline="");
writer = csv.writer(file)
file.close()
with open('marks.csv') as csvfile:
data = csv.reader(csvfile)
for row in data:
writer.writerow([row[0],row[1]])
3 Write the different methods to read a CSV File in Python. 5
ans There are two ways to read a CSV file.
(i) Use the csv modules reader function
(ii) Use the DictReader class.
124
CSV Module’s Reader Function:
(i) We can read the contents of CSV file with the help of csv.reader()
method. The reader function is designed to take each line of the file and
make a list of all columns.
(ii) Then, choose the column we want the variable data for. Using this
method one can read data from csv files of different formats like quotes
(""), pipe (|) and comma (,).
The syntax for csv.readerf() is
csv.reader(fileobject,delimiter,fmtparams) where
(iii) file object : passes the path and the mode of the file
(iv) delimiter:an optional parameter containing the standard dilects like , |
etc can be omitted.
(v) fmtparams : optional parameter which help to override the default
values of the dialects like skipinitialspace,quoting etc. can be omitted.
* CSV file - data with default delimiter comma (,)
* CSV file - data with Space at the beginning
* CSV file - data with quotes
* CSV file - data with custom Delimiters
CSV file with default delimiter comma (,): The following program read a
file called “sample 1. csv” with default delimiter comma (,) and print row
by row.
Program:
125
#importing csv
import csv
#opening the csv file which is in different location with read mode
with open('c:pyprgsamplel.csv', 'r') as F:
#other way to open the file is f= ('c:pyprgsample1.csv', 'r')
reader = csv.reader(F)
# printing each line of the Data row by row print(row)
F.close()
Output:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']
Reading CSV File Into A Dictionary:
(i) To read a CSV file into a dictionary can be done by using DictReader
class of csv module which works similar to the reader() class but creates an
object which maps data to a dictionary.
(ii) The keys are given by the fieldnames as parameter. DictReader works
by reading the first line of the CSV and using each comma separated value
in this line as a dictionary key.
(iii) The columns in each subsequent row then behave like dictionary
values and can be accessed with the appropriate key (i.e. fieldname).
126
(iv) If the first row of your CSV does not contain your column names, you
can pass a fieldnames parameter into the DictReader s constructor to assign
the dictionary keys manually.
(v) The main difference between the csv. reader() and DictReader() is in
simple terms csv.reader and csv.writer work with list/tuple, while
csv.DictReader and csv. DictWriter work with dictionary, csv. DictReader
and csv. DictWriter take additional argument fieldnames that are used as
dictionary keys.
(vi) For Example Reading “sample8.csv” file into a dictionary
Program:
import csv
filename = c:pyprgsample8.csv’
input_file =csv.DictReader(open(filename,’r’))
for row in input_file:
print(dict(row) ) #dict() to print data
Output:
{‘ItemName ‘: ‘Keyboard ‘, ‘Quantity’: ‘48’}
{‘ItemName ‘: ‘Monitor’ ‘Quantity’: ‘52’}
{‘ItemName ‘: ‘Mouse ‘, ‘Quantity’: ‘20’}
In the above program, DictReader() is used to read “sample8.csv” file and
map into a dictionary. Then, the function dict() is used to print the data in
dictionary format without order. Remove the dict() function from the above
program and use print(row).Check you are getting the following output
OrderedDict([(‘ItemName ‘, ‘Keyboard ‘), (‘Quantity’, ‘48’)])
OrderedDict([(‘ItemName ‘, ‘Monitor’), (‘Quantity’, ‘52’)])
OrderedDict( [(‘ItemName ‘, ‘Mouse ‘), (‘Quantity’, ‘20’)])
127
4 Radha Shah is a programmer, who has recently been given a task to write a
python code to perform the following CSV file operations with the help of
two
user defined functions/modules:
a. CSVOpen() : to create a CSV file called BOOKS.CSV in append mode
containing information of books – Title, Author and Price.
b. CSVRead() : to display the records from the CSV file called
BOOKS.CSV where the field title starts with 'R'.
She has succeeded in writing partial code and has missed out certain
statements,
so she has left certain queries in comment lines.
import csv
def CSVOpen():
with open('books.csv','______',newline='') as csvf: #Statement-1
cw=______ #Statement-2
______ #Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=______ #Statement-4
for r in cr:
if ______: #Statement-5
print(r)
except:
print('File Not Found')
128
CSVOpen()
CSVRead()
You as an expert of Python have to provide the missing statements and
other related queries based on the following code of Radha.
Answer any four questions (out of five) from the below mentioned
questions.
4.1
ans
Choose the appropriate mode in which the file is to be opened in append
mode
(Statement 1)
a. w+
b. ab
c. r+
d. a
Correct Answer: d. a
4.2
ans
Which statement will be used to create a csv writer object in Statement 2.
a. csv.writer(csvf)
b. csv.writer(csvf)
c. csvf.writer()
d. cs.writer(csvf)
Correct Answer: b. csv.writer(csvf)
4.3 Choose the correct option for Statement 3 to write the names of the column
headings in the CSV file, BOOKS.CSV.
a. cw.writerow('Title','Author','Price')
b. cw.writerow(['Title','Author','Price'])
c. cw.writerows('Title','Author','Price')
d. cw.writerows(['Title','Author','Price'])
129
ans Correct Answer: b. cw.writerow(['Title','Author','Price'])
4.4
ans
Which statement will be used to read a csv file in Statement 4.
a. cs.read(csvf)
b. csv.reader(csvf)
c. csvf.read()
d. csvf.reader(cs)
Correct Answer: b. csv.reader(csvf
4.5
ans
Fill in the appropriate statement to check the field Title starting with ‘R’
for
Statement 5 in the above program.
a. r[0][0]=='R'
b. r[1][0]=='R'
c. r[0][1]=='R'
d. d) r[1][1]=='R'
Correct Answer: a. r[0][0]=='R'
LEVEL – 3
I Answer the following Marks
1 Which of the following module is provided by Python to do several
operations on the CSV files?
(A) py
(B) xls
(C) csv
(D) os
1
130
Ans (C) csv
2 To open a file c:scores.csv for reading, we use _______ command.
a) infile = open(“c:scores.csv”, “r”)
b) infile = open(“c:scores.csv”, “r”)
c) infile = open(file = “c:scores.csv”, “r”)
d) infile = open(file = “c:scores.csv”, “r”)
1
Ans infile = open(“c:scores.csv”, “r”)
3 To read the entire content of the CSV file as a nested list from a file object
infile, we use __________ command.
(a) infile.read()
(b) infile.reader()
(c) csv.reader(infile)
(d) infile.readlines()
1
Ans c) csv.reader(infile)
4 The CSV files are popular because they are
a) capable of storing large amount of data
b) easier to create
c) preferred export and import format for databases and spread sheets
d) All the above
1
Ans d) All the above
5 .A _________ is a file format which stores records separated by comma.
a)numpy b)tsv c)csv d)dat
1
Ans csv
II Answer the following Marks
1 Deepesh works as a programmer with Delta Technologies. He has been
assigned the job of generating the salary of all employees using the file
“employee.csv”. He has written a program to read the CSV file
“employee.csv” which will contain details of all the employees. He has
2
131
written the following code. As a programmer, help him to successfully
execute the given task.
import______ # Line 1
def readCsvEmp( ): # to read data from the CSV file
with ______(’employees.csv’, newline=”) as f: # Line 2
reader = csv.______ (f) # Line 3
data_list = ______(reader) # Line 4
print (data_list)
i) Name the module he should import in Line 1.
ii)Write the method that he should use to open the file to read data from
it.
iii)Fill in the blank in Line 3 to read the data from a csv file
iv)Fill in the blank in Line 4 with the method to convert the data read
from the file into list.
Ans i)
ii)
iii)
iv)
import csv
open
reader
list
III Answer the following Marks
1 What is CSV file? What are its characteristics? 3
Ans CSV (Comma Separated Values) is a file format for data storage which
looks like a text file.
It is used to store tabular data, such as a spreadsheet or database.
The information is organized with one record on each line
132
Each field is separated by comma.
You can choose a different delimiter character such as ‘ ‘:’ , ‘;’ , ‘|’.
In CSV files space-characters adjacent to commas are ignored
IV Answer the following Marks
1 What are the Advantages and disadvantages of CSV files? 5
Ans Advantages of CSV:
•CSV is faster to handle
•CSV is smaller in size and is easy to generate
•CSV is human readable and easy to edit manually
•CSV is simple to implement and parse
•CSV is processed by almost all existing applications
Disadvantages of CSV:
•There is no standard way to represent binary data
•There is no distinction between text and numeric values
•There is poor support of special characters and control characters
•CSV allows to move most basic data only. Complex configurations
cannot be imported and exported this way
•There are problems with importing CSV into SQL (no distinction
between NULL and quotes)
2 What is the difference between writer object’s writerow() and writerows()
function? Write a python code based on these function
5
writer.writerow(row): Write the row parameter to the writer’s file object,
formatted according to delimiter defined in writer function
e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
133
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
f1.close()
writerows(rows): Writes multiple rows (sequence) to the writer’s file
object
e.g.
import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
w1.writerows([[1, ‘Ronit’, 84],[2,’Nihir’,90]])
f1.close()
Data structures - Stacks
❖ IntroductiontoPythondatastructurestack
❖ ImplementationofstackusingList
❖ Pushfunction
❖ PopFunction
❖ Displayfunction
❖ Checkingstackunderflow
Introduction toPython data structure-Stack
A data structure is a way of store, organize, or manage data in efficient and productive manner.
The python data structure stack is a linear data structure. It follows the principle of LIFO (Last In
First Out). The representation of data is something like this:
134
By observing the above image you can understand the following:
1. The data can be inserted or deleted from the top only
2. Elements can be inserted or deleted any time
3. The insert operation is known as push
4. The delete operation is known as pop
5. When the top element is inspected, it is known as a peek or inspection
6. When we have a fixed-length list and we are trying to push an element in a list, it raises one
error that is known as overflow
7. When the list is empty and we are trying to pop an element, it will raise an error that is
known as underflow
Push function
A function to push an element. To push the element append() method is used as well as the
position of the top should be changed. Observe the following code:
def push(stk,e):
stk.append(e)
Pop Function
The pop function requires validation to check whether the stack is underflow or not if it is not then
use the logic to delete the element from the top. Have a look at this code:
def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
return e
Display function
Write a function to check the element is inserted or not, observe this code:
def display(stk):
if stk==[]:
print("Stack Underflow")
135
else:
for i in (stk[::-1]):
print(i)
Applications of the stack:
• Infix to Postfix /Prefix conversion
• Redo-undo features at many places like editors, photoshop.
• Forward and backward features in web browsers
• Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and
histogram problems.
• String reversal is also another application of stack. Here one by one each character gets
inserted into the stack. So the first character of the string is on the bottom of the stack and
the last element of a string is on the top of the stack. After performing the pop operations
on the stack we get a string in reverse order.
Mind Map
BOARD PATTERN QUESTIONS
Considering the dictionary storing the price of vegetables,
veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
a) Write python function to build a stack costly by pushing the names of vegetables whose
price is > 40 from dictionary veg.
b) Pop and display the items in stack costly
Note:Write only 2 functions pushcostly(veg,costly) and popcostly(costly).Write appropriate
statements in the main part to call the functions.
def pushcostly(p,s):
for i in p:
if p[i]>40:
s.append(i)
def popcostly(s):
if s==[]:
print("Stack underflow")
else:
136
print("costly vegetables")
while(s):
print(s.pop())
return
veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60}
costly= []
while True:
print ('''Menu
1.push
2.pop and display
3.exit''')
ch=int (input ("enter your choice"))
if ch==1:
pushprod(veg,costly)
elifch==2:
popdisplay(costly)
else:
break
WORKSHEET
LEVEL – 1
Answer the following questions(1 marks)
1. A stack is one of the following types of data structure?
a) Linear b) Dynamic c) Circular d) All of these
2. A condition raise due to the stack is full is known as ___________.
a) Underflow b) Overflow c) List is full d) Completely Filled
3. While popping the element from the stack, a condition will be raised, this condition is known
as ____________.
a) Underflow b) Overflow c) List is Empty d) Blank List
4. Which of the following is not a compound data structure?
a) Stack
b) Queue
c) Array
d) Tree
5. Inspecting the value at the stack’s top without removing it.
a) peak operation
b) insert operation
c) pop operation
d) push operation
6. Which of the following statement is incorrect for stack?
137
a) Peek <stack>[top]
b) Push <stack>.append(<item>)
c) Pop <stack>.pop()
d) Plus <stack>plus()
Answer the following questions (2 marks)
1. What are the underflow and overflow conditions?
Answer the following questions (3 marks)
1. Write a python function to delete an element from the stack.
2. Write a function to inspect an element from the stack.
3. Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a
player by considering them as push and pop operations in a stack.
Answer the following questions (5 marks)
1. Vedika has created a dictionary containing names and marks as key-value pairs of 5 students.
Write a program, with separate user-defined functions to perform the following operations:
• Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
• Pop and display the content of the stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95}
Then the output will be: Umesh Vishal Ishika
LEVEL 1 ANSWERS
Answer the following questions(1 marks)
1 a) Linear
2 b) Overflow
3 a) Underflow
4 c) Array
5 a) peak operation
6 d) Plus <stack>plus()
Answer the following questions(2 marks)
138
1 Underflow is the condition which occurs when stack is empty while trying to
delete elements. Overflow is the condition which occurs while inserting an
element when memory is exhausted.
Answer the following questions(3 marks)
1 def pop_stack(stk):
if stk==[]:
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
2 def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
3 def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
139
Answer the following questions(5 marks)
1 def push(stk,item):
stk.append(item)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
LEVEL – 2
Answer the following questions(1 marks)
1. Stack data structure is following ____________ principle.
2. The peek operation refers to accessing/inspecting the top element in the stack. (True/False)
3. Stack overflow condition is raised in ____________ operation where as Stack underflow
condition is raised in _____________ operations.
4. Stack is a ___________ data structure.
a) Static
b) Dynamic
c) Double
140
d) Single
5. While implementing Stack using list when we want to delete element we must use pop
function as__________
a) list.pop(pos)
b) list.pop(0)
c) list.pop()
d) list.push()
6. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, in
what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Answer the following questions (2 marks)
1. What do you mean by data structure? Explain your answer with a suitable example.
2. Write a python function named is_underflow() to check a stack is an underflow.
3. Write a function to push an element into the stack.
Answer the following questions (3 marks)
1. Write a function to display the stack elements.
LEVEL 2 ANSWERS
I Answer the following questions (1 marks)
1 LIFO
2 True
3 Push , Pop
4 b) Dynamic
5 c) list.pop()
6 b) DCBA
II Answer the following questions (2 marks)
1 The systematic way of organization, storing, accessing and retrieving data including
well-defined operations, behaviour and properties is known as data structure.
Examples:
String – Contains sequence of characters
List – Contains sequence of different data types
2 def is_underflow(stk):
if stk==[]:
return True
141
else:
return False
3 def push(stk,e):
stk.append(e)
top = len(stk)-1
III Answer the following questions (3 marks)
1 def display(stk):
if stk==[]:
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
LEVEL – 3
Answer the following questions (1 marks)
1. The insert operation in the stack is known as pop. (True/False).
2. You can replace any element position in the stack. (True/False)
3. If the name of linear list of 10 elements is LIL, then its element will be referenced
a) LIL[0],LIL[1],LIL[2]………LIL[9]
b) LIL[0],LIL[1],LIL[2]………LIL[10]
c) LIL(0),LIL(1),LIL(2)………LIL(9)
d) LIL(0),LIL(1),LIL(2)………LIL(10)
4. LIFO Full form –
a) logical in first out
b) First in first out
c) last in first out
d) last in logical out
5. Which of the following statement(s) about stack data structure is/are NOT correct?
a) Stack data structure can be implemented using linked list
b) New node can only be added at the top of the stack
c) Stack is the FIFO data structure
d) The last node at the bottom of the stack has a NULL link
142
Answer the following questions(2 marks)
1. Define stack.
2. Expand the following:
a) LIFO
b) FIFO
3. What do you mean by the LIFO structure? Support your answer with real-life examples.
LEVEL 3 ANSWERS
Answer the following questions(1 marks)
1 False
2 False
3
4
a)LIL[0],LIL[1],LIL[2]………LIL[9]
c) last in first out
5 a)Stack is the FIFO data structure
II Answer the following questions(2 marks)
1 A stack is a data structure that allows adding and removing elements in a particular
order. Every time an element is added, it goes on the top of the stack; the only
element that can be removed is the element that was at the top of the stack.
2
2 LIFO: Last-In First-Out FIFO: First-In First-Out 1+1
3 LIFO is one of the principle to access data from a data structure. It stands for Last In
First Out. It refers to the item which is inserted last will be access first. So the top
element will be accessed first.
Example:
1. Books in the shelf
2. Stack of coins
3. Pile of chairs
4. Bangles on woman’s wrist
143
UNIT – 2 COMPUTER NETWORKS
1. Computer Network
A computer network is an interconnection among two or more computers or computing devices.
2. Who invented WWW? - Sir Tim Berners-Lee — a British computer scientist invented the
revolutionary World Wide Web in 1990.
3. ARPANET
i. Stands for Advanced Research Projects Agency Network.
ii. Started in 1960s by the U.S. Department of Defence to connect the academic and
research institutions located at different places for scientific collaborations.
iii. Gradually, more and more organisations joined the ARPANET, and many
independent smaller networks were formed which eventually gave birth to the today’s
INTERNET.
4. TYPES OF NETWORKS
i. PAN (Personal Area Network)
ii. LAN (Local Area Network)
iii. MAN (Metropolitan Area Network)
iv. WAN (Wide Area Network)
5. PAN
i. It is formed by connecting personal devices like computers, laptops, mobile phones,
smart phones, printers etc.
ii. The devices should be within an approximate range of 10 metres. A personal area
network may be wired or wireless.
6. LAN
i. A network that connects computers, mobile phones, tablet, mouse, printer, etc., placed
at a limited distance, viz, a LAN can range from a single room, a floor, an office
having one or more buildings in the same premise, laboratory, a school, college, or
university campus.
ii. LAN may be extended up to 1 km. Data transfer in LAN is quite high, and usually
varies from 10 Mbps (called Ethernet) to 1000 Mbps (called Gigabit Ethernet), where
Mbps stands for Megabits per second
7. MAN
i. It is extended form of LAN which covers a larger geographical area like a city or a
town.
ii. Data transfer rate in MAN also ranges in Mbps but it is less as compared to LAN.
iii. Cable TV network or cable based broadband internet services are examples of MAN.
iv. It can be extended up to 30-40 km.
144
8. Modem- It stands for ‘MOdulatorDEModulator’, is a device used for conversion between
electric signals and digital bits.
9. Ethernet card- It is also known as Network Interface Card (NIC card in short), and it is a
network adaptor used to set up a wired network.
10. MAC address
- It helps in uniquely identifying a computer on a network.
- The MAC address is also known as the physical or hardware address.
-It is a unique permanent value associated with a network adapter called a NIC.
-It is used to physically identify a machine on the network.
11. Repeater- It is a device that regenerate or amplifies the signals on a network.
12. Switch- It is a networking device used to connect multiple computers or communicating
devices.
13. Router- It is a network device that can receive the data, analyse it and transmit it to other
networks.
14. Gateway- It serves as the entry and exit point of a network, as all data coming in or going out
of a network must first pass through the gateway in order to use routing paths. In other words,
A Gateway is a network point that acts as an entrance to another network using different
protocols.
15. Topology- The arrangement of computers and other peripherals in a network is called its
topology. The Common network topologies are Mesh, Ring, Bus, Star and Tree.
- In mesh topology each communicating device is connected with every other device in the
network.
- In ring topology, each node is connected to two other devices, one each on either side.
- In bus topology, a single backbone wire called bus is shared among the nodes, which
makes it cheaper and easy to maintain.
- In star topology, each communicating device is connected to a central networking device
like a hub or a switch.
- In tree or hybrid topology, there are multiple branches and each branch can have one or
more basic topologies like star, ring and bus.
16. IP address- It is also known as Internet Protocol address, and it is a unique address that can
be used to uniquely identify each node in a network.
Unlike MAC address, IP address can change if a node is removed from one network and
connected to another network.
17. Protocol-A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network.
It allows connected devices to communicate with each other, regardless of any differences in
145
their internal processes, structure or design.
18. HTML- HTML (HyperText Markup Language) is a language which is used to design
standardised Web Pages so that the Web contents can be read NOTES 2022-23 COMPUTER
NETWORKS 201 and understood from any computer.
19. URI/URL- URI (Uniform Resource Identifier) or URL (Uniform Resource Locator) is a
unique address or path for each resource located on the web.
20. HTTP – The HyperText Transfer Protocol is a set of rules which is used to retrieve linked
web pages across the web. The more secure and advanced version is HTTPS.
21. Domain name - Each computer server hosting a website or web resource is given a name
against its IP address. These names are called the Domain names or hostnames.
22. Domain name resolution-Conversion of the domain name of each web server to its
corresponding IP address is called domain name resolution. It is done through a server called
DNS server.
23. Switching- It is the technique by which nodes control or switch data to transmit it between
specific points on a network. There are 3 common switching techniques: Circuit Switching.
Packet Switching.
24. Circuit switching- In this technique, first a physical path is obtained and dedicated to a single
connection between two endpoints in the network for the duration of a dedicated connection,
and thereafter communication takes place. Ordinary voice phone service uses circuit
switching. Traditional telephone systems (landlines) are examples of a technology that uses
circuit switching.
25. Message switching- In this technique, end-users communicate by sending and
receiving messages wherein, the sender and receiver are not directly connected. There are
a number of intermediate nodes that transfer data and ensure that the message reaches its
destination. It works on store and forward technique. Mobile sms is an example for it.
146
26. Packet switching- In this transfer of small pieces of data across various networks takes place.
These data chunks or “packets” allow for faster, more efficient data transfer.
Examples: Frame Relay, IP, and X. 25
27. Difference between Packet and message switching techniques
Message Switching Packet Switching
A complete message is passed across a
network.
Message is broken into smaller units
known as Packets.
In this, computer language used is ASCII Here, binary type is used.
In message switching there is no limit on
block size.
Packet switching places a tight upper
limit on block size.
147
Message exist only in one location in the
network.
Parts i.e. packets of the message exist in
many places in the network.
Physical links are allocated dynamically. Virtual links are made simultaneously.
Access time is reduced due to increase in
performance as packets are stored in disk. Packets are stored in main memory.
28. Hacker- A computer enthusiast, who uses his computer programming skill to intentionally
access a computer without authorization is known as hacker. A hacker accesses the computer
without the intention of destroying data or maliciously harming the computer.
29. Transmission media-Transmission media is a communication channel that carries the
information from the sender to the receiver.
30. Types of Transmission Media
In data communication terminology, a transmission medium is a physical path between the
transmitter and the receiver i.e. it is the channel through which data is sent from one place
to another. Transmission Media is broadly classified into the following types:
a-Guided Media: It is also referred to as Wired or Bounded transmission media. Signals being
transmitted are directed and confined in a narrow pathway by using physical links.
Features:
• High Speed
• Secure
• Used for comparatively shorter distances
b- Unguided media – By means of waves. Examples: Infrared, Radiowave, Microwave and
Satellite.
There are 3 major types of Guided Media:
(i) Twisted Pair Cable –
It consists of 2 separately insulated conductor wires wound about each other. Generally, several
such pairs are bundled together in a protective sheath. They are the most widely used Transmission
Media. Twisted Pair is of two types:
• Unshielded Twisted Pair (UTP):
UTP consists of two insulated copper wires twisted around one another. This type of
cable has the ability to block interference and does not depend on a physical shield for
this purpose. It is used for telephonic applications.
148
Advantages:
⇢ Least expensive
⇢ Easy to install
⇢ High-speed capacity
⇢ Susceptible to external interference
⇢ Lower capacity and performance in comparison to STP
⇢ Short distance transmission due to attenuation
• Shielded Twisted Pair (STP):
This type of cable consists of a special jacket (a copper braid covering or a foil shield)
to block external interference. It is used in fast-data-rate Ethernet and in voice and data
channels of telephone lines.
Advantages:
⇢ Better performance at a higher data rate in comparison to UTP
⇢ Eliminates crosstalk
⇢ Comparatively faster
⇢ Comparatively difficult to install and manufacture
⇢ More expensive and Bulky
(ii) Coaxial Cable
It has an outer plastic covering containing an insulation layer made of PVC or Teflon and 2 parallel
conductors each having a separate insulated protection cover. The coaxial cable transmits
information in two modes: Baseband mode(dedicated cable bandwidth) and Broadband mode(cable
bandwidth is split into separate ranges). Cable TVs and analog television networks widely use
Coaxial cables.
149
Advantages:
• High Bandwidth
• Better noise Immunity
• Easy to install and expand
• Inexpensive
Disadvantages:
• Single cable failure can disrupt the entire network
(iii) Optical Fiber Cable –
It uses the concept of refraction of light through a core made up of glass or plastic. The core is
surrounded by a less dense glass or plastic covering called the cladding. It is used for the
transmission of large volumes of data.
The cable can be unidirectional or bidirectional. The WDM (Wavelength Division Multiplexer)
supports two modes, namely unidirectional and bidirectional mode.
Advantages:
• Increased capacity and bandwidth
• Lightweight
• Less signal attenuation
• Immunity to electromagnetic interference
• Resistance to corrosive materials
Disadvantages:
• Difficult to install and maintain
• High cost
• Fragile
Worksheet – Solved questions
Question1:
Identify the Domain name and URL from the following:
150
http://www.income.in/home.aboutus.hml
Answer:
Domain name – income.in
URL – http://www.income.in/home.aboutus.hml
Question 2:
Write two characteristics of Wi-Fi.
Answer:It is wireless network.It is for short range.
Question 3:
What is cloud computing?
Answer:
The sharing of compute resources (dedicated, time-shared, or dynamically shared
servers) and related infrastructure components (load balancers, firewalls, network
storage, developer tools, monitors and management tools) to facilitate the
deployment and operation of web and network based applications. Cloud computing
relies on sharing of resources to achieve coherence and economies of scale, similar
to a utility (like the electricity grid) over a net-work.
Question 4:
Explain the purpose of a router.
Answer:
A router established connection between two networks and it can handle network
with different protocols. Using a routing table, routers make sure that the data packets
are travelling through the best possible paths
Question 5:
What are repeaters?
Answer:
A repeater is an electronic device that receives a signal and retransmits it at a higher
level and/ or higher power, or onto the other side of an obstruction, so that the signal
can cover longer distances.
Question 6:
What is VoIP?
Answer:
Voice over Internet Protocol (VoIP) is one of a family of internet technologies,
communication protocols, and transmission technologies for delivery of voice
communications and multi-media sessions over internet protocol (IP) network, such
as the internet.
151
Question 7:
Identify the type of topology from the following:
1. Each node is connected with the help of a single cable
2. Each node is connected with the help of independent cable with central switching.
Answer:
1. Bus topology
2. Star topology
Question 8:
Mahesh wants to transfer data within a city at very high speed. Write the wired
transmission medium and type of network.
Answer:
Wired transmission medium – Optical fibre cable Type of network – MAN.
Question 9:
Indian School, in Mumbai is starting up the network between its different wings. There are four
Buildings named as SENIOR, JUNIOR, ADMIN and HOSTEL as shown below:
The distance between various buildings is as follows:
152
Number of Computers in Each Building :
1. Suggest the cable layout of connections between the buildings.
2. Suggest the most suitable place (i.e., building) to house the server of this school,
provide a suitable reason.
3. Suggest the placement of the following devices with justification.
o Repeater
o Hub/Switch
4. The organisation also has inquiry office in another city about 50-60 km away in hilly
region. Suggest the suitable transmission media to interconnect to school and inquiry
office out of the following :
o Fiber optic cable
o Microwave
o Radiowave
Answers:
1.
2. Server can be placed in the ADMIN building as it has the maxium number of
computer.
3. Repeater can be placed between ADMIN
and SENIOR building as the distance is more than 110 m.
4. Radiowaves can be used in hilly regions as they can travel through obstacles.
Question 10:
Write any two differences between twisted pair and co-axial pair cable.
Answer:
153
Question 11:
The following is a 32 bit binary number usually represented as 4 decimal values, each
representing 8 bits, in the range 0 to 255 (known as octets) separated by decimal points.
140.179.220.200. What is it? What is its importance?
Answer:
It is an IP Address. It is used to identify the computers on a network.
Question 12:
What is the difference between domain name
and IP address?
Answer:
Domain Name is alphanumeric address of a resource over network and IP address is a Numeric
Address of a resource in a Network.
Example:
Domain Name- google.com and wikipedia.org
IP Address- 102.112.0.153
UNSOLVED QUESTIONS
Question 1:
In mid 80’s another federal agency, the NSF created a new high capacity network called
NSFnet, which was more capable than ARPANET. The only drawback of NSFnet
was that it allowed only academic research on its network and not any kind of private
business on it. Now, several private organisations and people started working to build
their own networks, named private networks, which were later (in 1990’s) connected
with ARPANET and NSFnet to form the Internet. The Internet really became popular
in 1990’s after the development of World Wide Web.
154
(i). NSFnet stand for _______________________
(ii). ARPANET stand for _______________
(iii).An interconnection of different networks is called ____________
(iv).To join the internet, the computer has to be connected to a _________
(v). Internet access by transmitting digital data over the wires of a local telephone
network is provided by ____________
(vi).A piece of icon or image on a webpage associated with another webpage is called
Question2:
TCP/IP, or the Transmission Control Protocol/Internet Protocol, is a suite of communication
protocols used to interconnect network devices on the internet. TCP/IP can also be used as
a communications protocol in a private computer network (an intranet or an extranet).
TCP defines how applications can create channels of communication across a network.It also
manages how a message is assembled into smaller packets before they are then transmitted
over the internet and reassembled in the right order at the destination address.
IP defines how to address and route each packet to make sure it reaches the right destination.
Each gateway computer on the network checks this IP address to determine where to
forward the message. TCP/IP uses the client-server model of communication in which a
user or machine (a client) is provided a service (like sending a webpage) by another
computer (a server) in the network. Collectively, the TCP/IP suite of protocols is classified
as stateless, which means each client request is considered new because it is unrelated to
previous requests. Being stateless frees up network paths so they can be used continuously.
(i). Which of the following protocols is used in the internet?
a. HTTP b. DHCP c. DNS d.All of these
(ii). Which protocol assigns IP address to the client connected to the internet?
a.DHCP b. IP c.RPC d. RSVP
(iii).Several protocols for upper layers in Bluetooth use:
a.UDP b.HSP c.ITC d. L2CAP
(iv).Internet protocols are a set of rules to govern:
a.communication between computers on a network
b.bandwidth
c.standard communication
d.metropolitan communication
155
(v). Network layer at source is responsible for creating a packet from data coming from another
a.station b. link c. node d. protocol
Question3:
Web server is a special computer system running on HTTP through webpages. The web page
is a medium to carry data from one computer system to another. The working of the web
server starts from the client or user. The client sends their request through the web browser
to the web server. Web server takes this request, processes it and then sends back processed
data to the client. The server gathers all of our web page information and sends it to the
user, which we see on our computer system in the form of a web page. When the client
sends a request for processing to the web server, a domain name and IP address are
important to the web server. The domain name and IP address are used to identify the user
on a large network.
(i). Web servers are:
a.IP addresses b.Computer systems
c.Webpages of a site d.A medium to carry data from one computer to another
(ii).What does the webserver need to send back information to the user?
a.Home address b.Domain name c.IP address d.Both b and c
(iii). What is the fullform of HTTP?
a.Hypertext Transfer Protocol b.Hypertext Transfer Procedure
c.Hyperlink Transfer Protocol d.Hyperlink Transfer Procedure
(iv).The __________translates internet domain and hostnames to IP address
a.Domain name system b.Routing information protocol
c. Google d.Network time protocol
(v).Computer that requests the resources or data from other computer is called as computer
a.Server b.Client c.None of the above d. Options a&b
(vi). DNS stands for:
a. Domain Name Security b.Domain Number System
c.Document Name System d.Domain Name System
156
(vii). What is the format of IP address?
a.34bit b.32 bit c.16bit d.64 bit
Question4:
GyanDeep International School is planning to connect all computers, each spread over a
distance within 40 m. Suggest an economical cable type having high-speed data transfer,
which can be used to connect these computers
Question5:
Mr. Taufiq Ahmad wants to prevent unauthorised access to/from his company’s local area
network. Write the name of system (software/hardware), which he should install.
Question6:
Beauty Lines Fashion Inc. is a fashion company with design unit and market unit 135 m away
from each other. The company recently connected their LANs using Ethernet cable to share
the stock related information. But after joining their LANs, they are not able to share the
information due to loss of signal in between. Which device out of the following should you
suggest to be installed for a smooth communication?
UPS/Modem /Repeater
Question7:
Refer to the following diagram and answer the questions given below.
(i). Which of the following devices acts as a server?
a.A b.B c.C d.D
(ii). The arrow from device D to pointing to A represents?
a. HTTP request b.HTTP response
157
c.HTTP request & response d.All of these
(iii).Which of the following device(s) can have IP Addresses?
a.A b.D c.F d.All the devices
(iv).Identify the network topology of the above network:
a.Ring b. Star c.Bus d.None of these
(v). ____is a protocol to transmit files (data) over the world wide web.
a.FTP b.HTTP c. SMP d.None of the above
Question 8:
Trine Tech Corporation (TTC) is a professional consultancy company. The company is planning to
set up their new offices in India with its hub at Hyderabad. As a network adviser, you have to
understand their requirement and suggest them the best available solutions. Their queries are
mentioned as (i) to (iv) below.
Physical Locations of the blocked of TTC
158
1. What will be the most appropriate block, where TTC should plan to install their
server?
2. Draw a block to cable layout to connect all the buildings in the most appropriate
manner for efficient communication.
3. What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bangalore with its London based office:
o Satellite Link
o Infrared
o Ethernet Cable
4. Which of the following device will be suggested by you to connect each computer in
each of the buildings:
o Switch
o Modem
o Gateway
Question 9:
Identify the following devices:
(i) Devices that are used to connect different types of networks. It performs the
necessary translation so that the connected networks can communicate properly.
(ii) A device that converts data from digital bit stream into an analog signal and vice-versa.
Question 10:
Rovenza Communications International (RCI) is an online corporate training provider company for
IT related courses. The company is setting up their new campus in Kolkata. You as a network
expert have to study the physical locations of various blocks and the number of computers to be
installed. In the planning phase, provide the best possible answers for the queries (i) to (iv) raised
by them.
159
Block to Block Distances(in Mtrs.)
Expected computers to be installed in each block
1. Suggest the most appropriate block, where RCI should plan to install the server.
2. Suggest the most appropriate block to block cable layout to connect all three blocks
for efficient communication.
3. Which type of network out of the following is formed by connecting the computers of
these three blocks?
o LAN
o MAN
o WAN
4. Which wireless channel out of the following should be opted by RCI to connect to
students from all over the world?
o Infrared
o Microwave
o Satellite
160
UNIT – 3 DATABASE MANAGEMENT
MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database, information is stored in Tables. A
single MySQL database can contain many tables at once and store thousands of individual
records.
SQL (Structured Query Language)
SQL is a language that enables you to create and operate on relational databases, which are sets of
related information stored in tables.
ADVANTAGES OF USING DBMS
➢ Reducing data redundancy – This ensures a consistent database and efficient use of
storage space.
➢ Aiding multiple views of the data: Database management system enables different users
to have a view of the data from their own perspective
➢ Implementation of data integrity The term data integrity refers to the accuracy and
consistency of data. When creating databases, attention needs to be given to data integrity
and how to maintain it.
➢ Data sharing and security – DBMS limits the accessibility of the data to the authorized
users only. This makes data sharing safer. Moreover shared data makes it possible to fulfill
data requirements with minimal modifications.
➢ Centralized data ensures a more effective backup and recovery process than the
conventional file processing systems.
➢ Program & Data independence: Programs and the data are not mutually dependent. If a
programmer wants to change the structure of the database then he/she can do so without
affecting the application programs that are using the database.
➢ Data Abstraction: It ensures that the users get an abstract view of the data without showing
implementation details and the physical storage of thedata.
RELATIONAL MODEL TERMINOLOGY
1. Relation: A table storing logically related data is called a Relation.
161
2. Tuple: A row of a relation is generally referred to as a tuple.
3. Attribute: A column of a relation is generally referred to as an attribute.
4. Degree: This refers to the number of attributes in a relation.
5. Cardinality: This refers to the number of tuples in a relation.
6. Primary Key: This refers to a set of one or more attributes that can uniquely identify tuples
within the relation.
7. Candidate Key : All attribute combinations inside a relation that can serve as primary
key are candidate keys as these are candidates for primary key position.
8. Alternate Key: A candidate key that is not primary key, is called an alternate key.
9. Foreign Key : A non-key attribute, whose values are derived from the primary key of
some other table, is known as foreign key in its current table.
REFERENTIAL INTEGRITY
A referential integrity is a system of rules that a DBMS uses to ensure that relationships
between records in related tables are valid, and that users don’t accidentally delete or
change related data. This integrity is ensured by foreign key.
CLASSIFICATION OF SQL STATEMENTS
SQL commands can be mainly divided into following categories:
DATA TYPES
Data types are means to identify the type of data and associated operations for handling it.
MySQL data types are divided into three categories:
➢ Numeric
➢ Date and time
➢ String types
Numeric Datatype
1. int– used for number without decimal.
162
2. decimal(m,d) – used for floating/real numbers. m denotes the total length of number
and d is number of decimal digits.
Date and Time Datatype
1. date–used to store date in YYYY-MM-DD format.
2. time–used to store time in HH:MM:SS format.
String Datatype
1. char(m)–used to store a fixed length string, m denotes max. number of characters.
2. varchar(m)–used to store a variable length string, m denotes max. no. of characters.
DATABASE COMMANDS
1. VIEW EXISTING DATABASE
To view existing database names, the command is: SHOW DATABASES;
2. CREATING DATABASE IN MYSQL
For creating the database in MySQL, we write the following command:
CREATE DATABASE <databasename>;
e.g.In order to create a database Student, command is:
CREATE DATABASE Student;
3. ACCESSING A DATABASE
For accessing already existing database,we write:
USE<databasename>;
e.g.to access a database named Student, we write command as:
USE Student;
4. DELETING DATABASE
For deleting any existing database,the command is:
DROP DATABASE <databasename>;
e.g.to delete a database, say student, we write command as:
DROP DATABASE Student;
5. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database, command is:
SHOW TABLES;
CREATING TABLES IN MYSQL
Syntax of CREATE TABLE command is:
CREATE TABLE <table-name>(<colname> datatype,<colname> datatype,…);
E.g. Inorder to create table EMPLOYEE given below:
ECODE ENAME GENDER GRADE GROSS
Create table employee (ecode integer, ename varchar(20),gender char(1),grade char(2),gross
integer);
Inserting Data into Table:
Syntax:
Insert into <tablename> values(<v1>,<v2>,…);
Or
Insert into <tablename>(<column list> )values(<values list>);
163
Eg: insert into employee values(1001,‘Ravi’,‘M’,‘E4’,50000);
Or
Insert into employee(ecode,ename)values(1002,’Meena’);
The left out columns will be filled with null values.
Select Command:
It helps to display the records as per our requirement.
Different forms of select command:
1. Select * from employee;
It displays all rows and columns from the table.
2.Select ecode, ename from employee;
It displays selected columns from the table.
3.For displaying particular rows.
Syntax: select * from <tablename> where <cond>;
Eg. Select * from employee where gender=’M’;
4. ELIMINATING REDUNDANT DATA
The distinct keyword is used to eliminate duplicate records from the table.
Eg. Select distinct (gender) from employee;
DISTINCT(GENDER)
M
F
5. USING COLUMN ALIASES
The columns that we select in a query can be given a different name, i.e.column alias name for
output purpose.
Syntax: SELECT <columnname>AS column alias ,<columnname>AS column alias
…..FROM<tablename>;
Eg.select ecode as “EMP_Code” from employee;
CONDITION BASED ON A RANGE
The BETWEEN operator defines a range of values that the column values must fall into make the
condition true. The range include both lower value and upper value.
e.g.To display ECODE,ENAME and GRADE of those employees whose salary is between 40000
and 50000,command is:
SELECT ECODE , ENAME ,GRADE FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000;
164
NOTE: For displaying records not in the specified range, we have to use not between operator.
CONDITION BASED ON A LIST
The in operator is used to display records based on a list of values.
Eg. To display details of employees who have scored A,B and C grades.
Select * from employee where grade in(‘A’,’B’,’C’);
Note: For displaying records that do not match in the list, we have to use not in operator.
CONDITION BASED ON PATTERN MATCHES
LIKE operator is used for pattern matching in SQL. Patterns are described using two special
wildcard characters: % and _ (underscore)
1. percent(%)– The % character matches any substring.
2. underscore(_)– The _ character matches any single character.
e.g.To display names of employee whose name starts with R in EMPLOYEE table, the command is:
select ename from employee where ename like “R%”;
e.g. To display details of employee whose second character in name is:
select * from employee where ename like ‘_e%’;
SEARCHING FOR NULL
The NULL value in a column can be searched for in a table using IS NULL in the WHERE
clause. E.g. to list employee details whose salary contain NULL, we use the command:
Select * from employee where gross is null;
Note: For listing employees who earn salary, then it is:
Select * from employee where gross is not null;
Relational Operators
• To compare two values, a relational operator is used. The result of the comparison is true or false.
Relational Operators recognized by SQL: =, >, <, <=, >=, <> (not equal or !=)
Eg. Select * from employee where ecode <> 1001;
Above query will not display those employee details whose ecode column value is 1001.
Logical Operators- (OR, AND, NOT)
1) To list the employee details having grades E2 or E3.
Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’);
2) To list all the employees’ details having grades as ‘E4’ but with gross < 9000.
165
Select ecode, ename, grade, gross from employee where grade=‘E4’ and gross< 9000;
3) To list all the employees’ details whose grades are other than ‘G1’.
Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);
Sorting Results- ORDER BY clause
Results of SQL query can be sorted in a specific order using ORDER BY clause.
The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be
done either in ascending or descending order.
Eg. Select * from emp order by ename;
Above query arranges the records in alphabetical order of ename value. By default order by clause
arranges in ascending order.
TO DISPLAY RECORDS IN DESCENDING ORDER
❖ Select * from employee order by ename desc;
Above query gives output in descending order of ename.
❖ Select * from employee ORDER BY grade DESC, ename ASC;
Above query displays records first in the descending order of grade and within the same
grade, employees are displayed in the ascending order of Ename.
SQL AGGREGATE FUNCTIONS:
All the aggregate functions ignore null values except count(*).
Avg – to compute average value
Min – to find minimum value
Max – to find maximum value
Sum – to find total value
Count – to count non-null values in a column
Count( *) – to count total number of rows in a table including null values.
Examples:
Select avg(gross) from employee;
Select min(gross) from employee where deptno= 10;
Select count(*) from emp where gross> 10000;
Select count (DISTINCT gender) from employee;
GROUP BY Clause
GROUP BY clause is used in SELECT statements to display the table contents based on similar
values in a column into groups.
166
Eg: To calculate the number of employees in each grade, the query is:
SELECT grade, count(*) from employee group by grade;
Placing conditions on Groups HAVING Clause
❖ The HAVING clause places conditions on groups in contrast to WHERE clause that places
conditions on individual rows.
❖ WHERE conditions cannot include aggregate functions but HAVING conditions can do so.
Eg: SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’ ;
DELETE Command
This command removes rows from a table.
Syntax: DELETE FROM <tablename> [WHERE <cond>];
Eg: To remove all the contents of items table, the query is:
DELETE from items;
Eg: To remove the tuples from employee that have gross less than 20000 is :
DELETE from employee WHERE gross<20000;
UPDATE Command
Update Command allows to change some or all the values in an existing rows. Update command
specifies the rows to be changed using the WHERE clause and the new data using the SET
keyword.
Eg. UPDATE employee SET gross= 25000;
The above query sets the gross of all records as 25000.
UPDATE employee SET gross=40000, grade=’A’ WHERE ecode=1001;
The above query changes the gross and grade values for the record with ecode 1001.
ALTER TABLE
ALTER TABLE command is used to change the structure of the existing table. It can be used to add
or drop new columns or modify the existing columns of table.
Eg. 1. Alter table Employee Add comm int;
2. ALTER TABLE Emp MODIFY (ename varchar(60));
3. Alter table emp drop comm;
DROP TABLE:
DROP TABLE command allows to remove a table from database. Once the DROP command is
issued, the table will no longer be available in the database.
167
Eg. DROP TABLE employee;
INTEGRITY CONSTRAINTS
A constraint is a condition or check applicable on a field or set of fields.
Common types of constraints include:
S.No.Constraints Description
1 NOT NULL Ensures that a column cannot have NULL value
2 DEFAULT Provides a default value for a column when none is
specified
3 UNIQUE Ensures that all values in a column are different
4 PRIMARY KEY Used to uniquely identify a row in the table
5 FOREIGN KEY Used to ensure referential integrity of the data
ADDING CONSTRAINT TO A TABLE
ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:
Eg: alter table employee add primary key(ecode);
REMOVING CONSTRAINTS FROM A TABLE
Eg: alter table employee drop primary key;
Setting primary and foreign key constraint:
Eg: CREATE TABLE STUDENT(ROLL_NO integer PRIMARY KEY ,NAME
VARCHAR(30),CLASSVARCHAR(3));
CREATE TABLE SCORE(ROLL_NO integer ,MARKS integer, FOREIGN KEY(ROLL_NO)
REFERENCES STUDENT(ROLL_NO));
SQL JOINS
SQL Joins are essential to display data from more than one table. SQL JOIN clause is used to
combine rows from two or more tables, based on a common field between them. SQL provides
various types of joins:
1. Cartesian Product or Cross Join
2. Equi-Join
3. Natural Join.
Cartesian Product (Cross Join)
Cartesian product of two tables is obtained by pairing up each row of one table with each row of
the other table.
168
❖ The number of columns in the Cartesian product is the sum of the number of columns in
both the tables.
❖ The number of rows in the Cartesian product is the product of rows of the tables.
Example:
Equi-Join
A join which is obtained by putting a condition of equality on cross join is called an 'equi join'.
We can extract meaningful information from the Cartesian product by placing some conditions in the
statement.
The join in which columns are compared for equality is called equi-join.
In this type of join we put * in the select list therefore the common column will appear twice in the
output.
Example: Consider the 2 tables emp and dept.
On performing equi-join, the result is as follows:
169
Note: We see that deptno column appears twice in output.
Natural Join
• The join in which only one of the identical columns exists is called natural join.
• It is similar to equi-join except that duplicate columns are eliminated in natural join that would
otherwise appear in equi-join.
Example:
Note: We see that deptno column appears only once in output.
Worksheet – L3
Q1. What does the abbreviation DBMS stand for?
(a) Data Borrowing and Movement Software.
(b) Database Management System.
(c) DigitalBase Mapping System.
(d) Database Manipulation Software.
Q2. Which is not an advantage of DBMS?
(a) Database Systems reduce data redundancy
(b) Database Systems control data inconsistency
(c) Database Systems restrict sharing of data
(d) Database Systems ensure data security.
Q3. In ..............,the data is organized into tables i.e. rows &columns.
170
(a) Relational Model
(b) Network Model
(c) Hierarchical Model
(d) ObjectOriented Model
Q4. The essential features of Object Oriented Data Model are;
(a) Object identity
(b) Encapsulation
(c) DataAbstraction
(d) All of the above
Q5. Which statement is false in context to the term Relation?
(a) Relation is a table storing logically related data.
(b) Data must be atomic in cell
(c) All rows of relation are distinct.
(d) Ordering of rows & columns is relevant.
Q6. A row of relation generally referred to as.............and column of a relation is
…………
(a) Domain & Attribute
(b) Attribute & Domain
(c) Tuple & Attribute
(d) Attribute & Tuple
Q7. A relation has 45 tuples & 5 attributes, what will be the Degree & Cardinality
of that relation?
(a) Degree5,Cardinality45
(b) Degree45,Cardinality5
(c) Degree50,Cardinality45
(d) Degree50,Cardinality2250
Q8. Is the attribute or group of attributes that uniquely identify
occurrence of each entity.
(a) Foreign key
(b) Super Key
(c) Primary Key
(d) All of these
Q9. A Candidate key that is not a primary key, is called ……………
171
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key
Q10.A non-key attribute, whose values are derived from primary key of some other
table.
(a) Alternate key
(b) Foreign key
(c) Primary key
(d) Super Key
Q11. MySQL database system consists of-
(a) MySQLServerInstance
(b) MySQLDatabase
(c) MySQL Query Optimizer
(d) (a)&(b)both
Q12. Which commands are used to define or redefine schema objects?
(a) DDL
(b) DML
(c) TCL
(d) (a)&(b)both
Q13. Data definition includes:
(a) Creating of database
(b) Undoing changes to the database.
(c) Modification of data stored in the database.
(d) All of the above
Q14. Which is not a TCL command?
(a) Commit
(b) Rollback
(c) Exit
(d) Savepoint
Q15. Which is not a function of DML?
(a) Retrieval of data stored in the database
(b) Insertion of data into the database
(c) Deletion of data from the database
(d) Making changes permanent to the database.
Q16. Which is not a numeric type?
172
(a) Int
(b) Float
(c) Blob
(d) Double
Q17. The default date format in MySQL is:
(a) DD/MM/YYYY
(b) YYYY/MM/DD
(c) MM-DD-YYYY
(d) YYYY-MM-DD
Q18. Which is not a way to represent comment in MySQL?
(a)/*------------- */
(b) --
(c) #
(d) //
Q19. The command is used to access database in MySQL is-
(a) Open <databasename>;
(b) USE <databasename>;
(c) Access <databasename>;
(d) (a)&(b) both
20. Which is a valid CREATE TABLE statement?
(a) Create table emp add(id integer(3));
(b) Create table emp(id integers(3));
(c) Create table emp modified(id integer(3));
(d) Create table emp(id integer(3));
Q21. How can you insert a new row into the “STORE” table.
(a) INSERT ROW(1,‟RAMSINGH‟)INTO STORE;
(b) INSERT VALUES(1,‟RAMSINGH‟)INTO STORE;
(c) INSERT INTO(1,‟RAMSINGH‟)STORE;
(d) INSERT INTO STORE VALUES(1,‟RAMSINGH‟);
Q22. Select statement has four clauses 1.Where 2.Having 3.Group By
4.Orderby
The correct order of all clauses in a select is:-
(a)1,2,3&4
(b)1,3,2&4
(c)1,4,3&2
(d)1,3,4&2
173
Q23. Conditionally retrieval of rows from a table with SELECT, which clause is
used?
(a) Where
(b) Having
(c) Group By
(d) Order by
Q24. The.................. key word eliminates duplicate rows from the result of a
SELECT statement.
(a) All
(b) Unique
(c) Distinct
(d) IN
Q25. Which operator defines a range of values that the column values must fall in?
(a) In
(b) Like
(c) Between
(d) Is
Q26. To specify a list of values...............Operator is used.
(a) In
(b) Like
(c) Between
(d) Is
Q27. We use..................operator with select for condition based on pattern matching.
(a) In
(b) Like
(c) Between
(d) Is
Q28. Which SQL statement will not generate any error message?
(a) SELECT*FROM EMP WHERE EMPNO LIKE(1,2,3,4);
(b) SELECT*FROM EMP WHERE SAL BETWEEN 3000 TO 15000;
(c) SELECT*FROM EMP WHERE COMM IS NOT NULL;
(d) All of the above
Q29.To display the detail of employee having ‘e’ in their name in descending order of
salary. The correct SQL statement is:
(a) SELECT*FROM emp WHERE ename LIKE “e%” ORDER BY SAL;
(b) SELECT*FROM emp ORDER BY SAL DESC WHERE ename LIKE
174
“%e%”;
(c) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY DESC
SAL;
(d) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY SAL
DESC;
Q30. Which statement is valid?
(a) ALTER TABLE EMPLOYEE MODIFY(last_name CHAR2(2000));
(b) ALTER TABLE EMPLOYEE CHANGE(last_name CHAR2(2000));
(c) ALTERTABLE EMPLOYEE CHANGE(last_name VARCHAR2(2000));
(d) ALTER TABLE EMPLOYEE MODIFY(last_name VARCHAR2(2000));
175
Answers
Q.No. Answers
1 B
2 C
3 A
4 d
5 d
6 c
7 a
8 c
9 a
10 b
11 d
12 a
13 a
14 c
15 d
16 c
17 d
18 d
19 b
20 d
21 d
22 b
23 a
24 c
25 c
26 a
27 b
28 c
29 d
30 d
176
WORK SHEET -2
Q1. Which is true in respect of Select Statement?
(a) By Select we can retrieve all the rows from table.
(b) By Where clause with select we can retrieve selected rows from table.
(c) We can retrieve unique rows from table with the use of Distinct keyword.
(d) All of the above.
Q2. The clause which is used to group rows based on distinct values that exist
for specified column.
(a) Group by clause
(b) Having clause
(c) Order by Clause
(d) Where Clause
Q3. For conditionally retrieval of row from groups which clause is used?
(a) Where clause
(b) Having Clause
(c) Order By Clause
(d) (a)&(b)both
Q4. Group functions are also known as.
(a) Aggregate functions
(b) Multiple row functions
(c) Single row functions
(d) (a)&(b)both
Q5.Which option cause a group function to consider only distinct values.
(a) All
(b) Distinct
(c) Unique
(d) Diverse
Q6. Which option cause a group functions to consider all values including
all duplicated.
(a) All
(b) Distinct
(c) Unique
177
(d) Diverse
Q7. Which is not a group function?
(a) AVG
(b) COUNT
(c) MAX
(d) MOD
Consider the relations/tables EMP and DEPT and give the correct answer of following
queries.
Relation: EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20
7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20
7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10
7788 SCOTT ANALYST 7566 1982-12-09 3000.00 NULL 20
7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10
7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30
7876 ADAMS CLERK 7788 1983-01-12 1100.00 NULL 20
7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30
7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20
7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10
Relation: DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEWYORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Q8. SELECT AVG(SAL) FROM EMP WHERE JOB=‘CLERK’;
(a)1037.5
(b)2073.21
(c)1040
(d)2074
Q9. SELECT COUNT(*) FROM EMP WHERE DEPTNO=10;
(a) 14
(b) 3
(c) 4
(d) 5
178
Q10. SELECT COUNT(DISTINCT JOB) FROMEMP;
(a) 14
(b) 5
(c) 4
(d) 6
Q11. SELECT COUNT(ALL JOB)FROM EMP;
(a) 14
(b) 5
(c) 4
(d) 6
Q12. SELECT MAX(SAL) FROM EMP WHERE JOB=‘MANAGER’;
(a)2975
(b)5000
(c)3000
(d)2850
Q13. SELECT MIN(HIREDATE) FROM EMP;
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None
Q14. SELECT MAX(HIREDATE) FROM EMP;
(a) 1980-12-17
(b) 1983-01-12
(c) 1982-12-09
(d)None
Q15. SELECT SUM(COMM) FROM EMP;
(a) Null
(b) 0
(c)2200
(d)1400
Q16.Which statement is used to display the total no. of employees in each
department?
(a) SELECT COUNT(*) FROM EMP WHERE DEPTNO;
179
(b) SELECTCOUNT(*)FROMEMPGROUPBYDEPTNO;
(c) SELECTCOUNT(DEPTNO)FROMEMPGROUPBYDEPTNO;
(d) (b)&(c)both
Q17. To display the jobs where the number of employees is less than 3.
(a) SELECT JOB,COUNT(*)FROM EMP WHERE COUNT(*)<3;
(b) SELECT JOB, COUNT(*) FROM EMP WHERE COUNT(*)<3
GROUP BY JOB;
(c) SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB WHERE
COUNT(*)<3;
(d) SELECT JOB,COUNT(*)FROM EMP GROUP BY JOB HAVING COUNT(*)
<3;
Q18.Which join is used for display all possible concatenations are formed of all
rows of two or more tables.
(a) Unrestricted join
(b) Cartesian Join
(c) Equi Join
(d) (a)&(b) both
Q19. How many rows are returned when we execute ‘SELECT*FROM EMP,DEPT’;
(a) 14
(b) 4
(c) 18
(d) 56
Q20.To display the name of employee & department name the MySQL statement
used:
(a) SELECT ENAME, DNAME FROM EMP,DEPT;
(b) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE DEPTNO=DEPTNO;
(c) SELECT ENAME, DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
(d) None of the above
Q21.The join where columns are compared for equality is called………………
(a) Equi Join
(b) Natural Join
(c) Cross Join
(d) Right Join
180
Q22. The join in which only one identical column exists is called………
(a) Equi Join
(b) Natural Join
(c) Cross Join
(d) Right Join
Q23. Which statement represent Cartesian join?
(a) SELECT*FROM EMP,DEPT;
(b) SELECT*FROM EMP JOIN DEPT;
(c) SELECT*FROM EMP CROSS JOIN DEPT;
(d) All of the above
Q24. Using sub-clause with JOIN causes a................join where as on sub-clause
with JOIN produces.......... join.
(a) Natural & Equi
(b) Equi & Natural
(c) Cross & Equi
(d) Natural & Cross.
Q25. Scalar functions are also known as:
(a) Single row function
(b) Multiple row function
(c) Group functions
(d) None
Answers
Q.No. Answers
1 A
2 C
3 C
4 A
5 C
6 C
7 D
8 D
9 B
10 C
11 B
12 B
13 D
14 A
15 B
16 D
17 B
18 A
19 D
20 A
21 B
22 B
23 A
24 A
25 a
182 | P a g e
INTERFACE PYTHON WITH MYSQL
Basically the process of transfer data between python programs and MySQL database is known as Python
Database Connectivity.
There few steps you have to follow to perform Python Database Connectivity. These steps are as follow:
1. Import the required packages
2. Establish a connection
3. Execute SQL command
4. Process as per the requirements
Importtherequired packages
To perform the Python MySQL Database Connectivity you need to install mysql-connector-python package
using pip command.
pip install mysql connector python
After installation just write the import statement to import the package in python code.
import mysql.connector as msql
importing package mysql connector in python
Here I have instantiated msql to mysql.connector which can be work as an alias name for the connector.
Establishaconnection
To establish a connection you need to create a connection object in Python. Take a variable as a connection
object and use connect() function with MySQL database specification like host name, username,
passoword or passwd and database itself. For example cn. Observe the code:
import mysql.connector as msql
cn=msql.connect(host='localhost',user='root',passwd='root',database='Studentdb')
Please ensure that you have provided appropriate username, password and database name available in your
MySQL interface.
After doing this, check for the errors if any. If your program runs without errors that means connection is
established. Although you can use is_connected() function to check whether the connection is established
or not! Observe this code:
import mysql.connector as msql
183 | P a g e
cn=msql.connect(host='localhost',user='root',passwd='root',database='Student')
if cn.is_connected():
print("Connection Established")
else:
print("Connection Errors! Kindly check!!!")
ExecuteSQLcommandandfetchrows
The next step after the successful connection is to write SQL command and fetch rows. The SQL
commands are used to perform DML operations and fetch rows read data from table. So we will see them in
detail later.
You have to create a cursor object for executing SQL command and fetch rows. Cursor object is a special
kind of structure that processes the data row by row in database. You can create cursor object in the
following manner.
cur=cn.cursor()
PerformingDMLoperations(insert,updateanddelete)
To perform the DML operations like insert, update or delete follow these steps:
1. Create a cursor object
2. Write command as parameters for execute() function
3. Use commit() function to save the changes and reflect the data in the table.
insertcommand
Observe the following code:
import mysql.connector as msql
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("insert into students values(1111,'Asmita',78.50,'B1'))
cn.commit()
updatecommand
import mysql.connector as msql
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("update students set marks=80.5 where rollno=1111")
cn.commit()
deletecommand
import mysql.connector as msql
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
184 | P a g e
cur.execute("delete from students where rollno=1111")
cn.commit()
SelectCommand
As you know the select command is used retrieve records from the database. The result is available in the
resultset or dataset. You can store the select the command in cursor object in python. Then for resultset you
can use the fetch…() function. These are:
1. fetchall(): It will retrieve all data from a database table in form of record or tuple or a row.
2. fetchone(): It will retrieve one record from the resultset as a tuple or a list. It returns the records in a
specific order like first record, the next time next record and so on. If records are not available then
it will return None.
3. fetchmany(n): It will retrieve a number of records from the database. If records are not available
then it will return an empty tuple.
4. rowcount: It is one of the properties of cursor object that return number of rows fetched from the
cursor object.
Observe the below-given code for fetchall() function:
import mysql.connector as msql
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")
d=cursor.fetchall()
for r in d:
print(r)
Observe the below-given code for fetchmany(n) function:
import mysql.connector as msql
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")
d=cursor.fetchmany(3)
for r in d:
print(r)
The above code will return 3 rows from the database.
Observe the below-given code for fetchone() function:
import mysql.connector as msql
import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
cur.execute("select * from students")
185 | P a g e
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
print(d)
time.sleep(3)
d=cur.fetchone()
time.sleep(3)
print(d)
Parameterized Queries
Sometimes we need to access values as per the user’s input. The query result is based on the values user has
passed. So for that we have this option parameterized queries. There are two ways to use parameterized
queries:
1. with % formatting pattern
2. with {}.format pattern
with % formatting pattern
This pattern takes the general form – f % v, where f is a format and v is the value. Consider the following
code:
import mysql.connector as msql
import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
cur=cn.cursor()
#display records more than 80%
cur.execute("select * from students where marks >%s" %(80,))
d=cur.fetchall()
for r in d:
print(r)
#display records having B1 grade
cur.execute("select * from students where grade='%s'" %('B1',))
d=cur.fetchall()
for r in d:
print(r)
with {}.formatpattern
In this pattern you can write {} where the value is placed followed by .format(values). Consider the
following code:
import mysql.connector as msql
import time
cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
186 | P a g e
cur=cn.cursor()
cur.execute("select * from students where marks >{}" .format(80))
d=cur.fetchall()
for r in d:
print(r)
cur.execute("select * from students where grade='{}'".format('B1'))
d=cur.fetchall()
for r in d:
print(r)
Closetheconnection
Finally, you have to close the established connect using close() function. It will help to clean up the
memory. Observe the following code:
con.close()
WORKSHEETS
L3 – Very Short Answer questions (1 mark)
1. Which package do we import in Python to establish MySQL connectivity ?
Ans. mysql.connector
2. What is the significance of using connect( ) function ?
Ans. connect( ) function is used to connect or establish a connection with MySQL database.
3. What is the role of execute( ) ?
Ans. The role of the execute function is execution of queries which are MySQL queries along
with Python interface.
4. What is the command to install mysql connector ?
Ans. pip install mysql-connector (OR)
pip install mysql-connector-python
5. What is a database connectivity ?
Ans. A database connectivity refers to the connection and communication between an
application and database system.
L3 – Multiple Choice Questions (1 mark)
1. A database _________ controls the connection to an actual database, established from within a
Python program.
(a) database object (b) connection object (c) fetch object (d) query object
187 | P a g e
Ans. (b)
2. The set of records retrieved after executing an SQL query over an established database connection is
called ___________ .
(a) table (b) sqlresult (c) result (d) resultset
Ans. (d)
3. A database _________ is a special control structure that facilitates the row by row processing of
records in the resultset.
(a) fetch (b) table (c) cursor (d) query
Ans. (c )
4. To obtain all the records retrieved, you may use the <cursor>. _______ method.
(a) fetchmany( ) (b) fetchall( ) (c) fetchone( ) (d) fetchmultiple( )
Ans. (b)
5. To reflect the changes made in the database permanently, you need to run <connection>. _______
method.
(a) done (b) reflect (c) commit (d) final
Ans. (c)
6. To run an SQL query within Python, you may use the <cursor>. _______ method.
(a) query (b) execute (c) run (d) None of the above
L2 – Short Answer Questions (2 marks)
1. What are the steps for creating database connectivity applications ?
Ans. To create database connectivity, follow the given steps:
Step 1: Start Python
Step 2: Import mysql.connector
Step 3: Open a connection to the database
Step 4: Create a cursor instance
Step 5: Execute a query
Step 6: Extract data from result set
Step 7. Clean up the environment
2. What is a connection? What is its role?
Ans. A connection (represented by the connection object) is the session between the application
program and database. To do anything with database, one must have a connection object.
3. What is a resultset?
Ans. A result set refers to a logical set of records that are fetched from the database by executing a
188 | P a g e
query and made available to the application program.
4. What is a database cursor?
Ans. A database cursor is a special control structure that facilitates row by row processing of records in
the result set, i.e., the set of records retrieved as per the query.
5. How to retrieve data from a table?
Ans. There are multiple ways to retrieve data:
i. fetchall( ) – fetches all the remaining rows of a query result, current pointer position
forwards
ii. fetchone( ) – fetches the next row as a sequence; returns None when no more data
L1 – Long Answer Questions (3 marks)
1. Write a Python code to connect to a database
Ans.
import mysql.connector
Mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,database=”project”)
Print(mycon)
2. How to create a database in MySQL through Python ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor( )
cursor.execute(“create database education”)
3. Write the Python code to display the present databases in MySQL
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“show databases”)
for i in cursor:
print(i)
4. How to create a table in MySQL through Python ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“create table student(admn_no int primary key,sname varchar(30),gender char(2),DOB
date, stream varchar(15), marks float”)
5. Write the Python code to insert data into a table in MYSQL
189 | P a g e
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
ano=int(input(“Enter admission no: “))
n=input(“Enter name: “)
g=input(“Enter gender:”)
dob=input(“Enter DOB: “)
s=input(“Enter stream: “)
m=float(input(“Enter marks:”))
query=”insert into student values({},’{}’,’{}’,’{}’,’{}’,’{}’,{})”.format(ano,n,g,dob,s,m)
cursor.execute(query)
mycon.commit( )
6. How to fetch data in Python from a table in MySQL ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“select * from student”)
for row in cursor:
print(row)
7. Write the Python code to update a record in the table
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“update student set marks=67 where admn_no=3456”)
mycon.commit( )
8. Write the Python code to delete a record from the table
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=”education”)
cursor=mycon.cursor()
cursor.execute(“delete from student where admn_no=3455”)
mycon.commit( )
*************
190 | P a g e
KENDRIYA VIDYALAYA SANGATHAN -CHENNAI REGION
CLASS-XII SESSION 2022-23
COMPUTER SCIENCE (083)
SAMPLE PAPER - I
Maximum Marks: 70 Time Allowed: 3 hours
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 Q35 against
part c only.
8. All programming questions are to be answered using Python Language only.
SECTION - A
1. The ___________ statement is an empty statement in Python. 1
2. Which of the following is not a keyword?
(a) eval (b) assert (c) nonlocal (d) pass
1
3. What will be the output for the following Python statements?
D= {“Amit”:90, “Reshma”:96, “Suhail”:92, “John”:95}
print(“John” in D, 90 in D, sep= “#”)
(a) True#False (b)True#True (c) False#True (d) False#False
1
4. What will the following Python statement evaluate to?
print (5 + 3 ** 2 / 2)
(a) 32 (b) 8.0 (c) 9.5 (d) 32.0
1
5. Consider the list aList=[ “SIPO”, [1,3,5,7]]. What would the following code print?
(a) S, 3 (b) S, 1 (c) I, 3 (d) I, 1
1
6. Which of the following mode in the file opening statement creates a new file if the file
does not exist?
(a) r+ (b) w+ (c) a+ (d) Both (b) and (c)
1
7. Which of the following is not an integrity constraint?
(a) Not null (b) Composite key (c) Primary key (d) Check
1
8. Choose the correct command to delete an attribute A from a relation R.
(a) ALTER TABLE R DELETE A
(b) ALTER TABLE R DROP A
(c) ALTER TABLE DROP A FROM R
1
191 | P a g e
(d) DELETE A FROM R
9. Identify the errors in the following code:
MyTuple1=(1, 2, 3) #Statement1
MyTuple2=(4) #Statement2
MyTuple1.append(4) #Statement3
print(MyTuple1, MyTuple2) #Statement4
(a) Statement 1 (b) Statement 2 (c) Statement 3 (d) Statement 2 &3
1
10. In the relational model, relationships among relations/table are created by using
_______ keys.
(a) composite (b) alternate (c) candidate (d) foreign
1
11. The correct statement to place the file handle fp1 to the 10th
byte from the current
position is:
(a) fp1.seek(10) (b) fp1.seek(10, 0)
(b) fp1.seek(10, 1) (d) fp1.seek(10, 2)
1
12. Which of the following aggregate functions ignore NULL values?
(a) COUNT (b) MAX (c) AVERAGE (d) All of these
1
13. _______ is a device that forwards data packets along networks.
(a) Gateway (b) Modem (c) Router (d) Switch
1
14. Suppose str1= ‘welcome’. All the following expression produce the same result except one.
Which one?
(a) str[ : : -6] (b) str[ : : -1][ : : -6] (c) str[ : :6] (d) str[0] + str[-1]
1
15. Which of the following is a DML command?
(a) SELECT (b) ALTER (c) CREATE (d) DROP
1
16. Mandatory arguments required to connect any database from Python are:
(a) Username, Password, Hostname, Database name, Port
(b) Username, Password, Hostname
(c) Username, Password, Hostname, Database Name
(d) Username, Password, Hostname, Port
1
Q17 and 18 are ASSERTION and REASONING based questions. Mark the correct
choice as:
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion (A): Keyword arguments are related to the function calls
Reason (R): When you use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.
1
18 Assertion (A): Text file stores information in ASCII or unicode characters. 1
192 | P a g e
Reason (R): In text file, there is no delimiter for a line.
SECTION-B
19 Identify the errors in the program segment given below. Rewrite the corrected code
and underline each correction.
def Tot (Number):
Sum=0
for C in RANGE (1, Number + 1):
Sum + = C
return Sum
print(Tot [3])
print(Tot[6])
2
20 Write two points of difference between HTTP and FTP.
OR
State the advantages and disadvantages of star topology over bus topology?
2
21 What will be the output of the following Python code?
d1={“a”:10, “b”=2, “c”:3}
str1= “ ”
for i in d1:
str1=str1+str(d1[i])+ “ ”
str2=str1[ : -1]
print(str2[: : -1])
2
22 What do you understand by Candidate keys in a table? Give a suitable example of
candidate keys from a table containing some meaningful data.
2
23 (i) Write the full forms of the following:
(a) SMTP (b) IPR
(ii) Which protocol is used in creating a connection with a remote machine?
2
24 What possible output(s) are expected to be displayed on screen at the time of execution
of the following code? Also specify the maximum and minimum value that can be
assigned to variable X.
import random
L=[10,7,21]
2
193 | P a g e
X=random.randint(1,2)
for i in range(X):
Y=random.randint(1,X)
print(L[Y],”$”,end=” ”)
(a) 10 $ 7 $ (b) 21 $ 7 $ (c) 21 $ 10 $ (d) 7 $
OR
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)
a=changer(a)
print(a,’$’,b)
25 Differentiate between Drop and Delete commands of MYSQL. Write its syntax.
OR
For a table “Company” having column cno, cname, department and salary, write the SQL
statement to display average salary of each department.
2
SECTION – C
26 Consider the following tables:
194 | P a g e
(i) Write any one point of difference between Equi join and Natural join.
(ii) Find output:
(a) select *from product p, supplier s where p.supid=s.supid;
(b) select *from product natural join supplier;
OR
(i) Write a Query to insert House_Name=Tulip, House_Captain= Rajesh and
House_Point=278 into table House(House_Name, House_Captain, House_Points).
(ii) Write the output for SQL queries (i) to (iv), which are based on the table: STUDENT
given below:
(i) SELECT COUNT(*), City FROM STUDENT GROUP BY CITY
HAVINGCOUNT(*)>1;
(ii) SELECT MAX(DOB),MIN(DOB) FROM STUDENT;
(iii) SELECT NAME,GENDER FROM STUDENT WHERE CITY=”Delhi”;
(iv) SELECT DISTINCT Class FROM STUDENT;
1
2
1
2
195 | P a g e
27 A text file “Quotes .Txt” has the following data written in it:
Living a life you can be proud of
Doing your best
Spending your time with people and activities that are important to you
Standing up for things that are right even when it’s hard
Becoming the best version of you
Write a user defined function to display the total number of words present in the file.
OR
Write a function in Python to count the number of lines in a text file ‘STORY.TXT’
which is starting with an alphabet ‘A’.
3
28. (i) Write the actual datatypes as per the following Structure requirement during
creation of a table:
(ii) Vani created a table named Customer that have fields Cno, Custname, Address,
Amount. Now she wants to increase the width to 30 Characters of the column
“Address”. Write the SQL command for it.
2
1
29 Write a function INDEX_LIST(L), where L is the list of elements passed as argument
to the function. The function returns another list named ‘indexList’ that stores the
indices of all Non-Zero Elements of L. For example: If L contains [12,4,0,11,0,56] The
indexList will have - [0,1,3,5]
3
30 Write a function in python, Push(Package) and Pop(Package) to add details of
employee contain information (Empid, Ename and Salary) in the form of tuple in
Package and delete a Package from a List of Package Description, considering them to
act as push and pop operations of the Stack data structure.
OR
Jiya has a list containing 8 integers. You need to help her create a program with two
user defined functions to perform the following operations based on this list.
• Traverse the content of the list and push those numbers into a stack which are
divisible by both 5 and 3.
• Pop and display the content of the stack.
3
196 | P a g e
For example: If the sample Content of the list is as follows:
L=[5,15,21,30,45,50,60,75] Sample Output of the code should be: 75 60 45 30 15
SECTION D
31 Alpha Pvt Ltd is setting up the network in Chennai. There are four blocks- Block A,
Block B, Block C & Block D.
Distance between various blocks are as given below:
Number of computers in each block are given below:
Block Number of Computers
Block A 85
Block B 28
Block C 43
Block D 20
i)Suggest the most suitable block to place the server with a suitable reason.
ii) Suggest the cable layout for connections between the various blocks.
iii) Suggest the placement of following devices with justification:
(a) Switch/Hub (b) Repeater
5
197 | P a g e
iv)The organization is planning to link its front office situated in the city in a hilly
region where cable connection is not possible. Suggest an economic way to connect
with reasonably high speed.
v) Out of following which type of Network it is LAN,MAN,WAN
32 (i) Find and write the output of the following Python code:
data=["P",20,"R",10,"S",30]
times=0
alpha=" "
add=0
for c in range(1,6,2):
times = times + c
alpha = alpha + data [c-1] + "$"
add = add + data[c]
print (times, add, alpha)
(ii) The given program is used to connect with MySQL abd show the name of the all
the record from the table “stmaster” from the database “oraclenk”. Write the missing
statements to complete the code.
import _____.connector_______ pymysql
dbcon=pymysql._____________(host=”localhost”, user=”root”,
________=”sia@1928”,database=” oraclenk”)
if dbcon.isconnected()==False:
print(“Error in establishing connection:”)
cur=dbcon.______________()
query= “select * from stmaster”
cur.execute(_________)
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.______()
2
3
198 | P a g e
OR
(i) Consider the program given below and justify the output.
c = 10
def add():
global c
c = c + 2
print("Inside add():", c)
add()
c=15
print("In main:", c)
Output:
Inside add() : 12
In main: 15
What is the output if “global c “ is not written in the function add()?
(ii) Avni is trying to connect Python with MySQL for her project. Help her to write the
python statement on the following:-
(i) Name the library, which should be imported to connect MySQL with Python.
(ii) Name the function, used to run SQL query in Python.
(iii) Write Python statement of connect function having the arguments values as :
Host name :192.168.11.111
User : root
Password: Admin
Database : MYPROJECT
2
3
199 | P a g e
33 (i) Differentiate between the writerow and writerows function.
(ii) Write a Program in Python that defines and calls the following user defined
functions:
(i) add() – To accept and add data of an employee to a CSV file
‘EMPLOYEE.CSV’. Each record consists of a list with field elements
as EId, EName and EPrice to store furniture id, furniture name and
furniture price respectively.
(ii) search()- To display the records of the furniture whose price is more
than 10000
OR
(i) State the difference between seek() and tell() functions of Python.
(ii) Write a Program in Python that defines and calls the following user defined
functions:
(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) COUNTR() – To count the number of records present in the CSV file
named ‘record.csv’.
2
3
2
3
SECTION-E
34 Consider the table MobileMaster
M_Id M_Company M_Name M_Price M_Mf_Date
MB001 Samsung Galaxy 13000 2014-02-12
MB002 Nokia N1100 7500 2011-04-15
MB003 Realme C35 12000 2021-11-20
MB004 Oppo SelfieEx 12500 2015-08-21
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as Primary
key.
(ii) If two columns are added and 2 rows are deleted from the table result, what
will be the new degree and cardinality of the above table?
(iii) Write the statements to:
a. To display details of those mobiles whose price isgreater than 8000.
b. Increase the M_Price of all mobiles manufactured after 2015-01-01 by 500.
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of mobileshaving price less than 8000.
b. Add a column REMARKS in the table with datatype as varchar with 50
characters
4
200 | P a g e
35 Alia has written a code and created a binary file EMPLOYEE.DAT with employeeid,
ename and salary. The file contains 10 records. He now has to update a record based
on the employee id entered by the user and update the salary. The updated record is
then to be written in the file updateemp.dat. The records which are not to be updated
also have to be written to the file updateemp.dat. If the employee id is not found, an
appropriate message should be displayed. As a Python expert, help him to complete the
following code based on the requirement given above:
import _______ #Statement 1
def update_data():
rec={}
fin=open("EMPLOYEE.DAT","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["employeeid"]==eid:
found=True
rec["salary"]=int(input("Enter new salary :: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
4
201 | P a g e
(ii) Write the correct statement required to open a temporary file named
updateemp.dat. (Statement 2)
(iii) Which statement should Alia fill in Statement 3 to read the data from the
binary file, EMPLOYEE.DAT and in Statement 4 to write the updated data
in the file, updateemp.dat?
COMPUTER SCIENCE (083)
SAMPLE PAPER - I MARKING SCHEME
Maximum Marks: 70 Time Allowed: 3 hours
1. pass (Q 1-18 – 1 Mark each)
2. a
3. a
4. c
5. I, 3
6. d
7. b
8. b
9. d
10. d
11. d
12. d
13. c
14. a
15. a
16. c
17. a
18. c
19. def Tot (Number):
Sum=0
for C in range (1, Number + 1):
Sum + = C (½ mark for each correction)
return Sum
print (Tot (3))
print (Tot(6)
20. HTTP - Hyper Text Transfer Protocol
- protocol used to transfer files from a web server to browser to view a webpage on the internet
- defines the format and transfers the webpage
FTP - File Transfer Protocol
- Protocol used to upload files from a workstation to a FTP server or download files from a
FTP server to a workstation
- Used to transfer the file from one system to another
(Any two differences. Each difference 1 mark)
OR
Advantages (Any two advantages and disadvantages – ½ mark each)
• Provide easy access for service or reconfiguration of the network
202 | P a g e
• One device per connection
• Simple access protocols
Disadvantages
• Central node dependency
• Long cable length
21. 3, 2, 01 (2 marks)
22. All attributes or group of attributes of a table that can identify a tuple uniquely is called a candidate key.
(1 mark)
ITEM
Ino Item Qt
I01 Pen 565
I02 Pencil 780
I03 CD 450
I04 Eraser 300
I05 Duster 200
Candidate keys – Ino, Item (Any example – 1 mark)
23. (a) SMTP – Simple Mail Transfer Protocol (½ mark each)
IPR – Intellectual Property Rights
(b) TELNET (1 mark)
24. (b) and (d) (1 mark)
Maximum value of X: 2 (½ mark each)
Minimum value of X: 1
OR
10 # 0 (Each line - ½ mark)
10 $ 20
1 # 0
1 $ 20
25. Delete - Data Manipulation Language (DML) command and used when you want to remove some or
all the tuples from a relation
Drop - Data Definition Language (DDL) command whichremoves the table from database
Syntax: (Definition – 1 mark ; Syntax: 1 mark)
Delete: DELETE FROM relation_name
WHERE condition;
Drop: Drop table tablename;
OR
SELECT department, avg(salary) from company Group by department; (2 marks)
26. Difference between equi join and natural join – 1 mark
Each output – 1 mark
OR
203 | P a g e
(i) insert into House values (‘Tulip’,’Rajesh’,278); (1 mark)
(ii) Each output ½ mark
27. def countwords( ):
S= open(“Quotes.txt”, “r”) (Opening the file in correct mode and closing – 1 mark)
f = S. read() ½ mark
z= f.split( ) ½ mark
for i in z: ½ mark
count = count + 1
print(“Total number of words”, count) ½ mark
S.close()
OR
def countlines():
file=open(“STORY.TXT”, “r”) (Opening the file in correct mode and closing – 1
mark)
lines= file.readlines() ½ mark
count=0
for w in lines:
if w[0]== ‘A’ or w[0]== ‘a’: 1 mark
count=count+1
print(“Total lines starting with A:”, count) ½ mark
file.close()
28.(i) PID – int(11)
ProdName – varchar(10)
DateofManufacture – Date
Price – float(7, 2)
(ii) ALTER TABLE Customer MODIFY Address(30);
29. def INDEX_LIST(L):
indexList=[]
for i in range(len(L)):
if L[i]!=0:
indexList.append(i)
return indexList
(½ mark for correct function header
1 mark for correct loop
1 mark for correct if statement
½ mark for return statement)
30. def Push(Package):
Empid=int(input(“Enter Id of Employee: "))
Ename=input(“Enter Name of employee”)
Salary= int(input(“Enter Salary of an employee”))
T=(Empid, Ename ,Salary)
Package.append(T)
def Pop(Package):
if (Package==[]):
print( "Stack empty")
204 | P a g e
else:
print ("Deleted element:",Package.pop())
OR
def PUSH(Arr,value):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%5 and Arr[x]%3==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
def popStack(st) :
if len(st)==0: # If stack is empty
print("Underflow")
else:
print(“Element deleted is”,st.pop( ))
31. (i) Block A
(ii) Any correct cable layout – 1 mark
(iii) (a) In all blocks
(b) To be placed between blocks where distance is greater than 70m
(iv) Radiowaves
(v) LAN
32. (i) 9 60 P$R$S$
(ii) import mysql.connectoraspymysql
dbcon=pymysql.connect(host=”localhost”, user=”root”, passwd=”sia@1928” ,database=” oraclenk”)
if dbcon.isconnected()==False
print(“Error in establishing connection:”)
cur=dbcon.cursor()
query=”select * from stmaster”
cur.execute(query)
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.close()
OR
(i) In the function add() global c is increment due to use of global keyword. In the main program
local c is printed as local takes precedence over global c. If global c is not used then c=c+2 will
show error as there is no local variable c in function.
(ii) (i) import mysql.connector
(ii) execute ()
(iii)mysql.connector.connect(host=”192.168.11.111”,user=”root”,passwd=”Admin”,databa 146
se=”MYPROJECT”)
33. (i) writerow() – 1 mark
205 | P a g e
writerows() – 1 mark
(ii) Definition of add() – 1 mark
Definition of search() – 1 mark
Function call – 1 mark
OR
(i) seek() – 1 mark
tell() – 1 mark
(ii) Definition of ADD() – 1 mark
Definition of COUNTR() – 1 mark
Function call – 1 mark
34. Each SQL statement 1 mark
35. (i) pickle (1 mark for correct module)
(ii) fout=open(‘updateemp.dat’, ‘wb’) (1 mark for correct statement)
(iii) Statement 3: pickle.load(fin)
Statement 4: pickle.dump(rec,fout) (1 mark for each correct statement)
KENDRIYA VIDYALAYA SANGATHAN – CHENNAI REGION
Class: XII Session: 2022-23
Computer Science (083)
Sample Question Paper - II
Maximum Marks: 70 Time Allowed: 3 hours
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 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 Q35 against part c only.
8. All programming questions are to be answered using Python Language only.
SECTION A
1. State whether True or False:
Variable names can begin with the _ symbol.
1
2. Identify which of the following is an invalid data type in Python:
(a) int (b) float (c) super (d) None
1
3. Consider the following code: 1
206 | P a g e
dict1 = {‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92, ‘Saritha’: 85}
What suitable code should be written to return a list of values in dict1 ?
4. Consider the following expression:
not True and False or not False
Which of the following will be the output:
a) True
b) False
c) None
d) NULL
1
5. Select the correct output of the following code:
>>>str1 = ‘India is a Great Country’
>>>str1.split(‘a’)
a) [‘India’,’is’,’a’,’Great’,’Country’]
b) [‘India’, ’is’, ’Great’, ’Country’]
c) [‘Indi’, ’is’, ’Gre’, ’t Country’]
d) [‘Indi’, ’is’, ’Gre’, ’t’, ‘Country’]
1
6. Which of the following is an invalid access mode for text files:
a) w
b) a+
c) ab
d) r
1
7. Fill in the blanks:
___________ command is used to add a new column in the table in SQL
1
8. Which of the following will display all the tables in a database:
a) SELECT * FROM <tablename>;
b) DISPLAY TABLES;
1
207 | P a g e
c) SHOW TABLES;
d) USE TABLES;
9. Which of the following will be the output of the code:
mySubject = “Computer Science”
print(mySubject[:3] + mySubject[3:])
a) Com
b) puter Science
c) Computer Science
d) Science Computer
1
10. Choose the correct option:
__________ is the number of columns in a table and ________ is the
number of rows in the table.
a) Cardinality, Degree
b) Degree, Cardinality
c) Domain, Range
d) Attribute, Tuple
1
11. The correct syntax of load( ) is:
a) <objectvariable> = pickle.load(<fileobject>)
b) pickle.load(<fileobject>, <objectvariable>)
c) <fileobject>.load(<objectvariable>)
d) <objectvariable> = <fileobject>.load( )
1
12. The _________clause is used to display result of an SQL query in ascending
or descending order with respect to specified attribute values
1
13. Fill in the blank:
________ is the protocol used for transferring files from one machine to
another.
a) HTTP
1
208 | P a g e
b) FTP
c) SMTP
d) VOIP
14. How will the following expression be evaluated in Python?
2 + 9 * ( ( 3 * 12) – 8 ) / 10
a) 29.2
b) 25.2
c) 27.2
d) 27
1
15. Which function is used to display the sum of values in a specified column ?
a) COUNT(column)
b) TOTAL(column)
c) SUM(column)
d) ADD(column)
1
16. To open a connector to the MySQL database, which statement is used to
connect with MySQL ?
a) connector
b) connect
c) password
d) username
1
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
:
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is False but R is True
17. Assertion (A) : A variable defined outside any function or any block is
known as a global variable.
Reason ( R ) : A variable defined inside any function or a block is known as
a local variable.
1
209 | P a g e
18. Assertion (A ) : The tell( ) method returns an integer that specifies the
current position of the file object in the file.
Reason ( R) : Offset can have any of the three values – 0, 1 and 2
1
SECTION B
19. Observe the following Python code very carefully and rewrite it after
removing all syntactical errors with each correction underlined.
DEF result_even( ):
x = input(“Enter a number”)
if (x % 2 = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
even ( )
2
20. Write two points of difference between LAN and WAN
(OR)
Write two points of difference between HTTP AND SMTP
2
21 (a) Given is a Python string declaration:
str1="!!Welcome to Python!!"
Write the output of: print(str1[::-2])
(b) Write the output of the code given below:
dict1 = {"name": "Suman", "age": 36}
dict1['age'] = 27
dict1['address'] = "Chennai"
1
1
210 | P a g e
print(dict1.keys())
22. Explain the use of Primary Key in a Relational Database Management
System. Give an example to support your answer.
2
23. (a) Expand the following:
i. XML
ii. HTML
(b) What is the use of PPP in computer networks ?
1
1
24. Predict the output of the following Python code:
def Bigger(N1,N2):
if N1>N2:
return N1
else:
return N2
L=[32,10,21,54,43]
for c in range (4,0,-1):
a=L[c]
b=L[c-1]
print(Bigger(a,b),'@', end=' ')
(OR)
Predict the output of the following Python code:
tup1 = ("George","Anderson","Mike","Luke","Amanda")
2
211 | P a g e
list1 =list(tup1)
list2 = []
for i in list1:
if i[-1]=="e":
list2.append(i)
tup2 = tuple(list2)
print(tup2)
25. Differentiate between COUNT(*) and SUM( ) functions in SQL with
appropriate example.
(OR)
Categorize the following commands as DDL or DML:
CREATE, DROP, UPDATE, INSERT
2
SECTION C
26. (a) Consider the following tables Uniform and Cost:
Table: Uniform
UCode UName UColour
1 Shirt White
2 Pant Grey
3 Tie Black
Table: Cost
UCode Size Price
1 L 550
1 M 500
2 L 850
2 M 810
1+2
212 | P a g e
What will be the output of the following statement?
SELECT * FROM Uniform NATURAL JOIN Cost;
(b) Write the output of the queries (i) to (iv) based on the tablegiven below:
Table: Activity
PID PARTICIPANT GRADE EVENT POINTS EVENTDATE HOUSE
101 Ajay Devgan A Running 200 2022-02-03 Gandhi
102
John
Abraham
Hopping
Bag 300 2021-12-02 Bose
103 Sunny Deol B Skipping 200 2019-09-23 Gandhi
104
Akshay
Kumar A
Bean
Bag 250 2020-11-14 Bhagat
105 Juhi Chawla A Obstacle 350 2022-03-17 Bose
106
Madhuri
Dixit
Egg &
Spoon 200 2021-10-15 Bose
(a) SELECT PARTICIPANT, POINTS FROM Activity ORDER BY
POINTS DESC;
(b) SELECT HOUSE, COUNT(PARTICIPANT) FROM Activity GROUP
BY HOUSE;
(c) SELECT DISTINCT POINTS FROM Activity;
(d) SELECT PID,EVENTDATE FROM Activity WHERE
EVENT=”Running” OR EVENT=”Skipping”;
27. Write a function in python to count the number lines in a text file
‘Country.txt’which is starting with an alphabet ‘W’ or ‘H’. If the file
contents are as follows:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
The output of the function should be:
W or w : 1
H or h : 2
3
213 | P a g e
(OR)
Write a user defined function countwords( ) to display the total number of
words present inthe text file “Quotes.Txt”. If the text file has the following
data written in it:
Living a life you can be proud of doing your best
Spending your time withpeople and activities that are important to you
Standing up for things that areright even when it’s hard
Becoming the best version of you
The countwords() function should display the output as:
Total number of words : 40
28. (a) Write the outputs of the SQL queries (i) to (iv) based on the
relations Book and Issued given below:
Table : Book
Book_id Book_name Author_name Publisher Price Type Qty
C0001 Fast Cook Latha Kapoor Oswaal 355 Cookery 5
F0001 The Tears
William
Hopkins First Publ 650 Fiction 20
T0001
My First
Python
Brain &
Brooke Oswaal 350 Text 10
T0002
Python Brain
Works A W Rossaine TDH 350 Text 15
F0002 Thunderbolts Anna Roberts First Publ 750 Fiction 50
Table: Issued
Book_id Qty_Issued
F0002 5
T0001 9
C0001 2
i. SELECT Type, MIN(Price) FROM Book GROUP BY Type;
3
214 | P a g e
ii. SELECT Book_Name, Author_name FROM Book WHERE Price
BETWEEN 300 AND 600;
iii. SELECT Book.Book_id, Publisher, Qty FROM Book, Issued
WHERE Book.Book_id = Issued.Book_id AND Qty > 10;
iv. SELECT Book.Book_id, Book_name, Type FROM Book, Issued
WHERE Book.Book_id = Issued.Book_id AND
Publisher=”Oswaal”;
(b) Write the command to view the structure of an already created table
29. Write a function LShift(arr,n) in python, which accepts a list of numbers
and a numeric value by which all elements of the list are shifted to left.
Sample Input data of the list
Arr=[10,20,30,40,12,11] and n=2
Output
Arr :[30,40,50,12,11,10,20]
3
30. (a)Write a function in python named PUSH(STACK, SET) where STACK
is list ofsome numbers forming a stack and SET is a list of some numbers.
The functionwill push all the EVEN elements from the SET into a STACK
implemented byusing a list. Display the stack after push operation.
(b)Write a function in python named POP(STACK) where STACK is a
stackimplemented by a list of numbers. The function will display the
popped elementafter function call.Also, display “Stack Empty” if there are
no elements in the stack.
(OR)
A stackBook contains the following details of various books –
[book_no, book_title, book_price].Write a function PushBook(Book)in
Python that inputs the book details from the user and pushes into the stack.
Also, display the stack elements.
3
SECTION D
215 | P a g e
31. Python University is setting up its academic blocks at Chennai
and is planning to set up a network. The University has 3 academic
blocks and one Human Resource Center as shown in the diagram
below:
Center to Center distances between various blocks/center is as follows:
No. of computers in each block/center is given above.
a) Suggest the most suitable place (i.e., Block/Center) toinstall the server of
this University with a suitable reason.
5
216 | P a g e
b)Suggest an ideal layout for connecting these blocks/centers for awired
connectivity.
c)Which device will you suggest to be placed/installed ineach of these
blocks/centers to efficiently connect all thecomputers within these
blocks/centers.
d) Suggest the placement of a Repeater in thenetwork with justification.
e) The university is planning to connect its admission officein Delhi, which
is more than 1250km from university.Which type of network out of LAN,
MAN, or WAN will beformed? Justify your answer.
32. (a) Write the output of the code given below:
def check(n1=1, n2=2):
n1=n1+n2
n2+=1
print(n1,n2)
check( )
check(3)
(b) The code given below inserts the following record in the table
Employee:
ENo – integer
EName – string
Dept – string
Salary – integer
Note the following to establish connectivity between Python and
MYSQL:
* Username is root
* Password is tiger
2+3
217 | P a g e
* The table exists in a MYSQL database named Company
* The details (ENo, EName, Dept, Salary) 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 Employee.
Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="tiger", database="Company")
mycursor = _________ #Statement 1
eno=int(input("Enter Employee No :: "))
ename=input("Enter Name :: ")
dept=input("Enter Dept :: ")
salary=int(input("Enter Salary :: "))
query="insert into employee
values({},'{}','{}',{})".format(eno,ename,dept,salary)
___________ #Statement 2
____________ # Statement 3
print("Data Added successfully")
(OR)
(a) Predict the output of the code given below:
218 | P a g e
s = 'mAhAtMaGaNdHi'
i = 0
while i<len(s):
if (s[i].islower()):
print(s[i].upper(),end=' ')
if (s[i].isupper()):
print(s[i].lower(),end=' ')
i += 1
(b) The code given below reads the following record from the table
named Employee and displays only those records who have salary
greater than 15,000:
ENo – integer
EName – string
Dept – string
Salary – 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 Company.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those employees
whose salary is greater than 15,000.
219 | P a g e
Statement 3- to read the complete result of the query (records whose salary
is greater than 15,000) into the object named data, from the table employee
in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",password="tiger",
database="Company")
mycursor = __________ #Statement 1
print("Employees whose salary greater than 15000 are : ")
___________________ #Statement 2
data = __________________ #Statement 3
for i in data:
print(i)
print()
33. What is the role of newline argument in opening of CSV files ?
Write a Program in Python that defines and calls the following user defined
functions:
a) ADD() – To accept and add data of a book to a CSV file
‘book.csv’. Each record consists of a list with field elements as
bookid, title and price to store book id, book title and
book price respectively.
b) COUNTR() – To count the number of records present in the CSV file
named ‘book.csv’.
(OR)
5
220 | P a g e
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:
(i) add() – To accept and add data of a toy store to a CSV
file ‘toydata.csv’. Each record consists of a list with field elements as tid,
tname and tprice to store toy id, toy name and toy price respectively.
(ii) search()- To display the records of the toys whose price is more than
500.
SECTION E
34. As part of Fit India Campaign, Suresh has started a juice shop that serves
healthy juices. As his database administrator, answer the following
questions based on the data given in the table below.
Table : HEALTHYDRINKS
(i) Identify the most appropriate column, which can be considered
as Primary key.
(ii) If two columns are added and 2 rows are deleted from the table
result, what will be the new degree and cardinality of the
1+1+2
221 | P a g e
above table?
(iii) Write the statements to:
a. Insert the following record into the table
DrinkCode – 107, Dname – Santara Special, Price – 25.00, Calorie – 130
b. Increase the price of the juices by 3% whose name begins with ‘A’.
OR (Option for part iii only)
(iii) Write the statements to:
a.Delete the record of those juices having calories more than 140.
b. Add a column Vitamins in the table with datatype as varchar with 20
characters.
35. Rehaan is a Python programmer. He has written a code and created a
binary file record.dat with student_id, sname and marks. The file contains
10 records.
He now has to update a record based on the student_id entered by the user
and update the marks. The updated record is then to be
written in the file temp.dat. The records which are not to be
updated also have to be written to the file temp.dat. If the student_id is not
found, an appropriate message should also be displayed.
As a Python expert, help him to complete the following code based on
the requirement given above:
1+1+2
222 | P a g e
import _______ #Statement 1
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
sid=int(input("Enter student id to update their marks :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Student_id"]==sid:
found=True
rec["Marks"]=int(input("Enter new marks ::
"))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The mark of student id ",sid," has been updated.")
else:
print("No student with such id is found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
223 | P a g e
(ii) Write the correct statement required to open a temporary file
named temp.dat. (Statement 2)
(iii) Which statement should Rehaan fill in Statement 3 to read the data from
the binary filerecord.dat, and in Statement 4 to write the updated data in the
file, temp.dat?
Computer Science (083)
Sample Question Paper - II
Maximum Marks: 70 Time Allowed: 3 hours
SECTION A
(1 mark to be awarded for every correct answer)
1. State whether True or False:
Variable names can begin with the _ symbol.
Ans. True
1
2. Identify which of the following is an invalid data type in Python:
(b) int (b) float (c) super (d) None
Ans. (c ) super
1
3. Consider the following code:
dict1 = {‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92, ‘Saritha’: 85}
What suitable code should be written to return a list of values in dict1 ?
Ans. dict1.values( )
1
4. Consider the following expression:
not True and False or not False
1
224 | P a g e
Which of the following will be the output:
e) True
f) False
g) None
h) NULL
Ans. a) True
5. Select the correct output of the following code:
>>>str1 = ‘India is a Great Country’
>>>str1.split(‘a’)
e) [‘India’, ’is’, ’a’,’ Great’, ’Country’]
f) [‘India’, ’is’, ’Great’, ’Country’]
g) [‘Indi’, ’is’, ’Gre’, ’t Country’]
h) [‘Indi’, ’is’, ’Gre’, ’t’, ‘Country’]
Ans. c) [‘Indi’, ’is’, ’Gre’, ’t Country’]
1
6. Which of the following is an invalid access mode for text files:
e) w
f) a+
g) ab
h) r
Ans. c) ab
1
7. Fill in the blanks:
___________ command is used to add a new column in the table in SQL
Ans. ALTER TABLE
1
8. Which of the following will display all the tables in a database:
e) SELECT * FROM <tablename>;
f) DISPLAY TABLES;
g) SHOW TABLES;
h) USE TABLES;
1
225 | P a g e
Ans. c) SHOW TABLES;
9. Which of the following will be the output of the code:
mySubject = “Computer Science”
print(mySubject[:3] + mySubject[3:])
e) Com
f) puter Science
g) Computer Science
h) Science Computer
Ans. c) Computer Science
1
10. Choose the correct option:
__________ is the number of columns in a table and ________ is the
number of rows in the table.
e) Cardinality, Degree
f) Degree, Cardinality
g) Domain, Range
h) Attribute, Tuple
Ans. b) Degree, Cardinality
1
11. The correct syntax of load( ) is:
e) <objectvariable> = pickle.load(<fileobject>)
f) pickle.load(<fileobject>, <objectvariable>)
g) <fileobject>.load(<objectvariable>)
h) <objectvariable> = <fileobject>.load( )
Ans. a) <objectvariable> = pickle.load(<fileobject>)
1
12. The _________clause is used to display result of an SQL query in ascending
or descending order with respect to specified attribute values.
1
226 | P a g e
Ans. ORDER BY
13. Fill in the blank:
________ is the protocol used for transferring files from one machine to
another.
e) HTTP
f) FTP
g) SMTP
h) VOIP
Ans. b) FTP
1
14. How will the following expression be evaluated in Python?
2 + 9 * ( ( 3 * 12) – 8 ) / 10
e) 29.2
f) 25.2
g) 27.2
h) 27
Ans. c) 27.2
1
15. Which function is used to display the sum of values in a specified column ?
e) COUNT(column)
f) TOTAL(column)
g) SUM(column)
h) ADD(column)
Ans. c) SUM(column)
1
16. To open a connector to the MySQL database, which statement is used to
connect with MySQL ?
e) connector
1
227 | P a g e
f) connect
g) password
h) username
Ans. b) connect
17. Assertion (A) : A variable defined outside any function or any block is
known as a global variable.
Reason ( R ) : A variable defined inside any function or a block is known as
a local variable.
Ans. b) Both A and R are true and R is not the correct explanation for
A
1
18. Assertion (A ) : The tell( ) method returns an integer that specifies the
current position of the file object in the file.
Reason ( R) : Offset can have any of the three values – 0, 1 and 2
Ans. c) A is True but R is False
1
SECTION B
19. Observe the following Python code very carefully and rewrite it after
removing all syntactical errors with each correction underlined.
DEF result_even( ):
x = input(“Enter a number”)
if (x % 2 = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
even ( )
Ans.
def result_even( ):
x = int(input(“Enter a number”))
2
228 | P a g e
if (x % 2 = = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
result_even ( )
(1/2 mark for each correction)
20. Write two points of difference between LAN and WAN
(OR)
Write two points of difference between HTTP AND SMTP
Ans.
(Any two relevant points of difference to be awarded 1 mark each)
2
21 (c) Given is a Python string declaration:
str1="!!Welcome to Python!!"
Write the output of: print(str1[::-2])
Ans.
!nhy teolW!
(b) Write the output of the code given below:
dict1 = {"name": "Suman", "age": 36}
dict1['age'] = 27
dict1['address'] = "Chennai"
print(dict1.keys())
2
229 | P a g e
Ans. dict_keys(['name', 'age', 'address'])
22. Explain the use of Primary Key in a Relational Database Management
System. Give an example to support your answer.
Ans.
Use of Primary Key – (1 mark)
Any correct example – (1 mark)
2
23. (a) Expand the following:
iii. XML
iv. HTML
Ans.
i. eXtensible Markup Language (1/2 mark)
ii. HyperText Markup Language (1/2 mark)
(d) What is the use of PPP in computer networks ?
Ans. Point to Point Protocol is the Internet standard for transmission of
IP packets over serial lines. It is the best solution for dial-up Internet
connections.
(any 1 correct point, 1 mark)
2
24. Predict the output of the following Python code:
def Bigger(N1,N2):
if N1>N2:
return N1
else:
return N2
L=[32,10,21,54,43]
for c in range (4,0,-1):
2
230 | P a g e
a=L[c]
b=L[c-1]
print(Bigger(a,b),'@', end=' ')
Ans. 54 @ 54 @ 21 @ 32 @
(OR)
Predict the output of the following Python code:
tup1 = ("George","Anderson","Mike","Luke","Amanda")
list1 =list(tup1)
list2 = []
for i in list1:
if i[-1]=="e":
list2.append(i)
tup2 = tuple(list2)
print(tup2)
Ans. ('George', 'Mike', 'Luke')
25. Differentiate between COUNT(*) and SUM( ) functions in SQL with
appropriate example.
Ans.
Any two valid differences – (1 mark)
Any valid example – (1 mark)
(OR)
Categorize the following commands as DDL or DML:
2
231 | P a g e
CREATE, DROP, UPDATE, INSERT
Ans.
DDL – DROP, CREATE (1 mark)
DML – UPDATE, INSERT (1 mark)
SECTION C
26.
UCode UName UColour
1 Shirt White
2 Pant Grey
3 Tie Black
Table: Uniform
UCode Size Price
1 L 550
1 M 500
2 L 850
2 M 810
Table: Cost
What will be the output of the following statement?
SELECT * FROM Uniform NATURAL JOIN Cost;
Ans.
UCode UName UColour Size Price
1 Shirt White L 550
1 Shirt White M 500
2 Pant Grey L 850
2 Pant Grey M 810
1+2
232 | P a g e
(1 mark for correct output)
(b) Write the output of the queries (i) to (iv) based on the table given below:
Table: Activity
PID PARTICIPANT GRADE EVENT POINTS EVENTDATE HOUSE
101 Ajay Devgan A Running 200 2022-02-03 Gandhi
102
John
Abraham
Hopping
Bag 300 2021-12-02 Bose
103 Sunny Deol B Skipping 200 2019-09-23 Gandhi
104
Akshay
Kumar A
Bean
Bag 250 2020-11-14 Bhagat
105 Juhi Chawla A Obstacle 350 2022-03-17 Bose
106
Madhuri
Dixit
Egg &
Spoon 200 2021-10-15 Bose
(e) SELECT PARTICIPANT, POINTS FROM Activity ORDER BY
POINTS DESC;
Ans.
PARTICIPANT POINTS
Juhi Chawla 350
John Abraham 300
Akshay Kumar 250
Ajay Devgan 200
Sunny Deol 200
Madhuri Dixit 200
(f) SELECT HOUSE, COUNT(PARTICIPANT) FROM Activity GROUP
BY HOUSE;
Ans.
HOUSE COUNT(PARTICIPANT)
Gandhi 2
Bose 3
233 | P a g e
Bhagat 1
(g) SELECT DISTINCT POINTS FROM Activity;
Ans.
POINTS
200
300
250
350
(d) SELECT PID, EVENTDATE FROM Activity WHERE EVENT =
”Running” OR EVENT =”Skipping”;
Ans.
PID EVENTDATE
101 2022-02-03
103 2019-09-23
27. Write a function in python to count the number lines in a text file
‘Country.txt’which is starting with an alphabet ‘W’ or ‘H’. If the file
contents are as follows:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
The output of the function should be:
W or w : 1
H or h : 2
3
234 | P a g e
Ans.
def count_W_H():
f = open (“Country.txt”, “r”)
W,H = 0,0
r = f.read()
for x in r:
if x[0] == “W” or x[0] == “w”:
W=W+1
elif x[0] == “H” or x[0] == “h”:
H=H+1
f.close()
print (“W or w :”, W)
print (“H or h :”, H)
(Note: Use of any correct code giving the same result is also accepted)
Correct function header – ½ mark
Correct open and close of file – ½ mark
Correct for loop and condition checking – 1 mark
Correct printing of output – 1 mark
(OR)
Write a user defined function countwords( ) to display the total number of
words present inthe text file “Quotes.Txt”. If the text file has the following
data written in it:
Living a life you can be proud of doing your best
Spending your time withpeople and activities that are important to you
Standing up for things that areright even when it’s hard
Becoming the best version of you
235 | P a g e
The countwords() function should display the output as:
Total number of words : 40
Ans.
def countwords():
s = open("Quotes.txt","r")
f = s.read()
z = f.split()
count = 0
for I in z:
count = count + 1
print ("Total number of words:", count)
f.close( )
(Note: Use of any correct code giving the same result is also accepted)
Correct function header – ½ mark
Correct open and close of file – ½ mark
Correct use of split( ) – ½ mark
Correct for loop and counter increment - 1 mark
Correct printing of output – ½ mark
28. (a) Write the outputs of the SQL queries (i) to (iv) based on the
relations Book and Issued given below:
Table : Book
Book_id Book_name Author_name Publisher Price Type Qty
C0001 Fast Cook Latha Kapoor Oswaal 355 Cookery 5
F0001 The Tears
William
Hopkins First Publ 650 Fiction 20
T0001
My First
Python
Brain &
Brooke Oswaal 350 Text 10
T0002
Python Brain
Works A W Rossaine TDH 350 Text 15
3
236 | P a g e
F0002 Thunderbolts Anna Roberts First Publ 750 Fiction 50
Table: Issued
Book_id Qty_Issued
F0002 5
T0001 9
C0001 2
v. SELECT Type, MIN(Price) FROM Book GROUP BY Type;
Ans.
+---------+------------+
| Type | MIN(Price) |
+---------+------------+
| Cookery | 355 |
| Fiction | 650 |
| Text | 350 |
+---------+------------+
vi. SELECT Book_Name, Author_name FROM Book WHERE Price
BETWEEN 300 AND 600;
Ans.
+--------------------+----------------+
| Book_Name | Author_name |
+--------------------+----------------+
| Fast Cook | Latha Kapoor |
| My First Python | Brain & Brooke |
| Python Brain Works | A W Rossaine |
+--------------------+----------------+
vii. SELECT Book.Book_id, Publisher, Qty FROM Book, Issued
WHERE Book.Book_id = Issued.Book_id AND Qty > 10;
Ans.
+---------+------------+------+
| Book_id | Publisher | Qty |
+---------+------------+------+
| F0002 | First Publ | 50 |
+---------+------------+------+
viii. SELECT Book.Book_id, Book_name, Type FROM Book,
Issued WHERE Book.Book_id = Issued.Book_id AND
Publisher=”Oswaal”;
237 | P a g e
Ans.
+---------+-----------------+---------+
| Book_id | Book_name | Type |
+---------+-----------------+---------+
| T0001 | My First Python | Text |
| C0001 | Fast Cook | Cookery |
+---------+-----------------+---------+
(1/2 mark for each correct output)
(c) Write the command to view the structure of an already created table
Ans.
DESCRIBE <tablename>;
(1 mark for correct answer)
29. Write a function LShift(arr,n) in python, which accepts a list of numbers
and a numeric value by which all elements of the list are shifted to left.
Sample Input data of the list
Arr=[10,20,30,40,12,11] and n=2
Output
Arr :[30,40,50,12,11,10,20]
Ans.
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)
(Note : Using of any correct code giving the same result is also accepted.)
3
238 | P a g e
30. (a)Write a function in python named PUSH(STACK, SET) where STACK
is list ofsome numbers forming a stack and SET is a list of some numbers.
The functionwill push all the EVEN elements from the SET into a STACK
implemented byusing a list. Display the stack after push operation.
Ans.
(1 ½ marks for correct code)
(b)Write a function in python named POP(STACK) where STACK is a
stackimplemented by a list of numbers. The function will display the
popped elementafter function call.Also, display “Stack Empty” if there are
no elements in the stack.
Ans.
(1 ½ marks for correct code)
(OR)
A stack Book contains the following details of various books –
[book_no, book_title, book_price]. Write a function PushBook(Book)in
Python that inputs the book details from the user and pushes into the stack.
Also, display the stack elements.
Ans.
def PushBook(Book):
3
239 | P a g e
book_id=int(input("Enter book id: "))
book_title=input("Enter book title: ")
book_price = int(input("Enter price: "))
data=[book_id,book_title,book_price]
Book.append(data)
print("The stack: ",Book)
Correct function header – ½ mark
Correct input from user – 1 mark
Correct use of append into Book – 1 mark
Correct display of stack content – ½ mark
(Note: Any other correct code giving same output can be accepted.)
SECTION D
31.
a)Suggest the most suitable place (i.e., Block/Center) to install the server of
this University with a suitable reason.
Ans. Most suitable place to install the server is HR center, as this center
has maximum number of computers.
b)Suggest an ideal layout for connecting these blocks/centers for awired
connectivity.
5
240 | P a g e
Ans.
c)Which device will you suggest to be placed/installed ineach of these
blocks/centers to efficiently connect all thecomputers within these
blocks/centers.
Ans.Hub / Switch
d)Suggest the placement of a Repeater in the network with justification.
Ans. Repeater may be placed when the distance between 2 buildings is
more than 100 meters.
e)The university is planning to connect its admission office in Delhi, which
is more than 1250km from university. Which type of network out of LAN,
MAN, or WAN will be formed? Justify your answer.
Ans.WAN, as the given distance is more than the range of LAN and
MAN.
32. (a) Write the output of the code given below:
def check(n1=1, n2=2):
n1=n1+n2
n2+=1
print(n1,n2)
check( )
check(3)
2+3
241 | P a g e
Ans.
3 3
5 3
(1 mark for 3 3 and 1 mark for 5 3)
(b)
Write the following missing statements to complete the code:
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="tiger", database="Company")
mycursor = _________ #Statement 1
eno=int(input("Enter Employee No :: "))
ename=input("Enter Name :: ")
dept=input("Enter Dept :: ")
salary=int(input("Enter Salary :: "))
query="insert into employee
values({},'{}','{}',{})".format(eno,ename,dept,salary)
___________ #Statement 2
____________ # Statement 3
print("Data Added successfully")
Statement 1 – to form the cursor object
Ans. con1.cursor()
Statement 2 – to execute the command that inserts the record in the
table Employee.
Ans. mycursor.execute(query)
242 | P a g e
Statement 3- to add the record permanently in the database
Ans. con1.commit()
(1 mark for each correct answer)
(OR)
(b) Predict the output of the code given below:
s = 'MoHaNdAs GaNdHi'
i = 0
while i<len(s):
if (s[i].islower()):
print(s[i].upper(),end=' ')
if (s[i].isupper()):
print(s[i].lower(),end=' ')
i += 1
Ans. m O h A n D a S g A n D h I
(1 mark for first 7 characters, 1 mark for next 7 characters)
(b) The code given below reads the following record from the table
named Employee and displays only those records who have salary
greater than 15,000:
ENo – integer
EName – string
Dept – string
243 | P a g e
Salary – 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 Company.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those employees
whose salary is greater than 15,000.
Statement 3- to read the complete result of the query (records whose salary
is greater than 15,000) into the object named data, from the table employee
in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",password="tiger",
database="Company")
mycursor = __________ #Statement 1
print("Employees whose salary greater than 15000 are : ")
___________________ #Statement 2
data = __________________ #Statement 3
for i in data:
print(i)
print()
Ans:
Statement 1:
244 | P a g e
con1.cursor()
Statement 2:
mycursor.execute("select * from employee where salary>15000")
Statement 3:
mycursor.fetchall()
(1 mark for each correct statement)
33. What is the role of newline argument in opening of CSV files ?
Ans. The role of newline argument is to specify how would Python
handle newline characters while working with CSV files. newline=’’ will
ensure that no translation of EOL character takes place.
(1 mark for correct answer)
Write a Program in Python that defines and calls the following user defined
functions:
a) ADD() – To accept and add data of a book to a CSV file
‘book.csv’. Each record consists of a list with field elements as
bookid, title and price to store book id, book title and
book price respectively.
b) COUNTR() – To count the number of records present in the CSV file
named ‘book.csv’.
Ans.
import csv
def ADD():
fout=open("record.csv","a",newline="n")
5
245 | P a g e
wr=csv.writer(fout)
empid=int(input("Enter Employee id :: "))
name=input("Enter name :: ")
mobile=int(input("Enter mobile number :: "))
lst=[empid,name,mobile] ---------1/2 mark
wr.writerow(lst) ---------1/2 mark
fout.close()
def COUNTR():
fin=open("record.csv","r",newline="n")
data=csv.reader(fin)
d=list(data)
print(len(d))
fin.close()
ADD()
COUNTR()
(½ mark for importing csv module
1 ½ marks each for correct definition of ADD() and COUNTR()
½ mark for function call statements)
(OR)
Give any one point of difference between a binary file and a csv file.
Ans. Difference between binary file and csv file: (Any one difference
may be given)
Binary file:
• Extension is .dat
• Not human readable
• Stores data in the form of 0s and 1s
CSV file
• Extension is .csv
246 | P a g e
• Human readable
• Stores data like a text file
(1 mark for correct difference)
Write a Program in Python that defines and calls the following user
defined functions:
(i) add() – To accept and add data of a toystore to a CSV
file ‘toydata.csv’. Each record consists of a list with field elements as tid,
tname and tprice to store toy id, toy name and toy price respectively.
(ii) search()- To display the records of the toys whose price is more than
500.
Ans.
import csv
def add():
fout=open("toydata.csv","a",newline='n')
wr=csv.writer(fout)
tid=int(input("Enter Toy Id :: "))
tname=input("Enter toy name :: ")
tprice=int(input("Enter toy price :: "))
TD=[tid,tname,tprice]
wr.writerow(TD)
fout.close()
def search():
fin=open("toydata.csv","r",newline='n')
data=csv.reader(fin)
found=False
print("The Details are: ")
247 | P a g e
for i in data:
if int(i[2])>500:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
add()
print("Now displaying")
search()
(½ mark for importing csv module
1 ½ marks each for correct definition of add() and search()
½ mark for function call statements)
SECTION E
34. Table : HEALTHYDRINKS
Based on the data given, answer the following questions:
i. Identify the most appropriate column, which can be considered as
Primary key.
Ans: Drinkcode
(1 mark for correct answer)
1+1+2
248 | P a g e
ii. If two columns are added and 2 rows are deleted from the table result,
what will be the new degree and cardinality of the above table?
Ans:
New Degree: 6
New Cardinality: 4
(1/2 mark for correct degree and ½ mark for correct cardinality)
(iii) Write the statements to:
a. Insert the following record into the table
DrinkCode – 107, Dname – Santara Special, Price – 25.00, Calorie – 130
Ans. INSERT INTO HEALTHYDRINKS VALUES(107,”Santara
Special”,25.00,130);
b. Increase the price of the juices by 3% whose name begins with ‘A’.
Ans. UPDATE HEALTHYDRINKS SET PRICE=PRICE +
3/100*PRICE WHERE DNAME LIKE “A%”;
(1 mark for each correct statement)
OR (Option for part iii only)
(iii) Write the statements to:
a.Delete the record of those juices having calories more than 140.
Ans. DELETE FROM HEALTHYDRINKS WHERE CALORIE > 140;
b. Add a column Vitamins in the table with datatype as varchar with 20
characters.
249 | P a g e
Ans. ALTER TABLE HEALTHYDRINKS ADD Vitamins
VARCHAR(20);
(1 mark for each correct statement)
35. As a Python expert, help Rehaan to complete the following code based on
the requirement given:
import ____________ #Statement 1
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
sid=int(input("Enter student id to update their marks :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Student_id"]==sid:
found=True
rec["Marks"]=int(input("Enter new marks ::
"))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The mark of student id ",sid," has been updated.")
else:
print("No student with such id is found")
1+1+2
250 | P a g e
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file
named temp.dat. (Statement 2)
(iii) Which statement should Rehaan fill in Statement 3 to read the data from
the binary filerecord.dat, and in Statement 4 to write the updated data in the
file, temp.dat?
Ans:
(i) pickle(1 mark for correct module)
(ii) fout=open(‘temp.dat’, ‘wb’) (1 mark for correct statement)
(iii) pickle.load(fin)
pickle.dump(rec,fout)
(1 mark for each correct statement)
KENDRIYA VIDYALAYA SANGATHAN-CHENNAI REGION
Class: XII session 2022-23
Computer Science(083)
Sample Question Paper - III
Maximum Marks:70 Time Allowed: 3 hours
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 Q35 against part
C only.
8. All programming questions are to be answered using Python Language only.
251 | P a g e
SECTION A Marks
1. Find output generated by the following code:
p=10
q=20
p*=q//3
q+=p=q**2
print(p,q)
1
2. A database can have only one table(True/False) 1
3. Which one of the following refers to the copies of the same data (or
information) occupying the memory space at multiple places.
a) Data Repository
b)Data Inconsistency
c)Data Mining
d)Data Redundancy
1
4. MAC address is of ___________
a) 24 bits
b) 36 bits
c) 42 bits
d) 48 bits
1
5. Read following statement about features of CSV file and select which
statement is TRUE?
Statement1: Only database can support import/export to CSV format
Statement2: CSV file can be created and edited using any text editor
Statement3: All the columns of CSV file can be separated by comma only
a. Statement 1 and statement 2
b. Statement 2 and statement 3
c. Statement 2
d. Statement 3
1
252 | P a g e
6. What is the output of the following program if the student.csv file contains
following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row);
1
7. The command used to skip a row in a CSV file is
A. next()
B. skip()
C. omit()
D. bounce()
1
8.
Inspecting the value at the stack’s top without removing it.
a) peak operation
b) insert operation
c) pop operation
d) push operation
1
9.
Stacks serve major role in ______________
a) Simulation of recursion
b) Simulation of linked list
c) Simulation of limited resource allocation
d) Simulation of all data
1
10. Which statement will give the output as : True from the following :
a) >>>not -5
b) >>>not 5
c) >>>not 0
d) >>>not(5-1)
1
1
253 | P a g e
11. Give the output of the following code:
>>>import math
>>>math.ceil(1.03)+math.floor(1.03)
a) 3
b) -3.0
c) 3.0
d) None of the above
1
12. The input() function always returns a value of ……………..type.
a) Integer
b) float
c) string
d) Complex
1
13. Directions: In the following questions, A statement of Assertion (A) is
followed by a statement of
Reason (R). Mark the correct choice as.
(A) Both A and R are true and R is the correct explanation for A. (B) Both
A and R are true and R is not correct explanation for A.
(C) A is true but R is false.
(D) A is false but R is true.
Question.
Assertion (A): A referential integrity is a system of rules of DBMS.
Reason (R): It ensures that user don't accidently delete or change related data.
1
14. Directions: In the following questions, A statement of Assertion (A) is
followed by a statement of
Reason (R). Mark the correct choice as.
254 | P a g e
(A) Both A and R are true and R is the correct explanation for A. (B) Both
A and R are true and R is not correct explanation for A.
(C) A is true but R is false.
(D) A is false but R is true.
Question.
Assertion (A): The keyword DISTINCT is used with SELECT command.
Reason (R): DISTINCT keyword eliminates duplicate rows
15. To include non-graphic characters in python, which of the following is used?
a. Special Literals
b. Boolean Literals
c. Escape Character Sequence
d. Special Literal – None
1
16. 50. Which of the following statement creates a tuple?
a) t=[1,2,3,4]
b) t={1,2,3,4}
c) t=<1,2,3,4>
d) t=(1,2,3,4)
1
17. Which of the following operation is supported in python with respect to tuple
t?
a) t[1]=33
b) t.append(33)
c) t=t+t
d) t.sum()
1
1
18. A ………………is a virtual table that does not really exist in its own right
but is instead derived from one or more underlying base table(s) in DBMS
a)SQL b) map c) view d) query
1
255 | P a g e
SECTION B
19.
Littu wrote a code function to display Fibonacci series. Correct the errors and
rewrite it.
def Fibonacci()
nterms = int(input("How many terms? "))# first two terms
n1, n2 = 0, 1
count = 0
if nterms<= 0:# check if the number of terms is valid
print("Please enter a positive integer");
elifnterms == 1:# if there is only one term, return n1
print("Fibonacci sequence upto",nterms,":")
print(n1);
else:# generate fibonacci sequence
print("Fibonacci sequence:")
while count >nterms:
print(n1)
nth = n1 + n2
n1 = n2# update values
n2 = nth
count -= 1
2
20. What Are Cookies? Why are protocols neededin networking?
OR
Why a switch is called an intelligent hub?
2
21.
a)Predict the output of the following code fragments:
keepgoing = True
x=100
while keepgoing :
print (x)
x = x - 10
if x < 50 :
keepgoing = False
b)counter = {}
defaddToCounter(country):
if country in counter:
counter[country] += 1
else:
counter[country] = 1
2
256 | P a g e
addToCounter('China')
addToCounter('Japan')
addToCounter('china')
print (len(counter))
22.
The Mname Column of a table Members is given below
Mname
Aakash
Hirav
Vinayak
Sheetal
Rajeev
(i) SELECT Mname FROM Members WHERE Mname ' “%v";
(ii) SELECT Mname FROM Members WHERE Mname LIKE "%e%";
2
23.
a. Give three examples of DDL & DML commands?
b. What is the referential integrity constraint?
2
24. How is HAVING clause similar to WHERE clause? How is HAVING clause
differentfrom WHEREclause? Explain with the help of examples of each.
OR
Give one difference between ROLLBACK and COMMIT commands used
in MySql.
2
25. What are python modules? Name some commonly used built-in modules in
Python?
OR
What is difference between tell() and seek() methods?
2
SECTION C
26. Write a method in python to write multiple line of text contents into a text
file mylife.txt.
3
257 | P a g e
OR
Write a method in Python to read lines from a text file INDIA.TXT, to find
and display the occurrence of the word 'India'. For example, if the content of
the file is:
India is the fastest-growing economy. India is looking for more investments
around the globe. The whole world is looking at India as great market. Most
of the Indians can foresee the heights that India is capable of reaching.
The output should be 4.
27. a)Define candidate key, Primary key and Foreign Key.
b)Write the SQL commands for the given questions below based on the table
STUDENT.
No Name Age Dept DOJ Fee Sex
1 Anu 24 CS 10-01-19 250 M
2 Manu 21 EE 09-02-17 480 M
3 Vinu 25 CS 23-01-19 400 M
4 Pallavi 26 IT 22-05-17 260 F
5 Sai 30 EE 16-03-20 310 F
6 Appu 34 BE 15-06-17 250 F
7 Minnu 23 CS 29-01-18 480 M
i)To count the number of students with age<26.
ii)To list the names of female students who are in EE department.
1+2
28. I)Consider the table given below. Write the output of
a)SELECTdistinct(color, fruit), sum(rating) FROM medleys;
b)SELECT distinct(fruit,color) FROM medleys WHERE color =”blue”;
c)SELECT DISTINCT fruit FROM medleys;
d)SELECT medley_id FROM medleys WHERE rating>10;
MEDLEYS
3
258 | P a g e
medley_id | color | fruit | rating
============================
1 red apple 25
2 blue pear 5
3 green apple 12
4 red apple 10
5 purple kiwi 5
6 purple kiwi 50
7 blue kiwi 3
8 blue pear 9
II) Write a COMMAND to delete the column DOP from the table
VEHICLE. Table have five columns V_ID, OWNER_NAME, ADDRESS,
MODEL_NO, COLOUR, DOP.
29. Write a python program using function to find the largest element in a list
and then reverse the list contents and display it. Don’t use in-built functions
for the program.
3
30. Write a code for the STACK PUSH and POP implementation.
a)Write functions AddPlayer(player) and DeletePlayer(player) in python to
add and remove a player by considering them as push and pop operations
in a stack.Write a function to display the stack elements.
OR
Vedika has created a dictionary containing names and marks as key-value pairs
of 5 students. Write a program, with separate user-defined functions to
perform the following operations:
Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
Pop and display the content of the stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60,
“Ishika”:95}
Then the output will be: Umesh Vishal Ishika
3
259 | P a g e
SECTION D
31. a. TellAbout Consultants are setting up a secured network for their
office campus at Gurgaon for their day-to-day office and web-based
activities. They are planning to have connectivity between three
buildings and the head office situated in Mumbai. Answer the
questions (i) to (iv) after going through the building positions in the
campus and other details, which are given below :
The given building blocks are named as Green, Blue and Red
i. Suggest the most suitable place (i.e., building) to house the server of
this organization. Also give a reason to justify your suggested
location.
5
260 | P a g e
ii. Suggest the placement of the following devices with justification:
a. Repeater.
b. Switch.
iii. Suggest a cable layout of connections between the buildings inside
the campus.
iv. The organization is planning to provide a high speed link with its
head office situated in Mumbai using a wired connection. Which
of the following cables will be most suitable for this job.
• Optical Fiber
• Co-axial Cable
• Ethernet Cable
v. While connecting the devices two modems are found to
be defected. What is the function of modem?
32. a) Write the output of the code
def L1(D):
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = D[CNT]
TOTAL = float (T) + C
print(TOTAL)
CNT-=1
TXT = ["20","50","30","40"]
L1(TXT)
b)The program to illustrate Insertion of records to database in Python is given
below. Note the following to establish connectivity between Python and
MYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named Company.
import mysql.connector as mysql
try:
det=ps.connect(host='localhost',user='root',password='tiger',database='
Company')
cmd=_________ #Statement 1
pid=input("Enter Product Id:")
pn=input("Enter Product Name:")
pr = input("Enter Product Rate:")
md = input("Enter Mf. Date:")
query="insert into products values('{}','{}',{},'{}')"
2+3
261 | P a g e
.format(pid,pn,pr, md)
____________ #Statement 2
____________ #Statement 3
det.close()
print("Record Submitted")
except Exception as e:
print(e)
OR
a) Write the output of the code
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) The code given below search for a record using ID in Python
The employee table consists of the following details:
Employee Name
Salary
Designation
City
Birth Date
Note the following to establish connectivity between Python and
MYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named Company.
import mysql.connector as mysql
try:
db=mysql.connect(host="localhost",user="root",password='tiger',
database="Company")
262 | P a g e
cmd=________. # Statement1
id=input("Enter Id you Want to Search?")
q="Select * from employee where employeeid={0}".format(id)
___________ #Statement2
row=_______ #Statement3
if(row):
print("Employee Name:",row[1])
print("Salary:", row[2])
print("Designation:",row[3])
print("City:", row[4])
print("Birth Date:", row[5])
else:
print("Record Not Found....")
db.close()
except Exception as e:
print(e)
33. What is pickle module and why we use this module?
The table given below have the details of customer. The name of the file
is cust.csv , write a code to insert multiple rows in the csv file.
SNo Customer Name City Amount
1 Dhaval Anand 1500
2 Anuj Ahmedabad 2400
3 Mohan Vadodara 1000
4 Sohan Surat 700
OR
What is aBinary File? Give examples.
The detail of marks of class XII are stored in file named RESULTS.CSV.
Raman, the Maths teacher wants to search the details of one student. Write
a program to search the details based on name .
5
SECTION E
263 | P a g e
34. Consider the following DEPT and WORKER tables. Write SQL queries for
(i) to and (iv) find outputs for queries Šv) to (viii):
(i) To display Wno, Name, Gender from the table WORKER in descending
order of Wno.
(ii) To display the Name of all the FEMALE workers from the table
WORKER
.
(iii) Write statements
a) To display the Wno and Name of those workers from the table WORKER
who are born between '1987-01-01' and '1991-12-01'.
b) To count and display MALE workers who have joined after '1986-01-
01"..
OR(only for part iii)
(iii) Write the output for the given statements
a) SELECT COUNT(*), DCODE FROM WORKER GROUP BY DCODE
HAVING COUNT(*) > 1;
b) SELECT DISTINCT DEPARTMENT FROM DEPT;
4
264 | P a g e
35.
Arun, during Practical Examination of Computer Science, has been assignedan
incomplete search() function to search in a pickled file student.dat. The
Filestudent.dat is created by his Teacher and the following information is
knownabout the file.
• File contains details of students in [roll_no,name,marks] format.
• File contains details of 10 students (i.e. from roll_no 1 to 10) and
separate list of each student is written in the binary file using dump().
Arun has been assigned the task to complete the code and print details of
rollnumber 1.
def search():
f = open("student.dat",____)#Statement-1
____: #Statement-2
while True:
rec = pickle.____#Statement-3
if(____): #Statement-4
print(rec)
except:
pass
f.close()
I). In which mode Arun should open the file in Statement-1?
a) r
b) r+
c) rb
d) wb
II). Identify the suitable code to be used at blank space in line marked as
Statement2
a) if(rec[0]==1)
4
265 | P a g e
b) for i in range(10)
c) try
d) pass
III). Identify the function (with argument), to be used at blank space in
line marked
as Statement-3.
a) load()
b) load(student.dat)
c) load(f)
d) load(fin)
IV). What will be the suitable code for blank space in line marked as
Statement-4.
a) rec[0]==2
b) rec[1]==2
c) rec[2]==2
d) rec[0]==1
Computer Science(083)
Sample Question Paper – III Marking Scheme
Maximum Marks:70 Time Allowed: 3 hours
SECTION A
1) Find output generated by the following code:
p=10
q=20
p*=q//3
q+=p=q**2
print(p,q)
Answer: 60,480
1
2) A database can have only one table(True/False)
Answer False
1
266 | P a g e
No, database does not have a limit on number of tables. It depends on the
disk space.
3) Which one of the following refers to the copies of the same data (or
information) occupying the memory space at multiple places.
a) Data Repository
b)Data Inconsistency
c)Data Mining
d)Data Redundancy
Answer: d)Data Redundancy
1
4) MAC address is of ___________
a) 24 bits
b) 36 bits
c) 42 bits
d) 48 bits
Answer: c)d) 48 bits
1
5) Read following statement about features of CSV file and select which
statement is TRUE?
Statement1: Only database can support import/export to CSV format
Statement2: CSV file can be created and edited using any text editor
Statement3: All the columns of CSV file can be separated by comma only
a. Statement 1 and statement 2
b. Statement 2 and statement 3
c. Statement 2
d. Statement 3
Answer: c. Statement 2
1
267 | P a g e
6) What is the output of the following program if the student.csv file
contains following data?
Student.csv
Ronit, 200
Akshaj, 400
import csv
d = csv.reader(“student.csv”)
next (d)
for row in d:
print (row);
Answer: Akshaj, 400
1
7) The command used to skip a row in a CSV file is
A. next()
B. skip()
C. omit()
D. bounce()
Answer: A. next()
1
8) Inspecting the value at the stack’s top without removing it.
a) peak operation
b) insert operation
c) pop operation
d) push operation
a) peak operation
1
9) Stacks serve major role in ______________
a) Simulation of recursion
b) Simulation of linked list
c) Simulation of limited resource allocation
d) Simulation of all data
Answer: a) Simulation of recursion
1
10) Which statement will give the output as : True from the following : 1
268 | P a g e
a) >>>not -5
b) >>>not 5
c) >>>not 0
d) >>>not(5-1)
ans >>>not 0
11) Give the output of the following code:
>>>import math
>>> math.ceil(1.03)+math.floor(1.03)
a) 3
b) -3.0
c) 3.0
d) None of the above
answer: a) 3
1
12) The input() function always returns a value of ……………..type.
a) Integer
b) float
c) string
d) Complex
answer: c)string
1
13) Directions: In the following questions, A statement of Assertion (A) is
followed by a statement of
Reason (R). Mark the correct choice as.
(A) Both A and R are true and R is the correct explanation for A. (B) Both
A and R are true and R is not correct explanation for A.
(C) A is true but R is false.
(D) A is false but R is true.
1
269 | P a g e
Question.
Assertion (A): A referential integrity is a system of rules of DBMS.
Reason (R): It ensures that user don't accidently delete or change related data.
Answer:
A
14) Question.
Assertion (A): The keyword DISTINCT is used with SELECT command.
Reason (R): DISTINCT keyword eliminates duplicate rows
Answer:
A
1
15) To include non-graphic characters in python, which of the following is
used?
a. Special Literals
b. Boolean Literals
c. Escape Character Sequence
d. Special Literal – None
Answer
Escape Character Sequence
1
16) Tuples can have various types of elements.
Which of the following statement creates a tuple?
a) t=[1,,2,3,4]
b) t={1,2,3,4}
c) t=<1,2,3,4>
d) t=(1,2,3,4)
answer d)
1
17) Which of the following operation is supported in python with respect to
tuple t?
a) t[1]=33
b) t.append(33)
c) t=t+t
d) t.sum()
1
270 | P a g e
answer: c)t=t+t
18) A ………………is a virtual table that does not really exist in its own right
but is instead derived from one or more underlying base table(s) in DBMS
a)SQLb)map c) view d) query
Answer:c) view
1
SECTION B
19)
Littu wrote a code to display Fibonacci series. Correct the errors and rewrite
it.
def Fibonacci():
nterms = int(input("How many terms? "))# first two terms
n1, n2 = 0, 1
count = 0
if nterms <= 0:# check if the number of terms is valid
print("Please enter a positive integer")
elif nterms == 1:# if there is only one term, return n1
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:# generate fibonacci sequence
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2# update values
n2 = nth
count += 1
2
20) What Are Cookies? Why are protocols needed?
Cookies are text files with small pieces of data — like a username and
password — that are used to identify your computer as you use a computer
network. Specific cookies known as HTTP cookies are used to identify
specific users and improve your web browsing experience.
Data stored in a cookie is created by the server upon your connection. This
data is labeled with an ID unique to you and your computer.When the
cookie is exchanged between your computer and the network server, the
server reads the ID and knows what information to specifically serve to
you.
In networks, communication occurs between the entities in different
systems. Two entities cannot just send bit streams to each other and expect
2
271 | P a g e
to be understood. For communication, the entities must agree on a protocol.
A protocol is a set of rules that govern data communication.
OR
Why a switch is called an intelligent hub?
A switch is called an intelligent hub because before simply forwarding a
packet it checks for the intended destination for the packet and forwards it
to that destination only, this is called packet filtering. While a hub forwards
a packet to all the workstations in a network but only destination computer
keeps it, rest all the computers drops that packet.
21) a)Predict the output of the following code fragments:
keepgoing = True
x=100
while keepgoing :
print (x)
x = x - 10
if x < 50 :
keepgoing = False
b)counter = {}
def addToCounter(country):
if country in counter:
counter[country] += 1
else:
counter[country] = 1
addToCounter('China')
addToCounter('Japan')
addToCounter('china')
print (len(counter))
a)Output:
100
90
80
70
60
50
1+1
272 | P a g e
b)3
22) The Mname Column of a table Members is given below
Mname
Aakash
Hirav
Vinayak
Sheetal
Rajeev
(i) SELECT Mname FROM Members WHERE Mname ' “%v";
(ii) SELECT Mname FROM Members WHERE Mname LIKE "%e%";
Answer:
The output of given commands will be as follows
(i) Hirav, Rajeev
(ii) Sheetal, Rajeev
2
23) a. Give three examples of DDL & DML commands?
b. What is the referential integrity constraint?
Answer
Data Definition Language (DDL) commands:
CREATE table
ALTER table
DROP table
Data Manipulation Language (DML) commands:
INSERT table
UPDATE table
DELETE
bAnswer
Foreign key constraints or referential integrity constraints. A logical rule about
the values in one or more columns in one or more tables is known as a
foreign key constraint, also known as a referential constraint or a referential
integrity constraint.
1+1
24) How is HAVING clause similar to WHERE clause? How is HAVING
clause differentfrom WHEREclause? Explain with the help of examples of
each.
Similarity: Both HAVING and WHERE clause are used for checking
condition(s).
Difference: WHEREclause is used for simple condition(s).
HAVINGclause is used for
conditions with group of values.
2
273 | P a g e
e.g.
WHERE clause:
SELECT * FROM EMP WHERE DEPT = “PHYSICS “ ;
HAVING clause :
SELECT SUM(SALARY), DEPT FROM EMP GROUP BYDEPT
HAVING COUNT(*) > 3;
OR
Give one difference between ROLLBACK and COMMIT commands used
in MySql.
• ROLLBACK command is used to end the current transaction and
undo all the changes we made since the current transaction began.
• Rollback is used to revert the last transaction in the Sql.
➢ COMMIT command is used to make all the changes permanent to
the underlying database which we made during the current
transaction.
➢ Commit is used to save all the recent transactions.
25) What are python modules? Name some commonly used built-in modules
in Python?
Ans: Python modules are files containing Python code. This code can either
be functions classes or variables. A Python module is a .py file containing
executable code.
Some of the commonly used built-in modules are:
os
sys
math
random
data time
JSON
2
274 | P a g e
OR
What is difference between tell() and seek() methods?
tell() seek()
It returns the current position of
cursor in file.
Change the cursor position by
bytes as specified by the offset
Example:
fout=open(“story.txt”,”w”)
fout.write(“Welcome Python”)
print(fout.tell( ))
fout.close( )
Example:
fout=open(“story.txt”,”w”)
fout.write(“Welcome Python”)
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output : 4 Output : 5
SECTION C
26) Write a method in python to write multiple line of text contents into a text
file mylife.txt.
OR
Write a method in Python to read lines from a text file INDIA.TXT, to find
and display the occurrence of the word 'India'. For example, if the content
of the file is:
India is the fastest-growing economy. India is looking for more
investments around the globe. The whole world is looking at India as a
great market. Most of the Indians can foresee the heights that India is
capable of reaching.
The output should be 4.
def writelines():
outfile = open('myfile.txt','w')
while True:
line = input('Enter line: ')
line += 'n'
3
275 | P a g e
outfile.write(line)
choice = input('Are there more lines y/n? ')
if choice == 'n':
break
outfile.close()
# Call the writelines function.
writelines()
or
def count_word():
file = open('india.txt','r')
count = 0
for line in file:
words = line.split()
for word in words:
if word == 'India':
count += 1
print(count)
file.close()
# call the function count_word().
count_word()
27) a)Define candidate key, Primary key and Foreign Key.
Primary Key: There can be more than one candidate key in relation out of
which one can be chosen as the primary key. For Example, STUD_NO, as
1+2
276 | P a g e
well as STUD_PHONE, are candidate keys for relation STUDENT but
STUD_NO can be chosen as the primary key (only one out of many
candidate keys).
Primary Key:
It is a unique key.
It can identify only one tuple (a record) at a time.
It has no duplicate values, it has unique values.
It cannot be NULL.
Primary keys are not necessarily to be a single column; more than one
the column can also be a primary key for a table.
Eg:- STUDENT table SNO is a primary key
SNO SNAME ADDRESS PHONE
Foreign Key: If an attribute can only take the values which are present as
values of some other attribute, it will be a foreign key to the attribute to
which it refers. The relation which is being referenced is called referenced
relation and the corresponding attribute is called referenced attribute and
the relation which refers to the referenced relation is called referencing
relation and the corresponding attribute is called referencing attribute. The
referenced attribute of the referenced relation should be the primary key to
it. For Example, STUD_NO in STUDENT_COURSE is a foreign key to
STUD_NO in STUDENT relation.
It acts as a primary key in one table and it acts as secondary key in
another table.
It combines two or more relations (table) at a time.
They act as a cross-reference between the tables.
For example, DNO is a primary key in the DEPT table and a non-key in
EMP
b)Write the SQL commands for the given questions below based on the
table STUDENT.
No Name Age Dept DOJ Fee Sex
1 Anu 24 CS 10-01-19 250 M
277 | P a g e
2 Manu 21 EE 09-02-17 480 M
3 Vinu 25 CS 23-01-19 400 M
4 Pallavi 26 IT 22-05-17 260 F
5 Sai 30 EE 16-03-20 310 F
6 Appu 34 BE 15-06-17 250 F
7 Minnu 23 CS 29-01-18 480 M
a)To count the number of students with age<26.
b)To list the names of female students who are in EE department.
a)SELECT COUNT(*) FROM STUDENT WHERE Age<26;
b)SELECT Name FROM STUDENT WHERE Sex=”F” AND Dept=”EE”;
28) I) Consider the table given below. Write the output of the SQL queries
(a to d).
a)SELECTdistinct(color, fruit), sum(rating) FROM medleys;
b)SELECT distinct(fruit,color) FROM medleys WHERE color =”blue”;
c)SELECT DISTINCT fruit FROM medleys;
d)SELECT medley_id FROM medleys WHERE rating>10;
medley_id | color | fruit | rating
============================
1 red apple 25
2 blue pear 5
3 green apple 12
4 red apple 10
5 purple kiwi 5
6 purple kiwi 50
7 blue kiwi 3
3
278 | P a g e
8 blue pear 9
Answers:
a)
color | fruit | sum
red apple 3
blue pear 14
blue kiwi 3
green apple 12
purple kiwi 55
b)
fruit | color
==========
Pear blue
Kiwi blue
c)
fruit
====
Apple
Pear
Kiwi
d)
medley_id
========
1
3
6
279 | P a g e
II)Write a COMMAND to deletethe column DOP from the table
VEHICLE. Table have five columns V_ID, OWNER_NAME,ADDRESS,
MODEL_NO, COLOUR, DOP.
ALTER TABLE VEHICLE DROP COLUMN DOP;
29) Write a python program using function to find the largest element in a list
and then reverse the list contents and display it. Don’t use in-built functions
for the program.
E.g.
M = [10, 24, 45, 90, 98]
Output
Largest in the give n List is 98
Reverse list: [98,90,45,24,10]
def largest(L,n) :
max = L[0]
for i in range(1, n) :
if L[i] > max :
max =L[i]
return max
M = [10, 24, 45, 90, 98]
n = len(M)
max= largest(M, n)
print ("Largest in the given List is", max)
#reverse the list
for i in range(n//2):
M[i],M[len(M)-1-i] = M[len(M)-1-i], M[i]#swapping elements
print('Reverse list:', M)
3
280 | P a g e
30) Write a code for the STACK PUSH and POP implementation.
a)Write functions AddPlayer(player) and DeletePlayer(player) in python
to add and remove a player by considering them as push and pop
operations in a stack.Write a function to display the stack elements.
OR
Vedika has created a dictionary containing names and marks as key-value pairs
of 5 students. Write a program, with separate user-defined functions to
perform the following operations:
Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70.
Pop and display the content of the stack.
The dictionary should be as follows:
d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60,
“Ishika”:95}
Then the output will be: Umesh Vishal Ishika
Answers
def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
def display(player):
if player==[]:
print("Stack is Empty")
else:
top = len(player)-1
print(player[top],"-Top")
for i in range(top-1,-1,-1):
print(player[i])
-------------------------------------------------------
def push(stk,item):
stk.append(item)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
3
281 | P a g e
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
SECTION D
31) a) TellAbout Consultants are setting up a secured network for their office
campus at Gurgaon for their day-to-day office and web-based activities.
They are planning to have connectivity between three buildings and the
head office situated in Mumbai. Answer the questions (i) to (iv) after going
through the building positions in the campus and other details, which are
given below :
The given building blocks are named as Green, Blue and Red
Distances between various buildings
Building GREEN to RED 110
Building GREEN to BLUE 45
Building BLUE to RED 65
Gurgaon to Head office 1760
GREEN
RED
BLUE
HEAD OFFICE MUMBAI
GURGAON CAMPUS
282 | P a g e
Computers in the buildings
Building GREEN 32
Building RED 150
Building BLUE 45
HEAD OFFICE 45
i. Suggest the most suitable place (i.e., building) to house the
server of this organization. Also give a reason to justify your
suggested location.
ii. Suggest the placement of the following devices with
justification:
Repeater.
Switch.
iii. Suggest a cable layout of connections between the buildings
inside the campus.
iv. The organization is planning to provide a high speed link with
its head office situated in Mumbai using a wired connection.
Which of the following cables will be most suitable for this job
?
Optical Fiber
Co-axial Cable
Ethernet Cable
v. While connecting the devices two modems are found to
be defected. What is the function of modem
Answers:
i. The most suitable place to install server is building “RED”
because this building have maximum computer which reduce
communication delay
ii. Since the cabling distance between buildings GREEN, BLUE
and RED are quite large, so a repeater each, would ideally be
need along their path to avoid loss of signals during the course
of data flow in their routes.
1
1
1
1
283 | P a g e
In the layout a switch each, would be needed in all the buildings, to
interconnect the group of cables from the different computers in each
building.
switch
switch
switch
iii. Cable Layout----Bus Topology
1
BLUE
GREEN
RED
GURGAON CAMPUS
284 | P a g e
iv. Optical Fiber
v. The modem will do the modulation and demodulation process.
That is, it converts digital signal to analog signal at senders side and analog
to digital at receivers side, respectively.
32) a)Write the output of the code
def L1(D):
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = D[CNT]
TOTAL = float (T) + C
print(TOTAL)
CNT-=1
TXT = ["20","50","30","40"]
L1(TXT)
b)The program to illustrate Insertion of records to database in Python is
given below. Note the following to establish connectivity between Python
and MYSQL:
• Username is root
• Password is tiger
2+3
285 | P a g e
• The table exists in a MYSQL database named Company.
import mysql.connector as mysql
try:
det=ps.connect(host='localhost',user='root',password='tiger',databa
se='Company')
cmd=_________#Statement 1
pid=input("Enter Product Id:")
pn=input("Enter Product Name:")
pr = input("Enter Product Rate:")
md = input("Enter Mf. Date:")
query="insert into products values('{}','{}',{},'{}')"
.format(pid,pn,pr,md)
____________#Statement 2
____________ #Statement 3
det.close()
print("Record Submitted")
except Exception as e:
print(e)
OR
a)Write the output of the code
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
286 | P a g e
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
b)The code given below search for a record using ID in Python
The employee table consists of the following details:
Employee Name
Salary
Designation
City
Birth Date
Note the following to establish connectivity between Python and
MYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named Company.
import mysql.connector as mysql
try:
db=mysql.connect(host="localhost",user="root",password='tiger',
database="Company")
cmd=________.# Statement1
id=input("Enter Id you Want to Search?")
q="Select * from employee where employeeid={0}".format(id)
___________#Statement2
row=_______#Statement3
if(row):
287 | P a g e
print("Employee Name:",row[1])
print("Salary:", row[2])
print("Designation:",row[3])
print("City:", row[4])
print("Birth Date:", row[5])
else:
print("Record Not Found....")
db.close()
except Exception as e:
print(e)
Answers:
a)
47.0
35.0
54.0
26.0
b)Answer:
Statement 1---det.cursor()
Statement 2---cmd.execute(query)
Statement 2---det.commit()
OR
a)SCHOOLbb
SCHOOLbbbb
b)Answer:
288 | P a g e
Statement1---db.cursor()
Statement2---cmd. .execute(q)
Statement3: cmd.fetchone()
33) What is pickle module and why we use this module?
Thetablegiven below have the details of customer.The name of the file
iscust.csv, write a code to insert multiple rows in the csv file.
SNo Customer Name City Amount
1 Dhaval Anand 1500
2 Anuj Ahmedabad 2400
3 Mohan Vadodara 1000
4 Sohan Surat 700
Pickle module provides us the ability to serialize and deserialize objects that
is, it helps to convertobjects into bitstreams that can be stored in files and
later utilized to recreate the original objects.
For us, writing different kinds of objects into the binary file and later, reading
the file's content is really challenging.The fact that some of the objects may
have changing lengths makes this a tedious task. So we use the pickle
module to solve this issue since it can handle dictionaries, sets, lists, tuples,
classes, and more.It can store lists, Tuples, dictionaries, sets, classes etc.
Program
from csv import writer
with open("cust.csv","a",newline="n") as f:
dt = writer(f)
while True:
sno= int(input("Enter Serial No:"))
cust_name = input("Enter customer name:")
city = input("Enter city:")
amt = int(input("Enter amount:"))
dt.writerow([sno, cust_name, city, amt])
print("Record has been added.")
print("Want to add more record?Type YES!!!")
ch = input()
ch = ch.upper()
if ch=="YES":
print("*************************")
else:
break
5
289 | P a g e
OR
What is a Binary File? Give examples.
The detail of marks of class XII are stored in file named RESULTS.CSV.
Raman, the Maths teacher wants to search the details of one student. Write
a program to search the details based on name .
A binary file is a file whose content is in a binary format consisting of a
series of sequential bytes, each of which is eight bits in length.Binary Files
contain raw data so are not in human readable format. It can be read by
using some special tool or program.
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc
b)
import csv
def searchname():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
name=input('Name to search? ')
found=0
for stu in stulist:
if name.upper()==stu[1]:
print(stu[0], stu[1], stu[2], sep='t')
found=1
break
fobj.close()
if found==0:
print(name,'not found in the file')
SECTION E
34) Consider the following DEPT and WORKER tables. Write SQL queries
for (i) to and (iv) find outputs for queries (v) to (viii):
1+1
+2
290 | P a g e
Table: DEPT
DCODE DEPARTMENT CITY
D01
D02
D03
D05
D04
MEDIA
MARKETING
INFRASTRUCTURE
FINANCE
HUMAN RESOURCE
DELHI
DELHI
MUMBAI
KOLKATA
MUMBAI
Table: WORKER
WNO NAME DOJ DOB GENDER DCODE
1001
1002
1003
1007
1004
1005
1006
George K
Ryma Sen
Mohitesh
Anil Jha
aya Priya
Manilasahai
R Sahay
2013-09-02
2012-12-11
2013-02-03
2014-01-17
2012-12-09
2013-11-18
2014-06-09
1991-09-01
1990-12-15
1987-09-04
1984-10-19
1986-11-14
1987-03-31
1985-06-23
MALE
FEMALE
MALE
MALE
FEMALE
MALE
FEMALE
D01
D03
D05
D04
D01
D02
D05
DOJ refers to date of joining and DOB refers to date of birth of workers.
(i) To display Wno, Name, Gender from the table WORKER in
descending order of Wno.
(ii) To display the Name of all the FEMALE workers from the table
WORKER.
(iii) Write statements
a) To display the Wno and Name of those workers from the table
WORKER who are born between '1987-01-01' and '1991-12-01'.
291 | P a g e
b) To count and display MALE workers who have joined after '1986-01-
01"..
OR
(iii) Write the output for the given statements
a) SELECT COUNT(*), DCODE FROM WORKER GROUP BY
DCODE HAVING COUNT(*) > 1;
b) SELECT DISTINCT DEPARTMENT FROM DEPT;
Answers:
i) SELECT WNO, NAME, Gender, FROM WORKER ORDER BY WNO
Desc;
ii) SELECT NAME FROM WORKER WHERE GENDER = 'FEMALE';
iii)
a) SELECT WNO, NAME, FROM WORKER WHERE DOB BETWEEN
'1987-01-01' AND '1991-12-01';
b) SELECT count(*) FROM WORKER WHERE GENDER = 'MALE'
AND DOJ > '1986-01-01';
OR
iii) a) COUNT(*) DCODE
2D01
2D05
b) DISTINCT DEPARTMENT
MEDIA
MARKETING
INFRASTRUCTURE
FINANCE
HUMAN RESOURCE
292 | P a g e
35) Arun, during Practical Examination of Computer Science, has been
assignedan incomplete search() function to search in a pickled file
student.dat. The Filestudent.dat is created by his Teacher and the
following information is knownabout the file.
• File contains details of students in [roll_no,name,marks] format.
• File contains details of 10 students (i.e. from roll_no 1 to 10) and
separate list of each student is written in the binary file using dump().
Arun has been assigned the task to complete the code and print details
of rollnumber 1.
def search():
f = open("student.dat",_________)#Statement-1
____: #Statement-2
while True:
rec = pickle.____#Statement-3
if(____): #Statement-4
print(rec)
except:
pass
____ #Statement-5
I). In which mode Arun should open the file in Statement-1?
a) r
b) r+
c) rb
d) wb
II). Identify the suitable code to be used at blank space in line marked
as Statement2
a) if(rec[0]==1)
b) for i in range(10)
c) try
d) pass
III). Identify the function (with argument), to be used at blank space in
line marked
as Statement-3.
a) load()
b) load(student.dat)
c) load(f)
d) load(fin)
IV). What will be the suitable code for blank space in line marked as
Statement-4.
a) rec[0]==2
b) rec[1]==2
c) rec[2]==2
d) rec[0]==1
Answers
1+1
+2
293 | P a g e
KENDRIYA VIDYALAYA SANGATHAN-CHENNAI REGION
CLASS: XII Session 2022-2023
COMPUTER SCIENCE (083)
SAMPLE QUESTION PAPER - IV
Max. Marks: 70 Time Allowed: 3 Hrs.
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 question 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 Q35 against part C
only.
8. All programming questions are to be answered using Python Language only.
SECTION-A
1 Which of the following is not a valid identifier in Python?
a)KV2 b) _main c) Hello_Dear1 d) 7 Sisters
1
2 A variable created or defined in a function body is known as…
a)local b) global c) built-in d) instance
1
3 Suppose list1 = [0.5 * x for x in range(0,4)], list1 is
a) [0, 1, 2, 3] b) [0, 1, 2, 3, 4]
c) [0.0, 0.5, 1.0, 1.5] d) [0.0, 0.5, 1.0, 1.5, 2.0]
1
4 Which statement is not correct
a)The statement x = x + 10 is a valid statement b)List slice is a list itself.
c)Lists are immutable while strings are mutable.
d)Lists and strings in pythons support two way indexing.
1
5 What will be the output of following code snippet:
msg = “Hello Friends”
msg [ : : -1]
1
I. c
II. c
III. a load(f)
IV. d. rec[0]==1
294 | P a g e
a)Hello b) Hello Friend c) 'sdneirF olleH' d) Friend
6 Which of the following function is used to write data in binary mode?
a) write ( ) b) output ( ) c) dump ( ) d) send ( )
1
7 Suppose a tuple T1 is declared as T1 = (10, 20, 30, 40, 50) which of the following is
incorrect?
a)print(T[1]) b) T[2] = -29 c) print(max(T)) d) print(len(T))
1
8 What will be output of following:
d = {1 : “SUM”, 2 : “DIFF”, 3 : “PROD”}
for i in d:
print (i)
a)1 b) SUM c) 1 d) 3
2 DIFF SUM SUM
3 PROD 2 3
DIFF DIFF
3 3
PROD PROD
1
9 What will be output of following code:
X = 50
def funct(X):
X = 2
funct (X)
print(„X is now: „, X)
a) X is now: 50 b) X is now: 2 c) Error d) None of the above
1
10 To read the next line from the file object fob, we can use:
a)fob.read(2) b) fob.read( ) c) fob.readline( ) d) fob.readlines( )
1
11 TCP/IP stands for
a) Transmission Communication Protocol / Internet Protocol
b) Transmission Control Protocol / Internet Protocol
c) Transport Control Protocol / Interwork Protocol
d) Transport Control Protocol / Internet Protocol
1
12 An attack that encrypts files in a computer and only gets decrypted after paying
money to the attacker..
a) Botnet b) Trojan c) Ransomware d) Spam
1
13 Which is known as range operator in MySQL.
a) IN b) BETWEEN c) IS d) DISTINCT
1
14 If column “salary” of table “EMP” contains the dataset {10000, 15000, 25000, 10000,
25000}, what will be the output of following SQL statement?
SELECT SUM(DISTINCT SALARY) FROM EMP;
a) 75000 b) 25000 c) 10000 d) 50000
1
15 Which of the following functions is used to find the largest value from the given data 1
295 | P a g e
in MySQL?
a) MAX ( ) b) MAXIMUM ( ) c) LARGEST ( ) d) BIG ( )
16 Name the clause used in query to place the condition on groups in MySQL? 1
Q17 and 18 are Assertion and Reasoning based questions.Mark the correct choice as
a)A is true R is false
b) A is false and R is true
c) Both A and R are correct and R is correct explanation of A
d) Both A and R are correct and R is not correct explanation of A
1
7
Assertion : The number of addresses used in IPv6 addressing method is 128
Reason : IPv6 address is a 128 bit unique address
1
1
8
Assertion : Delete command is used to remove rows or records from table.
Reason : This command is used to remove records along with structure of the table from
database
1
SECTION B
1
9
Rewrite the following code after removing the syntactical error(if any).Underline each
correction:
X=input("Enter a Number")
If x % 2 =0:
for i range (2*x):
print i
loop else:
print "#"
2
2
0
Write two points of difference between Client side script and Server side script
OR
Write two advantages of Twisted pair cable.
2
2
1
Write the output of the following python code:
def func(b):
global x
print ('Global x=',x)
y=x+b
x=7
z=x-b
print ('Local x=' ,x)
print ('y=' ,y)
print ('z=' ,z)
x=5
func(10)
2
2
2
What is the purpose of BETWEEN clause? 2
2
3
a) What do the following top level domains signify? (i) .com (ii) .org
b)What is the use of VoIP?
2
2 Write the output of the following python code: 2
296 | P a g e
4 x=7
def new():
x=70
print("x=",x)
print("x=",x)
new()
print("x=",x)
OR
Write the output of the following python code:
Numbers =[9,18,27,36]
for num in Numbers:
for N in range(1,num%8):
print(N,"$",end="")
print()
2
5
Differentiate between equi join and cross join function in SQL with a example
OR
Categorize the folowing commands as DML or TCL
COMMIT ,UPDATE , DELETE ,SAVE POINT
2
SECTION –C
2
6
a)Observe the table ‘Club’ given below:Table: Club
Member_id Member_name Address Age Fee
M001 Sujith New delhi 20 2000
M002 Nisha Trichy 18 3500
M003 Tarun Chennai 22 2100
M004 Arjun Coimbatore 19 3200
What is the cardinality and Degree of above table
b) Write the queries of the i to iv based on the table: Shop given below
Table: Shop
Code Iname Qty Price Company
101 Digital Pad 120 11000 Xenita
105 Pen Drive 64 GB 500 7000 Hp
103 LED Screen 40' 50 25000 Samsung
104 Car GPS system 20 9000 Digiclick
i) To display the details of all the item in ascending order of item names
ii)To display item name and price of all those items whose price in range of 10000 to
30000
iii) To display max and min price of the table
iv)To display the total amount of digiclick company
3
2
7
Write a function show_word() in python to read the contant of a text file 'words.txt' and
display the entire content in upper case.example,if the file contain
"I love my country ,i am proud to be indian"
3
297 | P a g e
Then the function should display the output as:
I LOVE MY COUNTRY ,I AM PROUD TO BE INDIAN
OR
Write a function mycount() in python to read the text file 'file.txt' and count the number
of times "i" occurs in the file. example,if the file is 'file.txt'contains:
"I love my country ,i am proud to be indian"
The mycount()function should display the output as:
"i occurs 4 times".
2
8
a) Write the output of the SQL queries i to iv based on the relations CARHUB and
CUSTOMER given below:
Table :CARHUB
Vcode Vehicle
Name
Make Color Capacity Charges
100 Innova Toyota White 7 15
102 SX4 Suzuki Blue 4 14
104 C Class Mercedes Red 4 35
105 A-star Suzuki White 3 14
108 Indigo Tata Silver 3 12
Table : CUSTOMER
CCode CName Vcode
1 Rajesh 101
2 Leela 108
3 John 105
4 Feroza shah 104
i)select vehiclename from carhub where color='white';
ii)select max,min from carhub;
iii)select count(*),make carhub;
iv)select cname,vehiclename,from customer,carhub where
customer.vcode=carhub.vcode;
b)Write the command to view all the tables in a database.
3
2
9
Write a python program using function to demonstrate random() with dictionary.
Should create the dictionary of 5 keys:valus random character as key and ASCII as its
value.
3
3
0
A list contains following records of students:
[Adm_no,SName,DOB,Mobile]
Write the following user defined function to perform given operations on the stack
named 'Admission':
i)PUSH() To insert an object containing admission number,student name and Mobile of
the students who's birth year is after 2008 to the stack. If stack holds more than 3 elements
show "stack is full"
ii) POP() To pop the object from the stack and display them in stack one by one.
For Example:
If the lists of students detail are :
["20221017","Guru","20-7-2008","9988779988"]
["20221018","Ragunath","06-8-2009","9977889988"]
["20221019","Jenifer","31-12-2007","9988996677"]
["20221020","Priya","21-10-2009","9966557864"]
3
298 | P a g e
The stack should contain
["20221017","Guru","9988779988"]
["20221018","Ragunath","9977889988"]
["20221020","Priya","9966557864"]
The output should contain
["20221017","Guru","9988779988"]
["20221018","Ragunath","9977889988"]
["20221020","Priya","9966557864"]
Stack is full
OR
Write a function in python, makepush(var) and makepop(var) ,to add a new variable and
delete a variable from list of variables description, considering them to act as push and pop
operations of the stack data structure.
SECTION-D
3
1
Uplifting Skills Hub India is a knowledge and skill community which has an aim to
uplift the standard of knowledge and skills in the society. It is planning to setup its training
centers 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 (a) to (d) keeping in mind the distances between various
locations and other given parameters.
Shortest distances between various locations:
Village 1 To B_Town 2 KM
Village 2 To B_Town 1.0
KM
Village 3 To B_Town 1.5
KM
Village 1 To Village 2 3.5
KM
Village 1 To Village 3 4.5
KM
Village 2 To Village 3 2.5
KM
A_city Head office to
B_HUB
25 KM
Number of Computers installed at various locations are as follows:
B_Town 120
Village 1 15
Village 1 10
Village 1 15
A_city Office 6
Note:
In Villages, there are community centers, in which one room has been given as training
center to this organization to install computers. The organization has got financial support
from the government and top IT companies.
(a) 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.
5
299 | P a g e
(b) Suggest the best wired medium and draw the cable layout (location to location) to
efficiently connect various locations within the B_HUB.
(c) Which hardware device will you suggest to connect all the computers within each
location of B_HUB?
(d) Which service/protocol will be most helpful to conduct live interactions of Experts
from Head Office and people at all locations of B_HUB
(e) Which type of network would be formed if B_HUB is connected to their A_city
3
2
a) What will be the output of the following python code?
v=25
def fun(ch):
v=50
print (v ,end=ch)
print(v, end="*")
fun("!")
print(v)
b)The code given below insert the record in the table employee:
Empno – integer
Name – string
Dept – string
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
❖ Username is host
❖ Password is root
❖ The table exists in a MYSQL database named company.
❖ The details (eno, Name, Dept and Salary) 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 employee.
Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="host", password="root",
database="company")
mycursor=_________________ #Statement 1
eno=int(input("Enter Employee Number :: "))
name=input("Enter name :: ")
dept=input("Enter department :: ")
salary=int(input("Enter salary :: "))
querry="insert into employee values({},'{}','{}',{})".format(eno,name,dept,salary)
______________________ #Statement 2
______________________ # Statement 3
5
300 | P a g e
print("Data Added successfully")
OR
a) Predict the output of the code given below:
str1=input ("Enter a string: ")
str2="aAeEiIoOuU"
v,c=0,0
for i in str1:
if i in str2:
v+=1
else:
c+=1
print ("The given string contains { } vowels and { } consonants".format(v,c))
b) The code given below reads the following record from the table named employee and
displays
only those records who have salary greater than 65000:
Empno – integer
Name – string
Dept – string
Salary – integer
Note the following to establish connectivity between Python and MYSQL:
❖ Username is host
❖ Password is root
❖ The table exists in a MYSQL database named company.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those employee whose salary
are greater
than 65000.
Statement 3- to read the complete result of the query (records whose salary are greater
than 65000) into the object named data, from the table employee in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="host",
password="root", database="company")
mycursor=_______________ #Statement 1
print("Employee with salary greater than 65000 are : ")
_________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()
301 | P a g e
3
3
What are the merits of using a csv file for storage?
Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of an Library to a CSV file ‘books.csv’. Each record
consists of a list with field elements as bno, name,Author and type to store Book number
id, Book name, Author Name and Type of Book respectively.
OR
Give any one point of difference between a text file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
(i) update() – To accept and update data of a student to a CSV file ‘mark.csv’. Each
record consists of a list with field elements as sid, sname and sclass to store student id,
student name and student class respectively.
5
SECTION-E
3
4
Write SQL commands for the following queries based on the relation Teacher given
below:
Table: Teacher
N
o Name
Ag
e
Departme
nt
Date_of_jo
in
Salar
y
Se
x
1 Jugal 34 Computer 10-01-1997
1200
0 M
2
Sharmil
a 31 History 24-03-1998
2000
0 F
3
Sandee
p 32 Maths 12-12-1996
3000
0 M
4
Sangeet
a 35 History 01-07-1999
4000
0 F
5 Rakesh 42 Maths 05-09-1997
2500
0 M
6 Shyam 50 History 27-06-1998
3000
0 M
7
Shiv
Om 44 Computer 25-02-1997
2100
0 M
8
Shalak
ha 33 Maths 31-07-1997
2000
0 F
(i) To show all information about the teacher of Computer department.
(ii) To list the names of all teachers with their date of joining in descending order.
(iii) Write the statements to
a) Delete the record of teacher age greater than 45
b)Increase the salary of teachers by 15% whose department is history
OR
4
302 | P a g e
a) To count the number of teachers with age less than 35
b)Add column QUALIFICATION in the table with datatype as varchar with 50
characters.
3
5
Mr.Mathew is a Python programmer. who has recently joined the company and given a
task to write a python code to perform update operation in binary file(stud.dat)which
contain admno(Admission no) and fee(Fee paid by student).
He has succeeded in writing partial code and has missed out certain statement ,you as an
expect of python have to provide the missing statements.
import _______ #Statement 1
St={}
Flag=0
File=open("____________","rb+) #Statement 2
Search=int(input("Enter Admission number whose fee is to be updated :"))
Amt=int(input("How much to be incresed:"))
try:
while True:
Try:
Pos=file.tell()
St=pickle.load(file)
If st['admno']==search:
st['fee']+=amt
file._________(pos) #Statement 3
pickle.__________(st.file) #Statement 4
print("Record Updated")
flag=1
expect EOFError:
if flag=0:
print("Record not found")
file.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open binary file (Statement 2)
(iii) Which statement should be fill in Statement 3 to place the file pointer at specified position
and statement 4 used to store the data
4
303 | P a g e
KENDRIYA VIDYALAYA SANGATHAN-CHENNAI REGION
CLASS: XII Session 2022-2023
COMPUTER SCIENCE (083)
SAMPLE PAPER - IV MARKING SCHEME
Section-A
1. d) 7 Sisters 1
2. a) local 1
3. c) [0.0, 0.5, 1.0, 1.5] 1
4. c) Lists are immutable while strings are mutable. 1
5. c) 'sdneirF olleH' 1
6. c) dump ( ) 1
7. b) T[2] = -29 1
8. a) 1
2
3
1
9. a) X is now: 50 1
10. c)fob.readline( ) 1
11. b) Transmission Control Protocol / Internet Protocol 1
12. c) Ransomware 1
13. b) BETWEEN 1
14. d) 50000 1
15. a) MAX ( ) 1
16. HAVING Clause 1
17. c) Both A and R are correct and R is correct explanation of A 1
18. a)A is true R is false 1
SECTION-B
19 x=input("Enter a Number")
if x % 2= =0: error 1
for i in range (2*x): error 2
print (i) error 3
else:
print ("#") error 4
1 2
⁄ mark for each correct correction made and underlined.)
20 Client Side Script Server Side Script
It is downloaded and run t client end It run at server end and result is send to
client end(browser).
304 | P a g e
It is browser dependent. It is not browser dependent
Eg:JavaScript ,VBScript Eg:ASP,JSP
( 1 mark for each correct point of difference)
OR
Advantages of Twisted Pair cable
• It is easy to install and maintain
• It is very inexpensive
• It can be easily connected
• It is flexible
( 1 mark for each correct point)
21 Global x=5
Local x=7
y=15
z=-3
( 2 mark for correct output)
22 Between clause is used to filter the record by providing the range in a column which
contains only a numeric value Text,Data can also be used with BETWEEN clause
Eg: select * from student where age between 15 and 18;
(1 mark for explanation and 1 mark for correct qurey)
23 a) (i) .com - commercial business
(ii) .org - organization (non profit)
(1 2
⁄ mark for each answer)
b) Voice over Internet Protocol Transmission of voice and multimedia content over
internet protocol(IP) network is through VoIP
(1 mark for correct answer)
24 X=7
X=70
X=7
(1 mark for correct answer)
OR
1 $
305 | P a g e
1 $ 2 $
1 $ 2 $ 3 $
(1 mark for correct answer)
25 Join clause is used to combine records from two or more tables in a database
they can be in two ways Equi Join and Cross Join
Equi Join Cross Join/Cartesian Product
It returns data from the table with matching
values
A product of two or more sets that
consists of all combinations of
records from two tables are joined
Syntax:
Select column from table1,table2 where
table1.common_col=table2.common_col
Syntax:
Select column from table1,table2
(1 mark for each difference)
OR
DML -UPDATE ,DELETE
TCL - COMMIT ,SAVE POINT
(1 mark for each category )
SECTION -C
26 (a) Cardinality: 4 Degree: 5
(1 mark for correct answer)
(b)
(i) select * from item order by iname;
(ii) select iname,price from shop where price between 10000 and 30000;
(iii) select max,min from shop;
(iv)select price*qty from shop where code=104;
(1
2
⁄ mark for each correct query )
27 def show_word():
file=open( "words.txt",'r')
Lines=file.readlines()
306 | P a g e
for L in Lines:
Print(L.upper())
File.close()
( ½ mark for correctly opening and closing the file
½ for readlines()
½ mark for correct loop
1 mark for using proper functions
½ mark for displaying the correct output)
OR
def mycount():
f=open("file.txt",'r')
count=0
x=f.read()
word=x.split()
for i in word:
if i=="I":
count =count +1
print("my occurs",count,"times")
f.close()
mycount()
( ½ mark for correctly opening and closing the file
½ for read()
½ mar for correct loop
½ for correct if statement
½ mark for correctly incrementing count
½ mark for displaying the correct output)
28 a)
i) Innova
A-Star
ii) Max Min
35 12
307 | P a g e
iii) count(*)
5
iv) Customer Name Vehicle Name
Leela Indigo
John A-star
Feroza Shah C Class
(½ mark for displaying the correct output)
b) Show Tables;
(1 mark for correct query)
29 import random
def createDict():
a={ }
for i in range(5):
x=random.randint(65,90)
x=chr(x)
n=random.randint(10,99)
a.update({x:n})
return a
dict =createDict()
print ("Dictionary :",dict)
(½ mark for correct function header
1 mark for correct loop
1 mark for using correct function
½ mark for return statement)
30 status =[ ]
def Push_ele(stud):
if len(status) ≤ 3
if stud[2] ==2008:
L1=[stud[0],stud[1]]
308 | P a g e
Status.append(L1)
Else:
Print("Stack is Full")
def pop_ele():
num=len(status)
while len(status)!=0:
dele=status.pop()
print(dele)
num=num-1
else:
print("Stack Empty")
(1.5 marks for correct push_element() and 1.5 marks for correct pop_element())
OR
def makepush(var):
a=int(input("Enter Variable name:"))
var.append(a)
def makepop(var):
if (var ==[ ]):
print(stack empty")
else:
print("Deleted Variable:",var.pop())
(1.5 marks for correct makepush() and 1.5 marks for correct makepop())
SECTION D
31 (a) B_TOWN. Since it has the maximum number of computers and is closest to all other
locations.
(b)
309 | P a g e
(c) Switch OR Hub
(d) Videoconferencing OR VoIP OR any other correct service/protocol
(e ) MAN- Metropolitan Area Network
(1 Mark for each correct answer)
32 a) Output:
25*50!100!25
b)Output:
Statement 1:
con1.cursor( )
Statement 2:
mycursor.execute(querry)
Statement 3:
con1.commit( )
(1 mark for each correct answer)
OR
a) Output
Entered string : Tamilnadu
The given string contains 4 vowels and 5 consonants
b) Output:
Statement 1:
con1.cursor( )
Statement 2:
mycursor.execute("select * from employee where salary >65000")
Statement 3:
mycursor.fetchall( )
(1 mark for each correct answer)
33 Ans:
Merits of a csv file:
❖ It is human readable – can be opened in Excel and Notepad applications
❖ It is just like text file
❖ Easy to extract data as required.
Program
def addrecord():
try:
csvfile=open('e:datasetdata.csv','a',newline='')
csvobj=csv.write(csvfile)
310 | P a g e
while True:
bno=int(input("Book Number:"))
name=input("Title of the Book:")
author=input("Author Name :")
type=input("Type of the Book :")
Line=[bno,name,author,type]
csvobj.writerow(Line)
ch=input("More (Y/N)?")
if ch=='N':
break
expect:
csvfile.close( )
addrecord()
(1 mark for merits
1 mark for importing csv module
1½ mark for each correct definition of ADD()
½ mark for function call statement
½ mark for return statement)
OR
a) Binary file:
❖ Extension is .txt
❖ Default file type
❖ Used to store character data
CSV file
❖ Extension is .csv
❖ Human readable
❖ Stores data like a text file
b) Program
def modifysid( ):
csvfile=open('e:datasetmark.csv','r',newline='')
csvobj=csv.reader(csvfile)
n=input("Enter the Student ID to be searched")
l=[ ]
k=[ ]
for Line in csvobj:
if Line[0] ==n:
print("Record Found‼!")
t=input("Enter Class")
311 | P a g e
k=[Line[0],Line[1],Line[2],t]
l.append(k)
print (Line)
else:
l.append(Line)
else:
print ("Record not found")
print(l)
csvfile.close( )
csvfile=open('e:datasetmark.csv','w',newline='')
csvobj=csv.witer(csvfile)
for i in l:
csvobj.writerow(i)
csvfile.close()
modifysid()
(1 mark for difference
1 mark for importing csv module
1½ mark for each correct definition of search statement
½ mark for function call statement
½ mark for append( ) statement)
SECTION E
34 Output:
i) SELECT * FROM TEACHER WHERE DEPARTMENT ="COMPUTER";
II)SELECT NAME FROM TEACHER ORDER BY DATE_OF_JOIN DESC
iii) a) Delete From Teacher Where Age≥45
b) UPDATE TEACHER SET SALARY=SALARY +(SALARY*0.15) WHERE
DEPARTMENT="HISTORY";
OR
iii) a)SELECT COUNT(*) FROM TEACHER WHERE AGE ≤ 35;
b) ALTER TABLE TEACHER ADD(QUALIFICATION VARCHAR(50));
(1 mark for each correct statement)
35 i) Statement 1: import pickle
ii) Statement 2: file =open ("stud.dat","rb+")
iii) Statement 3: file.seek(pos)
Statement 4: pickle.dump(st,file)
(1 mark for each correct statement)
312 | P a g e
KENDRIYA VIDYALAYA SANGATHAN -CHENNAI REGION
Class: XII Session: 2022-23
Computer Science (083)
Sample Question Paper - V
Maximum Marks: 70 Time Allowed: 3 hours
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 Q35 against part
c only.
8. All programming questions are to be answered using Python Language only.
SECTION A
1. State True or False
“Python identifiers are dynamically typed.”
1
2. Which of the following is an invalid operator in Python?
(a)- (b) //= (c)in (d) =%
1
3. Given the following dictionary
employee={'salary':10000,'age':22,'name':'Mahesh'}
employee.pop('age')
print(employee)
What is output?
a. {‘age’:22}
b. {'salary': 10000, 'name': 'Mahesh'}
c. {'salary':10000,'age':22,'name':'Mahesh'}
d. None of the above
1
313 | P a g e
4. Consider the given expression:
True and False or Not True
Which of the following will be correct output if the given expression is evaluated?
(a) True
(b) False
(c) NONE
(d) NULL
1
5. What will the following code print?
print(max("zoo 145 com"))
a. 145 b. 122 c. z d. zoo
1
6. Which of the following statements is incorrect regarding the file access modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.
b. ‘w+’ opens a file for both writing and reading. Overwrites the existing file if it
exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it
exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the end of the file if the file
exists.
1
7. All aggregate functions except ___________ ignore null values in their input
collection.
a) Count (attribute) b) Count (*) c) Avg () d) Sum ()
1
8. Which of the following SQL commands will change the attribute value of an
existing tuple in a table?
(a) insert
(b) update
(c) alter
(d) change
1
314 | P a g e
9. Consider the following code that inputs a string and removes all special characters
from it after converting it to lowercase.
s = input("Enter a string")
s = s.lower()
for c in ',.;:-?!()'"':
_________________
print(s)
For eg: if the input is 'I AM , WHAT I AM", it should print
i am what i am
Choose the correct option to complete the code .
a. s = s.replace(c, '')
b. s = s.replace(c, '0')
c. s = s.replace(c, None)
d. s = s.remove(c)
1
10. Fill in the blank:
An attribute or set of attributes in a table that can become a primary key is termed as -
--------------------
a) Alternate key
b) Candidate key
c) Foreign key
d) Unique key
1
11. Observe the following code snippet
file = open(“station.txt”,”r”)
try:
……..
except EOFError: # When will this line execute
……..
When will the line underlined execute?
a. When the file is closed.
b. This is a text file.
c. When the file pointer is at the beginning of the file.
1
315 | P a g e
d. When the file pointer has reached the end of file.
12. Fill in the blank:
The SELECT statement when combined with __________ clause, is used for pattern
matching
(a) Order by
(b) distinct
(c) like
(d) between
1
13. ______is a standard network protocol used to transfer files from one
host to another host over a TCP-based network, such as the
Internet.
a) TCP
b) IP
c) FTP
d) SMTP
1
14. What will the following expression be evaluated to in Python?
2**3**2+15//3
a) 69
b) 517
c) 175
d) 65
1
15. Identify the invalid SQL aggregate function from the following
a) sum b)max c)min d) add
1
16. Identify the invalid method to get the data from the result set of query fetched by a
cursor object mycursor.
a) mycursor.fetchone()
b) mycursor.fetchall()
c) mycursor.fetchmany()
d) mycursor.fetchnow()
1
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
316 | P a g e
17. Assertion (A):-global keyword is used inside a function to enable the function alter the
value of a global variable.
Reasoning (R):- A global variable can not be accessed by a function without the use of
global keyword.
1
18. Assertion (A): The ‘with’ block clause is used to associate a file object to a file.
Reason (R): It is used so that at the end of the ‘with’ block the file resource is
automatically closed.
1
SECTION B
19. Shraddha wrote the code that, prints the sum of numbers between 1 and the number, for
each number till 10.She could not get proper output.
i = 1
while (i <= 10): # For every number i from 1 to 10
sum = 0 # Set sum to 0
for x in range(1,i+1):
sum += x # Add every number from 1 to i
print(i, sum) # print the result
a) What is the error you have identified in this code ?
b) Rewrite the code by underlining the correction/s.
2
20. Write two points of difference between star and bus topology.
OR
Differentiate Web browser and Webserver.
2
21. a) Write the output of the code snippet.
txt = "Time, will it come back?"
x = txt.find(",")
y = txt.find("?")
print(txt[x+2:y])
b) The score of a student in a test is stored as a Python tuple. The test had 3 questions,
with some questions having subparts whose scores are recorded separately.Give the
output of the code snippet.
1
1
317 | P a g e
score = (6, (5, (2, 1), 8), (4, 3, (1, 3, 2)))
print (score [2][2])
22. What is a not null constraint in SQL? Give example to illustrate. 2
23. (a) Write the full forms of the following:
(i) SMTP (ii) URL
(b)Differentiate http and https protocols.
2
24. Predict the output of the Python code given below:
value = 50
def display(N):
global value
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")
display(20)
print(value)
OR
Predict the output of the Python code given below:
l=[]
for i in range(4):
l.append(2*i+1)
print(l[::-1])
2
318 | P a g e
25. Differentiate betweendrop anddelete commands in SQL with appropriate example.
OR
What is the use of order by clause in SQL ? Give example.
2
SECTION C
26 i) Considering the following table SALEORDER which stores the name of items
sold on a day ,give the output of the query that follows:-
DATE ITEM
12-09-2022 RICE
12-09-2022 RICE
12-09-2022 SUGAR
12-09-2022 RICE
12-09-2022 COFFEE
12-09-2022 COFFEE
12-09-2022 TEA
SELECT ITEM,COUNT(*) FROM SALEORDER GROUP BY ITEM HAVING
COUNT(*)>1;
ii)Writethe outputofthequeries(a)to(d)basedonthetable BOOK,given below:
(a) SELECT PUBLISHER,PRICE FROM BOOK WHERE QTY>=10;
(b) SELECT BOOK_NAME, TYPE FROM BOOK WHERE BOOK_NAME LIKE 'T%';
(c) SELECT SUM(PRICE) FROM BOOK WHERE PUBLISHER IN (‘EPB’,’TMH’);
(d) SELECT MIN(QTY) FROM BOOK WHERE PRICE>500;
Book_Id Book_Name Publisher Price Type Qty
F0001 The Tears EEE 750 Fiction 10
F0002 Thunderbolts EEE 700 Fiction 5
T0001 Let us C++ EPB 250 Text 10
T0002 C++ Brain TMH 325 Text 5
C0001 Fast Cook EPB 350 Cookery 8
1+2
319 | P a g e
27. Write a Python function which reads a text file “poem.txt” and prints the
number of vowels in each line of that file, separately.
Eg: if the content of the file “poem.txt” is
The plates will still shift
and the clouds will still spew.
The sun will slowly rise
and the moon will follow too.
The output should be
6
7
6
9
OR
Write a Python program that writes the reverse of each line in “input.txt”
to another text file “output.txt”. Eg: if the content of input.txt is:
The plates will still shift
and the clouds will still spew.
The sun will slowly rise
and the moon will follow too.
The content of “output.txt” should be:
tfihs llits lliw setalp ehT
.weps llits lliw sduolc eht dna
esir ylwols lliw nus ehT
.oot wollof lliw noom eht dna
3
28 (a) Write the outputs of the SQL queries (i) to (iii) based on the tables VEHICLES and
TRAVELS
Table: VEHICLE
VCODE VEHICLETYPE PERKM
V01 VOLVO BUS 150
3
320 | P a g e
V02 AC DELUXE
BUS
125
V03 ORDINARY
BUS
80
V04 CAR 18
V05 SUV 30
Table: TRAVEL
CNO CNAME TRAVELDATE KM VCODE NOP
101 Arun 2015-12-13 200 V01 32
102 Balaji 2016-06-21 120 V03 45
103 Vignesh 2016-04-23 450 V02 42
104 Selva 2016-01-13 80 V02 40
105 Anupam 2015-02-10 65 V04 2
106 Tarun 2016-04-06 90 V05 4
● PERKM is Freight Charges per kilometer.
● Km is kilometers Travelled
● NOP is number of passengers travelling in vehicle.
(i) SELECT VCODE, COUNT(*) AS NUMTRIPS
FROM TRAVEL
GROUP BY VCODE;
(ii) SELECT CNAME, TRAVEL.VCODE, VEHICLETYPE
FROM VEHICLE, TRAVEL
WHERE VEHICLE.VCODE = TRAVEL.VCODE AND NOP >= 30;
(iii) SELECT MAX(TRAVELDATE), MIN(TRAVELDATE)
FROM TRAVEL ;
(iv) SELECT VEHICLETYPE FROM VEHICLE WHERE VEHICLETYPE LIKE
“%BUS”;
(b) Write the command to view the structure of the table TRAVEL.
321 | P a g e
29 Write a function sumcube(L) to test if an element from list L is equal to the sum of the
cubes of its digits ie it is an ”Armstrong number”. Print such numbers in the list.
If L contains [67,153,311,96,370,405,371,955,407]
The function should print 153,370,371,407
3
30 Vikram has a list containing 10 integers. You need to help him to create a program with
separate user defined functions to perform the following operations based on this list.
● pushnum() to Traverse the content of the list and push the numbers that are divisible by 5
into a stack.
● popnum() to Pop and display the content of the stack and display “Stack underflow” if
the stack is empty.
For Example:
If the sample Content of the list is as follows:
N=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
35
55
10
OR
Write a function in Python, Push(Ride) where , Ride is a dictionary containing the details
of Cab ride , Ride={driver: billamt }.
The function should push the names of those driver names in the stack,INCENTIVE who
have billed greater than 400. Also display the count of names pushed into the stack
For example:
If the dictionary contains the following data:
Ride={‘Raghu’:389,’Anbu’:560,’Siraj’:768,’Syed’:450 }.
The stack INCENTIVE should contain
[‘Anbu’,’Siraj’,’Syed’]
The output should be:
The count of Drivers in the stack is 3
3
SECTION D
322 | P a g e
31 University of Correspondence in Allahabad is setting up the network between its different
wings (units). There are four wings named as Science(S), Journalism(J), Arts(A) and Home
Science(H).
Distance between various wings
Wing A to Wing S 100 m
Wing A to Wing J 200 m
Wing A to Wing H 400 m
Wing S to Wing J 300 m
Wing S to Wing H 100 m
Wing J to Wing H 450 m
Number of Computers in each wing
Wing A 150
Wing S 10
Wing J5
Wing H 50
(a) Suggest the suitable topology and draw the cable layout to efficiently connect
various blocks / wings of network.
(b) Where should the server be housed ? justify your answer.
(c) What kind of network (LAN/MAN/WAN) will be formed?
(d) Suggest the fast and very effective wired communication medium to connect
another sub office at Kanpur, 670 km far apart from above network.
(e) Suggest the placement of the following devices in the network.
i. Hub/ Switch
ii. Repeater
5
323 | P a g e
32 (a) Find and write the output of the following Python code:
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i]+'*'
elif str[i].islower():
m=m+'@'
elif str[i]==' ' :
m=m+'#'
print(m)
Display('LION king')
(b) The code given below inserts the following record in the table Player:
PNo – integer
Name – string
NoofGames– int
Goals – integer
Note the following to establish connectivity between Python and MYSQL:
a. Username is root
b. Password is sport
c. The table exists in a MYSQL database named Football.
d. The details (Pno,Name,NoofGames,Goals) are to be accepted from the user.
Write the following missing statements to complete the code:
(a)Statement 1 – to form the cursor object
(b)Statement 2 – to execute the command that inserts the record in the table Player.
(c) Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="sport", database="football")
mycursor=_________________ #Statement 1
pno=int(input("Enter player Number :: "))
name=input("Enter player name :: ")
noofgames=int(input("Enter no of games :: "))
goals=int(input("Enter Goals :: "))
querry="insert into player
values({},'{}',{},{})".format(pno,name,noofgames,goals)
______________________ #Statement 2
2+3
324 | P a g e
______________________ # Statement 3
print("Data Added successfully")
OR
(a) Predict the output for the following code
def repToInt(repString, base):
decimal = 0
exponent = len(repString) - 1
for digit in repString:
decimal = decimal + int(digit) * base ** exponent
exponent -= 1
return decimal
print(repToInt("100011",2))
(b) Considering a table Product stored in database Inventory,complete the Mysql
connectivity code to delete the products whose name is beginning with “M”
Product table has following attributes –(pno,pname,price,qty)
Note the following to establish connectivity between Python and MYSQL:
a. Username is root
b. Password is stock
Write the following missing statements to complete the code:
(a)Statement 1 – to form the cursor object
(b)Statement 2 – the query string to perform the required operation
(c) Statement 3- to execute the query
import mysql.connector as msc
mydb = msc.connect(host = "localhost",user = "root",password = "stock",
database = "inventory")
crs =__________________ # Statement 1
query2=___________________________________________#Statement 2
crs.___________________________ #Statement 3
mydb.close()
325 | P a g e
33 a) Mention the advantage of csv files.
b) Write the functions to performthe required operations on csv files and call the
functions appropriately.
i) Newgadget() to add the details of new gadgets in csv file gadget.csv which
stores records in the format.Deviceno,name,price,brand
Get the input from the user.
ii) Countgadget() to read the csv file ‘gadget.csv’ and count the devices whose
brand is “Samsung”
OR
a) Is CSV file a text file?
b) Write the functions to perform the required operations on csv files and call the
functions appropriately.
i) Namelist() to add the participants for Music competition in a csv file
“music.csv” where each record has the format
Name,class,age
ii) Display() to read the csv file ‘music.csv’ and display the participants under
15 years of age
5
SECTION E
34 In a database School, there are two tables given below:
STUDENTS
RNO NAME CLASS SEC ADDRESS ADMNO PHONE
1 MEERA 12 D A-26 1211 3245678
2 MEENA 12 A NULL 1213 NULL
3 KARISH 10 B AB-234 1214 4567890
4 SURAJ 11 C ZW12 1215 4345677
SPORTS
ADMNO GAME COACHNAME GRADE
1215 CRICKET RAVI A
1213 VOLLEYBALL AMANDEEP B
1211 VOLLEYBALL GOWARDHAN A
1214 BASKET
BALL
TEJASWINI B
Based on the given information answer the questions which follows,
(i) Identify the attribute used as foreign key in table sports
(ii) What is the degree of the table students?
(iii) Write SQL statements to perform the following operations
a) To display the name and game played by sports students
b) To change the address and phonenumber of “Meena ” to B 54, 8864113
(OR only to subpart iii)
1+1
+2
326 | P a g e
iii) a) To make the field class in table STUDENTS mandatory while inserting
data
b) To delete the game CRICKET from SPORTS TABLE.
35 Aditi is a Python programmer. He has written a code and created a binary file employee.dat
with employeeid, ename and salary. The file contains 10 records.
He now has to update a record based on the employee id entered by the user and update the
salary. The updated record is then to be written in the file temp.dat. The records which are
not to be updated also have to be written to the file temp.dat. If the employee id is not
found, an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the requirement
given above:
import _______ #Statement 1
def update_data():
rec={}
fin=open("employee.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary :: "))
pickle.____________ #Statement 4
1+1
+2
327 | P a g e
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named temp.dat.
(Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary file,
record.dat and in Statement 4 to write the updated data in the file, temp.dat?
328 | P a g e
Computer Science (083)
Sample Paper – V Marking scheme
Maximum Marks: 70 Time Allowed: 3 hours
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 Q35 against part
c only.
8. All programming questions are to be answered using Python Language only.
SECTION A
1. State True or False
“Python identifiers are dynamically typed.”
Ans: True
1
2. Which of the following is an invalid operator in Python?
(a)- (b) //= (c)in (d) =%
Ans: d) =%
1
3. Given the following dictionary
employee={'salary':10000,'age':22,'name':'Mahesh'}
employee.pop('age')
print(employee)
What is output?
a. {‘age’:22}
b. {'salary': 10000, 'name': 'Mahesh'}
c. {'salary':10000,'age':22,'name':'Mahesh'}
d. None of the above
Ans: b. {'salary': 10000, 'name': 'Mahesh'}
1
329 | P a g e
4. Consider the given expression:
True and False or Not True
Which of the following will be correct output if the given expression is evaluated?
(e) True
(f) False
(g) NONE
(h) NULL
Ans:b)False
1
5. What will the following code print?
print(max("zoo 145 com"))
a. 145 b. 122 c. z d. zoo
Ans:
C )z
1
6. Which of the following statements is incorrect regarding the file access modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.
b. ‘w+’ opens a file for both writing and reading. Overwrites the existing file if it
exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it
exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the end of the file if the file
exists.
Ans:c. . ‘wb’ opens a file for reading and writing in binary format. Overwrites the
file if it exists and creates a new one if it does not exist.
1
7. All aggregate functions except ___________ ignore null values in their input
collection.
a) Count (attribute) b) Count (*) c) Avg () d) Sum ()
Ans: b.Count(*)
1
8. Which of the following SQL commands will change the attribute value of an
existing tuple in a table?
(e) insert
(f) update
(g) alter
(h) change
Ans: b. update
1
330 | P a g e
9. Consider the following code that inputs a string and removes all special characters
from it after converting it to lowercase.
s = input("Enter a string")
s = s.lower()
for c in ',.;:-?!()'"':
_________________
print(s)
For eg: if the input is 'I AM , WHAT I AM", it should print
i am what i am
Choose the correct option to complete the code .
a. s = s.replace(c, '')
b. s = s.replace(c, '0')
c. s = s.replace(c, None)
d. s = s.remove(c)
Ans: a. s = s.replace(c, '')
1
10. Fill in the blank:
An attribute or set of attributes in a table that can become a primary key is termed as
---------------------
e) Alternate key
f) Candidate key
g) Foreign key
h) Unique key
Ans: b.Candidate key
1
11. Observe the following code snippet
file = open(“station.txt”,”r”)
try:
……..
except EOFError: # When will this line execute
……..
When will the line underlined execute?
1
331 | P a g e
a. When the file is closed.
b. This is a text file.
c. When the file pointer is at the beginning of the file.
d. When the file pointer has reached the end of file.
Ans: d.When the file pointer has reached the end of file
12. Fill in the blank:
The SELECT statement when combined with __________ clause, is used for
pattern matching
(e) Order by
(f) distinct
(g) like
(h) between
Ans: c) like
1
13. ______is a standard network protocol used to transfer files from one
host to another host over a TCP-based network, such as the
Internet.
e) TCP
f) IP
g) FTP
h) SMTP
Ans: FTP
1
14. What will the following expression be evaluated to in Python?
2**3**2+15//3
e) 69
f) 517
g) 175
h) 65
Ans: b) 517
1
15. Identify the invalid SQL aggregate function from the following
b) sum b)max c)min d) add
Ans:d.add
1
332 | P a g e
16. Identify the invalid method to get the data from the result set of query fetched by a
cursor object mycursor.
e) mycursor.fetchone()
f) mycursor.fetchall()
g) mycursor.fetchmany()
h) mycursor.fetchnow()
Ans: d. mycursor.fetchnow()
1
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(e) Both A and R are true and R is the correct explanation for A
(f) Both A and R are true and R is not the correct explanation for A
(g) A is True but R is False
(h) A is false but R is True
17. Assertion (A):-global keyword is used inside a function to enable the function alter
the value of a global variable.
Reasoning (R):- A global variable can not be accessed by a function without the use
of global keyword.
Ans: c. A is True but R is False
1
18. Assertion (A): The ‘with’ block clause is used to associate a file object to a file.
Reason (R): It is used so that at the end of the ‘with’ block the file resource is
automatically closed.
Ans: a) Both A and R are true and R is the correct explanation for A
1
SECTION B
19. Shraddha wrote the code that, prints the sum of numbers between 1 and the number,
for each number till 10.She could not get proper output.
i = 1
while (i <= 10): # For every number i from 1 to 10
sum = 0 # Set sum to 0
for x in range(1,i+1):
sum += x # Add every number from 1 to i
print(i, sum) # print the result
c) What is the error you have identified in this code ?
2
333 | P a g e
d) Rewrite the code by underlining the correction/s.
Ans:
a.The code will cause infinite loop
b.Correction
i = 1
while (i <= 10): # For every number i from 1 to 10
sum = 0 # Set sum to 0
for x in range(1,i+1):
sum += x # Add every number from 1 to i
print(i, sum)
i+=1
(1 mark for error detection,1 mark for error correction)
20. Write two points of difference between star and bus topology.
Bus Star
In Bus topology all devices are
connected to a common backbone wire
known as Bus. All data is transmitted
through the Bus.
In star topology each device is
connected to a central node, which is a
networking device like a hub or a
switch.
Less easy to find faults in the network Easy to find and rectify fault
Easy to install and configure High initial cost of wires
Failure of bus brings the network down Failure of one line will not bring the
entire network down.
(1 mark each for any two difference)
OR
Differentiate Web browser and Webserver.
WEBSERVER:
A web server is a computer that runs websites. It's a computer program that distributes
web pages as they are requisitioned. The basic objective of the web server is to store,
process and deliver web pages to the users. This intercommunication is done using
Hypertext Transfer Protocol (HTTP).
WEB BROWSER:
2
334 | P a g e
The web browser is the software application used to access resources on the internet.
E.g. Chrome, Firefox,Internet Explorer etc.
(1 mark each for correct difference)
21. a) Write the output of the code snippet.
txt = "Time, will it come back?"
x = txt.find(",")
y = txt.find("?")
print(txt[x+2:y])
Ans: will it come back
(1 mark for correct answer)
b) The score of a student in a test is stored as a Python tuple. The test had 3 questions,
with some questions having subparts whose scores are recorded separately.Give the
output of the code snippet.
score = (6, (5, (2, 1), 8), (4, 3, (1, 3, 2)))
print (score [2][2])
Ans:
(1, 3, 2)
(1 mark for correct answer)
1
1
22. What is a not null constraint in SQL? Give example to illustrate.
A not null constraint is a restriction that does not allow a column to be left blank
during insertion.In other words it makes the field a mandatory one.
If a field pname is given a constraint
pname varchar notnull ,
The value for the field should necessarily be provided in an insert query.
(1 mark for explanation 1 for illustration)
2
23. (c) Write the full forms of the following:
(i) SMTP (ii) URL
2
335 | P a g e
Ans: Simple Mail Transfer Protocol
Universal Resource Locator/Uniform resource locator)
½ mark for each correct abbreviation
(d)Differentiate http and https protocols.
Hyper text transfer protocol is used to transmit web pages over the internet.It does not
provide encryption.(Insecure connection)
Hyper text transfer protocol secure is used to transmit web pages over the internet.It
provides encryption when data is transmitted between web client and server.It has
Secure Sockets Layer certificate which provides encryption. (Secure connection)
(1 mark for correct differentiation)
24. Predict the output of the Python code given below:
value = 50
def display(N):
global value
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")
display(20)
print(value)
Ans: 50#5 (1 mark for 50# and 1 mark for 5)
OR
Predict the output of the Python code given below:
l=[]
for i in range(4):
l.append(2*i+1)
print(l[::-1])
2
336 | P a g e
Ans:[7, 5, 3, 1]
(1/2 mark for each correct values)
25. Differentiate betweendrop anddelete commands in SQL with appropriate example.
Drop: DDL command used to remove a database object
Syntax:
Drop table tname;
Delete:DML command used to remove rows from a table
Syntax:
Delete from tablename [ where Condn]
(1 mark for difference ,1 mark for correct example)
OR
What is the use of order by clause in SQL ? Give example.
The order by clause is used to arrange the table based on asc /desc order of a particular
field.
Syntax: select fn1,fn2 … from tablename order by fn1 [asc/desc];
Select name,marks from student order by marks asc; [any appropriate example]
(1 mark for difference 1 mark for correct example)
2
SECTION C
26 j) Considering the following table SALEORDER which stores the name of items
sold on a day ,give the output of the query that follows:-
DATE ITEM
12-09-2022 RICE
12-09-2022 RICE
12-09-2022 SUGAR
12-09-2022 RICE
12-09-2022 COFFEE
12-09-2022 COFFEE
12-09-2022 TEA
SELECT ITEM,COUNT(*) FROM SALEORDER GROUP BY ITEM HAVING
COUNT(*)>1;
ITEM COUNT(*)
RICE 3
1+2
337 | P a g e
COFFEE 2
1 MARK FOR CORRECT OUTPUT
ii)Writethe outputofthequeries(a)to(d)basedonthetable BOOK,given below:
(a) SELECT PUBLISHER,PRICE FROM BOOK WHERE QTY>=10;
PUBLISHER PRICE
EEE 750
EPB 250
(b)SELECT BOOK_NAME, TYPE FROM BOOK WHERE BOOK_NAME LIKE 'T%';
BOOK_NAME TYPE
The Tears Fiction
Thunderbolts Fiction
(c)SELECT SUM(PRICE) FROM BOOK WHERE PUBLISHER IN (‘EPB’,’TMH’);
SUM(price)
575
(d)SELECT MIN(QTY) FROM BOOK WHERE PRICE>500;
MIN(QTY)
5
1/2 mark for each of the outputs
Book_Id Book_Name Publisher Price Type Qty
F0001 The Tears EEE 750 Fiction 10
F0002 Thunderbolts EEE 700 Fiction 5
T0001 Let us C++ EPB 250 Text 10
T0002 C++ Brain TMH 325 Text 5
C0001 Fast Cook EPB 350 Cookery 8
27. Write a Python function which reads a text file “poem.txt” and prints the
number of vowels in each line of that file, separately.
Eg: if the content of the file “poem.txt” is
The plates will still shift
and the clouds will still spew.
The sun will slowly rise
and the moon will follow too.
The output should be
3
338 | P a g e
6
7
6
9
PROGRAM
def vowelsinline():
f=open("poem.txt","r")
l=f.readlines()
vc=0
for i in l:
vc=0
for c in i:
if c.upper() in "AEIOU":
vc+=1
print(vc)
f.close()
vowelsinline()
Ans:
( ½ mark for correctly opening and closing the file
½ for readlines()
½ mar for correct loop
½ for correct if statement
½ mark for correctly incrementing count
½ mark for displaying the correct output)
OR
Write a Python program that writes the reverse of each line in “input.txt”
to another text file “output.txt”. Eg: if the content of input.txt is:
The plates will still shift
and the clouds will still spew.
The sun will slowly rise
339 | P a g e
and the moon will follow too.
The content of “output.txt” should be:
tfihs llits lliw setalp ehT
.weps llits lliw sduolc eht dna
esir ylwols lliw nus ehT
.oot wollof lliw noom eht dna
PROGRAM
def reverseline():
f=open("poem.txt","r")
o=open("output.txt","w")
l=f.readlines()
for i in l:
o.write(i[::-1])
f.close()
o.close()
reverseline()
(½ mark for correctly opening and closing the file
½ for readlines()
½ mark for correct loops
½ for correct if statement
½ mark for correctly incrementing counts
½ mark for displaying the correct output)
340 | P a g e
28 (c) Write the outputs of the SQL queries (i) to (iii) based on the tables VEHICLES and
TRAVELS
Table: VEHICLE
VCODE VEHICLETYPE PERKM
V01 VOLVO BUS 150
V02 AC DELUXE
BUS
125
V03 ORDINARY
BUS
80
V04 CAR 18
V05 SUV 30
Table: TRAVEL
CNO CNAME TRAVELDATE KM VCODE NOP
101 Arun 2015-12-13 200 V01 32
102 Balaji 2016-06-21 120 V03 45
103 Vignesh 2016-04-23 450 V02 42
104 Selva 2016-01-13 80 V02 40
105 Anupam 2015-02-10 65 V04 2
106 Tarun 2016-04-06 90 V05 4
● PERKM is Freight Charges per kilometer.
● Km is kilometers Travelled
● NOP is number of passengers travelling in vehicle.
(i) SELECT VCODE, COUNT(*) AS NUMTRIPS
FROM TRAVEL
GROUP BY VCODE;
(ii) SELECT CNAME, TRAVEL.VCODE, VEHICLETYPE
3
341 | P a g e
FROM VEHICLE, TRAVEL
WHERE VEHICLE.VCODE = TRAVEL.VCODE AND NOP >= 30;
(iii) SELECT MAX(TRAVELDATE), MIN(TRAVELDATE)
FROM TRAVEL ;
(iv) SELECT VEHICLETYPE FROM VEHICLE WHERE VEHICLETYPE LIKE
“%BUS”;
[1/2 mark for each correct output]
(d) Write the command to view the structure of the table TRAVEL.
Ans: DESC TRAVEL
[1 mark for correct query]
29 Write a function sumcube(L) to test if an element from list L is equal to the sum of the
cubes of its digits ie it is an ”Armstrong number”. Print such numbers in the list.
If L contains [67,153,311,96,370,405,371,955,407]
The function should print 153,370,371,407
Ans:
def sumcube(L):
for i in L:
t=i
s=0
while t:
r=t%10
s=s+r**3
t=t//10
if s==i:
print(i,end=' ')
3
342 | P a g e
#main
L=[67,153,311,96,370,405,371,955,407]
sumcube(L)
(½ mark for correct function header
1 mark for correct loop
1 mark for correct if statement
½ mark for return statement)
Note: Any other relevant and correct code may be marked
30 Vikram has a list containing 10 integers. You need to help him to create a program with
separate user defined functions to perform the following operations based on this list.
● pushnum() to Traverse the content of the list and push the numbers that are divisible by 5
into a stack.
● popnum() to Pop and display the content of the stack and display “Stack underflow” if
the stack is empty.
For Example:
If the sample Content of the list is as follows:
N=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
35
55
10
Ans:
def pushnum(Num,stk):
for i in Num:
if i%5==0:
stk.append(i)
def popnum(stk):
if len(stk):
print("The elements of Stack")
while stk:
print(stk.pop())
else:
print("Stack Empty")
3
343 | P a g e
L=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38]
stk=[]
pushnum(L,stk)
popnum(stk)
(1.5 marks for correct push() and 1.5 marks for correct pop())
OR
Write a function in Python, Push(Ride) where , Ride is a dictionary containing the details
of Cab ride , Ride={driver: billamt }.
The function should push the names of those driver names in the stack,INCENTIVE who
have billed greater than 400. Also display the count of names pushed into the stack
For example:
If the dictionary contains the following data:
Ride={‘Raghu’:389,’Anbu’:560,’Siraj’:768,’Syed’:450 }.
The stack INCENTIVE should contain
[‘Anbu’,’Siraj’,’Syed’]
The output should be:
The count of Drivers in the stack is 3
Ans:
def push(Ride):
for i in Ride:
if Ride[i]>400:
incentive.append(i)
print("The count of drivers in the stack",len(incentive))
print("The stack is")
for i in incentive[::-1]:
print(i)
344 | P a g e
#main
Ride={'Raghu':389,'Anbu':560,'Siraj':768,'Syed':450 }
incentive=[]
push(Ride)
(1 mark for correct function header
1 mark for correct loop
½ mark for correct If statement
½ mark for correct display of count)
SECTION D
31 University of Correspondence in Allahabad is setting up the network between its different
wings (units). There are four wings named as Science(S), Journalism(J), Arts(A) and Home
Science(H).
Distance between various wings
Wing A to Wing S 100 m
Wing A to Wing J 200 m
Wing A to Wing H 400 m
Wing S to Wing J 300 m
Wing S to Wing H 100 m
Wing J to Wing H 450 m
Number of Computers in each wing
Wing A 150
Wing S 10
Wing J 5
Wing H 50
(a) Suggest the suitable topology and draw the cable layout to efficiently connect
various blocks / wings of network.
Ans: Star topology
100m 100m
300 m
5
H
S
A
J
345 | P a g e
(1/2 mark for topology and ½ mark for layout)
(b) Where should the server be housed ? justify your answer.
Ans:Wing A ,as it has maximum number of computers(1/2 mark for correct
wing and ½ mark for justification)
(c) What kind of network (LAN/MAN/WAN) will be formed?
Ans:LAN
Ans: 1 mark for correct answer
(d) Suggest the fast and very effective wired communication medium to connect
another sub office at Kanpur, 670 km far apart from above network.
Ans:Optical Fibre( 1 mark for correct answer)
(e) Suggest the placement of the following devices in the network.
i. Hub/ Switch
ii. Repeater
Ans: Hub/Switch In All Wings
Repeater: Between S and J blocks as the distance is > 100m
( 1 mark for correct answer)
32 (c) Find and write the output of the following Python code:
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i]+'*'
elif str[i].islower():
m=m+'@'
elif str[i]==' ' :
m=m+'#'
print(m)
Display('LION king')
Ans:L*I*O*N*#@@@@ (1 marks for first 8 characters and 1 mark for consecutive 5
correct characters in the output)
(d) The code given below inserts the following record in the table Player:
PNo – integer
Name – string
NoofGames– int
Goals – integer
2+3
346 | P a g e
Note the following to establish connectivity between Python and MYSQL:
a. Username is root
b. Password is sport
c. The table exists in a MYSQL database named Football.
d. The details (Pno,Name,NoofGames,Goals) are to be accepted from the user.
Write the following missing statements to complete the code:
(a)Statement 1 – to form the cursor object
(b)Statement 2 – to execute the command that inserts the record in the table Player.
(C ) Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="sport", database="football")
mycursor=_________________ #Statement 1
pno=int(input("Enter player Number :: "))
name=input("Enter player name :: ")
noofgames=int(input("Enter no of games :: "))
goals=int(input("Enter Goals :: "))
querry="insert into player
values({},'{}',{},{})".format(pno,name,noofgames,goals)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")
Ans:
mycursor=con1.cursor() #Statement 1
mycursor.execute(querry) #Statement 2
con1.commit() #statement3
OR
(c) Predict the output for the following code
def repToInt(repString, base):
decimal = 0
exponent = len(repString) - 1
for digit in repString:
decimal = decimal + int(digit) * base ** exponent
exponent -= 1
return decimal
print(repToInt("100011",2))
Ans:
35 (2 marks for correct answer)
(d) Considering a table Product stored in database Inventory,complete the Mysql
connectivity code to delete the products whose name is beginning with “M”
347 | P a g e
Product table has following attributes –(pno,pname,price,qty)
Note the following to establish connectivity between Python and MYSQL:
c. Username is root
d. Password is stock
Write the following missing statements to complete the code:
(a)Statement 1 – to form the cursor object
(b)Statement 2 – the query string to perform the required operation
(c) Statement 3- to execute the query
import mysql.connector as msc
mydb = msc.connect(host = "localhost",user = "root",password = "stock",
database = "inventory")
crs =__________________ # Statement 1
query2=___________________________________________#Statement 2
crs.___________________________ #Statement 3
mydb.close()
Ans:
Statement1:
mydb.cursor()
Statement2:
query2=”Delete from product where name like “M%”;”
Statement 3:
crs.execute(query2)
(1 mark for each correct statement)
33 c) Mention the advantage of csv files.
d) Write the functions to performthe required operations on csv files and call the
functions appropriately.
i) Newgadget() to add the details of new gadgets in csv file gadget.csv which
stores records in the format, Deviceno,name,price,brandGet the input from
the user.
ii) Countgadget() to read the csv file ‘gadget.csv’ and count the devices
whose brand is “Samsung”
Ans:
a) • CSV is human readable and easy to edit manually
• CSV is processed by almost all existing applications.
• CSV is smaller in size
• CSV is considered to be standard format (Any 2 correct advantage 1 mark)
b)
import csv
def Newgadget():
fout=open("gadget.csv","a",newline="n")
wr=csv.writer(fout)
devno=int(input("Enter Device no :: "))
name=input("Enter name :: ")
price=int(input("Enter Price :: "))
5
348 | P a g e
brand=input("Enter brand :: ")
lst=[devno,name,price,brand] ---------1/2 mark
wr.writerow(lst) ---------1/2 mark
fout.close()
def Countgadget():
fin=open("gadget.csv","r",newline="n")
data=csv.reader(fin)
count=0
for i in data:
if i[3].upper()=='SAMSUNG':
count=count+1
print("Number of Samsung Gadgets",count)
fin.close()
#main
Newgadget()
Countgadget()
(1 mark for advantage
½ mark for importing csv module
1 ½ marks each for correct definition of Newgadget()
Countgadget(), ½ mark for function call statements)
OR
c) Is CSV file a text file?
d) Write the functions to perform the required operations on csv files and call the
functions appropriately.
iv) Namelist() to add the participants for Music competition in a csv file
“music.csv” where each record has the formatName,class,age
v) Display() to read the csv file ‘gadget.csv’ and display the participants under
15 years of age
Ans: a) Yes CSV is a special text file where each line represents a record with fields
separated by commas.
b)
import csv
def Namelist():
fout=open("music.csv","a",newline="n")
wr=csv.writer(fout)
name=input("Enter name :: ")
clas=input("Enter Class :: "))
age=int(input("Enter age :: ")
lst=[name,clas,age]--------1/2 mark
wr.writerow(lst) ---------1/2 mark
fout.close()
def Display():
fin=open("music.csv","r",newline="n")
data=csv.reader(fin)
349 | P a g e
print("Participants under 15 years of age")
for i in data:
if int(i[2])<15:
print(i)
fin.close()
#main
Namelist()
Display()
(1 mark for difference
½ mark for importing csv module
1 ½ marks each for correct definition of Namelist() and display()
½ mark for function call statements
)
SECTION E
34 In a database School, there are two tables given below:
STUDENTS
RNO NAME CLASS SEC ADDRESS ADMNO PHONE
1 MEERA 12 D A-26 1211 3245678
2 MEENA 12 A NULL 1213 NULL
3 KARISH 10 B AB-234 1214 4567890
4 SURAJ 11 C ZW12 1215 4345677
SPORTS
ADMNO GAME COACHNAME GRADE
1215 CRICKET RAVI A
1213 VOLLEYBALL AMANDEEP B
1211 VOLLEYBALL GOWARDHAN A
1214 BASKET
BALL
TEJASWINI B
Based on the given information answer the questions which follows,
(iv) Identify the attribute used as foreign key in table sports
(v) What is the degree of the table students?
Ans:
i) ADMNNO is used as foreign key in table sports
ii) Degree of Student table-7
( 1 mark each for each correct answer)
(vi) Write SQL statements to perform the following operations
1+1
+2
350 | P a g e
c) To display the name and game played by sports students
d) To change the address and phonenumber of “Meena ” to B 54, 8864113
iii) a) Select NAME,GAME from STUDENTS S,SPORTS T where
S.ADMNNO=T.ADMNNO
b)update students set address=’B 54’ ,Phone=’ 8864113’ where
name=”MEENA”
(1 Mark each for correct query)
(OR only to subpart iii)
vi)a) To make the field class in table STUDENTS mandatory while inserting data
b)To delete the game CRICKET from SPORTS TABLE.
Ans:
a) ALTER TABLE STUDENTS MODIFY CLASS VARCHAR(20) NOT NULL;
b) DELETE FROM STUDENTS WHERE GAME=’CRICKET’
(1 Mark each for correct query)
35 Aditi is a Python programmer. He has written a code and created a binary file employee.dat
with employeeid, ename and salary. The file contains 10 records.
He now has to update a record based on the employee id entered by the user and update the
salary. The updated record is then to be written in the file temp.dat. The records which are
not to be updated also have to be written to the file temp.dat. If the employee id is not
found, an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the requirement
given above:
import _______ #Statement 1
def update_data():
rec={}
fin=open("employee.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
351 | P a g e
rec["Salary"]=int(input("Enter new salary :: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named temp.dat.
(Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary file,
record.dat and in Statement 4 to write the updated data in the file, temp.dat?
Ans:
i) Pickle module(1 mark for correct module)
ii) fout=open(“temp.dat”,”wb”)(1 mark for mode)
iii) pickle.load(fin)
pickle.dump(rec,fout) (1 mark each for correct statements)
**********

More Related Content

Similar to computer science CLASS 11 AND 12 SYLLABUS.pdf (20)

PPTX
Python unit 2 is added. Has python related programming content
swarna16
 
PDF
GE3151_PSPP_UNIT_2_Notes
Guru Nanak Technical Institutions
 
PPTX
Python Programming for problem solving.pptx
NishaM41
 
PPTX
Welcome to python workshop
Mukul Kirti Verma
 
PDF
🐍⚡ “Python Panache: Code Like a Pro, Not a Programmer!”
yashikanigam1
 
PDF
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 
PDF
data science with python_UNIT 2_full notes.pdf
mukeshgarg02
 
PPTX
intro to python.pptx
UpasnaSharma37
 
PPTX
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
PDF
problem solving and python programming UNIT 2.pdf
rajesht522501
 
PDF
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
 
PPTX
Plc part 2
Taymoor Nazmy
 
PDF
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
PDF
Python Programming
Saravanan T.M
 
PPTX
Python-Basics.pptx
TamalSengupta8
 
PPTX
UNIT 1 .pptx
Prachi Gawande
 
PPT
Unit 2 python
praveena p
 
PPTX
C++ Basics introduction to typecasting Webinar Slides 1
Ali Raza Jilani
 
PDF
prakash ppt (2).pdf
ShivamKS4
 
PDF
Python Programming by Dr. C. Sreedhar.pdf
Sreedhar Chowdam
 
Python unit 2 is added. Has python related programming content
swarna16
 
GE3151_PSPP_UNIT_2_Notes
Guru Nanak Technical Institutions
 
Python Programming for problem solving.pptx
NishaM41
 
Welcome to python workshop
Mukul Kirti Verma
 
🐍⚡ “Python Panache: Code Like a Pro, Not a Programmer!”
yashikanigam1
 
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 
data science with python_UNIT 2_full notes.pdf
mukeshgarg02
 
intro to python.pptx
UpasnaSharma37
 
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
problem solving and python programming UNIT 2.pdf
rajesht522501
 
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
 
Plc part 2
Taymoor Nazmy
 
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
Python Programming
Saravanan T.M
 
Python-Basics.pptx
TamalSengupta8
 
UNIT 1 .pptx
Prachi Gawande
 
Unit 2 python
praveena p
 
C++ Basics introduction to typecasting Webinar Slides 1
Ali Raza Jilani
 
prakash ppt (2).pdf
ShivamKS4
 
Python Programming by Dr. C. Sreedhar.pdf
Sreedhar Chowdam
 

Recently uploaded (20)

PPTX
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
PPTX
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
PPTX
grade 8 week 2 ict.pptx. matatag grade 7
VanessaTaberlo
 
PDF
Cooperative wireless communications 1st Edition Yan Zhang
jsphyftmkb123
 
PDF
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PPTX
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PPTX
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
PPTX
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PDF
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PPTX
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
PDF
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
PPTX
IvĂĄn Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PDF
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
PDF
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
grade 8 week 2 ict.pptx. matatag grade 7
VanessaTaberlo
 
Cooperative wireless communications 1st Edition Yan Zhang
jsphyftmkb123
 
Andreas Schleicher_Teaching Compass_Education 2040.pdf
EduSkills OECD
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
Lesson 1 Cell (Structures, Functions, and Theory).pptx
marvinnbustamante1
 
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
IvĂĄn Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
Nanotechnology and Functional Foods Effective Delivery of Bioactive Ingredien...
rmswlwcxai8321
 
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
Ad

computer science CLASS 11 AND 12 SYLLABUS.pdf

  • 1. 1 KENDRIYA VIDYALAYA SANGATHAN CHENNAI REGION Session 2022-23 Class XII Computer Science (083) Based on Latest CBSE Exam Pattern
  • 2. 2 KENDRIYA VIDYALAYA SANGATHAN CHENNAI REGION OUR PATRONS Smt. T RUKMANI Offg. DEPUTY COMMISIONER KVS RO CHENNAI Sh. P.I.T. RAJA ASSISTANT COMMISSIONER KVS RO CHENNAI
  • 3. 3 MEMBERS AND DETAILS OF TOPICS ALLOTTED Name of the co-ordinator – Smt. Sangeetha S, KV Sulur S.No. Name of the Teacher Name of the KV Name of the Chapter allotted 1 Sh. Renju Leopold KV Aruvankadu Python Revision Tour, Functions and Text File Handling 2 Smt. R Srikeerthy KV HVF Binary files, CSV and Data Structures 3 Sh. Prem Kumar Singh KV DGQA Computer Networks 4 Smt. Merina Paul NO.2 Madurai Database Management 5 Smt. Meera G KV Gill Nagar Interfacing Python with MySQL With support of other contractual PGT CS of different KVs of Chennai Region COURSE DIRECTOR Sh. N. RAKHESH PRINCIPAL KV VIJAYANARAYANAM, CHENNAI
  • 4. 4 INDEX Sl.No Contents Page No. 1 Curriculum 2022-23 5 2 CBSE Sample Question Paper 9 4 Revision of Python topics covered in Class XI 23 5 Functions 45 6 File handling -Introduction and Text file 69 7 Binay files 82 8 CSV files 100 9 Data structures - Stacks 118 10 Computer Networks 127 11 Database Management 144 12 Interface Python with MySQL 166 13 Sample Papers 189
  • 6. 6
  • 7. 7
  • 8. 8
  • 9. 9
  • 10. 10
  • 11. 11
  • 12. 12
  • 13. 13
  • 14. 14
  • 15. 15
  • 16. 16
  • 17. 17
  • 18. 18
  • 19. 19
  • 20. 20
  • 21. 21
  • 22. 22
  • 23. 23 Unit-I Computational Thinking and Programming – 2 Revision of Python topics covered in class XI PYTHON BASICS Python is a simple, general purpose, high level, and object-oriented programming language.Python is an interpreted scripting language also. Guido Van Rossum is the founder of Python programming language.Guido was a fan of the popular BBC comedy show of that time, "Monty Python's Flying Circus". So he decided to pick the name Python for his newly created programming language. Features of Python • Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures. • Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for Application Development. • Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting and rapid application development. • Python supports multiple programming pattern, including object-oriented, imperative, and functional or procedural programming styles. • Python is not intended to work in a particular area, such as web programming. That is why it is known as multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc. • We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign an integer value in an integer variable. • Python makes the development and debugging fast because there is no compilation step included in Python development, and edit-test-debug cycle is very fast. Applications of Python Programming Language • Data Science • Date Mining • Desktop Applications • Console-based Applications • Mobile Applications • Software Development • Artificial Intelligence • Web Applications • Enterprise Applications • 3D CAD Applications • Machine Learning
  • 24. 24 • Computer Vision or Image Processing Applications. • Speech Recognitions How To Use Python? Python can be downloaded from www.python.org. (Standard Installation) It is available in two versions- • Python 2.x • Python 3.x (It is in Syllabus) Apart from above standard Python. We have various Python IDEs and Code Editors. Some of them are as under: (i) Anaconda Distribution: free and open-source distribution of the Python, having various inbuilt libraries and tools like Jupyter Notebook, Spyder etc (ii) PyCharm (iii) Canopy (iv) Thonny (v) Visual Studio Code (vi) Eclipse + PyDev (vii) Sublime Text (viii) Atom (ix) GNU Emacs (x) Vim (xi) Spyder and many more . . Python Interpreter - Interactive And Script Mode: We can work in Python in Two Ways: (i) Interactive Mode: It works like a command interpreter as shell prompt works in DOS Prompt or Linux. On each (>>>) symbol we can execute one by one command. (ii) Script Mode: It used to execute the multiple instruction (complete program) at once. Python Character Set: Character Set is a group of letters or signs which are specific to a language. Character set includes letter, sign, number and symbol. • Letters: A-Z, a-z • Digits: 0-9 • Special Symbols: _, +, -, *, /, (, #,@, {, } etc. • White Spaces: blank space, tab, carriage return, newline, form feed etc. • Other characters: Python can process all characters of ASCII and UNICODE. Tokens A token is the smallest individual unit in a python program. All statements and instructions in a program are built with tokens.It is also known as Lexical Unit. Types of token are • Keywords • Identifiers (Names) • Literals • Operators • Punctuators
  • 25. 25 Keywords Python keywords are unique words reserved with defined meanings and functions that we can only apply for those functions.Python contains thirty-five keywords in the version, Python 3.9. Identifiers In programming languages, identifiers are names used to identify 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 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 reserved word. • We cannot use special symbols like !, @, #, $, %, etc. in identifiers. Legal Identifier Names Example: Myvar my_var _my_var myVar myvar2 Illegal Identifier Names Example:- 2myvar my-var my var= 9salary Literals or Values: Literals are the fixed values or data items used in a source code. Python supports different types of literals such as: a. String literals - “Rishaan” b. Numeric literals – 10, 13.5, 3+5i c. Boolean literals – True or False d. Special Literal None e. Literal collections Literal collections Literals collections in python includes list, tuple, dictionary, and sets. • List: It is a list of elements represented in square brackets with commas in between. These variables can be of any data type and can be changed as well. • Tuple: It is also a list of comma-separated elements or values in round brackets. The values can be of any data type but can’t be changed. • Dictionary: It is the unordered set of key-value pairs. • Set: It is the unordered collection of elements in curly braces ‘{}’. Operators An operator is used to perform specific mathematical or logical operation on values. The values that the operator works on are called operands. • Arithmetic operators • Assignment operators • Comparison operators • Logical operators
  • 26. 26 • Identity operators • Membership operators • Bitwise operators Arithmetic operators: used with numeric values to perform common mathematical operations. + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y Assignment operators: used to assign values to variables = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 Comparison Operators: Comparison operators are used to compare two values. == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y Logical Operators: Logical operators are used to combine conditional statements and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10) Identity Operators: used to compare the objects, not if they are equal, but if they are actually the
  • 27. 27 same object, with the same memory location. is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y Membership operators: used to test if a sequence is present in an object. in Returns True if a sequence with the specified x in y value is present in the object not in Returns True if a sequence with the specified x not in y value is not present in the object Punctuators Punctuators are symbols that are used in programming languages to organize sentence structure, and indicate the rhythm and emphasis of expressions, statements, and program structure. Common punctuators are: „ “ # $ @ []{}=:;(), Python Variables Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables. • Variables are containers for storing data values. • Unlike other programming languages, Python has no command for declaring a variable. • A variable is created the moment you first assign a value to it. Example: x = 5 y = "John" print(x) print(y) • Variables do not need to be declared with any particular type and can even change type after they have been set. x = 4 # x is of type int x = "Sally" # x is now of type str print(x) • String variables can be declared either by using single or double quotes: x = "John" # is the same as x = 'John' Output Variable: The Python print statement is often used to output variables. To combine both text and a variable, Python uses the, character: x = "awesome"
  • 28. 28 print("Python is " , x) Display Multiple variable:- x = "awesome“ y=56 print(“Value of x and y is=" , x, y) Assigning Values to Variables Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. Also Python allows you to assign a single value to several variables simultaneously. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print (counter) print (miles) print (name) a = b = c = 1 a,b,c = 1,2,"john" Data Types The data stored in memory can be of many types, i.e., Every value belongs to a specific data type in Python. Data type identifies the type of data which a variable can hold and the operations that can be performed on those data.Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. The different standard data types − • Numbers
  • 29. 29 • String • List • Tuple • Dictionary • Boolean • Set Numbers Number data types store numeric values. Number objects are created when you assign a value to them. For example − var1 = 1 var2 = 10 Python supports four different numerical types • int (signed integers) • long (long integers, they can also be represented in octal and hexadecimal) • float (floating point real values) • complex (complex numbers) int long float complex 10 51924361L 0.0 3.14j 100 -0x19323L 15.20 45.j -786 0122L -21.9 9.322e -36j 080 0xDEFABCECBDAE 32.3+e18 .876j -0490 535633629843L -90. -.6545+0J -0x260 -052318172735L -32.54e100 3e+26J 0x69 -4721885298529L 70.2-E12 4.53e-7j You can also delete the reference to a number object by using the del statement. The syntax of the del statement is − del var1[,var2[,var3[....,varN]]]] e.g. del var del var_a, var_b Strings Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ). str = 'Hello World!' print str # Prints complete string Hello World! print str[0] # Prints first character of the string H
  • 30. 30 print str[2:5] # Prints characters starting from 3rd to 5th llo print str[2:] # Prints string starting from 3rd character llo World! print str * 2 # Prints string two times Hello World!Hello World! print str + "TEST" # Prints concatenated string Hello World!TEST Lists Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list ['abcd', 786, 2.23, 'john', 70.2] print list[0] # Prints first element of the list- abcd print list[1:3] # Prints elements starting from 2nd till 3rd - [786, 2.23] print list[2:] # Prints elements starting from 3rd element -[2.23, 'john', 70.2] print tinylist * 2 # Prints list two times-[123, 'john', 123, 'john'] print list + tinylist # Prints concatenated lists-['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] Tuples A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple # Prints the complete tuple--('abcd', 786, 2.23, 'john', 70.2) print tuple[0] # Prints first element of the tuple-- abcd print tuple[1:3] # Prints elements of the tuple starting from 2nd till 3rd --(786, 2.23) print tuple[2:] # Prints elements of the tuple starting from 3rd element--(2.23, 'john', 70.2) print tinytuple * 2 # Prints the contents of the tuple twice--(123, 'john', 123, 'john') print tuple + tinytuple # Prints concatenated tuples-- ('abcd', 786, 2.23, 'john', 70.2, 123, 'john') Dictionary Python's dictionaries are kind of hash table type. They consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example − dict = {}
  • 31. 31 dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # Prints value for 'one' key This is one print dict[2] # Prints value for 2 key This is two print tinydict # Prints complete dictionary {'dept': 'sales', 'code': 6734, 'name': 'john'} print tinydict.keys() # Prints all the keys ['dept', 'code', 'name'] print tinydict.values() # Prints all the values ['sales', 6734, 'john'] Boolean Boolean represent one of two values: True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer.Also, almost any value is evaluated to True if it has some sort of content. print(10 > 9) True print(10 == 9) False print(10 < 9) False bool("abc") True bool(123) True bool(["apple", "cherry"])True bool(False) False bool(None) False bool(0) False bool("") False bool(()) False bool([]) False bool({}) False Mutable and Immutable Objects in Python Everything in Python is an object. So, every variable holds an object instance. All objects in Python can be either mutable or immutable. When an object is initiated, it is assigned a unique object id. Its type is defined at runtime and once set can never change, however its state can be changed if it is mutable. Generally, a mutable object can be changed after it is created, and an immutable object can’t. Mutable objects Mutability means the ability to modify or edit a value. Mutable objects in Python enable the programmers to have objects that can change their values. They generally are utilized to store a collection of data. It can be regarded as something that has mutated, and the internal state applicable within an object has changed.
  • 32. 32 In mutable data types, we can modify the already existing values of the data types (such as lists, dictionaries, etc.). Or, we may add new values or remove the existing values from our data types. Basically, we may perform any operation with our data without having to create a new copy of our data type. Hence, the value assigned to any variable can be changed. e.g.color = ["red", "blue", "green"] print(color) color[0] = "pink" color[-1] = "orange" print(color) Output: ['red', 'blue', 'green'] ['pink', 'blue', 'orange'] Immutable Objects Immutable objects in Python are objects wherein the instances do not change over the period. Immutable instances of a specific type, once created, do not change, and this can be verified using the id method of Python e.g.message = "Welcome to GeeksforGeeks" message[0] = 'p' print(message) Output Traceback (most recent call last): File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in message[0] = 'p' TypeError: 'str' object does not support item assignment ❖ Exception: However, there is an exception in immutability as well.Tuple in python is immutable. But the tuple consists of a sequence of names with unchangeable bindings to objects.
  • 33. 33 Consider a tuple tup = ([3, 4, 5], 'myname') The tuple consists of a string and a list. Strings are immutable so we can’t change its value. But the contents of the list can change. The tuple itself isn’t mutable but contain items that are mutable. Expression in python: A combination of constants, operands and operators is called an expression. The expression in Python produces some value or result after being interpreted by the Python interpreter. The expression in Python can be considered as a logical line of code that is evaluated to obtain some result. If there are various operators in an expression then the operators are resolved based on their precedence. E.g. Expression 6-3*2+7-1 evaluated as 6 Types of Expression in Python Constant Expressions x = 10 + 15 Arithmetic Expressions y=x**3+x-2+5/2 Integral Expressions x=10 y=5.00 result = x + int(y) Floating Expressions result = float(x) + y Relational Expressions 10+15>20 Logical Expressions r=x and y Combinational Expressions result = x + (y << 1) Type Casting in Python Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by users. There can be two types of Type Casting in Python – • Implicit Type Casting • Explicit Type Casting Implicit Type Conversion In this, methods, Python converts data type into another data type automatically, where users don’t have to involve.
  • 34. 34 # Python automatically converts # a to int a = 7 print(type(a)) # Python automatically converts # b to float b = 3.0 print(type(b)) # Python automatically converts # c to float as it is a float addition c = a + b print(c) print(type(c)) # Python automatically converts # d to float as it is a float multiplication d = a * b print(d) print(type(d)) Explicit Type Casting In this method, Python need user involvement to convert the variable data type into certain data type in order to the operation required.Mainly in type casting can be done with these data type function: int() : int() function take float or string as an argument and return int type object. float() : float() function take int or string as an argument and return float type object. str() : str() function take float or int as an argument and return string type object. E,g, # int variable a = 5 # typecast to float n = float(a) print(n) print(type(n)) Precedence and Associativity of Operators Operator Precedence: This is used in an expression with more than one operator with different precedence to determine which operation to perform first.
  • 35. 35 Operator Associativity: If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left. Comments in python: Comments are non-executable statements of python. It increases the readability and understandability of code. Types of comment: i. Single line comment (#) – comments only single line. e.g. a=7 # 7 is assigned to variable ‘a’ print(a) # displaying the value stored in ‘a’ ii. Multi-line comment (‘‘‘………..’’’) – Comments multiple line. e.g. ‘‘‘Program -1 A program in python to store a value invariable ‘a’ and display the value stored in it.’’’ a=7 print(a) Python Input and Output Python executes code top to bottom, when written in the correct syntax.Once the interpreter is running you can start typing in commands to get the result. Input using the input( ) function input (): This function first takes the input from the user and converts it into a string. The type of the returned object always will be <type ‘str’>. It does not evaluate the expression it just returns the complete statement as String. Python provides a built-in function called input which takes the input from the user. When the input function is called it stops the program and waits for the user’s input. When the user presses enter, the program resumes and returns what the user typed. name = input('What is your name?n') What is your name? Ram Taking multiple inputs from user
  • 36. 36 Using split() method Using List comprehension split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it in taking multiple inputs. input().split(separator, maxsplit) List comprehension is an elegant way to define and create list in Python. We can create lists just like mathematical statements in one line only. It is also used in getting multiple inputs from a user. x, y, z = [int(x) for x in input("Enter three values: ").split()] Output using print() function print() : function prints the message on the screen or any other standard output device. print(value(s), sep= ' ', end = 'n', file=file, flush=flush) value(s) : Any value, and as many as you like. Will be converted to string before printed sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.Default :’ ‘ end=’end’: (Optional) Specify what to print at the end.Default : ‘n’ file : (Optional) An object with a write method. Default :sys.stdout flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False Debugging:- Debugging is a process of locating and removing errors from program. Errors in a program An error or exception refers to an interruption in the execution of code due to which we cannot attain the expected outcome to the end-users. These errors are classified on the basis of the event when the program generate the error. The two types of errors are Compile Time Errors and Runtime Errors and Logical errors Compile Time Errors These errors occur when we violate the rules present in a syntax. The compile-time error indicates something that we need to fix before compiling the code. A compiler can easily detect these errors. Eg Syntax error and Semantic Error. Logic errors These errors are not always easy to recognize immediately. This is due to the fact that such errors, unlike that of syntax errors, are valid when considered in the language, but do not produce the intended behavior. These can occur in both interpreted and compiled languages. It may occur due to the logic of the program.
  • 37. 37 Runtime Errors These errors occur during the run-time program execution after a successful compilation. Division error is one of the most common errors (runtime). It occurs due to the division by zero. It is very difficult for a compiler to find out a runtime error because it cannot point out the exact line at which this particular error occurs. --------------------------------------------------------------------------------------------------------------------- Control flow statements The control flow of a Python program is regulated by conditional statements, loops, and function calls. In order to control the flow of execution of a program there are three categories of statements in python. They are: 1. Selection statements 2. Iteration statements 3. Jump statements / Transfer statements Selection Statements Decision making is valuable when something we want to do depends on some user input or some other value that is not known when we write our program. This is quite often the case and Python, along with all interesting programming languages, has the ability to compare values and then take one action or another depending on that outcome. Python have following types of selection statements 1. if statement 2. if else statement 3. Ladder if else statement (if-elif-else) 4. Nested if statement if statements This construct of python program consist of one if condition with one block of statements. When condition becomes true then executes the block. Syntax:
  • 38. 38 if ( condition): Statement(s) Example: age=int(input(“Enter Age: “)) if ( age>=18): print(“You are eligible for vote”) if(age<0): print(“You entered Negative Number”) if - else statements This construct of python program consist of one if condition with two blocks. When condition becomes true then executes the block given below Syntax: if ( condition): Statement(s) else: Statement(s) Example x = int(input("Please enter an integer: ")) y = int(input("Please enter another integer: ")) i f x > y: print(x,"is greater than",y) e l s e : print(y,"is greater than or equal to",x) Ladder if else statements (if-elif-else) The Python compound statement if, which uses if, elif, and else clauses, lets you conditionally execute blocks of statements. Here’s the syntax for the if statement: if expression: statement(s) elif expression: statement(s) elif expression: statement(s) ... else: statement(s) Example i = 20 if (i == 10):
  • 39. 39 print("i is 10") elif (i == 15): print("i is 15") elif (i == 20): print("i is 20") else: print("i is not present") Nested-if Nested if statements mean an if statement inside another if statement. if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here Example num=int(input(“Enter Number: “)) if ( num<=0): if ( num<0): print(“You entered Negative number”) else: print(“You entered Zero ”) else: print(“You entered Positive number”) Python Iteration Statements The iteration (Looping) constructs mean to execute the block of statements again and again depending upon the result of condition. This repetition of statements continues till condition meets True result. As soon as condition meets false result, the iteration stops. Python supports following types of iteration statements 1. while 2. for Four Essential parts of Looping: i. Initialization of control variable ii. Condition testing with control variable iii. Body of loop Construct iv. Increment / decrement in control variable
  • 40. 40 for loop For loops are useful when you need to do something for every element of a sequence <statements before for loop> for <variable> in <sequence>: <body of for loop> <statements after for loop> Example s = input("Please type some characters and press enter:") for c in s: print(c) print("Done") while Loop Python's while statement is its most general iteration construct. In simple terms, it repeatedly executes a block of indented statements, as long as a test at the top keeps evaluating to a true value. When the test becomes false, control continues after all the statements in the while, and the body never runs if the test is false to begin with. while <test>: # loop test <statements1> # loop body else: # optional else <statements2> # run if didn't exit loop with b Example count = 0 while (count < 9): print ('The count is:', count ) count = count + 1 print ("Good bye!" ) Python supports to have an else statement associated with a loop statement. If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a while loop, the else statement is executed when the condition becomes false Example: count = 0 while count < 5: print (count, " is less than 5" ) count = count + 1 else: print( count, " is not less than 5”) Single Statement Suites: If there is only one executable statement in while loop, then we can use this
  • 41. 41 format. Example: flag = 1 while (flag): print ('Given flag is really true!' ) print( "Good bye!" ) Jump Statements Now that we‘ve seen a few Python loops in action, it‘s time to take a look at two simple statements that have a purpose only when nested inside loops—the break and continue statements. In Python: pass Does nothing at all: it‘s an empty statement placeholder break Jumps out of the closest enclosing loop (past the entire loop statement) continue Jumps to the top of the closest enclosing loop (to the loop‘s header line) --------------------------------------------------------------------------------------------------------------------- Python range( ) Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax: range( start value, stop value, step value ) Where all 3 parameters are of integer type ● Start value is Lower Limit ● Stop value is Upper Limit ● Step value is Increment / Decrement Note: The Lower Limit is included but Upper Limit is not included in result. Example range(5) => sequence of 0,1,2,3,4 range(2,5) => sequence of 2,3,4 range(1,10,2) => sequence of 1,3,5,7,9 range(5,0,-1) => sequence of 5,4,3,2,1 range(0,-5) => sequence of [ ] blank list (default Step is +1) range(0,-5,-1) => sequence of 0, -1, -2, -3, -4 range(-5,0,1) => sequence of -5, -4, -3, -2, -1
  • 42. 42 range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0
  • 43. 43 WORK SHEET LEVEL-1 Q.No Questions Marks 1 Which of the following is not a Tuple in Python ? (a) (1,2,3) (b) (‘one’,two’,’three’) (c) (10,) (d) (‘one’) Ans: (‘one’) (1) 2 What will be output of the following code snippet: A=[1.2.3.4,5] print(a[3:0:-1]) Ans : [4,3,2] (1) 3 Write the output of the code given below: my_dict = {"name": "Kuhan",'Door No.': 100} my_dict["Door No."] = 128 my_dict['address'] = "Karnataka" print(my_dict.items()) Ans: dict_items([('name', 'Kuhan'), ('Door No.', 128), ('address', 'Karnataka')]) (2) 4 Find and write the output of the following python code: Msg="CompuTer" Msg1='' for i in range(0, len(Msg)): if Msg[i].isupper(): Msg1=Msg1+Msg[i].lower() elif i%2==0: Msg1=Msg1+'*' else: Msg1=Msg1+Msg[i].upper() print(Msg1) Ans: cO*P*t*R (4)
  • 44. 44 LEVEL-2 1 D={“AMIT”:90,”RESHMA”:96,”SUMAN”:92} Print(“SUMAN” in D, 90 in D, sep=”#”) (a) True#False (b) True#True (c) False#True (d) False#False Ans : (a) True#False (1) 2 Find and write the output of the following python code: x = "Welcome" i = "e" while i in x: print(i, end = "$") Ans :e$e$e$e$e$...... (1) 3. What is the output of the following Python statement : print(5+3**2/2) Ans : 9.5 (1) 4. The return type of the input() function is Ans:String (1) 5. Consider the given expression : not True and True or False Ans : False (1) 6. Given is a Python string declaration: myexam="@@CBSE Examination 2022@@" Write the output of: print(myexam[::-3]) Ans: @2 ina B@ (2) 7. What will be the output if entered number n is 1 and n is 4 : i=2 n=int(input("enter the value of n")) while i<n: if n % i==0: break print(i) i=i+1 (3)
  • 45. 45 else: print("done") Ans : n=1 ------ done n=4 ------- no output 8. What is the output of the following code snippet? def ChangeVal(M,N): for i in range(N): if M[i]%5 == 0: M[i]//=5 if M[i]%3 == 0: M[i]//=3 L = [25,8,75,12] ChangeVal(L,4) for i in L: print(i,end="#") Ans : 5#8#5#4# (4) LEVEL-3 1 State True or False: The # symbol used for inserting comments in python is a token Ans : True (1) 2 Which of the following invalid identifier in Python? (a) name (b) section (c) true (d) break Ans: (d) break (1) 3 Evaluate the following expressions : a) 8 // 4 + 18 * 6 / 3– 3 (2)
  • 46. 46 b) 35/5 or 5.0 + 30/10 Ans: a) 35.0 b)7.0 4 Concatenation operator in list is : (a) * (b) , (c) + (d) = Ans : + (1) 5 Find error in the following code(if any) and correct code by rewriting code and underline the correction;‐ x= int(input(“Enter value of x:”) ) for I in range [0,10]: if x=y: print( x + y) else: print( x‐y) (2) WORKING WITH FUNCTIONS Function Definition: A function is a programming block of codes which is used to perform a single, related, specific task. It only works when it is called. We can pass data, known as parameters, into a function. A function can return data as a result. Python treats functions like a first-class member. It implies that in Python, functions and other objects are of same significance.Functions can be assigned to variables, stored in collections, or passed as arguments. This brings additional flexibility to the language. Advantages of Functions • Reducing duplication of code • Decomposing complex problems into simpler pieces • Improving clarity of the code • Reuse of code • Information hiding Python function types There are three categories of functions: • Built-in functions
  • 47. 47 • Function defined in modules • User defined functions. Built-in functions The functions whose functionality is predefined in Python are referred to as built-in functions. The python interpreter has several such functions that are always available for use. E.g. len(), type(), int(), input() Function defined in modules These functions are pre-defined in particular modules and can only be used after the specific module is imported. E.g. All mathematical functions are defined in the module math. User-defined functions Python User Defined Functions allow users to write unique logic that the user defines. It is the most important feature in Python that consists of custom-defined logics with a set of rules and regulations that can be passed over the data frame and used for specific purposes. Structure of functions in Python Internally Python names the segment with top-level statements (no indentation) as _main_ Python begins execution of a program from top-level statements. Defining a Function A function in Python is defined as given below: def< function name >(parameters): [“ ” ”<function’s docstring>” “ “] <statements> [<statements>] ……………………..
  • 48. 48 • Keyword def that marks the start of the function header. • A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python. • Parameters (arguments) through which we pass values to a function. They are optional. • A colon (:) to mark the end of the function header. • Optional documentation string (docstring) to describe what the function does. • One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces). • An optional return statement to return a value from the function. Function header: The Header of a function specifies the name of the function and the name of each of its parameters. It begins with the keyword def. Parameters: Variables that are listed within the parenthesis of a function header. Function Body: The block of statements to be carried out, ie the action performed by the function. Indentation: The blank space needed for the python statements. (four spaces convention) Flow of execution in a function call The flow refers to the order in which statements are executed during a program run. The function body is a block of statements and python executes every block in an execution frame. An execution frame contains: • Some internal information (used for debugging) • Name of the function • Values passed to the function • Variables created within the function
  • 49. 49 • Information about the next instruction to be executed Whenever a function call statement is encountered, an execution frame for the function is created and the control is transferred to it. The statements are then executed and if there is return statement in the program, it will be executed and returns to the function call statement block. def message(): print('Hello I am learning how to create function in python.') def sum(a,b): c=a+b print('Sum of %d and %d is %d' %(a,b,c)) # main program # calling the function message() message() # calling the function sum() sum(10,20) In the above program, two functions message() and sum() is declared. The message() function does not accept any argument but displays a text on the screen whenever we call it. On the other hand, the sum() function accept two arguments and display their sum on the screen. when the main program calls the function message(), the program flow goes to the body of the function message() and execute its codes. After that, it returns to the main program and then calls the second function sum() by sending it two arguments (10,20), the program flow goes to the body of the function sum(), and execute its code and again returns to the main program. At last, the main programs end. The function calling another function is called the caller and the functions being called is the called function or callee. Parameters and Arguments The parameters are the variables that we can define in the function declaration. In fact, we utilized these variables within the function. Also, the programming language in the function description determines the data type specification. These variables facilitate the function’s entire execution. In addition, they are known as local variables because they are only available within the function. The arguments are the variables given to the function for execution. Besides, the local variables of the function take the values of the arguments and therefore can process these parameters for the final output.
  • 50. 50 Passing parameters:- Python support three types of formal arguments/parameters: 1. Positional argument (required arguments):- When the functions call statement must match the number and order of arguments as define in the functions definition this is called the positional arguments. Example:- def check(a,b,c): : Then possible functions call for this can be:- check(x,y,z)#3values(allvariables)passed check(2,x,y)#3values(literal+variables)passed check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed. Thus through such function calls- • The argument must be provided for all parameters (required) • The values of argument are matched with parameters, position(order)wise(positional) 2. Default arguments:- A parameter having defined value in the function header is known as a default parameter. Example:- def interest(principal,time,rate=10): si=interest(5400,2) #third argument missing So the parameter principal get value 5400,time get 2 and since the third argument rate is missing, so default value 0.10 is used for rate. • Default argument are useful in situations where some parameters always have same value. Some advantages of the default parameters are listed below:-
  • 51. 51 • They can be used to add new parameters to the existing functions. • They can be used to combine similar function in to one. 3. Keyword(or named)arguments:- Keyword arguments are the named arguments with assigned values being passed in the function call statement. Example:- def interest(prin,time,rate): return prin * time * rate print (interest ( prin = 2000 , time = 2 , rate 0.10 )) print (interest ( time = 4 , prin = 2600 , rate = 0.09 )) print(interest(time=2,rate=0.12,prin=2000)) All the above functions call are valid now, even if the order of arguments does not match. 4. Using multiple argument type together:- Python allows you to combine multiple argument types in a function call. Rules for combining all three types of arguments:- • And argument list must first contain positional(required) arguments followed by any keyword argument. • Keyword arguments should be taken from the required arguments preferably. • You cannot specify a value for an argument more than once. Example:- def interest(prin,cc,time=2,rate=0.09): return prin * time * rate Types of user defined function 1. No Argument No return 2. With Argument No return 3. No Argument with return 4. With Argument with return 1. No Argument No return def Add(): a= int (input(“Enter First Number”)) b= int (input(“Enter Second Number”)) c=a+b print (“The Sum of inputted Numbers is:”, c) Add() print(“ Executed”) 2. With Argument No return def Add(a,b): c=a+b
  • 52. 52 print(“The Sum of inputted Numbers is:”, c) num1=int (input(“Enter First Number”)) num2= int (input(“Enter Second Number”)) add(num1,num2) Remember: The variable in main program are differ from the variable in function definition i.e. a and b should be x and y. In this scenario the variable passed (num1,num2)will be called argument, and when it replace with the variable defined in the function will be called as parameter. 3. No Argument with return def Add(): a=int (input(“Enter First Number”)) b= int (input(“Enter Second Number”)) c=a+b return c x= add() print (“The Sum of inputted Numbers is:”, x) Note: { As return does not show the result we have to store the returned value on another variable x} 4. With Argument with return def Add (a,b): c=a+b return c a=int (input(“Enter First Number”)) b= int (input(“Enter Second Number”)) x= add(a,b) print (“The Sum of inputted Numbers is:”, x) Calling function and Called function: • Function which is called by another Function is called Called Function. The called function contains the definition of the function and formal parameters are associated with them. • The Function which calls another Function is called Calling Function and actual Paramaters are associated with them. • In python, a function must be defined before the function call otherwise python interpreter gives an error. Difference between Arguments and parameters These two terms are very interchangeable, so it is not so important to know the difference. The terms they refer to are almost identical. However, in order to sound more professional, correct terminology is important. Function Parameters: Variables that are in brackets when defining the function. When a method is called, the arguments are the data passed to the method’s parameters.
  • 53. 53 Function arguments : Arguments are used to pass information from the rest of the program to the function. This information return a result. There is no limit to the number of arguments that can be written. Depending on the type of function you’re performing, there might even be no argument. Use commas to separate the arguments in a function. Take into account the number of arguments you put in a function call. The number of arguments must be exactly the same as the number of parameters. In the example below, the variable name is the input parameter, where as the value, “Arnav”, passed in the function call is the argument. def welcome(name): print("Hello! " + name + " Good Morning!!") welcome("Arnav") Output: Hello! Arnav Good Morning!! Returning a Function If you wish to return some values from the function to the rest of the program, you can use the return statement. As the name suggests, it returns a value without printing it. Executing this statement will cause the Python function to end immediately and store the value being returned into a variable. Scope of variables Scope means in which part(s) of the program, a particular piece of code or data is accessible or known. In python there are broadly 2 kinds of Scopes: • Global Scope • Local Scope Global Scope: • A name declared in top level segment(_main_) of a program is said to have global scope and can be used in entire program. • Variable defined outside of the all functions are global variables. Local Scope : • A name declared in a function body is said to have local scope i.e. it can be used only within this function and the other block inside the function. • The formal parameters are also having local scope. When dealing with Python functions, you should also consider the scope of the variables. The code in a function is in its own little world, separate from the rest of the program. Any variable declared in the function is ignored by the rest of the function. This means that two variables with the same name can exist, one inside the function and the other outside the function. However, this is not a good practice. All variable names must be unique regardless of their scope.
  • 54. 54 Local variable: A variable that is defined within a function and can only be used within that particular function. With respect to the local variable, the area in a function is called “local area”. Global variable: A variable that is defined in the main part of the programming and, unlike local variables, can be accessed via local and global areas. Example: Lifetime of Variables: Lifetime is the time for which a variable lives in memory. For global variables the lifetime is entire program run i.e. as long as program is executing. For local variable, lifetime is their function’s run i.e. as long as function is executing. Name Resolution(Scope Resolution) For every name used within program, python follows name resolution rules known as LEGB rule. • Local Environment : first check whether name is in local environment, if yes Python uses its value otherwise moves to (ii) • Enclosing Environment:if not in local,Python checks whether name is in Enclosing Environment, if yes Python uses its value otherwise moves to (iii) • Global Environment:if not in above scope Python checks it in Global environment, if yes Python uses it otherwise moves to (iv) • Built-In Environment:if not in above scope, Python checks it in built-in environment, if yes, Python uses its value otherwise Python would report the error: name <variable> notdefined. WORKSHEET LEVEL I I. Questions (1 mark)
  • 55. 55 1. Which of the following is the use of function in python? a) Functions are reusable pieces of programs b) Functions don’t provide better modularity for your application c) you can’t also create your own functions d) All of the mentioned 2. What is the output of the below program? def printMax(a, b): if a > b: print(a, ‘is maximum’) elif a == b: print(a, ‘is equal to’, b) else: print(b, ‘is maximum’) printMax(3, 4) a) 3 b) 4 c) 4 is maximum d) None of the mentioned 3. What is the output of the below program? x = 50 def func(): global x print('x is', x) x = 2 print('Changed global x to', x) func() print('Value of x is', x) a) x is 50 Changed global x to 2 Value of x is 50 b) x is 50 Changed global x to 2 Value of x is 2 c) x is 50 Changed global x to 50 Value of x is 50 d) None of the mentioned 4. What is the output of the below program? def C2F(c): return c * 9/5 + 32 print (C2F(100)) print (C2F(0)) a) 212.0 32.0
  • 56. 56 b) 314.0 24.0 c) 567.0 98.0 d) None of the mentioned 5. The default value for a parameter is defined in function ……….. 6. Python names the top level segment as………….. 7. Variable declared inside functions may have global scope (True/False) 8. Which arguments given below is skipped from function call? a)Positional b)Default c)Keyword d)named 9. What is the order of resolving scope in Python? a)BGEL b)LEGB c)GEBL d)LBEG 10.Complete the function body. def f(num): ………….. print (f(8)) a)return 0 b)print(num) c)print(“num”) d)return num 11. The function pow(x,y,z) is evaluated as: a) (x**y)**z b) (x**y) / z c) (x**y) % z d) (x**y)*z 12. The function seed is a function which is present in the ……………..module 13. What are the outcomes of the functions shown below? sum(2,4,6) sum([1,2,3]) 14. What is the output of the functions shown below? min(max(False,-3,-4), 2,7) a) 2 b) False c) -3 d)0 15. What is the output of the programgiven below? a = 100 def func (a) : a = 20 func (a) print (' a is now ', a) A. a is now 50 B. a is now 100 C. a is now 2 D. error 16. What will be the output of the following python code: val = 100 def display(N): global val val = 50 if N%14==0:
  • 57. 57 val = val + N else: val = val - N print(val, end="@") display(40) print(val) A. 100@10 B. 50@5 C. 5@50 D. 100@10@ 17. What will be the output of the following python code: def A_func (x=10, y=20): x =x+1 y=y-2 return (x+y) print(A_func(5),A_func()) A. 24,29 B. 15,20 C. 20,30 D. 25,30 18. Consider the following code and choose correct answer def nameage(name=”kishan”, age=20): return age,name t=nameage(20,”kishan”) print(t[1]) A. kishan B. 20 C. (kishan, 20) D. (20,kishan) II. Questions (2 marks) 1. Write the output of the pseudocode def absolute_value(num): if num>= 0: return num else: return -num print(absolute_value(2)) print(absolute_value(-4)) III.Questions (3 marks) 1. Differentiate ceil() and floor() function? IV.Questions (5 marks)
  • 58. 58 1. What are the arguments supported by python? Explain each of them with a suitable example. 2. What is the difference between the formal parameters and actual parameters? What are their alternative names? Also, give a suitable Python code to illustrate both. ANSWERS I Answer the following 1 mark 1 A 2 C 3 B 4 A 5 Header 6 _main_ 7 False 8 B 9 B 10 B 11 C 12 Random 13 The first function will result in an error because the function sum() is used to find the sum of iterablenumbers. Hence the outcomes will be Error and 6respectively. 14 The function max() is being used to find themaximum value from among -3, -4 and false. Since falseamounts to the value zero, hence we are left with min(0, 2, 7)Hence the output is 0 (false) 15 B 16 A 17 A 18 B II Answer the following 2 marks 1 2
  • 59. 59 4 III Answer the following 3 marks 1 Floor Function Ceil Function floor function returns the integer value just lesser than the given rational value. ceil function returns the integer value just greater than the given rational value represented as floor(x). represented as ceil(x) The floor of negative fractional numbers is represented using the floor function The ceil of negative fractional numbers are represented using ceil function. It returns the value which is just less than or equal to the given value. It returns the value which is just greater than or equal to the given value. Eg. the floor of 78.38 is 78 and the floor of -39.78 is -40. Eg. ceil of 78.38 is 79 and ceil of - 39.78 is -39. IV Answer the following 5 marks 1 Python supports four argument types: Positional Arguments: Arguments passed to a function in correct positional order, no. of arguments must match with no. of parameters required. Default Arguments: Assign a default value to a certain parameter, it is used when the user knows the value of the parameter, default values are specified in the function header. It is optional in the function call statement. If not provided in the function call statement then the default value is considered. Default arguments must be provided from right to left. Key Word Arguments: Keyword arguments are the named arguments with assigned values being passed in the function call statement, the user can combine any type of argument. Variable Length Arguments: It allows the user to pass as many arguments as required in the program. Variable-length arguments are defined with the * symbol.
  • 60. 60 2 Actual Parameter is a parameter, which is used in function call statement to send the value from calling function to the called function. It is also known as Argument. Formal Parameter is a parameter, which is used in function header of the called function to receive the value from actual parameter. It is also known as Parameter. For example, def addEm(x, y, z): print(x + y + z) addEm (6, 16, 26) In the above code, actual parameters are 6, 16 and 26; and formal parameters are x, y and z. LEVEL II IV. Questions (1 mark) 1. Name the Python Library modules which need to be imported to invoke the following functions : load () pow () 2. What is the output of the below program ? x = 50 def func(x): #print(‘x is’, x) x = 2 #print(‘Changed local x to’, x) func(x) print(‘x is now’, x) a) x is now 50 b) x is now 2 c) x is now 100 d) None of the mentioned 3. What is the output of the below program? def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 7) func(25, c = 24) func(c = 50, a = 100)
  • 61. 61 a) a is 7 and b is 3 and c is 10 a is 25 and b is 5 and c is 24 a is 5 and b is 100 and c is 50 b) a is 3 and b is 7 and c is 10 a is 5 and b is 25 and c is 24 a is 50 and b is 100 and c is 5 c) a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50 d) None of the mentioned 4. What is the output of below program? def maximum(x, y): if x > y: return x elif x == y: return 'The numbers are equal' else: return y print(maximum(2, 3)) a) 2 b) 3 c) The numbers are equal d) None of the mentioned 5. A function is executed in an execution frame. True / False 6. Function returning values are also known as ………. Functions 7. Default return value for a function that does not return any value is ….. 8. Where is the function call and parameters stored in the system? a.Heap b.Queue c.Array d.Stack 9. What is the output of the function shown below?all([2,4,0,6]) a) Error b) True c) False d)0 10. What is the output of the following function?any([2>8, 4>2, 1>2]) a) Error b) True c) False d) 4>2 11. What is the output of the function shown below? import math.abs(math.sqrt(25)) a) Error b) -5 c) 5 d) 5.0 12. What is the output of the function: all(3,0,4.2) a) True b) False c) Error d)0 13. What is the output of the function complex() ? a) 0j b) 0+0j c) 0 d) Error
  • 62. 62 14. Predict the output of the following code def fun3(num1,num2): for x in range(num1,num2): if x%4==0: print(x,end=’ ‘) fun3(10,20) A. 10 12 16 20 B. 12 16 C. 12 16 20 15. Identify correct output (K) def fun3(a,b,c): return a+1,b+2,c+3 t=fun3(10,20,30) print(t) A. 11,22,33 B. 11 22 33 C. (11, 22, 33) D. (11 22 33) 16. The correct way to call a function is: A. A_func() B. def A_func() C. return A_func() D. call A_func() Questions (2 marks) 1. What is the output of the below program? def sayHello(): print('Hello World!') sayHello() sayHello() 2. From the program code given below, identify the parts mentioned below: def processNumber(x): x = 72 return x + 3 y = 54 res processNumber(y) Identify these parts: function header, function call, arguments, parameters Questions (3 marks) 1. What is a function? Why is it needful? 2. Compute the code. Write the output of the pseudocode. r=30 t=15
  • 63. 63 def swap(f,g): f = r+t g= f - g g = f - g print("f=", f,"g=", g) swap(r,t) swap(11,3) swap(t,10) swap(r,t) 3. Trace the following code and predict output produced by it. (a) 1. def power (b, p): 2. y = b **p 3 return y 4. 5 def calcSquare(x) : 6. a = power (x, 2) 7. return a 8. 9. n=5 10. result = calcSquare (n) + power (3, 3) 11. print(result) (b) 1.def power (b, p): 2 .r = b ** p 3. return r 4 5. def calcSquare(a): 6. a = power (a, 2) 7. return a 9.n = 5 10. result = calcSquare(n) 11. print (result) (c) 1. def increment(X): 2. X = X + 1 3. 4. # main program 5. X = 3 6. print(x) 7. increment(x) 8. print(x)
  • 64. 64 Questions (5 marks) 1. Differentiate between parameters and arguments. 2. Differentiate between actual parameter(s) and a formal parameter(s) with a suitable example for each. ANSWERS I Answer the following 1 mark 1 pickle math 2 A 3 C 4 B 5 True 6 Fruitful functions 7 None 8 D 9 C 10 True 11 5.0 12 The function all() returns ‘True’ if any one or more of the elements of the iterable are non zero. In theabove case, the values are not iterable, hence an error isthrown. 13 A 14 B 15. C 16 A II Answer the following 2 marks
  • 65. 65 1 Hello World! Hello World! 2 Function header-- def processNumber(x): Function call--- processNumber (y) Arguments----- y Parameters ----- x Function body-------x = 72 return x + 3 Main program-------- y = 54 res processNumber(y) III Answer the following 3 marks 1 A function is a set of instructions or subprograms that are used to perform a specific task. It divides the large program into smaller blocks of a program that processes the data and often returns a value. Functions are needful -To make the program easy -Divide the large program into a small block of codes -Reduce the lines of code -Easy to update -Reuse of the code is possible -Error correction is easier 2 f= {45} g= {15} f= {45} g= {3} f= {45} g= {10} f= {45} g= {15} 3 (a)1→5→9→10→5→6→1→2→36→7→10→1→2→3→10→11 (b) 1-59→10→56→1→2→36→710→11 (c) 1-5-6-7→1→2→8
  • 66. 66 IV Answer the following 5 marks 1 Parameters Arguments These are specified during the function definition. Values passed during the function call. They are also known as formal parameters. They are also known as actual parameters. The values passed as parameters are local variables and are assigned values of the arguments during the function call. Every argument is assigned to a parameter when the function is defined. These variables help in the complete execution of the function. These variables are passed to the function for execution. The values contained by these parameters can only be accessed from function return statements or if the scope of these parameters is made global. The arguments are accessible throughout the program depending upon the scope of the variable assigned. 2 Actual Parameter is a parameter, which is used in function call statement to send the value from calling function to the called function. It is also known as Argument. Formal Parameter is a parameter, which is used in function header of the called function to receive the value from actual parameter. It is also known as Parameter. For example, def addEm(x, y, z): print(x + y + z) addEm (6, 16, 26) In the above code, actual parameters are 6, 16 and 26; and formal parameters are x, y and z. LEVEL III I Questions (1 mark)
  • 67. 67 1. Which keyword is used for function? a) fun b) define c) def d) function 2. What are the two main types of functions? a) Custom function & User defined function b) Built-in function & User defined function c) User defined function & System function d) System function & Built-in functions 3. What is the output of below program? def cube(x): return x * x * x x = cube(3) print( x) a) 9 b) 3 c) 27 d) 30 4. Which of the following functions is a built-in function in python? a) seed() b) sqrt() c) factorial() d) print() 5. What is the output of the expression?round(4.5676,2)? a) 4.5 b) 4.6 c) 4.57 d) 4.56 6. What is the output of the following function?complex(1+2j) a) Error b) 1 c) 2j d) 1+2j 7. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as: a) (a%b, a//b) b) (a//b, a%b) c) (a//b, a*b) d) (a/b, a%b) 8. What is the output of the function shown below? list(enumerate([2, 3])) 9. What is the result of the code? def p(x): print(2**x) p(3) a)8 b)64 c)6 d)x 10. The default value of the parameter is defined in the …………. 11. Choose correct answer for the following code def abc(X,Y): print(X,Y) abc(10,20) A. X and Y are called actual parameter B. X and Y are default argument C. 10 and 20 are formal parameter D. None of above 12. Predict the output of the following code def fun2(list1): for x in list1: print(x.upper(),end=”#”)
  • 68. 68 fun2([‘Rajesh’,’Kumar’) 13. What will be the result of thefollowing code: def func1(a): a= a + '1' a = a * 2 func1("good") A. good B. good2good C. goodgood D. indentation error 14. Which of the following functions acceptsinteger as argument: A. chr() B. ord() C. sum() D. mul() 15. The function header contains: A. Function name only B. Parameter list only C. Both function name & Parameter list D. Return valu 16. A variable defined outside of all functions is known as : A. Local variable B. Global variable C. Static variable D. Unknown variable II. Questions (2 marks) 1. What is the local variable and global variable? 2. Write the output of the code def res(): eng = 56 math = 40 sci = 60 if eng<=35 || math<=35 || sci=35: print(‘Not Qualified’) else: print(“Qualified”) res() 3. Write the output of the code def my_func(): x = 10 print("Value inside function:",x) x = 20 my_func()
  • 69. 69 print("Value outside function:",x) 4. What are default arguments? What are the advantages of keyword arguments? III. Questions (3 marks) 1. What is a function? Why do we need functions in python programming? 2. Write and explain the types of functions supported by python. 3. What are keyword arguments? 4. IV.Questions (5 marks) 1. Explain the following built-in functions. (a) id () (b) chr () (c) round () (d) type () (e) pow () ANSWERS I Answer the following 1 mark 1 C 2 B 3 C 4 D 5 C 6 D 7 B 8 The built-in function enumerate() accepts an iterable as an argument. The function shown in the above case returns containing pairs of the numbers given, starting from 0.Hence the output will be: [(0, 2), (1,3)]. 9 A 10 Header 11 D 12 B 13 D 14 A 15 C 16 B
  • 70. 70 II Answer the following 2 marks 1 Global Variable: A variable that is declared in top-level statements is called a global variable. To access the value of a global variable user need to write a global keyword in front of the variable in a function. Local Variable: A name declared in a specific function body is called a local variable 2 Qualified 3 Value inside function: 10 Value outside function: 20 4 Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value III Answer the following 3 marks 2 Built in Functions: Pre-defined functions of python such as len(), type(), input() etc. Functions defined in modules: Functions defined in particular modules, can be used when the module is imported. A module is a container of functions, variables, constants, classes in a separate file which can be reused. User Defined Functions: Function created by the programmer 4 If there is a function with many parameters and we want to specify only some of them in function call, then value for such parameters can be provided by using their names instead of the positions. These are called keyword argument. (eg) def simpleinterest(p, n=2, r=0.6) def simpleinterest(p, r=0.2, n=3) It is easier to use since we need not remember the order of the arguments. We can specify the values for only those parameters which we want, and others have default values. IV Answer the following 5 marks
  • 71. 71 a)id(): Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. This is the address of the object in memory. (b) chr (): Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord(). The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range. (c) round () Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if ndigits is omitted or None. Otherwise, the return value has the same type as number (d) type () With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__. (e) pow () Return base to the power exp; if mod is present, return base to the power exp, modulo mod (computed more efficiently than pow(base, exp) % mod). The two-argument form pow(base, exp) is equivalent to using the power operator: base**exp. The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, pow(10, 2) returns 100, but pow(10, - 2) returns 0.01. For a negative base of type int or float and a non-integral
  • 72. 72 exponent, a complex result is delivered. For example, pow(-9, 0.5) returns a value close to 3j. FILE HANDLING Files are of bytes stored on storage devices such as hard-disks. Files help in storing information permanently on a computer. Data Files: Data files are files that store data pertaining to a specific application. The data files can be stored in following ways: • Text files: These files store information in the form of a stream of ASCII or UNICODE characters. Each line is terminated by an EOL character. Python programs, contents written in text editors are some of the example of text files. • Binary files: These files store information in the form of a stream of bytes. No EOL character is used and binary files hold information in the same format in which it is held in the memory. The .exe files, mp3 file, image files, word documents are some of the examples of binary files.We can’t read a binary file using a text editor. Difference Between Text File And Binary File Text File Binary File Stores information in ASCII characters. Stores information in the same format which the information is held in memory. Less prone to get corrupt as change reflects as soon as made and can be undone. Can easily get corrupted, corrupt on even single bit change. Store only plain text in a file. Can store different types of data. Widely used file format and can be opened in any text editor. Developed for an application and can be opened in that only. Slower than binary files. Binary files are faster and easier for a program to read and write the text files. Opened in any text editor. Mostly .txt and .rtf are used as extensions of text files. Can have any application defined extensions. In Python, File Handling consists of following three steps: • Open the file. • Process file i.e.perform read or write operation. • Close the file.
  • 73. 73 Opening Files : To perform file operation, it must be opened first then after reading, writing,editing operation can be performed.To create any new file then too it must be opened. On opening of any file, a file relevant structure is created in memory as well as memory space is created to store contents. Once we are done working with the file, we should close the file. Itisdoneusing open() function as per one of the following syntax: <fileobjectname>=open(<filename>) <fileobjectname>=open(<filename>,<mode>) For example: stu=open("students.txt") The above statement open file"students.txt" in file mode as read mode(defaultmode) and attaches it to file object namely stu. Consider one more file open statement: - stu=open ("e:mainstudents.txt","w") The above statement open file"students.txt"(storedinfoldere:main)in write mode(because of"w"givenasmode)and attaches it to file object namely stu. • Please note that when you open a file in read mode,the given file must exist in folder, otherwise Python will raise error. File Object/File Handle:-A file object is a reference to a file on disk.It opens and makes it available for a number of different tasks. FileAccessModes:- Text file mode Binary File Mode Description ‘r’ ‘rb’ Read-Default value. Opens a file for reading, error if the file does not exist. ‘w’ ‘wb’ Write- Opens a file for writing, creates the file if it does not exist ‘a’ ‘ab’ Append- Opens a file for appending, creates the file if it does not exist ‘r+’ ‘rb+’ Read and Write- File must exist, otherwise error is raised.
  • 74. 74 ‘w+’ ‘wb+’ Read and Write-File is created if does not exist. ‘a+’ ‘ab+’ Read and write – Append new data A file-mode governs the type of operations(e.g.,read/write/append) possible in the opened file i.e., it refers to how the file will be used once it's opened. Closing Files : One must always close a file when the file is no longer required for any more operations.The file can be closed by using the close( ) function which can be used w ith the file pointer as follows: <file_handle>.close() Working with Text Files: 1. Read the data from a file 2. Write the data to a file 3. Append the data to a file Reading from Text Files Python provides three types of read functions to read from a data file. • Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file. • Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read bytes in the form of string ending with line character or blank string if no more bytes are left for reading. • Filehandle.readlines(): reads all lines and returns them in a list Examples: Let a text file “Book.txt” has the following text: Example-1:Programusingread()function: fin=open("D:pythonprogramsBoo k.txt",'r') str=fin.read( ) OUTPUT: Python is interactive language. It is case sensitive language. It makes the difference between uppercase and “Python is interactive language. It is case sensitive language. It makes the difference between uppercase and lowercase letters. It is official language of google.”
  • 75. 75 print(str) fin.close() lowercase letters. It is official language of google. Example-2:Programusingread()function: fin=open("D:python programsBook.txt",'r') str=fin.read(10) print(str) fin.close() OUTPUT: Python is Example-3:usingreadline()function: fin=open("D:python programsBook.txt",'r') str=fin.readline( ) print(str) fin.close( ) OUTPUT: Python is interactive language. It is case sensitive language. Example-4:usingreadlines()function: fin=open("D:python programsBook.txt",'r') str=fin.readline( ) print(str) fin.close( ) OUTPUT: ['Python is interactive language. It is case sensitive language.n', 'It makes the difference between uppercase and lowercase letters.n', 'It is official language of google.'] Writing onto Text Files: Like reading functions , the writing functions also work on open files. • <filehandle>.write(str1): Wrties string str1 to file referenced by <file handle>. • <filehandle>.writelines(L): Wrties all strings in list L as lines to file referenced by <file handle>. Myfile Example-1:Program using write()function: f=open(r’MyFile.txt’,’w’) data = ‘My name is Aarav.’ f.write(data) f.close( ) f=open(r’MyFile.txt’,’r’) data = f.read( ) OUTPUT: My name is Aarav. I am Peter. How are you?
  • 76. 76 print(data) f.close( ) Example-2:Program using writelines()function: f=open(r’Myfile.txt’,’a’) data=[‘I have a dog., ‘nI love my cat.’] f.writelines(data) f.close( ) f=open(r’Myfile.txt’,’r’) data = f.read( ) print(data) f.close( ) OUTPUT: #It will append the content. My name is Aarav.I have a dog. I love my cat. flush( ) function: •When we write any data to file, python hold everything in buffer (temporary memory) and pushes it onto actual file later. If you want to force Python to write the content of buffer onto storage, you can use flush() function. •Python automatically flushes the files when closing them i.e. it will be implicitly called by the close(), but if you want to flush before closing any file you can use flush() seek( ) function: The seek( ) function allows us to change the position of the file pointer in the opened file as follows: f.seek(offset,mode) where offset - is a number specifying number of bytes. mode - specifies the reference point from where the offset will be calculated to place the file pointer. The mode argument is optional and has three possible values namely 0, 1 and 2. The default value of mode is 0. 0 - beginning of file 1 - current position in file 2 - end of file tell( ) function: The tell() method returns the current position of the file pointer in the opened file. It is used as follows: f.tell()
  • 77. 77 Example-1: tell()function: Example: fout=open("story.txt","w") fout.write("Welcome Python") print(fout.tell( )) fout.close( ) OUTPUT: 14 WORKSHEET LEVEL-I 1 To open a file "c:marks.txt" for reading, we use (a) file_read = open("c:marks.txt", "r") (b) file_read = open("c:marks.txt", "r") (c) file_read = open(file = "c:marks.txt", "r") (d) file_read = open(file = "c:marks.txt", "r") 1 2 What is the use of tell() method in Python? (a) returns the current position of record pointer within the file (b) returns the end position of record pointer within the file (c) returns the current position of record pointer within the line (d) none of the above 1 3 Which of the following commands can be used to read "n" number of characters from a file using the file object <File>? (a) File.read(n) (b) N = file.read() (c) File.readline(n) (d) File.readlines() 1 4 What is the correct syntax of open() function? (a) File = open(file_name[, access_mode][, buffering]) (b) File object = open(file_name [, access_mode][,buffering]) (c) File object = open(file_name) (d) None of the above 1 5 Write the coding to display the content of file "welcome.txt". 1 6 Write the output of the given program: 1 7 Write a python program to accept a line from the user and store that in a file “story.txt”. 2 8 Write a function to copy all the upper case words to another file. 2 9 Write the function to read the content from the file display the word which are having the length of exactly 4 characters. 3 10 Krishna is confused in Python code given below. Please help him to answer the following questions. 5
  • 78. 78 (a) Which line in the above code check for capital letter? (b) Which line in the above code read the file “story. txt”? (c) Which line in the above code does not affect the execution of program? (d) Which line is the above code coverts capital letter to small letter? (e) Which line is the above code opens the file in write mode? (f) Which line is the above code saves the data? (g) Which line(s) is/are the part of selection statement. (h) Which line(s) is/are used to close story1.txt? ANSWERS 1 (b) file_read = open("c:marks.txt", "r") 2 (a) returns the current position of record pointer within the file 3 (a) File.read(n) 4 (b) File object = open(file_name [, access_mode][,buffering]) 5 6 22 7
  • 79. 79 8 9 10 (a) Line 6 (b) Line 4 (c) Line 10 (d) Line 7 (e) Line 2 (f) Line 13 (g) Line 6, Line 8 and Line 11 (h) Line 15 LEVEL-2 1 To read two characters from a file object "file_read" (a) file_read.read(2) (b) file_read(2) (c) file_read(read,2) (d) file_read.readlines(2) 1 2 seek() method in files used for 1 3 What does the <readlines()> method returns? (a) Str (b) A list of lines(c) List of single characters(d) List of integers 1 4 Differentiate the following: (a) f = open('diary.txt', 'r') (b) f = open('diary.txt', 'w') 1
  • 80. 80 5 Assume that file “tear.txt”, already contain “I love my India” in the file. What will be the output of the given program: 1 6 Write a function to count the Upper case vowel in file “All.txt”. 2 7 Write a function to read the content from the file “Story.txt”. The function will take a string as parameter and search the string into the file. 2 8 Aarti is new in python data-handling. Please help her to count the number of lines which begins with ‘W’ or ‘w’ in poem.txt. (a) # Line 1 : To open file POEM.txt in read mode (b) # Line 2 : To check first character of every line is ‘W’ or ‘w’. (c) # Line 3 : To increase the value of count by 1. (d) # Line 4 : To call the function count_poem. 4 ANSWERS 1 (a) file_read.read(2) 2 Sets the file's current position at the offset 3 (b) A list of lines 4 (a) It opens the file in reading mode only in text format. (b) It opens the file in writing mode only in text format. If the file exists, then it erases the previous data.
  • 81. 81 5 13 6 7 8 (a) file1 = open("POEM.TXT","r") (b) r1[0]=='W' or r1[0]=='w': (c) count=count+1 (d) count_Poem() LEVEL-3 1 To read the content of the file as a string via a file object "f" (a) f.read(2) (b) f.read()(c) f=file.readline() (d) f.readlines() 1 2 The readlines() returns (a) only first line from the file (b) only last line from the file (c) all lines from the file (d) none of the above 1 3 Observe the following code and answer the questions that follow: (i) What type (Text/Binary) of file is Mydata? (ii) Fill the Blank 1 with statement to write “ABC” in the file “Mydata”. 1
  • 82. 82 4 A text file “Quotes.Txt” has the following data written in it: Write the output of the given program. 1 5 Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word "India". 2 6 Write a function to read the content from the file “India.txt”, and store the frequency of each word in dictionary and display the dictionary in the screen. Content of the file is: ‘‘India is the fastest growing economy. India is looking for more investments around the globe. The whole world is looking at India as a great market. Most of the Indians can foresee the heights that India is capable of reaching.’’ Output of the file: {‘India’: 4, ‘is’: 4, ‘the’: 4, ‘fastest’: 1, ‘growing’: 1, ‘economy.’: 1, ‘looking’: 2, ‘for’: 1, ‘more’: 1, ‘investments’: 1, ‘around’: 1, ‘globe.’: 1, ‘The’: 1, ‘whole’: 1, ‘world’: 1, ‘at’: 1, ‘as’: 1, ‘a’: 1, ‘great’: 1, ‘market.’: 1, ‘Most’: 1, ‘of’: 2, ‘Indians’: 1, ‘can’: 1, ‘foresee’: 1, ‘heights’: 1, ‘that’: 1, ‘capable’: 1, ‘reaching.’: 1} 4 7 Mohan has written the following code: 4 Living a life you can be proud of Doing your best Spending your time with people and activities that are important to you Standing up for things that are right even when it’s hard Becoming the best version of you.
  • 83. 83 (a) What will be the output? (i) It will display first 20 characters. (ii) It will display 20th character and onwards. (iii) It will display first 20 bytes. (iv) It will display content at 20th byte. (b) Meenu, Mohan's friend has written the following Python code. What will be the output? (i) True (ii) False (iii) None (iv) Error (c) The read() method returns____________. (i) str (ii) list (iii) tuple (iv) None of these (d) The readline() method returns ______________. (e) The readlines() method returns _______________. ANSWERS 1 (b) f.read() 2 (c) all lines from the file 3 (i) Text File (default mode) (ii) File.write(“ABC”) 4 ife y 5
  • 84. 84 6 7 (a) (iii) It will display first 20 bytes. (b) (i) True (c) (i) str (d) str (e) list
  • 85. 85 BINARY FILES Topics Covered : o Binary file: basic operations on a binary file: o Open using file open modes (rb, rb+,wb,wb+, ab, ab+), o Close a binary file, o import pickle module, dump() and load() method, o read, write/create, search, append and update operations in a binary file. Binary files store data in the binary format (0’s and 1’s) which is understandable by the machine. So when we open the binary file in our machine, it decodes the data and displays in a human-readable format. There are three basic modes of a binary file: • read: This mode is written as rb • write: This mode is written as wb • append: This mode is written as ab The plus symbol followed by file mode is used to perform multiple operations together. For example, rb+ is used for reading the opening file for reading and writing. The cursor position is at the beginning when + symbol is written with file mode. To open a binary file follow this syntax: file = open(<filepath>, mode) For example: f = open(“one.dat”,”rb”) Binary File Modes: File mode governs the type of operations read/write/append possible in the opened file. It refers to how the file will be used once its opened. File Mode Description rb Read Only: Opens existing file for read operation wb Write Only: Opens file for write operation. If file does not exist, file is created. If file exists, it overwrites data. ab Append: Opens file in write mode. If file exist, data will be appended at the end. rb+ Read and Write: File should exist, Both read and write operations can be performed. wb+ Write and Read: File created if not exist, If file exist, file is truncated. ab+ Write and Read: File created if does not exist, If file exist data is truncated.
  • 86. 86 Pickle Module: Python pickle is used to serialize and deserialize a python object structure. Any object on python can be pickled so that it can be saved on disk. Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte stream. It is also known as serialization Unpickling: A byte stream is converted into object hierarchy. To use the pickling methods in a program, we have to import pickle module using import keyword. Example: import pickle In this module,we shall discuss two functions of pickle module, which are: i) dump():To store/write the object data to the file. ii) load():To read the object data from a file and returns the object data. Syntax: Write the object to the file: pickle.dump(objname, file-object ) Read the object from a file: pickle.load(file-object) Write data to a Binary File: Example: import pickle list =[ ] # empty list while True: roll = input("Enter student Roll No:") sname=input("Enter student Name:") student={"roll":roll,"name":sname} # create a dictionary list.append(student) #add the dictionary as an element in the list choice=input("Want to add more record(y/n):") if(choice=='n'): break file=open("student.dat","wb") # open file in binary and write mode pickle.dump(list, file) file.close() OUTPUT: Enter student Roll No: 1201 Enter student Name: Anil Want to add more record(y/n): y
  • 87. 87 Enter student Roll No: 1202 Enter student Name: Sunil Want to add more record(y/n): n Read data from a Binary File: To read the data from a binary file, we have to use load() function Example: import pickle file = open("student.dat", "rb") list =pickle.load(file) print(list) file.close() OUTPUT: [{'roll':'1201','name':'Anil'},{'roll':'1202','name':'Sunil'}] Update a record in Binary File: def update(): name=input("Enter the name to be updated ") newstu=[] while True: try: stu=p.load(f) for i in stu: if i[1].lower()==name.lower(): rno=int(input("Enter the updated Roll number")) s=[rno,name] newstu.append(s) else: newstu.append(i) except: break f.close() f=open("student.dat","rb+") update() p.dump(newstu,f) print(“Record updated”) f.close() OUTPUT: Enter the name to be updated Sunil Enter the updated Roll number 1204 Record updated
  • 88. 88 Delete a record from binary file: import pickle def deletestudent(): roll=input('Enter roll number whose record you want to delete:') list = pickle.load(fw) found=0 lst= [] for x in list: if roll not in x['roll']: lst.append(x) else: found=1 fw=open(“student.dat”,”rb+”) delestudent() pickle.dump(lst,fw) fw.close() if found==1: print(“Record Deleted”) else: print(“Record not found”) OUTPUT: Enter roll number whose record you want to delete:1201 Record Deleted WORKSHEET LEVEL – 1 I Answer the following questions Marks 1 Which type of file does not have delimiters? 1 2 The process of converting the structure to a byte stream before writing to the file is known as _________. 1 3 The process of converting byte stream back to the original structure is known as _______ 1 4 Raman open a file in readmode, but the file doesn’t exist in the folder. Python raised an error for the code. What type of error will be shown? 1 5 The prefix ______ in front of a string makes it raw string that is no special meaning attached to any character. 1
  • 89. 89 6 Pickling is otherwise known as ________________ 1 7 CSV files are opened with __________argument to supress EOL translation. 1 8 Which of the following statement is incorrect in the context of binary files? a. Information is stored in the same format in which the information is held in memory. b. No character translation takes place c. Every line ends with a new line character d. pickle module is used for reading and writing 1 II Answer the following 1 What is EOFError? How can we handle EOFError in python? 2 2 How text files and binary files are stored inside computer memory? 2 3 Name any two exceptions that occur while working with pickle module. 2 4 What is the difference between writer object’s writerow() and writerows() function? 2 III Answer the following 1 Binary files are the best way to store program information. Discuss 3 2 The code given below reads from a file “sales.dat” which has following information [itemcode, amount] Read from the file and find the sum of the amount. import pickle F1 = open ("sales.dat", "rb") sum = 0 while True: try: ________________ 3
  • 90. 90 ________________ except EOFError: break print (sum) F1.close() IV Answer the following 1 What are the different file access modes? Explain 5 2 Write the differences between read(), readline(), readlines(). Explain it with this example a) Consider the following lines. The Dowry system is evil in society. It has reduced the sacred affair of marriage to a business deal. Brides are treated as a marketable commodity. The parents of the brides are often put under inhuman pressure for a handsome dowry. 5 3 Arun, during Practical Examination of Computer Science, has been assigned an incomplete search() function to search in a pickled file student.dat. The Filestudent.dat is created by his Teacher and the following information is known about the file. • File contains details of students in [roll_no,name,marks] format. • File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each student is written in the binary file using dump(). Arun has been assigned the task to complete the code and print details of roll number 1. def search(): f = open("student.dat",____)#Statement-1 ____: #Statement-2 while True: rec = pickle.____#Statement-3 if(____): #Statement-4 print(rec) except: pass ____ #Statement-5 I. In which mode Arun should open the file in Statement-1? a) r b) r+ c) rb d) wb 5
  • 91. 91 II. Identify the suitable code to be used at blank space in line marked as Statement2 a) if(rec[0]==1) b) for i in range(10) c) try d) pass III. Identify the function (with argument), to be used at blank space in line marked as Statement-3. a) load() b) load(student.dat) c) load(f) d) load(fin) IV. What will be the suitable code for blank space in line marked as Statement-4. a) rec[0]==2 b) rec[1]==2 c) rec[2]==2 d) rec[0]==1 V. Which statement Arun should use at blank space in line marked as Statement4 to close the file. a) file.close() b) close(file) c) f.close() d) close() Answers I 1. Binary files 2. Pickling 3. Unpickling 4. FileNotFoundError 5. r 6. Serialization. 7. Newline 8. Every line ends with a new line character II 1.EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file condition (EOF) without reading any data. We can overcome this issue by using try and except keywords in Python, called Exception Handling. 2.A text file stores information in the form of a stream of ASCII or Unicode characters based on the default state of programming languages. Binary file store information as stream of bytes . 3. Pickle.PicklingError and pickle.Unpickling Error
  • 92. 92 4.writer.writerow(row): Write the row parameter to the writer’s file object, formatted according to delimiter defined in writer function. writerows(rows): Writes multiple rows (sequence) to the writer’s file object III 1.Binary files store the information in the form of a stream of bytes similar to the format a computer memory holds data. Also there is no delimiter for a line and no translations occur in binary files. Thus binary files are faster and easier for a program to read and write. So the best method for a data or program information is to store it as binary files. 1. Program L = pickle.load(F1) 1. sum = sum + L[1] IV 1. Mode & Description a) r - reading only. Sets file pointer at beginning of the file. This is the default a. mode. b) rb – same as r mode but with binary file. c) r+ - both reading and writing. The file pointer placed at the a. beginning of the file. d) rb+ - same as r+ mode but with binary file. e) w - writing only. Overwrites the file if the file exists. If not, a. creates a new file for writing. f) wb – same as w mode but with binary file. g) w+ - both writing and reading. Overwrites. If no file exists, a. creates a new file for R & W. h) wb+ - same as w+ mode but with binary file. i) a -for appending. Move file pointer at end of the file.Creates a. new file for writing,if not exist. j) ab – same as a but with binary file 2. a) read() – Reads at most n bytes. If no n is specified it will read the entire file e.g. f1=open(“E:mydatainfo.txt”) info=f1.read(15) output: The Dowry syste b) readline() – Reads a line of input. If n is specified it reads at most n bytes.
  • 93. 93 It returns read bytes in the form of a string ending with line character or returns a blank string if no more bytes are left for reading in the file. e.g. f1=open(“E:mydatainfo.txt”) info=f1.readlines() output: The Dowry system is evil in society c) readlines() – Read all lines and returns them in a list output: [“The Dowry system is evil in society.n”” It has reduced the sacred affair of marriage to a business deal.n”“Brides are treated as a marketable commodity. n””The parents of the brides are often put under inhuman pressure for a handsome dowry.n“] 3.c,c,c,d,c LEVEL – 2 Answer the following questions Marks 1 A collection of bytes stored in computer’s secondary memory is known as ______ 1 2 Default EOL character in Python is the _______ 1 3 The _________ files are used to store large data such as images, video files, audio files etc 1 4 ______ module is used to store data into a python objects with their structure. 1 5 ______ function of pickle module is used to write data into binary 1 6 _______ function of pickle module is used to read data from binary file. 1 7 Ms. Suman is working on a binary file and wants to write data from a list to a binary file. Consider list object as L1, binary file suman_list.dat, and file object as f. Which of the following can be the correct statement for her? a) f = open(‘sum_list’,’wb’); pickle. dump(L1,f) b) f = open(‘sum_list’,’rb’); L1=pickle.dump(f) c) f = open(‘sum_list’,’wb’); pickle.load(L1,f) 1
  • 94. 94 d) f = open(‘sum_list’,’rb’); L1=pickle.load(f) 8 Ranjani is working on the sports.dat file but she is confused about how to read data from the binary file. Suggest a suitable line for her to fulfil her wish. import pickle def sports_read(): f1 = open("sports.dat","rb") _________________ print(data) f1.close() sports_read() 1 9 Which of the following statement is incorrect in the context of binary files? a. Information is stored in the same format in which the information is held in memory. b. No character translation takes place c. Every line ends with a new line character d. pickle module is used for reading and writing 1 10 Which of the following statement opens a binary file record.bin in write mode and writes data from a list L = [1,2,3,4] on the binary file? a. with open('record.bin','wb') as myfile: pickle.dump(L,myfile) b. with open('record.bin','wb') as myfile: pickle.dump(myfile,L) c. with open('record.bin','wb+') as myfile: 1
  • 95. 95 pickle.dump(myfile,L) d. with open('record.bin','ab') as myfile: pickle.dump(myfile,L) II Answer the following questions 1 What are delimited text files? Give examples 2 2 What is a file object? 2 3 What is the difference between write() and writelines()? 2 4 The code given below writes Name and Roll Nos into a binary file. Fill in the blanks to complete the code. import pickle with open ("file.dat", "wb") as F1: while True: op = int (input ("Enter 1 to add data, 0 to quit")) if (op == 1): __________________________ __________________________ pickle.dump([name,rollno],F1) elif op == 0: break 2 5 Write a code to include list of items Apple, Mango, Banana to a Binary File. 2 6 Read the following Python code carefully and answers the question given after the code import pickle #open file in binary mode for writing. 2
  • 96. 96 with open('emp.dat', '____') as outfile: #Line 1 #Store data in list employee = [101,'Simran',20000] _________________ #Line 2 a) Fill in the blank in line 1 to open file in binary mode for append data to the file b) Fill in the blank in line 2 to pickle the list and write to file 7 What will be displayed by the following code ? import pickle Names = ['First', 'second', 'third', 'fourth', 'Fifth'] for i in range(-1, -5, -1): lst.append(Names[i]) with open('test.dat', 'wb') as fout: pickle.dump(1st, fout) with open('test.dat', 'rb') as fin: nlist = pickle.load(fin) print(nlist) 2 III 1 What is pickle module? Why we use pickle module? 3 2 Write a code to show how a dictionary is stored as binary file. 3 3 A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a function countrec() in Python that would read contents of the file “salary.DAT” and display the details of those employee whose salary is above 20000. 3
  • 97. 97 4 A file sports.dat contains information in following format [event, participant]. Write a program that would read the contents from file and copy only those records from sports.dat where the event name is “Athletics” in new file named Athletics.dat 3 5 A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage]. Write a function countrec() in Python that would read contents of the file “STUDENT.DAT” and display the details of those students whose percentage is above 75. Also display number of students scoring above 75% 3 6 What is pickle.dump()?What is pickle.load()? 3 7 Write a function in to search and display details of all trains, whose destination is "Delhi" from a binary file "'TRAIN .DAT'" Assuming the binary file is containing the objects of the following dictionary type: Train = {'Tho' :_______ , 'From': _____, " To': ________} 3 ANSWERS I 1.Files 2. Newline (n) 3. Binary 4. PICKLE 5.dump() 6.load() 7.option d 8.data = f1.load(f). 9. c 10. with open('record.bin','wb') as myfile: pickle.dump(L,myfile) II 1.Text files where a particular character is stored to separate the data in it are known as delimited text files. In these files. there will be a tab (→) , comma(,) , pipe(│) or tilde(~ ) placed after each value.
  • 98. 98 E.g.: CSV files – Comma Separated Files TSV files – Tab separated files 2. Python file object provides methods and attributes to access and manipulate files. Using file objects, we can read or write any files. Whenever we open a file to perform any operations on it, Python returns a file object. 3.The difference between Write() and WriteLine() method is based on new line character. Write() method displays the output but do not provide a new line character. WriteLine() method displays the output and also provides a new line character it the end of the string, This would set a new line for the next output. 4.rollno=int(input("Enter the Roll Number: ")) name=input("Enter the name: ") 5. import pickle def writefile(): f=open("datafile.dat", "wb") list=["Apple","Mango", "Banana"] pickle.dump(list,f) f.close writefile() print("Writing done") 6. a) ab b)pickle.dump(employee, outfile) 7. ['Fifth', 'fourth', 'third', 'second"] III 1. Pickle module provides us the ability to serialise and deserialize objects that is, it helps to convertobjects into bitstreams that can be stored in files and later utilised to recreate the original objects.
  • 99. 99 For us, writing different kinds of objects into the binary file and later, reading the file's content is really challenging.The fact that some of the objects may have changing lengths makes this a tedious task. So we use the pickle module to solve this issue since it can handle dictionaries, sets, lists, tuples, classes, and more.It can store lists, Tuples, dictionaries, sets, classes etc. 2. import pickle F1 = open ("file.dat", "wb") Icode = input ("Enter code : ") quantity = int (input ("Quantity : ")) d = {Icode:quantity}, pickle.dump(d, F1) F1.close() 3. def countrec(): num=0 fobj=open("data.dat","rb") try: print("Emp idtEmp NametEmp Sal") while True: rec=pickle.load(fobj) if rec[2]>20000: print(rec[0],"tt",rec[1],"tt",rec[2]) except: fobj.close() countrec() 4. import pickle
  • 100. 100 F1 = open ("sports.dat", "rb") F2 = open ("athletics.dat", "wb") sum = 0 while True: try: l = pickle.load(F1) if (l[0].lower() == "athletics"): print (l) pickle.dump(l,F2) except EOFError: break F1.close() F2.close() 5. import pickle def countrec(): fobj=open("student.dat","rb") num = 0 try: while True: rec=pickle.load(fobj) if rec[2]>75: num = num + 1 print(rec[0],rec[1],rec[2]) except: fobj.close() return num
  • 101. 101 6. dump() function is used to store the object data to the file. dump( object, filehandle ) It takes 3 arguments. First argument is the object that we want to store. The second argument is the file object we get by opening the desired file in write-binary (wb) mode. the third defines the protocol. load() function is used to retrieve pickled data. mylist = pickle.load(filehandle) Arguments The primary argument is the filehandle that you get by opening the file in read-binary (rb) mode. 7. The code includes following steps, Import of pickle module.Opens the TRAIN.DAT file as read-only in binary format and starts reading from the beginning of the file.using while loop searches the "Delhi".if the "Delhi" does not exits its results a string " Not found ! ! ! " import pickle def search(): file open("TRAIN.DAT","rb") found = 0 try: while True : Train = pickle.load(file) if Train [ "To" ] ¡ 'Delhi': print(Train) found=1 except EOFError : if found == 0:
  • 102. 102 print("Not found !!!") file.close() search() LEVEL – 3 Answer the following questions Marks 1. Write Python statements to open a binary file "student.dat" in both read & write mode. 1 2. Which of the following statement is true? a. pickling creates an object from a sequence of bytes b. pickling is used for object serialization c. pickling is used for object deserialization d. pickling is used to manage all types of files in Python 1 3. Read the following Python code carefully and answers the question given after the code import pickle #open file in binary mode for writing. with open('emp.dat', '____') as outfile: #Line 1 #Store data in list employee = [101,'Simran',20000] _________________ #Line 2 Fill in the blank in line 1 to open file in binary mode for append data to the file. Fill in the blank in line 2 to pickle the list and write to file 1 1 4. Raghav is trying to write a tuple t = (1,2,3,4,5) on a binary file test.bin. Consider the following code written by him. import pickle t = (1,2,3,4,5) 1
  • 103. 103 myfile = open("test.bin",'wb') pickle._________ #Statement 1 myfile.close() Identify the missing code in Statement 1. a. dump(myfile,t) b. dump(t, myfile) c. write(t,myfile) d. load(myfile,t) 5. Computers store every file as a collection of ……… a)strings b)Bytes c)characters d)object e)none of the above 1 6. The default file-open mode is ……….. a)r b)a c)w d)w+ e)none of the above 1 7. Which of the following file mode open a file for reading and writing both in the binary file? a) rb) rb c) rb+ d) rwb 1 8. The _____ file mode is used to handle binary file for reading. a)rb b)wb c)r+ d)wb+ e)None of the above 1 9. Which of the following file mode opens a file for reading and writing both as well as overwrite the existing file if the file exists otherwise creates a new file? a) w b) wb+ c) wb d) rwb 1 10. ______ module is used to store data into an python objects with their structure. a)csv b)pickle c)os d)numpy 1 11. A _________ is a file format which stores records separated by comma. a)numpy b)tsv c)csv d)dat 1 II Answer the following 12. What are the two types of data files? Give examples for each. 2 13. What is pickling and unpickling of data? 2 14. What is aBinary File? Give examples 2
  • 104. 104 15. How can you delete a file? Write a pseudocode to delete a file 2 16. Write a function to read name and roll no from a binary file. 3 III Answer the following 1 Amritya Seth is a programmer, who has recently been given a task to write a python code to perform the following binary file operations with the help of two user defined functions/modules: a. AddStudents() to create a binary file called STUDENT.DAT containing student information – roll number, name and marks (out of 100) of each student. b. GetStudents() to display the name and percentage of those students who have a percentage greater than 75. In case there is no student having percentage > 75 the function displays an appropriate message. The function should also display the average percent. He has succeeded in writing partial code and has missed out certain statements, so he has left certain queries in comment lines. You as an expert of Python have to provide the missing statements and other related queries based on the following code of Amritya Answer any four questions (out of five) from the below mentioned questions. import pickle def AddStudents(): ____________ #1 statement to open the binary file to write data while True: Rno = int(input("Rno :")) Name = input("Name : ") Percent = float(input("Percent :")) L = [Rno, Name, Percent] ____________ #2 statement to write the list Linto the file Choice = input("enter more (y/n): ") if Choice in "nN": break 5
  • 105. 105 F.close() def GetStudents(): Total=0 Countrec=0 Countabove75=0 with open("STUDENT.DAT","rb") as F: while True: try: ____________ #3 statement to readfrom the file Countrec+=1 Total+=R[2] if R[2] > 75: print(R[1], " has percent =",R[2]) Countabove75+=1 except: break if Countabove75==0: print("There is no student who has percentage more than 75") average=Total/Countrec print("average percent of class = ",average) AddStudents() GetStudents() I. Which of the following commands is used to open the file “STUDENT.DAT” for writing only in binary format? (marked as #1 in the Python code) a. F= open("STUDENT.DAT",'wb') b. F= open("STUDENT.DAT",'w') c. F= open("STUDENT.DAT",'wb+') d. F= open("STUDENT.DAT",'w+')
  • 106. 106 II. Which of the following commands is used to write the list L into the binary file, STUDENT.DAT? (marked as #2 in the Python code) a. pickle.write(L,f) b. pickle.write(f, L) c. pickle.dump(L,F) d. f=pickle.dump(L) III. Which of the following commands is used to read each record from the binary file STUDENT.DAT? (marked as #3 in the Python code) a. R = pickle.load(F) b. pickle.read(r,f) c. r= pickle.read(f) d. pickle.load(r,f) IV. Which of the following statement(s) are correct regarding the file access modes? a. ‘r+’ opens a file for both reading and writing. File object points to its beginning. b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists and creates a new one if it does not exist. c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates a new one if it does not exist. d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists V. Which of the following statements correctly explain the function of seek() method? a. tells the current position within the file. b. determines if you can move the file position or not. c. indicates that the next read or write occurs from that position in a file.
  • 107. 107 d. moves the current file position to a given specified position 2 Compare Text files, Binary Files and CSV files 5 ANSWERS I 1.file = open("student.dat", "rb+") 2.pickling is used for object serialization 3.a) ab b)pickle.dump(employee,outfile) 4. dump(t, myfile) 5. b 6.a 7.c 8.c 9.b 10 b 11. c II 12. There are two types of files: Text Files- A file whose contents can be viewed using a text editor is called atext file. A text file is simply a sequence of ASCII or Unicode characters.Python programs, contents written in text editors are some of the example oftext files. Binary Files-A binary file stores the data in the same way as as stored in thememory. The .exe files, mp3 file, image files, word documents are some of theexamples of binary files. We can’t read a binary file using a text editor 13. Pickling is the process of transforming data or an object in memory (RAM) to a stream of bytes called byte streams. These byte streams in a binary file can then be stored in a disk or in a database or sent through a network. Unpickling is the inverse of pickling process where a byte stream is converted back to Python object
  • 108. 108 14. A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length.Binary Files contain raw data so are not in human readable format. It can be read by using some special tool or program. Document files: .pdf, .doc, .xls etc. Image files: .png, .jpg, .gif, .bmp etc. Video files: .mp4, .3gp, .mkv, .avi etc. Audio files: .mp3, .wav, .mka, .aac etc. Database files: .mdb, .accde, .frm, .sqlite etc. Archive files: .zip, .rar, .iso, .7z etc. Executable files: .exe, .dll, .class etc 15. To delete a file, import the OS module, and run its os.remove() function. import os os.remove("demofile.txt") 16. def Readrecord(): with open ('StudentRecord1.dat','rb') as Myfile: print("n-------DISPALY STUDENTS DETAILS--------") print("nRoll No.",' ','Name','t',end='') print() while True: try: rec=pickle.load(Myfile) print(' ',rec['SROLL'],'t ' ,rec['SNAME']) except EOFError: break
  • 109. 109 III 1. I. a) II.c) III. a) IV. a) V.d) 2. Text Files Binary Files CSV Files 1 It is capable to handle textual data. It is capable to handle large file. It is very common format and platform independent. 2 It consists of series of lines of a set of letters, numbers or symbols (String) It consists of data with a specific pattern without any delimiter. It consists of plain text with a list of data with a delimiter. 3 Any text editors like notepad can be used to read them. No specific programs can be used to read them, python provides functions to read data. It can be read using text editors like notepads and spreadsheet software. 4 Every line ends with EOL. There is no specific EOL character. It terminates a line automatically when the delimiter is not used after data. CSV Files The CSV (Comma Separated Values) is a special text file format in which rows of data are present and the individual data elements are separated by commas. The CSV format is the most common import and export format for spreadsheets and databases. The csv files have the extension .csv Example for data contained in csv file Raghu,23,100
  • 110. 110 Tisha,45,230 Yatin,67,90 Advantages of csv files: • CSV is human readable and easy to edit manually. • CSV is simple to implement and parse. • CSV is processed by almost all existing applications. • CSV is smaller in size • CSV is considered to be standard format • CSV is compact. For XML you start tag and end tag for each column in each row. In CSV you write the column headers only once. • CSV can handle large unstructured data generated by social media effectively Examples of some valid formats of CSV files are: 1. Each record is located on a separate line, delimited by a line break (CRLF). For example: One,two,three CRLF four,five,six CRLF 2. The last record in the file may or may not have an ending line break. For example: One,two,three CRLF four,five,six 3. There maybe an optional header line appearing as the first line of the file with the same format as normal record lines. For example: Name,Rollno,Marks CRLF  Header line Raghu,1011,56 CRLF Swara,1012,78 CRLF 4. Each field may or may not be enclosed in double quotes. If fields are not enclosed with double quotes, then double quotes may not appear inside the fields. For example: "one","two","three" CRLF Eight,nine,ten [Note: 1. CR stands for the character 'Carriage Return' with Integer ASCII code - 13 and C++/Python notation r or 'r'. 2. LF stands for the character 'Line Feed' with Integer ASCII code - 10 and C++/Python notation n or 'n'.
  • 111. 111 3. In Windows platform the Enter Key / End of Line(EOL) / newline character is represented by the character combination CRLF i.e. 'rn' in python. 4. In Unix/Linux platforms the Enter Key /End of Line (EOL) / newline character is represented by the character LF only i.e. 'n' in python. 5. In Macintosh platforms the Enter Key / End of Line (EOL) / newline character is represented by the character CR only i.e. 'r' in python. 6. When opening a file for reading CSV file add the parameter, newline='EOL_character' to process the End of Line correctly. While opening a CSV file for reading on Windows platform, add the parameter, newline='rn' in the open() method to avoid adding an extra blank line while processing/displaying output on the screen ] In CSV files there can be delimiters other than comma(,) Tab separated values Raghu 23 100 Tisha 45 230 Yatin 67 90 Semicolon separated values Raghu ;23;100 Tisha;45;230 Yatin;67;90 Using CSV module to handle csv files What is csv module? The csv module implements classes to read and write tabular data in CSV format. The csv module handles the different types of delimiters and quoting characters in CSV files and efficiently manipulate such data, hiding the details of reading and writing the data from the programmer. The module has to be imported in python program to handle csv files. import csv as c or import csv READING FROM A CSV FILE-READER OBJECT Reading from a csv file is done using a reader object. The CSV file is opened as a text file with Python’s built-in open() function, which returns a file object. This creates a special type of object to access the CSV file (reader object), using the reader() function.
  • 112. 112 The reader object is an iterable that gives us access to each line of the CSV file as a list of fields. You can also use next() directly on it to read the next line of the CSV file, or you can treat it like a list in a for loop to read all the lines of the file (as lists of the file’s fields). Syntax: csv.reader(fileobject,delimiter=“ “)-> it returns a reader object PROGRAM TO READ AND DISPLAY CONTENTS OF CSV FILE #reading and displaying contents from a csv file import csv as c with open(‘12ACS.csv’,"r") as mycsv: csvreader=c.reader(mycsv,delimiter=",") for row in csvreader: print (row) CREATING A CSV FILE THROUGH A PYTHON PROGRAM FOR WRITING DATA To write to a CSV file in Python, we can use the csv.writer() function. The csv.writer() function returns a writer object that converts the user's data into a delimited string. This string can later be used to write into CSV files using the writerow() function. In order to write to a CSV file, we create a special type of object to write to the CSV file "writer object", which is defined in the CSV module, and which we create using the writer() function. The writerow() method allows us to write a list of fields to the file. The fields can be strings or numbers or both. Also, while using writerow(), you do not need to add a new line character (or other EOL indicator) to indicate the end of the line, writerow() does it for you as necessary. PROGRAM TO CREATE A CSV FILE AND WRITE DATA IN IT def createcsv(): f=open("cricket.csv","w",newline='') s=csv.writer(f,delimiter="-") s.writerow(["playername","runsscored","Matchsplayed"]) while True: c=eval(input("Enter the name ,runs, matches")) s.writerow(c) ch=input("Do you want to continue (Y/N)") if ch.upper()!="Y": break f.close() writerow() Vs writerows() writerow() is used to write a single row to a csv file.
  • 113. 113 writerows() is used to write multiple rows/lines to csv file To demonstrate writerow() and writerows() import csv f=open("one.csv","w",newline='') csvwriter=csv.writer(f,delimiter=',') csvwriter.writerow(['one','two','three']) l=[(23,45,67),(34,56,78),(45,67,78)] csvwriter.writerows(l) f.close() OUTPUT: one,two,three 23,45,67 34,56,78 45,67,78 WORKSHEET LEVEL – 1 I Questions (1 mark) 1 CSV files are opened with __________argument to supress EOL translation. 2 The _________ parameter of csv.reader() function is used to set a specific delimiter like a single quote or double quote or space or any other character. 3 When you read csv file using csv.reader() function it returns the values in _______ object. 4 If you want to change a default delimiter of csv file, you can specify ________ parameter. 5 Which of the following is not a function of csv module? a. readline() b. writerow() c. reader() d. writer() 6 Anshuman wants to separate the values by a $ sign. Suggest to him a pair of function and parameter to use it. A open,quotechar B writer,quotechar C open,delimiter D writer, delimiter 7 Which of the following is tasks cannot be done or difficult with CSV module? A Data in tabular form B Uniqueness of data C Saving data permanently D All of these 8 Observe the following code and fill the blank in statement1 import csv with _________ as f: #statement1 r = csv.______(f) #statement2 for row in ______: #statement3
  • 114. 114 print(_____) #statement4 a) open(“data.csv”) b) f=open(“data.csv”) c) Both A & B are Correct d) Both A & B are incorrect 9 A CSV file is also known as a …. A. Flat File B. 3D File C. String File D. Random File 10 The command used to skip a row in a CSV file is A. next() B. skip() C. omit() D. bounce() 11 Which of the following is a string used to terminate lines produced by writer()method of csv module? A. Line Terminator B. Enter key C. Form feed D. Data Terminator 12 Making some changes in the data of the existing file or adding more data is called A. Editing B. Appending C. Modification D. Alteration 13 Observe the following code and fill the blank in statement4 import csv with _________ as f: #statement1 r = csv.______(f) #statement2 for row in ______: #statement3 print(_____) #statement4 a) r b) row c) f d) csv 14 One row of CSV file can be considered as _______ in terms of database 15 What is the output of the following program? import csv d=csv.reader(open('c:PYPRGch13city.csv')) next(d) for row in d: print(row) if the file called “city.csv” contain the following details chennai,mylapore
  • 115. 115 mumbai,andheri A. chennai,mylapore B. mumbai,andheri C. Chennai, mumbai D. chennai,mylapore mumbai, andheri II Questions (2 marks) 1 What is the difference between writer object’s writerow() and writerows() function? 2 How will you sort more than one column from a csv file?Give an example statement. 3 What Is CSV File” 4 Syntax for opening Student.csv file in write mode is myfile = open("Student.csv","w",newline=''). What is the importance of newline=''? 5 What is the output of the following program if the student.csv file contains following data? Student.csv Ronit, 200 Akshaj, 400 import csv d = csv.reader(“student.csv”) next (d) for row in d: print (row) III Questions (3 marks) 1 Write a note on open() function of python. What is the difference between the two methods? 2 Write a Python program to modify an existing file 3 Write a Python program to read a CSV file with default delimiter comma (,). 4 What is the difference between reader() and DictReader() function? 5 Observe the following code and fill in the given blanks: import csv with _________ as f: #1 r = csv.______(f) #2 for row in ______: #3 print(_____) #4 IV Questions (5 marks) 1 Vijay Kumar of class 12 is writing a program to create a CSV file "user.csv" which will contain user name and password for some entries. He has written the following code. As a programmer, help him to successfully execute the given task. import ____________ # Line 1 # to write / add data into the CSV file def addRecord(user,password): file=open('users.csv','___',newline='') # Line 2 cwriter = csv.writer(file) cwriter.writerow([user,password]) file.close()
  • 116. 116 #csv file reading code def readRecord(): # to read data from CSV file f=open('users.csv','r') creader = csv._________(f) # Line 3 for row in creader: print (row[0],row[1]) __________ # Line 4 addRecord("Neil", "123@456") addRecord("Swati","sw@tee") addRecord("Farida","myname@FRD") readRecord() #Line 5 1a Name the module he should import in Line 1. 1b In which mode, Vijay should open the file to append data into the file. 1c Fill in the blank in Line 3 to read the data from a csv file. 1d Fill in the blank in Line 4 to close the file 1e Write the output he will obtain while executing Line 5. 2 What are the different file access modes? Explain 3 Puneeta is storing the data of her gift store in a csv file named gift.csv which will store Gift_code and Gift_name of items of her gift store. She has written the following code .As a programmer help her to successfully execute her program in python: import ___________ # Line 1 def writeFile(Gift_code,Gift_name): F=open(“gift.csv”,‟___‟) #Line 2 FW=csv.________(F) #Line 3 FW.writerow([Gift_code,Gift_name) F.close() #CSV file for reading def readFile(): with ________(„gift.csv‟,‟r‟) as newF #Line 4 FR=csv.reader(newF) for row in FR: if row[0]==101: print(row) writeFile(101,”Photoframe”) writeFile(102,”Soft Toys”) writeFile(103,”Flower Pot”) readFile() #Line 5 3a Name the module she should import in line 1. 3b In which mode Puneeta should open the file to add data in it? 3c Fill in the blanks in Line 3 to write data to csv file gift.csv 3d Fill in the blank in Line 4 to open the csv file from the disk 3e Which user defined function is used here for reading data? 4 Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he
  • 117. 117 has been assigned an incomplete python code (shown below) to create a CSV File 'Student.csv' (content shown below). Help him in completing the code which creates the desired CSV File. CSV File 1,AKSHAY,XII,A 2,ABHISHEK,XII,A 3,ARVIND,XII,A 4RAVI,XII,A 5,ASHISH,XII,A Incomplete Code import_____ #Statement-1 fh = open(_____, _____, newline='') #Statement-2 stuwriter = csv._____ #Statement-3 data = [] header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION'] 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 fh.close() I.Identify the suitable code for blank space in line marked as Statement-1. a) csv file b) CSV c) csv d) Csv II.Identify the missing code for blank space in line marked as Statement-2? a) "School.csv","w" b) "Student.csv","w" c) "Student.csv","r" d) "School.csv","r" III.Choose the function name (with argument) that should be used in the blankspace of line marked as Statement-3 a) reader(fh) b) reader(MyFile) c) writer(fh) d) writer(MyFile) IV.Identify the suitable code for blank space in line marked as Statement-4. a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION' b) ROLL_NO, NAME, CLASS, SECTION c) 'roll_no','name','Class','section' d) roll_no,name,Class,sectionc) co.connect()
  • 118. 118 V.Choose the function name that should be used in the blank space of line markedas Statement- 5 to create the desired CSV File? a) dump() b) load() c) writerows() d) writerow() LEVEL – 2 I Answer the following Marks 1 The expansion of CRLF is (A) Control Return and Line Feed (B) Carriage Return and Form Feed (C) Control Router and Line Feed (D) Carriage Return and Line Feed 1 ans (D) Carriage Return and Line Feed 2 Importing CSV files can be much faster, and it also consumes less memory while comparing with .xls files(True/False) 1 an True 3 A ________ parameter is used to quote all fields of csv files. ans Quoting 4 Read following statement about features of CSV file and select which statement is TRUE? Statement1: Only database can support import/export to CSV format Statement2: CSV file can be created and edited using any text editor Statement3: All the columns of CSV file can be separated by comma only a. Statement 1 and statement 2 b. Statement 2 and statement 3 c. Statement 2 d. Statement 3 ans c. Statement 2
  • 119. 119 5 Which of the following file types can be opened with notepad as well as ms excel? a. Text Files b. Binary Files c. CSV Files d. None of thes ans CSV Files 6 What is the output of the following program if the student.csv file contains following data? Student.csv Ronit, 200 Akshaj, 400 import csv d = csv.reader(“student.csv”) next (d) for row in d: print (row); 1 ans Akshaj, 400 II Answer the following Marks 1 Write a program to copy the data from “data.csv” to “temp.csv” 2 ans import csv f=open("data.csv","r") f1=open("temp.csv",'w') d=csv.reader(f) d1=csv.writer(f1) for i in d: d1.writerow(i) f.close( ) f1.close( )
  • 120. 120 2 When is a CSV file ? When do we use CSV? 2 A CSV (Comma Separated Values) file is a form of plain text document which uses a particular format to organize tabular information. CSV file format is a bounded text document that uses a comma to distinguish the values. Every row in the document is a data log. Each log is composed of one or more fields, divided by commas. It is the most popular file format for importing and exporting spreadsheets and databases. 3 Write a Python program to modify an existing file. ans import csv row = [‘3’, ‘Meena’,’Bangalore’] with open(‘student.csv’, r’) as readFile: reader = csv.reader(readFile) lines = list(reader) # list()- to store each row of data as a list lines [3] = row with open( student.csv’, ‘w’) as writeFile: # returns the writer object which converts the user data with delimiter writer = csv.writer(writeFile) #writerows()method writes multiple rows to a csv file writer.writerows(lines) III Answer the following Marks 1 a) Write a Python program to read each row from a given csv file and print a list of strings department_id,department_name,manager_id,location_id 10,Administration,200,1700 20,Marketing,201,1800 30,Purchasing,114,1700 40,Human Resources,203,2400 50,Shipping,121,1500 60,IT,103,1400 70,Public Relations,204,2700 80,Sales,145,2500 2+1
  • 121. 121 90,Executive,100,1700 b) What does tell() method do? Ans a b import csv with open('departments.csv', newline='') as csvfile: data = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in data: print(', '.join(row)) It tells you the current position of cursor within the file Syntax: file_object.tell() 2 What is difference between tell() and seek() methods? 3 ans tell() seek() It returns the current position of cursor in file. Change the cursor position by bytes as specified by the offset Example: fout=open(“story.txt”,”w”) fout.write(“Welcome Python”) print(fout.tell( )) fout.close( ) Example: fout=open(“story.txt”,”w”) fout.write(“Welcome Python”) fout.seek(5) print(fout.tell( )) fout.close( ) Output : 4 Output : 5 IV Answer the following Marks 1 Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv” which will contain user name and password for some entries. He has written the following code. As a programmer, help him to successfully execute the given task. import _____________ # Line 1 def addCsvFile(UserName,PassWord): # to write / add data into the CSV file f=open(' user.csv','________') # Line 2 5
  • 122. 122 newFileWriter = csv.writer(f) newFileWriter.writerow([UserName,PassWord]) f.close() #csv file reading code def readCsvFile(): # to read data from CSV file with open(' user.csv','r') as newFile: newFileReader = csv._________(newFile) # Line 3 for row in newFileReader: print (row[0],row[1]) newFile.______________ # Line 4 addCsvFile(“Arjun”,”123@456”) addCsvFile(“Arunima”,”aru@nima”) addCsvFile(“Frieda”,”myname@FRD”) readCsvFile() #Line 5 (a) Name the module he should import in Line 1. (b) In which mode, Ranjan should open the file to add data into the file (c) Fill in the blank in Line 3 to read the data from a csv file. (d) Fill in the blank in Line 4 to close the file. (e) Write the output he will obtain while executing Line 5. ans a) Line 1 : csv b) Line 2 : a c) Line 3 : reader d) Line 4 : close() e) . Line 5 : Arjun 123@456 Arunimaaru@nima Frieda myname@FRD 2 Ronit has a CSV file “marks.csv” which has name, class and marks separated by comma. He is writing a Python program to copy only the 5
  • 123. 123 name and class to another CSV file “class.csv”. He has written the following code. As a programmer, help him to successfully execute the given task. import csv file = open('class.csv', ---------a--------- , newline=""); writer = csv.writer(file) file.close() ----- b ----- open('marks.csv') as csvfile: data = csv. ----- c------- (csvfile) for row in data: writer.writerow([----d ------ ,-----e --------- ]) a. In which mode should Ronit open the file to make a new file? b. Which Python keyword should be used to manage the file stream? c. Fill in the blank in Line 3 to read the data from a csv file. d. Fill in the blank to write name into marks.csv e. Fill in the blank to write class into marks.csv. ans import csv file = open('class.csv', 'w', newline=""); writer = csv.writer(file) file.close() with open('marks.csv') as csvfile: data = csv.reader(csvfile) for row in data: writer.writerow([row[0],row[1]]) 3 Write the different methods to read a CSV File in Python. 5 ans There are two ways to read a CSV file. (i) Use the csv modules reader function (ii) Use the DictReader class.
  • 124. 124 CSV Module’s Reader Function: (i) We can read the contents of CSV file with the help of csv.reader() method. The reader function is designed to take each line of the file and make a list of all columns. (ii) Then, choose the column we want the variable data for. Using this method one can read data from csv files of different formats like quotes (""), pipe (|) and comma (,). The syntax for csv.readerf() is csv.reader(fileobject,delimiter,fmtparams) where (iii) file object : passes the path and the mode of the file (iv) delimiter:an optional parameter containing the standard dilects like , | etc can be omitted. (v) fmtparams : optional parameter which help to override the default values of the dialects like skipinitialspace,quoting etc. can be omitted. * CSV file - data with default delimiter comma (,) * CSV file - data with Space at the beginning * CSV file - data with quotes * CSV file - data with custom Delimiters CSV file with default delimiter comma (,): The following program read a file called “sample 1. csv” with default delimiter comma (,) and print row by row. Program:
  • 125. 125 #importing csv import csv #opening the csv file which is in different location with read mode with open('c:pyprgsamplel.csv', 'r') as F: #other way to open the file is f= ('c:pyprgsample1.csv', 'r') reader = csv.reader(F) # printing each line of the Data row by row print(row) F.close() Output: ['SNO', 'NAME', 'CITY'] ['12101', 'RAM', 'CHENNAI'] ['12102', 'LAVANYA', 'TIRUCHY'] ['12103', 'LAKSHMAN', 'MADURAI'] Reading CSV File Into A Dictionary: (i) To read a CSV file into a dictionary can be done by using DictReader class of csv module which works similar to the reader() class but creates an object which maps data to a dictionary. (ii) The keys are given by the fieldnames as parameter. DictReader works by reading the first line of the CSV and using each comma separated value in this line as a dictionary key. (iii) The columns in each subsequent row then behave like dictionary values and can be accessed with the appropriate key (i.e. fieldname).
  • 126. 126 (iv) If the first row of your CSV does not contain your column names, you can pass a fieldnames parameter into the DictReader s constructor to assign the dictionary keys manually. (v) The main difference between the csv. reader() and DictReader() is in simple terms csv.reader and csv.writer work with list/tuple, while csv.DictReader and csv. DictWriter work with dictionary, csv. DictReader and csv. DictWriter take additional argument fieldnames that are used as dictionary keys. (vi) For Example Reading “sample8.csv” file into a dictionary Program: import csv filename = c:pyprgsample8.csv’ input_file =csv.DictReader(open(filename,’r’)) for row in input_file: print(dict(row) ) #dict() to print data Output: {‘ItemName ‘: ‘Keyboard ‘, ‘Quantity’: ‘48’} {‘ItemName ‘: ‘Monitor’ ‘Quantity’: ‘52’} {‘ItemName ‘: ‘Mouse ‘, ‘Quantity’: ‘20’} In the above program, DictReader() is used to read “sample8.csv” file and map into a dictionary. Then, the function dict() is used to print the data in dictionary format without order. Remove the dict() function from the above program and use print(row).Check you are getting the following output OrderedDict([(‘ItemName ‘, ‘Keyboard ‘), (‘Quantity’, ‘48’)]) OrderedDict([(‘ItemName ‘, ‘Monitor’), (‘Quantity’, ‘52’)]) OrderedDict( [(‘ItemName ‘, ‘Mouse ‘), (‘Quantity’, ‘20’)])
  • 127. 127 4 Radha Shah is a programmer, who has recently been given a task to write a python code to perform the following CSV file operations with the help of two user defined functions/modules: a. CSVOpen() : to create a CSV file called BOOKS.CSV in append mode containing information of books – Title, Author and Price. b. CSVRead() : to display the records from the CSV file called BOOKS.CSV where the field title starts with 'R'. She has succeeded in writing partial code and has missed out certain statements, so she has left certain queries in comment lines. import csv def CSVOpen(): with open('books.csv','______',newline='') as csvf: #Statement-1 cw=______ #Statement-2 ______ #Statement-3 cw.writerow(['Rapunzel','Jack',300]) cw.writerow(['Barbie','Doll',900]) cw.writerow(['Johnny','Jane',280]) def CSVRead(): try: with open('books.csv','r') as csvf: cr=______ #Statement-4 for r in cr: if ______: #Statement-5 print(r) except: print('File Not Found')
  • 128. 128 CSVOpen() CSVRead() You as an expert of Python have to provide the missing statements and other related queries based on the following code of Radha. Answer any four questions (out of five) from the below mentioned questions. 4.1 ans Choose the appropriate mode in which the file is to be opened in append mode (Statement 1) a. w+ b. ab c. r+ d. a Correct Answer: d. a 4.2 ans Which statement will be used to create a csv writer object in Statement 2. a. csv.writer(csvf) b. csv.writer(csvf) c. csvf.writer() d. cs.writer(csvf) Correct Answer: b. csv.writer(csvf) 4.3 Choose the correct option for Statement 3 to write the names of the column headings in the CSV file, BOOKS.CSV. a. cw.writerow('Title','Author','Price') b. cw.writerow(['Title','Author','Price']) c. cw.writerows('Title','Author','Price') d. cw.writerows(['Title','Author','Price'])
  • 129. 129 ans Correct Answer: b. cw.writerow(['Title','Author','Price']) 4.4 ans Which statement will be used to read a csv file in Statement 4. a. cs.read(csvf) b. csv.reader(csvf) c. csvf.read() d. csvf.reader(cs) Correct Answer: b. csv.reader(csvf 4.5 ans Fill in the appropriate statement to check the field Title starting with ‘R’ for Statement 5 in the above program. a. r[0][0]=='R' b. r[1][0]=='R' c. r[0][1]=='R' d. d) r[1][1]=='R' Correct Answer: a. r[0][0]=='R' LEVEL – 3 I Answer the following Marks 1 Which of the following module is provided by Python to do several operations on the CSV files? (A) py (B) xls (C) csv (D) os 1
  • 130. 130 Ans (C) csv 2 To open a file c:scores.csv for reading, we use _______ command. a) infile = open(“c:scores.csv”, “r”) b) infile = open(“c:scores.csv”, “r”) c) infile = open(file = “c:scores.csv”, “r”) d) infile = open(file = “c:scores.csv”, “r”) 1 Ans infile = open(“c:scores.csv”, “r”) 3 To read the entire content of the CSV file as a nested list from a file object infile, we use __________ command. (a) infile.read() (b) infile.reader() (c) csv.reader(infile) (d) infile.readlines() 1 Ans c) csv.reader(infile) 4 The CSV files are popular because they are a) capable of storing large amount of data b) easier to create c) preferred export and import format for databases and spread sheets d) All the above 1 Ans d) All the above 5 .A _________ is a file format which stores records separated by comma. a)numpy b)tsv c)csv d)dat 1 Ans csv II Answer the following Marks 1 Deepesh works as a programmer with Delta Technologies. He has been assigned the job of generating the salary of all employees using the file “employee.csv”. He has written a program to read the CSV file “employee.csv” which will contain details of all the employees. He has 2
  • 131. 131 written the following code. As a programmer, help him to successfully execute the given task. import______ # Line 1 def readCsvEmp( ): # to read data from the CSV file with ______(’employees.csv’, newline=”) as f: # Line 2 reader = csv.______ (f) # Line 3 data_list = ______(reader) # Line 4 print (data_list) i) Name the module he should import in Line 1. ii)Write the method that he should use to open the file to read data from it. iii)Fill in the blank in Line 3 to read the data from a csv file iv)Fill in the blank in Line 4 with the method to convert the data read from the file into list. Ans i) ii) iii) iv) import csv open reader list III Answer the following Marks 1 What is CSV file? What are its characteristics? 3 Ans CSV (Comma Separated Values) is a file format for data storage which looks like a text file. It is used to store tabular data, such as a spreadsheet or database. The information is organized with one record on each line
  • 132. 132 Each field is separated by comma. You can choose a different delimiter character such as ‘ ‘:’ , ‘;’ , ‘|’. In CSV files space-characters adjacent to commas are ignored IV Answer the following Marks 1 What are the Advantages and disadvantages of CSV files? 5 Ans Advantages of CSV: •CSV is faster to handle •CSV is smaller in size and is easy to generate •CSV is human readable and easy to edit manually •CSV is simple to implement and parse •CSV is processed by almost all existing applications Disadvantages of CSV: •There is no standard way to represent binary data •There is no distinction between text and numeric values •There is poor support of special characters and control characters •CSV allows to move most basic data only. Complex configurations cannot be imported and exported this way •There are problems with importing CSV into SQL (no distinction between NULL and quotes) 2 What is the difference between writer object’s writerow() and writerows() function? Write a python code based on these function 5 writer.writerow(row): Write the row parameter to the writer’s file object, formatted according to delimiter defined in writer function e.g. import csv f1=open(‘one.csv’,’w’) w1=csv.writer(f1,delimiter = ‘,’)
  • 133. 133 w1.writerow([‘S.No’, ‘Name’, ‘Marks’]) f1.close() writerows(rows): Writes multiple rows (sequence) to the writer’s file object e.g. import csv f1=open(‘one.csv’,’w’) w1=csv.writer(f1,delimiter = ‘,’) w1.writerow([‘S.No’, ‘Name’, ‘Marks’]) w1.writerows([[1, ‘Ronit’, 84],[2,’Nihir’,90]]) f1.close() Data structures - Stacks ❖ IntroductiontoPythondatastructurestack ❖ ImplementationofstackusingList ❖ Pushfunction ❖ PopFunction ❖ Displayfunction ❖ Checkingstackunderflow Introduction toPython data structure-Stack A data structure is a way of store, organize, or manage data in efficient and productive manner. The python data structure stack is a linear data structure. It follows the principle of LIFO (Last In First Out). The representation of data is something like this:
  • 134. 134 By observing the above image you can understand the following: 1. The data can be inserted or deleted from the top only 2. Elements can be inserted or deleted any time 3. The insert operation is known as push 4. The delete operation is known as pop 5. When the top element is inspected, it is known as a peek or inspection 6. When we have a fixed-length list and we are trying to push an element in a list, it raises one error that is known as overflow 7. When the list is empty and we are trying to pop an element, it will raise an error that is known as underflow Push function A function to push an element. To push the element append() method is used as well as the position of the top should be changed. Observe the following code: def push(stk,e): stk.append(e) Pop Function The pop function requires validation to check whether the stack is underflow or not if it is not then use the logic to delete the element from the top. Have a look at this code: def pop_stack(stk): if stk==[]: return "UnderFlow" else: e = stk.pop() return e Display function Write a function to check the element is inserted or not, observe this code: def display(stk): if stk==[]: print("Stack Underflow")
  • 135. 135 else: for i in (stk[::-1]): print(i) Applications of the stack: • Infix to Postfix /Prefix conversion • Redo-undo features at many places like editors, photoshop. • Forward and backward features in web browsers • Used in many algorithms like Tower of Hanoi, tree traversals, stock span problems, and histogram problems. • String reversal is also another application of stack. Here one by one each character gets inserted into the stack. So the first character of the string is on the bottom of the stack and the last element of a string is on the top of the stack. After performing the pop operations on the stack we get a string in reverse order. Mind Map BOARD PATTERN QUESTIONS Considering the dictionary storing the price of vegetables, veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60} a) Write python function to build a stack costly by pushing the names of vegetables whose price is > 40 from dictionary veg. b) Pop and display the items in stack costly Note:Write only 2 functions pushcostly(veg,costly) and popcostly(costly).Write appropriate statements in the main part to call the functions. def pushcostly(p,s): for i in p: if p[i]>40: s.append(i) def popcostly(s): if s==[]: print("Stack underflow") else:
  • 136. 136 print("costly vegetables") while(s): print(s.pop()) return veg={‘potato’:30,’beans’:40,’carrot’:40,’cabbage’:20,’brinjal’:10,’tomato’:50,’drumstick’:60} costly= [] while True: print ('''Menu 1.push 2.pop and display 3.exit''') ch=int (input ("enter your choice")) if ch==1: pushprod(veg,costly) elifch==2: popdisplay(costly) else: break WORKSHEET LEVEL – 1 Answer the following questions(1 marks) 1. A stack is one of the following types of data structure? a) Linear b) Dynamic c) Circular d) All of these 2. A condition raise due to the stack is full is known as ___________. a) Underflow b) Overflow c) List is full d) Completely Filled 3. While popping the element from the stack, a condition will be raised, this condition is known as ____________. a) Underflow b) Overflow c) List is Empty d) Blank List 4. Which of the following is not a compound data structure? a) Stack b) Queue c) Array d) Tree 5. Inspecting the value at the stack’s top without removing it. a) peak operation b) insert operation c) pop operation d) push operation 6. Which of the following statement is incorrect for stack?
  • 137. 137 a) Peek <stack>[top] b) Push <stack>.append(<item>) c) Pop <stack>.pop() d) Plus <stack>plus() Answer the following questions (2 marks) 1. What are the underflow and overflow conditions? Answer the following questions (3 marks) 1. Write a python function to delete an element from the stack. 2. Write a function to inspect an element from the stack. 3. Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a player by considering them as push and pop operations in a stack. Answer the following questions (5 marks) 1. Vedika has created a dictionary containing names and marks as key-value pairs of 5 students. Write a program, with separate user-defined functions to perform the following operations: • Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is greater than 70. • Pop and display the content of the stack. The dictionary should be as follows: d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95} Then the output will be: Umesh Vishal Ishika LEVEL 1 ANSWERS Answer the following questions(1 marks) 1 a) Linear 2 b) Overflow 3 a) Underflow 4 c) Array 5 a) peak operation 6 d) Plus <stack>plus() Answer the following questions(2 marks)
  • 138. 138 1 Underflow is the condition which occurs when stack is empty while trying to delete elements. Overflow is the condition which occurs while inserting an element when memory is exhausted. Answer the following questions(3 marks) 1 def pop_stack(stk): if stk==[]: return "UnderFlow" else: e = stk.pop() if len(stk)==0: top = None else: top = len(stk)-1 return e 2 def peek(stk): if stk==[]: return "UnderFlow" else: top = len(stk)-1 return stk[top] 3 def AddPlayer(player): pn=input("enter player name:") player.append(pn) def DeletePlayer(player): if player==[]: print("No player found") else: return player.pop()
  • 139. 139 Answer the following questions(5 marks) 1 def push(stk,item): stk.append(item) def Pop(stk): if stk==[]: return None else: return stk.pop() stk=[] d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95} for i in d: if d[i]>70: push(stk,i) while True: if stk!=[]: print(Pop(stk),end=" ") else: break LEVEL – 2 Answer the following questions(1 marks) 1. Stack data structure is following ____________ principle. 2. The peek operation refers to accessing/inspecting the top element in the stack. (True/False) 3. Stack overflow condition is raised in ____________ operation where as Stack underflow condition is raised in _____________ operations. 4. Stack is a ___________ data structure. a) Static b) Dynamic c) Double
  • 140. 140 d) Single 5. While implementing Stack using list when we want to delete element we must use pop function as__________ a) list.pop(pos) b) list.pop(0) c) list.pop() d) list.push() 6. If the elements “A”, “B”, “C” and “D” are placed in a stack and are deleted one at a time, in what order will they be removed? a) ABCD b) DCBA c) DCAB d) ABDC Answer the following questions (2 marks) 1. What do you mean by data structure? Explain your answer with a suitable example. 2. Write a python function named is_underflow() to check a stack is an underflow. 3. Write a function to push an element into the stack. Answer the following questions (3 marks) 1. Write a function to display the stack elements. LEVEL 2 ANSWERS I Answer the following questions (1 marks) 1 LIFO 2 True 3 Push , Pop 4 b) Dynamic 5 c) list.pop() 6 b) DCBA II Answer the following questions (2 marks) 1 The systematic way of organization, storing, accessing and retrieving data including well-defined operations, behaviour and properties is known as data structure. Examples: String – Contains sequence of characters List – Contains sequence of different data types 2 def is_underflow(stk): if stk==[]: return True
  • 141. 141 else: return False 3 def push(stk,e): stk.append(e) top = len(stk)-1 III Answer the following questions (3 marks) 1 def display(stk): if stk==[]: print("Stack is Empty") else: top = len(stk)-1 print(stk[top],"-Top") for i in range(top-1,-1,-1): print(stk[i]) LEVEL – 3 Answer the following questions (1 marks) 1. The insert operation in the stack is known as pop. (True/False). 2. You can replace any element position in the stack. (True/False) 3. If the name of linear list of 10 elements is LIL, then its element will be referenced a) LIL[0],LIL[1],LIL[2]………LIL[9] b) LIL[0],LIL[1],LIL[2]………LIL[10] c) LIL(0),LIL(1),LIL(2)………LIL(9) d) LIL(0),LIL(1),LIL(2)………LIL(10) 4. LIFO Full form – a) logical in first out b) First in first out c) last in first out d) last in logical out 5. Which of the following statement(s) about stack data structure is/are NOT correct? a) Stack data structure can be implemented using linked list b) New node can only be added at the top of the stack c) Stack is the FIFO data structure d) The last node at the bottom of the stack has a NULL link
  • 142. 142 Answer the following questions(2 marks) 1. Define stack. 2. Expand the following: a) LIFO b) FIFO 3. What do you mean by the LIFO structure? Support your answer with real-life examples. LEVEL 3 ANSWERS Answer the following questions(1 marks) 1 False 2 False 3 4 a)LIL[0],LIL[1],LIL[2]………LIL[9] c) last in first out 5 a)Stack is the FIFO data structure II Answer the following questions(2 marks) 1 A stack is a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack. 2 2 LIFO: Last-In First-Out FIFO: First-In First-Out 1+1 3 LIFO is one of the principle to access data from a data structure. It stands for Last In First Out. It refers to the item which is inserted last will be access first. So the top element will be accessed first. Example: 1. Books in the shelf 2. Stack of coins 3. Pile of chairs 4. Bangles on woman’s wrist
  • 143. 143 UNIT – 2 COMPUTER NETWORKS 1. Computer Network A computer network is an interconnection among two or more computers or computing devices. 2. Who invented WWW? - Sir Tim Berners-Lee — a British computer scientist invented the revolutionary World Wide Web in 1990. 3. ARPANET i. Stands for Advanced Research Projects Agency Network. ii. Started in 1960s by the U.S. Department of Defence to connect the academic and research institutions located at different places for scientific collaborations. iii. Gradually, more and more organisations joined the ARPANET, and many independent smaller networks were formed which eventually gave birth to the today’s INTERNET. 4. TYPES OF NETWORKS i. PAN (Personal Area Network) ii. LAN (Local Area Network) iii. MAN (Metropolitan Area Network) iv. WAN (Wide Area Network) 5. PAN i. It is formed by connecting personal devices like computers, laptops, mobile phones, smart phones, printers etc. ii. The devices should be within an approximate range of 10 metres. A personal area network may be wired or wireless. 6. LAN i. A network that connects computers, mobile phones, tablet, mouse, printer, etc., placed at a limited distance, viz, a LAN can range from a single room, a floor, an office having one or more buildings in the same premise, laboratory, a school, college, or university campus. ii. LAN may be extended up to 1 km. Data transfer in LAN is quite high, and usually varies from 10 Mbps (called Ethernet) to 1000 Mbps (called Gigabit Ethernet), where Mbps stands for Megabits per second 7. MAN i. It is extended form of LAN which covers a larger geographical area like a city or a town. ii. Data transfer rate in MAN also ranges in Mbps but it is less as compared to LAN. iii. Cable TV network or cable based broadband internet services are examples of MAN. iv. It can be extended up to 30-40 km.
  • 144. 144 8. Modem- It stands for ‘MOdulatorDEModulator’, is a device used for conversion between electric signals and digital bits. 9. Ethernet card- It is also known as Network Interface Card (NIC card in short), and it is a network adaptor used to set up a wired network. 10. MAC address - It helps in uniquely identifying a computer on a network. - The MAC address is also known as the physical or hardware address. -It is a unique permanent value associated with a network adapter called a NIC. -It is used to physically identify a machine on the network. 11. Repeater- It is a device that regenerate or amplifies the signals on a network. 12. Switch- It is a networking device used to connect multiple computers or communicating devices. 13. Router- It is a network device that can receive the data, analyse it and transmit it to other networks. 14. Gateway- It serves as the entry and exit point of a network, as all data coming in or going out of a network must first pass through the gateway in order to use routing paths. In other words, A Gateway is a network point that acts as an entrance to another network using different protocols. 15. Topology- The arrangement of computers and other peripherals in a network is called its topology. The Common network topologies are Mesh, Ring, Bus, Star and Tree. - In mesh topology each communicating device is connected with every other device in the network. - In ring topology, each node is connected to two other devices, one each on either side. - In bus topology, a single backbone wire called bus is shared among the nodes, which makes it cheaper and easy to maintain. - In star topology, each communicating device is connected to a central networking device like a hub or a switch. - In tree or hybrid topology, there are multiple branches and each branch can have one or more basic topologies like star, ring and bus. 16. IP address- It is also known as Internet Protocol address, and it is a unique address that can be used to uniquely identify each node in a network. Unlike MAC address, IP address can change if a node is removed from one network and connected to another network. 17. Protocol-A network protocol is an established set of rules that determine how data is transmitted between different devices in the same network. It allows connected devices to communicate with each other, regardless of any differences in
  • 145. 145 their internal processes, structure or design. 18. HTML- HTML (HyperText Markup Language) is a language which is used to design standardised Web Pages so that the Web contents can be read NOTES 2022-23 COMPUTER NETWORKS 201 and understood from any computer. 19. URI/URL- URI (Uniform Resource Identifier) or URL (Uniform Resource Locator) is a unique address or path for each resource located on the web. 20. HTTP – The HyperText Transfer Protocol is a set of rules which is used to retrieve linked web pages across the web. The more secure and advanced version is HTTPS. 21. Domain name - Each computer server hosting a website or web resource is given a name against its IP address. These names are called the Domain names or hostnames. 22. Domain name resolution-Conversion of the domain name of each web server to its corresponding IP address is called domain name resolution. It is done through a server called DNS server. 23. Switching- It is the technique by which nodes control or switch data to transmit it between specific points on a network. There are 3 common switching techniques: Circuit Switching. Packet Switching. 24. Circuit switching- In this technique, first a physical path is obtained and dedicated to a single connection between two endpoints in the network for the duration of a dedicated connection, and thereafter communication takes place. Ordinary voice phone service uses circuit switching. Traditional telephone systems (landlines) are examples of a technology that uses circuit switching. 25. Message switching- In this technique, end-users communicate by sending and receiving messages wherein, the sender and receiver are not directly connected. There are a number of intermediate nodes that transfer data and ensure that the message reaches its destination. It works on store and forward technique. Mobile sms is an example for it.
  • 146. 146 26. Packet switching- In this transfer of small pieces of data across various networks takes place. These data chunks or “packets” allow for faster, more efficient data transfer. Examples: Frame Relay, IP, and X. 25 27. Difference between Packet and message switching techniques Message Switching Packet Switching A complete message is passed across a network. Message is broken into smaller units known as Packets. In this, computer language used is ASCII Here, binary type is used. In message switching there is no limit on block size. Packet switching places a tight upper limit on block size.
  • 147. 147 Message exist only in one location in the network. Parts i.e. packets of the message exist in many places in the network. Physical links are allocated dynamically. Virtual links are made simultaneously. Access time is reduced due to increase in performance as packets are stored in disk. Packets are stored in main memory. 28. Hacker- A computer enthusiast, who uses his computer programming skill to intentionally access a computer without authorization is known as hacker. A hacker accesses the computer without the intention of destroying data or maliciously harming the computer. 29. Transmission media-Transmission media is a communication channel that carries the information from the sender to the receiver. 30. Types of Transmission Media In data communication terminology, a transmission medium is a physical path between the transmitter and the receiver i.e. it is the channel through which data is sent from one place to another. Transmission Media is broadly classified into the following types: a-Guided Media: It is also referred to as Wired or Bounded transmission media. Signals being transmitted are directed and confined in a narrow pathway by using physical links. Features: • High Speed • Secure • Used for comparatively shorter distances b- Unguided media – By means of waves. Examples: Infrared, Radiowave, Microwave and Satellite. There are 3 major types of Guided Media: (i) Twisted Pair Cable – It consists of 2 separately insulated conductor wires wound about each other. Generally, several such pairs are bundled together in a protective sheath. They are the most widely used Transmission Media. Twisted Pair is of two types: • Unshielded Twisted Pair (UTP): UTP consists of two insulated copper wires twisted around one another. This type of cable has the ability to block interference and does not depend on a physical shield for this purpose. It is used for telephonic applications.
  • 148. 148 Advantages: ⇢ Least expensive ⇢ Easy to install ⇢ High-speed capacity ⇢ Susceptible to external interference ⇢ Lower capacity and performance in comparison to STP ⇢ Short distance transmission due to attenuation • Shielded Twisted Pair (STP): This type of cable consists of a special jacket (a copper braid covering or a foil shield) to block external interference. It is used in fast-data-rate Ethernet and in voice and data channels of telephone lines. Advantages: ⇢ Better performance at a higher data rate in comparison to UTP ⇢ Eliminates crosstalk ⇢ Comparatively faster ⇢ Comparatively difficult to install and manufacture ⇢ More expensive and Bulky (ii) Coaxial Cable It has an outer plastic covering containing an insulation layer made of PVC or Teflon and 2 parallel conductors each having a separate insulated protection cover. The coaxial cable transmits information in two modes: Baseband mode(dedicated cable bandwidth) and Broadband mode(cable bandwidth is split into separate ranges). Cable TVs and analog television networks widely use Coaxial cables.
  • 149. 149 Advantages: • High Bandwidth • Better noise Immunity • Easy to install and expand • Inexpensive Disadvantages: • Single cable failure can disrupt the entire network (iii) Optical Fiber Cable – It uses the concept of refraction of light through a core made up of glass or plastic. The core is surrounded by a less dense glass or plastic covering called the cladding. It is used for the transmission of large volumes of data. The cable can be unidirectional or bidirectional. The WDM (Wavelength Division Multiplexer) supports two modes, namely unidirectional and bidirectional mode. Advantages: • Increased capacity and bandwidth • Lightweight • Less signal attenuation • Immunity to electromagnetic interference • Resistance to corrosive materials Disadvantages: • Difficult to install and maintain • High cost • Fragile Worksheet – Solved questions Question1: Identify the Domain name and URL from the following:
  • 150. 150 http://www.income.in/home.aboutus.hml Answer: Domain name – income.in URL – http://www.income.in/home.aboutus.hml Question 2: Write two characteristics of Wi-Fi. Answer:It is wireless network.It is for short range. Question 3: What is cloud computing? Answer: The sharing of compute resources (dedicated, time-shared, or dynamically shared servers) and related infrastructure components (load balancers, firewalls, network storage, developer tools, monitors and management tools) to facilitate the deployment and operation of web and network based applications. Cloud computing relies on sharing of resources to achieve coherence and economies of scale, similar to a utility (like the electricity grid) over a net-work. Question 4: Explain the purpose of a router. Answer: A router established connection between two networks and it can handle network with different protocols. Using a routing table, routers make sure that the data packets are travelling through the best possible paths Question 5: What are repeaters? Answer: A repeater is an electronic device that receives a signal and retransmits it at a higher level and/ or higher power, or onto the other side of an obstruction, so that the signal can cover longer distances. Question 6: What is VoIP? Answer: Voice over Internet Protocol (VoIP) is one of a family of internet technologies, communication protocols, and transmission technologies for delivery of voice communications and multi-media sessions over internet protocol (IP) network, such as the internet.
  • 151. 151 Question 7: Identify the type of topology from the following: 1. Each node is connected with the help of a single cable 2. Each node is connected with the help of independent cable with central switching. Answer: 1. Bus topology 2. Star topology Question 8: Mahesh wants to transfer data within a city at very high speed. Write the wired transmission medium and type of network. Answer: Wired transmission medium – Optical fibre cable Type of network – MAN. Question 9: Indian School, in Mumbai is starting up the network between its different wings. There are four Buildings named as SENIOR, JUNIOR, ADMIN and HOSTEL as shown below: The distance between various buildings is as follows:
  • 152. 152 Number of Computers in Each Building : 1. Suggest the cable layout of connections between the buildings. 2. Suggest the most suitable place (i.e., building) to house the server of this school, provide a suitable reason. 3. Suggest the placement of the following devices with justification. o Repeater o Hub/Switch 4. The organisation also has inquiry office in another city about 50-60 km away in hilly region. Suggest the suitable transmission media to interconnect to school and inquiry office out of the following : o Fiber optic cable o Microwave o Radiowave Answers: 1. 2. Server can be placed in the ADMIN building as it has the maxium number of computer. 3. Repeater can be placed between ADMIN and SENIOR building as the distance is more than 110 m. 4. Radiowaves can be used in hilly regions as they can travel through obstacles. Question 10: Write any two differences between twisted pair and co-axial pair cable. Answer:
  • 153. 153 Question 11: The following is a 32 bit binary number usually represented as 4 decimal values, each representing 8 bits, in the range 0 to 255 (known as octets) separated by decimal points. 140.179.220.200. What is it? What is its importance? Answer: It is an IP Address. It is used to identify the computers on a network. Question 12: What is the difference between domain name and IP address? Answer: Domain Name is alphanumeric address of a resource over network and IP address is a Numeric Address of a resource in a Network. Example: Domain Name- google.com and wikipedia.org IP Address- 102.112.0.153 UNSOLVED QUESTIONS Question 1: In mid 80’s another federal agency, the NSF created a new high capacity network called NSFnet, which was more capable than ARPANET. The only drawback of NSFnet was that it allowed only academic research on its network and not any kind of private business on it. Now, several private organisations and people started working to build their own networks, named private networks, which were later (in 1990’s) connected with ARPANET and NSFnet to form the Internet. The Internet really became popular in 1990’s after the development of World Wide Web.
  • 154. 154 (i). NSFnet stand for _______________________ (ii). ARPANET stand for _______________ (iii).An interconnection of different networks is called ____________ (iv).To join the internet, the computer has to be connected to a _________ (v). Internet access by transmitting digital data over the wires of a local telephone network is provided by ____________ (vi).A piece of icon or image on a webpage associated with another webpage is called Question2: TCP/IP, or the Transmission Control Protocol/Internet Protocol, is a suite of communication protocols used to interconnect network devices on the internet. TCP/IP can also be used as a communications protocol in a private computer network (an intranet or an extranet). TCP defines how applications can create channels of communication across a network.It also manages how a message is assembled into smaller packets before they are then transmitted over the internet and reassembled in the right order at the destination address. IP defines how to address and route each packet to make sure it reaches the right destination. Each gateway computer on the network checks this IP address to determine where to forward the message. TCP/IP uses the client-server model of communication in which a user or machine (a client) is provided a service (like sending a webpage) by another computer (a server) in the network. Collectively, the TCP/IP suite of protocols is classified as stateless, which means each client request is considered new because it is unrelated to previous requests. Being stateless frees up network paths so they can be used continuously. (i). Which of the following protocols is used in the internet? a. HTTP b. DHCP c. DNS d.All of these (ii). Which protocol assigns IP address to the client connected to the internet? a.DHCP b. IP c.RPC d. RSVP (iii).Several protocols for upper layers in Bluetooth use: a.UDP b.HSP c.ITC d. L2CAP (iv).Internet protocols are a set of rules to govern: a.communication between computers on a network b.bandwidth c.standard communication d.metropolitan communication
  • 155. 155 (v). Network layer at source is responsible for creating a packet from data coming from another a.station b. link c. node d. protocol Question3: Web server is a special computer system running on HTTP through webpages. The web page is a medium to carry data from one computer system to another. The working of the web server starts from the client or user. The client sends their request through the web browser to the web server. Web server takes this request, processes it and then sends back processed data to the client. The server gathers all of our web page information and sends it to the user, which we see on our computer system in the form of a web page. When the client sends a request for processing to the web server, a domain name and IP address are important to the web server. The domain name and IP address are used to identify the user on a large network. (i). Web servers are: a.IP addresses b.Computer systems c.Webpages of a site d.A medium to carry data from one computer to another (ii).What does the webserver need to send back information to the user? a.Home address b.Domain name c.IP address d.Both b and c (iii). What is the fullform of HTTP? a.Hypertext Transfer Protocol b.Hypertext Transfer Procedure c.Hyperlink Transfer Protocol d.Hyperlink Transfer Procedure (iv).The __________translates internet domain and hostnames to IP address a.Domain name system b.Routing information protocol c. Google d.Network time protocol (v).Computer that requests the resources or data from other computer is called as computer a.Server b.Client c.None of the above d. Options a&b (vi). DNS stands for: a. Domain Name Security b.Domain Number System c.Document Name System d.Domain Name System
  • 156. 156 (vii). What is the format of IP address? a.34bit b.32 bit c.16bit d.64 bit Question4: GyanDeep International School is planning to connect all computers, each spread over a distance within 40 m. Suggest an economical cable type having high-speed data transfer, which can be used to connect these computers Question5: Mr. Taufiq Ahmad wants to prevent unauthorised access to/from his company’s local area network. Write the name of system (software/hardware), which he should install. Question6: Beauty Lines Fashion Inc. is a fashion company with design unit and market unit 135 m away from each other. The company recently connected their LANs using Ethernet cable to share the stock related information. But after joining their LANs, they are not able to share the information due to loss of signal in between. Which device out of the following should you suggest to be installed for a smooth communication? UPS/Modem /Repeater Question7: Refer to the following diagram and answer the questions given below. (i). Which of the following devices acts as a server? a.A b.B c.C d.D (ii). The arrow from device D to pointing to A represents? a. HTTP request b.HTTP response
  • 157. 157 c.HTTP request & response d.All of these (iii).Which of the following device(s) can have IP Addresses? a.A b.D c.F d.All the devices (iv).Identify the network topology of the above network: a.Ring b. Star c.Bus d.None of these (v). ____is a protocol to transmit files (data) over the world wide web. a.FTP b.HTTP c. SMP d.None of the above Question 8: Trine Tech Corporation (TTC) is a professional consultancy company. The company is planning to set up their new offices in India with its hub at Hyderabad. As a network adviser, you have to understand their requirement and suggest them the best available solutions. Their queries are mentioned as (i) to (iv) below. Physical Locations of the blocked of TTC
  • 158. 158 1. What will be the most appropriate block, where TTC should plan to install their server? 2. Draw a block to cable layout to connect all the buildings in the most appropriate manner for efficient communication. 3. What will be the best possible connectivity out of the following, you will suggest to connect the new setup of offices in Bangalore with its London based office: o Satellite Link o Infrared o Ethernet Cable 4. Which of the following device will be suggested by you to connect each computer in each of the buildings: o Switch o Modem o Gateway Question 9: Identify the following devices: (i) Devices that are used to connect different types of networks. It performs the necessary translation so that the connected networks can communicate properly. (ii) A device that converts data from digital bit stream into an analog signal and vice-versa. Question 10: Rovenza Communications International (RCI) is an online corporate training provider company for IT related courses. The company is setting up their new campus in Kolkata. You as a network expert have to study the physical locations of various blocks and the number of computers to be installed. In the planning phase, provide the best possible answers for the queries (i) to (iv) raised by them.
  • 159. 159 Block to Block Distances(in Mtrs.) Expected computers to be installed in each block 1. Suggest the most appropriate block, where RCI should plan to install the server. 2. Suggest the most appropriate block to block cable layout to connect all three blocks for efficient communication. 3. Which type of network out of the following is formed by connecting the computers of these three blocks? o LAN o MAN o WAN 4. Which wireless channel out of the following should be opted by RCI to connect to students from all over the world? o Infrared o Microwave o Satellite
  • 160. 160 UNIT – 3 DATABASE MANAGEMENT MYSQL It is freely available open source Relational Database Management System (RDBMS) that uses Structured Query Language(SQL). In MySQL database, information is stored in Tables. A single MySQL database can contain many tables at once and store thousands of individual records. SQL (Structured Query Language) SQL is a language that enables you to create and operate on relational databases, which are sets of related information stored in tables. ADVANTAGES OF USING DBMS ➢ Reducing data redundancy – This ensures a consistent database and efficient use of storage space. ➢ Aiding multiple views of the data: Database management system enables different users to have a view of the data from their own perspective ➢ Implementation of data integrity The term data integrity refers to the accuracy and consistency of data. When creating databases, attention needs to be given to data integrity and how to maintain it. ➢ Data sharing and security – DBMS limits the accessibility of the data to the authorized users only. This makes data sharing safer. Moreover shared data makes it possible to fulfill data requirements with minimal modifications. ➢ Centralized data ensures a more effective backup and recovery process than the conventional file processing systems. ➢ Program & Data independence: Programs and the data are not mutually dependent. If a programmer wants to change the structure of the database then he/she can do so without affecting the application programs that are using the database. ➢ Data Abstraction: It ensures that the users get an abstract view of the data without showing implementation details and the physical storage of thedata. RELATIONAL MODEL TERMINOLOGY 1. Relation: A table storing logically related data is called a Relation.
  • 161. 161 2. Tuple: A row of a relation is generally referred to as a tuple. 3. Attribute: A column of a relation is generally referred to as an attribute. 4. Degree: This refers to the number of attributes in a relation. 5. Cardinality: This refers to the number of tuples in a relation. 6. Primary Key: This refers to a set of one or more attributes that can uniquely identify tuples within the relation. 7. Candidate Key : All attribute combinations inside a relation that can serve as primary key are candidate keys as these are candidates for primary key position. 8. Alternate Key: A candidate key that is not primary key, is called an alternate key. 9. Foreign Key : A non-key attribute, whose values are derived from the primary key of some other table, is known as foreign key in its current table. REFERENTIAL INTEGRITY A referential integrity is a system of rules that a DBMS uses to ensure that relationships between records in related tables are valid, and that users don’t accidentally delete or change related data. This integrity is ensured by foreign key. CLASSIFICATION OF SQL STATEMENTS SQL commands can be mainly divided into following categories: DATA TYPES Data types are means to identify the type of data and associated operations for handling it. MySQL data types are divided into three categories: ➢ Numeric ➢ Date and time ➢ String types Numeric Datatype 1. int– used for number without decimal.
  • 162. 162 2. decimal(m,d) – used for floating/real numbers. m denotes the total length of number and d is number of decimal digits. Date and Time Datatype 1. date–used to store date in YYYY-MM-DD format. 2. time–used to store time in HH:MM:SS format. String Datatype 1. char(m)–used to store a fixed length string, m denotes max. number of characters. 2. varchar(m)–used to store a variable length string, m denotes max. no. of characters. DATABASE COMMANDS 1. VIEW EXISTING DATABASE To view existing database names, the command is: SHOW DATABASES; 2. CREATING DATABASE IN MYSQL For creating the database in MySQL, we write the following command: CREATE DATABASE <databasename>; e.g.In order to create a database Student, command is: CREATE DATABASE Student; 3. ACCESSING A DATABASE For accessing already existing database,we write: USE<databasename>; e.g.to access a database named Student, we write command as: USE Student; 4. DELETING DATABASE For deleting any existing database,the command is: DROP DATABASE <databasename>; e.g.to delete a database, say student, we write command as: DROP DATABASE Student; 5. VIEWING TABLE IN DATABASE In order to view tables present in currently accessed database, command is: SHOW TABLES; CREATING TABLES IN MYSQL Syntax of CREATE TABLE command is: CREATE TABLE <table-name>(<colname> datatype,<colname> datatype,…); E.g. Inorder to create table EMPLOYEE given below: ECODE ENAME GENDER GRADE GROSS Create table employee (ecode integer, ename varchar(20),gender char(1),grade char(2),gross integer); Inserting Data into Table: Syntax: Insert into <tablename> values(<v1>,<v2>,…); Or Insert into <tablename>(<column list> )values(<values list>);
  • 163. 163 Eg: insert into employee values(1001,‘Ravi’,‘M’,‘E4’,50000); Or Insert into employee(ecode,ename)values(1002,’Meena’); The left out columns will be filled with null values. Select Command: It helps to display the records as per our requirement. Different forms of select command: 1. Select * from employee; It displays all rows and columns from the table. 2.Select ecode, ename from employee; It displays selected columns from the table. 3.For displaying particular rows. Syntax: select * from <tablename> where <cond>; Eg. Select * from employee where gender=’M’; 4. ELIMINATING REDUNDANT DATA The distinct keyword is used to eliminate duplicate records from the table. Eg. Select distinct (gender) from employee; DISTINCT(GENDER) M F 5. USING COLUMN ALIASES The columns that we select in a query can be given a different name, i.e.column alias name for output purpose. Syntax: SELECT <columnname>AS column alias ,<columnname>AS column alias …..FROM<tablename>; Eg.select ecode as “EMP_Code” from employee; CONDITION BASED ON A RANGE The BETWEEN operator defines a range of values that the column values must fall into make the condition true. The range include both lower value and upper value. e.g.To display ECODE,ENAME and GRADE of those employees whose salary is between 40000 and 50000,command is: SELECT ECODE , ENAME ,GRADE FROM EMPLOYEE WHERE GROSS BETWEEN 40000 AND 50000;
  • 164. 164 NOTE: For displaying records not in the specified range, we have to use not between operator. CONDITION BASED ON A LIST The in operator is used to display records based on a list of values. Eg. To display details of employees who have scored A,B and C grades. Select * from employee where grade in(‘A’,’B’,’C’); Note: For displaying records that do not match in the list, we have to use not in operator. CONDITION BASED ON PATTERN MATCHES LIKE operator is used for pattern matching in SQL. Patterns are described using two special wildcard characters: % and _ (underscore) 1. percent(%)– The % character matches any substring. 2. underscore(_)– The _ character matches any single character. e.g.To display names of employee whose name starts with R in EMPLOYEE table, the command is: select ename from employee where ename like “R%”; e.g. To display details of employee whose second character in name is: select * from employee where ename like ‘_e%’; SEARCHING FOR NULL The NULL value in a column can be searched for in a table using IS NULL in the WHERE clause. E.g. to list employee details whose salary contain NULL, we use the command: Select * from employee where gross is null; Note: For listing employees who earn salary, then it is: Select * from employee where gross is not null; Relational Operators • To compare two values, a relational operator is used. The result of the comparison is true or false. Relational Operators recognized by SQL: =, >, <, <=, >=, <> (not equal or !=) Eg. Select * from employee where ecode <> 1001; Above query will not display those employee details whose ecode column value is 1001. Logical Operators- (OR, AND, NOT) 1) To list the employee details having grades E2 or E3. Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’); 2) To list all the employees’ details having grades as ‘E4’ but with gross < 9000.
  • 165. 165 Select ecode, ename, grade, gross from employee where grade=‘E4’ and gross< 9000; 3) To list all the employees’ details whose grades are other than ‘G1’. Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’); Sorting Results- ORDER BY clause Results of SQL query can be sorted in a specific order using ORDER BY clause. The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be done either in ascending or descending order. Eg. Select * from emp order by ename; Above query arranges the records in alphabetical order of ename value. By default order by clause arranges in ascending order. TO DISPLAY RECORDS IN DESCENDING ORDER ❖ Select * from employee order by ename desc; Above query gives output in descending order of ename. ❖ Select * from employee ORDER BY grade DESC, ename ASC; Above query displays records first in the descending order of grade and within the same grade, employees are displayed in the ascending order of Ename. SQL AGGREGATE FUNCTIONS: All the aggregate functions ignore null values except count(*). Avg – to compute average value Min – to find minimum value Max – to find maximum value Sum – to find total value Count – to count non-null values in a column Count( *) – to count total number of rows in a table including null values. Examples: Select avg(gross) from employee; Select min(gross) from employee where deptno= 10; Select count(*) from emp where gross> 10000; Select count (DISTINCT gender) from employee; GROUP BY Clause GROUP BY clause is used in SELECT statements to display the table contents based on similar values in a column into groups.
  • 166. 166 Eg: To calculate the number of employees in each grade, the query is: SELECT grade, count(*) from employee group by grade; Placing conditions on Groups HAVING Clause ❖ The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on individual rows. ❖ WHERE conditions cannot include aggregate functions but HAVING conditions can do so. Eg: SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’ ; DELETE Command This command removes rows from a table. Syntax: DELETE FROM <tablename> [WHERE <cond>]; Eg: To remove all the contents of items table, the query is: DELETE from items; Eg: To remove the tuples from employee that have gross less than 20000 is : DELETE from employee WHERE gross<20000; UPDATE Command Update Command allows to change some or all the values in an existing rows. Update command specifies the rows to be changed using the WHERE clause and the new data using the SET keyword. Eg. UPDATE employee SET gross= 25000; The above query sets the gross of all records as 25000. UPDATE employee SET gross=40000, grade=’A’ WHERE ecode=1001; The above query changes the gross and grade values for the record with ecode 1001. ALTER TABLE ALTER TABLE command is used to change the structure of the existing table. It can be used to add or drop new columns or modify the existing columns of table. Eg. 1. Alter table Employee Add comm int; 2. ALTER TABLE Emp MODIFY (ename varchar(60)); 3. Alter table emp drop comm; DROP TABLE: DROP TABLE command allows to remove a table from database. Once the DROP command is issued, the table will no longer be available in the database.
  • 167. 167 Eg. DROP TABLE employee; INTEGRITY CONSTRAINTS A constraint is a condition or check applicable on a field or set of fields. Common types of constraints include: S.No.Constraints Description 1 NOT NULL Ensures that a column cannot have NULL value 2 DEFAULT Provides a default value for a column when none is specified 3 UNIQUE Ensures that all values in a column are different 4 PRIMARY KEY Used to uniquely identify a row in the table 5 FOREIGN KEY Used to ensure referential integrity of the data ADDING CONSTRAINT TO A TABLE ALTER TABLE statement can be used to add constraints to your existing table by using it in following manner: Eg: alter table employee add primary key(ecode); REMOVING CONSTRAINTS FROM A TABLE Eg: alter table employee drop primary key; Setting primary and foreign key constraint: Eg: CREATE TABLE STUDENT(ROLL_NO integer PRIMARY KEY ,NAME VARCHAR(30),CLASSVARCHAR(3)); CREATE TABLE SCORE(ROLL_NO integer ,MARKS integer, FOREIGN KEY(ROLL_NO) REFERENCES STUDENT(ROLL_NO)); SQL JOINS SQL Joins are essential to display data from more than one table. SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. SQL provides various types of joins: 1. Cartesian Product or Cross Join 2. Equi-Join 3. Natural Join. Cartesian Product (Cross Join) Cartesian product of two tables is obtained by pairing up each row of one table with each row of the other table.
  • 168. 168 ❖ The number of columns in the Cartesian product is the sum of the number of columns in both the tables. ❖ The number of rows in the Cartesian product is the product of rows of the tables. Example: Equi-Join A join which is obtained by putting a condition of equality on cross join is called an 'equi join'. We can extract meaningful information from the Cartesian product by placing some conditions in the statement. The join in which columns are compared for equality is called equi-join. In this type of join we put * in the select list therefore the common column will appear twice in the output. Example: Consider the 2 tables emp and dept. On performing equi-join, the result is as follows:
  • 169. 169 Note: We see that deptno column appears twice in output. Natural Join • The join in which only one of the identical columns exists is called natural join. • It is similar to equi-join except that duplicate columns are eliminated in natural join that would otherwise appear in equi-join. Example: Note: We see that deptno column appears only once in output. Worksheet – L3 Q1. What does the abbreviation DBMS stand for? (a) Data Borrowing and Movement Software. (b) Database Management System. (c) DigitalBase Mapping System. (d) Database Manipulation Software. Q2. Which is not an advantage of DBMS? (a) Database Systems reduce data redundancy (b) Database Systems control data inconsistency (c) Database Systems restrict sharing of data (d) Database Systems ensure data security. Q3. In ..............,the data is organized into tables i.e. rows &columns.
  • 170. 170 (a) Relational Model (b) Network Model (c) Hierarchical Model (d) ObjectOriented Model Q4. The essential features of Object Oriented Data Model are; (a) Object identity (b) Encapsulation (c) DataAbstraction (d) All of the above Q5. Which statement is false in context to the term Relation? (a) Relation is a table storing logically related data. (b) Data must be atomic in cell (c) All rows of relation are distinct. (d) Ordering of rows & columns is relevant. Q6. A row of relation generally referred to as.............and column of a relation is ………… (a) Domain & Attribute (b) Attribute & Domain (c) Tuple & Attribute (d) Attribute & Tuple Q7. A relation has 45 tuples & 5 attributes, what will be the Degree & Cardinality of that relation? (a) Degree5,Cardinality45 (b) Degree45,Cardinality5 (c) Degree50,Cardinality45 (d) Degree50,Cardinality2250 Q8. Is the attribute or group of attributes that uniquely identify occurrence of each entity. (a) Foreign key (b) Super Key (c) Primary Key (d) All of these Q9. A Candidate key that is not a primary key, is called ……………
  • 171. 171 (a) Alternate key (b) Foreign key (c) Primary key (d) Super Key Q10.A non-key attribute, whose values are derived from primary key of some other table. (a) Alternate key (b) Foreign key (c) Primary key (d) Super Key Q11. MySQL database system consists of- (a) MySQLServerInstance (b) MySQLDatabase (c) MySQL Query Optimizer (d) (a)&(b)both Q12. Which commands are used to define or redefine schema objects? (a) DDL (b) DML (c) TCL (d) (a)&(b)both Q13. Data definition includes: (a) Creating of database (b) Undoing changes to the database. (c) Modification of data stored in the database. (d) All of the above Q14. Which is not a TCL command? (a) Commit (b) Rollback (c) Exit (d) Savepoint Q15. Which is not a function of DML? (a) Retrieval of data stored in the database (b) Insertion of data into the database (c) Deletion of data from the database (d) Making changes permanent to the database. Q16. Which is not a numeric type?
  • 172. 172 (a) Int (b) Float (c) Blob (d) Double Q17. The default date format in MySQL is: (a) DD/MM/YYYY (b) YYYY/MM/DD (c) MM-DD-YYYY (d) YYYY-MM-DD Q18. Which is not a way to represent comment in MySQL? (a)/*------------- */ (b) -- (c) # (d) // Q19. The command is used to access database in MySQL is- (a) Open <databasename>; (b) USE <databasename>; (c) Access <databasename>; (d) (a)&(b) both 20. Which is a valid CREATE TABLE statement? (a) Create table emp add(id integer(3)); (b) Create table emp(id integers(3)); (c) Create table emp modified(id integer(3)); (d) Create table emp(id integer(3)); Q21. How can you insert a new row into the “STORE” table. (a) INSERT ROW(1,‟RAMSINGH‟)INTO STORE; (b) INSERT VALUES(1,‟RAMSINGH‟)INTO STORE; (c) INSERT INTO(1,‟RAMSINGH‟)STORE; (d) INSERT INTO STORE VALUES(1,‟RAMSINGH‟); Q22. Select statement has four clauses 1.Where 2.Having 3.Group By 4.Orderby The correct order of all clauses in a select is:- (a)1,2,3&4 (b)1,3,2&4 (c)1,4,3&2 (d)1,3,4&2
  • 173. 173 Q23. Conditionally retrieval of rows from a table with SELECT, which clause is used? (a) Where (b) Having (c) Group By (d) Order by Q24. The.................. key word eliminates duplicate rows from the result of a SELECT statement. (a) All (b) Unique (c) Distinct (d) IN Q25. Which operator defines a range of values that the column values must fall in? (a) In (b) Like (c) Between (d) Is Q26. To specify a list of values...............Operator is used. (a) In (b) Like (c) Between (d) Is Q27. We use..................operator with select for condition based on pattern matching. (a) In (b) Like (c) Between (d) Is Q28. Which SQL statement will not generate any error message? (a) SELECT*FROM EMP WHERE EMPNO LIKE(1,2,3,4); (b) SELECT*FROM EMP WHERE SAL BETWEEN 3000 TO 15000; (c) SELECT*FROM EMP WHERE COMM IS NOT NULL; (d) All of the above Q29.To display the detail of employee having ‘e’ in their name in descending order of salary. The correct SQL statement is: (a) SELECT*FROM emp WHERE ename LIKE “e%” ORDER BY SAL; (b) SELECT*FROM emp ORDER BY SAL DESC WHERE ename LIKE
  • 174. 174 “%e%”; (c) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY DESC SAL; (d) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY SAL DESC; Q30. Which statement is valid? (a) ALTER TABLE EMPLOYEE MODIFY(last_name CHAR2(2000)); (b) ALTER TABLE EMPLOYEE CHANGE(last_name CHAR2(2000)); (c) ALTERTABLE EMPLOYEE CHANGE(last_name VARCHAR2(2000)); (d) ALTER TABLE EMPLOYEE MODIFY(last_name VARCHAR2(2000));
  • 175. 175 Answers Q.No. Answers 1 B 2 C 3 A 4 d 5 d 6 c 7 a 8 c 9 a 10 b 11 d 12 a 13 a 14 c 15 d 16 c 17 d 18 d 19 b 20 d 21 d 22 b 23 a 24 c 25 c 26 a 27 b 28 c 29 d 30 d
  • 176. 176 WORK SHEET -2 Q1. Which is true in respect of Select Statement? (a) By Select we can retrieve all the rows from table. (b) By Where clause with select we can retrieve selected rows from table. (c) We can retrieve unique rows from table with the use of Distinct keyword. (d) All of the above. Q2. The clause which is used to group rows based on distinct values that exist for specified column. (a) Group by clause (b) Having clause (c) Order by Clause (d) Where Clause Q3. For conditionally retrieval of row from groups which clause is used? (a) Where clause (b) Having Clause (c) Order By Clause (d) (a)&(b)both Q4. Group functions are also known as. (a) Aggregate functions (b) Multiple row functions (c) Single row functions (d) (a)&(b)both Q5.Which option cause a group function to consider only distinct values. (a) All (b) Distinct (c) Unique (d) Diverse Q6. Which option cause a group functions to consider all values including all duplicated. (a) All (b) Distinct (c) Unique
  • 177. 177 (d) Diverse Q7. Which is not a group function? (a) AVG (b) COUNT (c) MAX (d) MOD Consider the relations/tables EMP and DEPT and give the correct answer of following queries. Relation: EMP EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO 7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20 7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30 7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30 7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20 7654 MARTIN SALESMAN 7698 1981-09-28 1250.00 1400.00 30 7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30 7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10 7788 SCOTT ANALYST 7566 1982-12-09 3000.00 NULL 20 7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10 7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30 7876 ADAMS CLERK 7788 1983-01-12 1100.00 NULL 20 7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30 7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20 7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10 Relation: DEPT DEPTNO DNAME LOC 10 ACCOUNTING NEWYORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Q8. SELECT AVG(SAL) FROM EMP WHERE JOB=‘CLERK’; (a)1037.5 (b)2073.21 (c)1040 (d)2074 Q9. SELECT COUNT(*) FROM EMP WHERE DEPTNO=10; (a) 14 (b) 3 (c) 4 (d) 5
  • 178. 178 Q10. SELECT COUNT(DISTINCT JOB) FROMEMP; (a) 14 (b) 5 (c) 4 (d) 6 Q11. SELECT COUNT(ALL JOB)FROM EMP; (a) 14 (b) 5 (c) 4 (d) 6 Q12. SELECT MAX(SAL) FROM EMP WHERE JOB=‘MANAGER’; (a)2975 (b)5000 (c)3000 (d)2850 Q13. SELECT MIN(HIREDATE) FROM EMP; (a) 1980-12-17 (b) 1983-01-12 (c) 1982-12-09 (d)None Q14. SELECT MAX(HIREDATE) FROM EMP; (a) 1980-12-17 (b) 1983-01-12 (c) 1982-12-09 (d)None Q15. SELECT SUM(COMM) FROM EMP; (a) Null (b) 0 (c)2200 (d)1400 Q16.Which statement is used to display the total no. of employees in each department? (a) SELECT COUNT(*) FROM EMP WHERE DEPTNO;
  • 179. 179 (b) SELECTCOUNT(*)FROMEMPGROUPBYDEPTNO; (c) SELECTCOUNT(DEPTNO)FROMEMPGROUPBYDEPTNO; (d) (b)&(c)both Q17. To display the jobs where the number of employees is less than 3. (a) SELECT JOB,COUNT(*)FROM EMP WHERE COUNT(*)<3; (b) SELECT JOB, COUNT(*) FROM EMP WHERE COUNT(*)<3 GROUP BY JOB; (c) SELECT JOB, COUNT(*) FROM EMP GROUP BY JOB WHERE COUNT(*)<3; (d) SELECT JOB,COUNT(*)FROM EMP GROUP BY JOB HAVING COUNT(*) <3; Q18.Which join is used for display all possible concatenations are formed of all rows of two or more tables. (a) Unrestricted join (b) Cartesian Join (c) Equi Join (d) (a)&(b) both Q19. How many rows are returned when we execute ‘SELECT*FROM EMP,DEPT’; (a) 14 (b) 4 (c) 18 (d) 56 Q20.To display the name of employee & department name the MySQL statement used: (a) SELECT ENAME, DNAME FROM EMP,DEPT; (b) SELECT ENAME, DNAME FROM EMP,DEPT WHERE DEPTNO=DEPTNO; (c) SELECT ENAME, DNAME FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO; (d) None of the above Q21.The join where columns are compared for equality is called……………… (a) Equi Join (b) Natural Join (c) Cross Join (d) Right Join
  • 180. 180 Q22. The join in which only one identical column exists is called……… (a) Equi Join (b) Natural Join (c) Cross Join (d) Right Join Q23. Which statement represent Cartesian join? (a) SELECT*FROM EMP,DEPT; (b) SELECT*FROM EMP JOIN DEPT; (c) SELECT*FROM EMP CROSS JOIN DEPT; (d) All of the above Q24. Using sub-clause with JOIN causes a................join where as on sub-clause with JOIN produces.......... join. (a) Natural & Equi (b) Equi & Natural (c) Cross & Equi (d) Natural & Cross. Q25. Scalar functions are also known as: (a) Single row function (b) Multiple row function (c) Group functions (d) None
  • 181. Answers Q.No. Answers 1 A 2 C 3 C 4 A 5 C 6 C 7 D 8 D 9 B 10 C 11 B 12 B 13 D 14 A 15 B 16 D 17 B 18 A 19 D 20 A 21 B 22 B 23 A 24 A 25 a
  • 182. 182 | P a g e INTERFACE PYTHON WITH MYSQL Basically the process of transfer data between python programs and MySQL database is known as Python Database Connectivity. There few steps you have to follow to perform Python Database Connectivity. These steps are as follow: 1. Import the required packages 2. Establish a connection 3. Execute SQL command 4. Process as per the requirements Importtherequired packages To perform the Python MySQL Database Connectivity you need to install mysql-connector-python package using pip command. pip install mysql connector python After installation just write the import statement to import the package in python code. import mysql.connector as msql importing package mysql connector in python Here I have instantiated msql to mysql.connector which can be work as an alias name for the connector. Establishaconnection To establish a connection you need to create a connection object in Python. Take a variable as a connection object and use connect() function with MySQL database specification like host name, username, passoword or passwd and database itself. For example cn. Observe the code: import mysql.connector as msql cn=msql.connect(host='localhost',user='root',passwd='root',database='Studentdb') Please ensure that you have provided appropriate username, password and database name available in your MySQL interface. After doing this, check for the errors if any. If your program runs without errors that means connection is established. Although you can use is_connected() function to check whether the connection is established or not! Observe this code: import mysql.connector as msql
  • 183. 183 | P a g e cn=msql.connect(host='localhost',user='root',passwd='root',database='Student') if cn.is_connected(): print("Connection Established") else: print("Connection Errors! Kindly check!!!") ExecuteSQLcommandandfetchrows The next step after the successful connection is to write SQL command and fetch rows. The SQL commands are used to perform DML operations and fetch rows read data from table. So we will see them in detail later. You have to create a cursor object for executing SQL command and fetch rows. Cursor object is a special kind of structure that processes the data row by row in database. You can create cursor object in the following manner. cur=cn.cursor() PerformingDMLoperations(insert,updateanddelete) To perform the DML operations like insert, update or delete follow these steps: 1. Create a cursor object 2. Write command as parameters for execute() function 3. Use commit() function to save the changes and reflect the data in the table. insertcommand Observe the following code: import mysql.connector as msql cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb') cur=cn.cursor() cur.execute("insert into students values(1111,'Asmita',78.50,'B1')) cn.commit() updatecommand import mysql.connector as msql cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb') cur=cn.cursor() cur.execute("update students set marks=80.5 where rollno=1111") cn.commit() deletecommand import mysql.connector as msql cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb') cur=cn.cursor()
  • 184. 184 | P a g e cur.execute("delete from students where rollno=1111") cn.commit() SelectCommand As you know the select command is used retrieve records from the database. The result is available in the resultset or dataset. You can store the select the command in cursor object in python. Then for resultset you can use the fetch…() function. These are: 1. fetchall(): It will retrieve all data from a database table in form of record or tuple or a row. 2. fetchone(): It will retrieve one record from the resultset as a tuple or a list. It returns the records in a specific order like first record, the next time next record and so on. If records are not available then it will return None. 3. fetchmany(n): It will retrieve a number of records from the database. If records are not available then it will return an empty tuple. 4. rowcount: It is one of the properties of cursor object that return number of rows fetched from the cursor object. Observe the below-given code for fetchall() function: import mysql.connector as msql cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb') cur=cn.cursor() cur.execute("select * from students") d=cursor.fetchall() for r in d: print(r) Observe the below-given code for fetchmany(n) function: import mysql.connector as msql cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb') cur=cn.cursor() cur.execute("select * from students") d=cursor.fetchmany(3) for r in d: print(r) The above code will return 3 rows from the database. Observe the below-given code for fetchone() function: import mysql.connector as msql import time cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb') cur=cn.cursor() cur.execute("select * from students")
  • 185. 185 | P a g e d=cur.fetchone() print(d) time.sleep(3) d=cur.fetchone() print(d) time.sleep(3) d=cur.fetchone() time.sleep(3) print(d) Parameterized Queries Sometimes we need to access values as per the user’s input. The query result is based on the values user has passed. So for that we have this option parameterized queries. There are two ways to use parameterized queries: 1. with % formatting pattern 2. with {}.format pattern with % formatting pattern This pattern takes the general form – f % v, where f is a format and v is the value. Consider the following code: import mysql.connector as msql import time cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb') cur=cn.cursor() #display records more than 80% cur.execute("select * from students where marks >%s" %(80,)) d=cur.fetchall() for r in d: print(r) #display records having B1 grade cur.execute("select * from students where grade='%s'" %('B1',)) d=cur.fetchall() for r in d: print(r) with {}.formatpattern In this pattern you can write {} where the value is placed followed by .format(values). Consider the following code: import mysql.connector as msql import time cn=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='Studentdb')
  • 186. 186 | P a g e cur=cn.cursor() cur.execute("select * from students where marks >{}" .format(80)) d=cur.fetchall() for r in d: print(r) cur.execute("select * from students where grade='{}'".format('B1')) d=cur.fetchall() for r in d: print(r) Closetheconnection Finally, you have to close the established connect using close() function. It will help to clean up the memory. Observe the following code: con.close() WORKSHEETS L3 – Very Short Answer questions (1 mark) 1. Which package do we import in Python to establish MySQL connectivity ? Ans. mysql.connector 2. What is the significance of using connect( ) function ? Ans. connect( ) function is used to connect or establish a connection with MySQL database. 3. What is the role of execute( ) ? Ans. The role of the execute function is execution of queries which are MySQL queries along with Python interface. 4. What is the command to install mysql connector ? Ans. pip install mysql-connector (OR) pip install mysql-connector-python 5. What is a database connectivity ? Ans. A database connectivity refers to the connection and communication between an application and database system. L3 – Multiple Choice Questions (1 mark) 1. A database _________ controls the connection to an actual database, established from within a Python program. (a) database object (b) connection object (c) fetch object (d) query object
  • 187. 187 | P a g e Ans. (b) 2. The set of records retrieved after executing an SQL query over an established database connection is called ___________ . (a) table (b) sqlresult (c) result (d) resultset Ans. (d) 3. A database _________ is a special control structure that facilitates the row by row processing of records in the resultset. (a) fetch (b) table (c) cursor (d) query Ans. (c ) 4. To obtain all the records retrieved, you may use the <cursor>. _______ method. (a) fetchmany( ) (b) fetchall( ) (c) fetchone( ) (d) fetchmultiple( ) Ans. (b) 5. To reflect the changes made in the database permanently, you need to run <connection>. _______ method. (a) done (b) reflect (c) commit (d) final Ans. (c) 6. To run an SQL query within Python, you may use the <cursor>. _______ method. (a) query (b) execute (c) run (d) None of the above L2 – Short Answer Questions (2 marks) 1. What are the steps for creating database connectivity applications ? Ans. To create database connectivity, follow the given steps: Step 1: Start Python Step 2: Import mysql.connector Step 3: Open a connection to the database Step 4: Create a cursor instance Step 5: Execute a query Step 6: Extract data from result set Step 7. Clean up the environment 2. What is a connection? What is its role? Ans. A connection (represented by the connection object) is the session between the application program and database. To do anything with database, one must have a connection object. 3. What is a resultset? Ans. A result set refers to a logical set of records that are fetched from the database by executing a
  • 188. 188 | P a g e query and made available to the application program. 4. What is a database cursor? Ans. A database cursor is a special control structure that facilitates row by row processing of records in the result set, i.e., the set of records retrieved as per the query. 5. How to retrieve data from a table? Ans. There are multiple ways to retrieve data: i. fetchall( ) – fetches all the remaining rows of a query result, current pointer position forwards ii. fetchone( ) – fetches the next row as a sequence; returns None when no more data L1 – Long Answer Questions (3 marks) 1. Write a Python code to connect to a database Ans. import mysql.connector Mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,database=”project”) Print(mycon) 2. How to create a database in MySQL through Python ? Ans. import mysql.connector mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”) cursor=mycon.cursor( ) cursor.execute(“create database education”) 3. Write the Python code to display the present databases in MySQL Ans. import mysql.connector mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”) cursor=mycon.cursor() cursor.execute(“show databases”) for i in cursor: print(i) 4. How to create a table in MySQL through Python ? Ans. import mysql.connector mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”) cursor=mycon.cursor() cursor.execute(“create table student(admn_no int primary key,sname varchar(30),gender char(2),DOB date, stream varchar(15), marks float”) 5. Write the Python code to insert data into a table in MYSQL
  • 189. 189 | P a g e Ans. import mysql.connector mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”) cursor=mycon.cursor() ano=int(input(“Enter admission no: “)) n=input(“Enter name: “) g=input(“Enter gender:”) dob=input(“Enter DOB: “) s=input(“Enter stream: “) m=float(input(“Enter marks:”)) query=”insert into student values({},’{}’,’{}’,’{}’,’{}’,’{}’,{})”.format(ano,n,g,dob,s,m) cursor.execute(query) mycon.commit( ) 6. How to fetch data in Python from a table in MySQL ? Ans. import mysql.connector mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”, database=”education”) cursor=mycon.cursor() cursor.execute(“select * from student”) for row in cursor: print(row) 7. Write the Python code to update a record in the table Ans. import mysql.connector mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”, database=”education”) cursor=mycon.cursor() cursor.execute(“update student set marks=67 where admn_no=3456”) mycon.commit( ) 8. Write the Python code to delete a record from the table Ans. import mysql.connector mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”, database=”education”) cursor=mycon.cursor() cursor.execute(“delete from student where admn_no=3455”) mycon.commit( ) *************
  • 190. 190 | P a g e KENDRIYA VIDYALAYA SANGATHAN -CHENNAI REGION CLASS-XII SESSION 2022-23 COMPUTER SCIENCE (083) SAMPLE PAPER - I Maximum Marks: 70 Time Allowed: 3 hours 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 Q35 against part c only. 8. All programming questions are to be answered using Python Language only. SECTION - A 1. The ___________ statement is an empty statement in Python. 1 2. Which of the following is not a keyword? (a) eval (b) assert (c) nonlocal (d) pass 1 3. What will be the output for the following Python statements? D= {“Amit”:90, “Reshma”:96, “Suhail”:92, “John”:95} print(“John” in D, 90 in D, sep= “#”) (a) True#False (b)True#True (c) False#True (d) False#False 1 4. What will the following Python statement evaluate to? print (5 + 3 ** 2 / 2) (a) 32 (b) 8.0 (c) 9.5 (d) 32.0 1 5. Consider the list aList=[ “SIPO”, [1,3,5,7]]. What would the following code print? (a) S, 3 (b) S, 1 (c) I, 3 (d) I, 1 1 6. Which of the following mode in the file opening statement creates a new file if the file does not exist? (a) r+ (b) w+ (c) a+ (d) Both (b) and (c) 1 7. Which of the following is not an integrity constraint? (a) Not null (b) Composite key (c) Primary key (d) Check 1 8. Choose the correct command to delete an attribute A from a relation R. (a) ALTER TABLE R DELETE A (b) ALTER TABLE R DROP A (c) ALTER TABLE DROP A FROM R 1
  • 191. 191 | P a g e (d) DELETE A FROM R 9. Identify the errors in the following code: MyTuple1=(1, 2, 3) #Statement1 MyTuple2=(4) #Statement2 MyTuple1.append(4) #Statement3 print(MyTuple1, MyTuple2) #Statement4 (a) Statement 1 (b) Statement 2 (c) Statement 3 (d) Statement 2 &3 1 10. In the relational model, relationships among relations/table are created by using _______ keys. (a) composite (b) alternate (c) candidate (d) foreign 1 11. The correct statement to place the file handle fp1 to the 10th byte from the current position is: (a) fp1.seek(10) (b) fp1.seek(10, 0) (b) fp1.seek(10, 1) (d) fp1.seek(10, 2) 1 12. Which of the following aggregate functions ignore NULL values? (a) COUNT (b) MAX (c) AVERAGE (d) All of these 1 13. _______ is a device that forwards data packets along networks. (a) Gateway (b) Modem (c) Router (d) Switch 1 14. Suppose str1= ‘welcome’. All the following expression produce the same result except one. Which one? (a) str[ : : -6] (b) str[ : : -1][ : : -6] (c) str[ : :6] (d) str[0] + str[-1] 1 15. Which of the following is a DML command? (a) SELECT (b) ALTER (c) CREATE (d) DROP 1 16. Mandatory arguments required to connect any database from Python are: (a) Username, Password, Hostname, Database name, Port (b) Username, Password, Hostname (c) Username, Password, Hostname, Database Name (d) Username, Password, Hostname, Port 1 Q17 and 18 are ASSERTION and REASONING based questions. Mark the correct choice as: (a) Both A and R are true and R is the correct explanation for A (b) Both A and R are true and R is not the correct explanation for A (c) A is True but R is False (d) A is false but R is True 17 Assertion (A): Keyword arguments are related to the function calls Reason (R): When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. 1 18 Assertion (A): Text file stores information in ASCII or unicode characters. 1
  • 192. 192 | P a g e Reason (R): In text file, there is no delimiter for a line. SECTION-B 19 Identify the errors in the program segment given below. Rewrite the corrected code and underline each correction. def Tot (Number): Sum=0 for C in RANGE (1, Number + 1): Sum + = C return Sum print(Tot [3]) print(Tot[6]) 2 20 Write two points of difference between HTTP and FTP. OR State the advantages and disadvantages of star topology over bus topology? 2 21 What will be the output of the following Python code? d1={“a”:10, “b”=2, “c”:3} str1= “ ” for i in d1: str1=str1+str(d1[i])+ “ ” str2=str1[ : -1] print(str2[: : -1]) 2 22 What do you understand by Candidate keys in a table? Give a suitable example of candidate keys from a table containing some meaningful data. 2 23 (i) Write the full forms of the following: (a) SMTP (b) IPR (ii) Which protocol is used in creating a connection with a remote machine? 2 24 What possible output(s) are expected to be displayed on screen at the time of execution of the following code? Also specify the maximum and minimum value that can be assigned to variable X. import random L=[10,7,21] 2
  • 193. 193 | P a g e X=random.randint(1,2) for i in range(X): Y=random.randint(1,X) print(L[Y],”$”,end=” ”) (a) 10 $ 7 $ (b) 21 $ 7 $ (c) 21 $ 10 $ (d) 7 $ OR 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) a=changer(a) print(a,’$’,b) 25 Differentiate between Drop and Delete commands of MYSQL. Write its syntax. OR For a table “Company” having column cno, cname, department and salary, write the SQL statement to display average salary of each department. 2 SECTION – C 26 Consider the following tables:
  • 194. 194 | P a g e (i) Write any one point of difference between Equi join and Natural join. (ii) Find output: (a) select *from product p, supplier s where p.supid=s.supid; (b) select *from product natural join supplier; OR (i) Write a Query to insert House_Name=Tulip, House_Captain= Rajesh and House_Point=278 into table House(House_Name, House_Captain, House_Points). (ii) Write the output for SQL queries (i) to (iv), which are based on the table: STUDENT given below: (i) SELECT COUNT(*), City FROM STUDENT GROUP BY CITY HAVINGCOUNT(*)>1; (ii) SELECT MAX(DOB),MIN(DOB) FROM STUDENT; (iii) SELECT NAME,GENDER FROM STUDENT WHERE CITY=”Delhi”; (iv) SELECT DISTINCT Class FROM STUDENT; 1 2 1 2
  • 195. 195 | P a g e 27 A text file “Quotes .Txt” has the following data written in it: Living a life you can be proud of Doing your best Spending your time with people and activities that are important to you Standing up for things that are right even when it’s hard Becoming the best version of you Write a user defined function to display the total number of words present in the file. OR Write a function in Python to count the number of lines in a text file ‘STORY.TXT’ which is starting with an alphabet ‘A’. 3 28. (i) Write the actual datatypes as per the following Structure requirement during creation of a table: (ii) Vani created a table named Customer that have fields Cno, Custname, Address, Amount. Now she wants to increase the width to 30 Characters of the column “Address”. Write the SQL command for it. 2 1 29 Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The function returns another list named ‘indexList’ that stores the indices of all Non-Zero Elements of L. For example: If L contains [12,4,0,11,0,56] The indexList will have - [0,1,3,5] 3 30 Write a function in python, Push(Package) and Pop(Package) to add details of employee contain information (Empid, Ename and Salary) in the form of tuple in Package and delete a Package from a List of Package Description, considering them to act as push and pop operations of the Stack data structure. OR Jiya has a list containing 8 integers. You need to help her create a program with two user defined functions to perform the following operations based on this list. • Traverse the content of the list and push those numbers into a stack which are divisible by both 5 and 3. • Pop and display the content of the stack. 3
  • 196. 196 | P a g e For example: If the sample Content of the list is as follows: L=[5,15,21,30,45,50,60,75] Sample Output of the code should be: 75 60 45 30 15 SECTION D 31 Alpha Pvt Ltd is setting up the network in Chennai. There are four blocks- Block A, Block B, Block C & Block D. Distance between various blocks are as given below: Number of computers in each block are given below: Block Number of Computers Block A 85 Block B 28 Block C 43 Block D 20 i)Suggest the most suitable block to place the server with a suitable reason. ii) Suggest the cable layout for connections between the various blocks. iii) Suggest the placement of following devices with justification: (a) Switch/Hub (b) Repeater 5
  • 197. 197 | P a g e iv)The organization is planning to link its front office situated in the city in a hilly region where cable connection is not possible. Suggest an economic way to connect with reasonably high speed. v) Out of following which type of Network it is LAN,MAN,WAN 32 (i) Find and write the output of the following Python code: data=["P",20,"R",10,"S",30] times=0 alpha=" " add=0 for c in range(1,6,2): times = times + c alpha = alpha + data [c-1] + "$" add = add + data[c] print (times, add, alpha) (ii) The given program is used to connect with MySQL abd show the name of the all the record from the table “stmaster” from the database “oraclenk”. Write the missing statements to complete the code. import _____.connector_______ pymysql dbcon=pymysql._____________(host=”localhost”, user=”root”, ________=”sia@1928”,database=” oraclenk”) if dbcon.isconnected()==False: print(“Error in establishing connection:”) cur=dbcon.______________() query= “select * from stmaster” cur.execute(_________) resultset=cur.fetchmany(3) for row in resultset: print(row) dbcon.______() 2 3
  • 198. 198 | P a g e OR (i) Consider the program given below and justify the output. c = 10 def add(): global c c = c + 2 print("Inside add():", c) add() c=15 print("In main:", c) Output: Inside add() : 12 In main: 15 What is the output if “global c “ is not written in the function add()? (ii) Avni is trying to connect Python with MySQL for her project. Help her to write the python statement on the following:- (i) Name the library, which should be imported to connect MySQL with Python. (ii) Name the function, used to run SQL query in Python. (iii) Write Python statement of connect function having the arguments values as : Host name :192.168.11.111 User : root Password: Admin Database : MYPROJECT 2 3
  • 199. 199 | P a g e 33 (i) Differentiate between the writerow and writerows function. (ii) Write a Program in Python that defines and calls the following user defined functions: (i) add() – To accept and add data of an employee to a CSV file ‘EMPLOYEE.CSV’. Each record consists of a list with field elements as EId, EName and EPrice to store furniture id, furniture name and furniture price respectively. (ii) search()- To display the records of the furniture whose price is more than 10000 OR (i) State the difference between seek() and tell() functions of Python. (ii) Write a Program in Python that defines and calls the following user defined functions: (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) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’. 2 3 2 3 SECTION-E 34 Consider the table MobileMaster M_Id M_Company M_Name M_Price M_Mf_Date MB001 Samsung Galaxy 13000 2014-02-12 MB002 Nokia N1100 7500 2011-04-15 MB003 Realme C35 12000 2021-11-20 MB004 Oppo SelfieEx 12500 2015-08-21 Based on the data given above answer the following questions: (i) Identify the most appropriate column, which can be considered as Primary key. (ii) If two columns are added and 2 rows are deleted from the table result, what will be the new degree and cardinality of the above table? (iii) Write the statements to: a. To display details of those mobiles whose price isgreater than 8000. b. Increase the M_Price of all mobiles manufactured after 2015-01-01 by 500. OR (Option for part iii only) (iii) Write the statements to: a. Delete the record of mobileshaving price less than 8000. b. Add a column REMARKS in the table with datatype as varchar with 50 characters 4
  • 200. 200 | P a g e 35 Alia has written a code and created a binary file EMPLOYEE.DAT with employeeid, ename and salary. The file contains 10 records. He now has to update a record based on the employee id entered by the user and update the salary. The updated record is then to be written in the file updateemp.dat. The records which are not to be updated also have to be written to the file updateemp.dat. If the employee id is not found, an appropriate message should be displayed. As a Python expert, help him to complete the following code based on the requirement given above: import _______ #Statement 1 def update_data(): rec={} fin=open("EMPLOYEE.DAT","rb") fout=open("_____________") #Statement 2 found=False eid=int(input("Enter employee id to update their salary :: ")) while True: try: rec=______________ #Statement 3 if rec["employeeid"]==eid: found=True rec["salary"]=int(input("Enter new salary :: ")) pickle.____________ #Statement 4 else: pickle.dump(rec,fout) except: break if found==True: print("The salary of employee id ",eid," has been updated.") else: print("No employee with such id is not found") fin.close() fout.close() (i) Which module should be imported in the program? (Statement 1) 4
  • 201. 201 | P a g e (ii) Write the correct statement required to open a temporary file named updateemp.dat. (Statement 2) (iii) Which statement should Alia fill in Statement 3 to read the data from the binary file, EMPLOYEE.DAT and in Statement 4 to write the updated data in the file, updateemp.dat? COMPUTER SCIENCE (083) SAMPLE PAPER - I MARKING SCHEME Maximum Marks: 70 Time Allowed: 3 hours 1. pass (Q 1-18 – 1 Mark each) 2. a 3. a 4. c 5. I, 3 6. d 7. b 8. b 9. d 10. d 11. d 12. d 13. c 14. a 15. a 16. c 17. a 18. c 19. def Tot (Number): Sum=0 for C in range (1, Number + 1): Sum + = C (½ mark for each correction) return Sum print (Tot (3)) print (Tot(6) 20. HTTP - Hyper Text Transfer Protocol - protocol used to transfer files from a web server to browser to view a webpage on the internet - defines the format and transfers the webpage FTP - File Transfer Protocol - Protocol used to upload files from a workstation to a FTP server or download files from a FTP server to a workstation - Used to transfer the file from one system to another (Any two differences. Each difference 1 mark) OR Advantages (Any two advantages and disadvantages – ½ mark each) • Provide easy access for service or reconfiguration of the network
  • 202. 202 | P a g e • One device per connection • Simple access protocols Disadvantages • Central node dependency • Long cable length 21. 3, 2, 01 (2 marks) 22. All attributes or group of attributes of a table that can identify a tuple uniquely is called a candidate key. (1 mark) ITEM Ino Item Qt I01 Pen 565 I02 Pencil 780 I03 CD 450 I04 Eraser 300 I05 Duster 200 Candidate keys – Ino, Item (Any example – 1 mark) 23. (a) SMTP – Simple Mail Transfer Protocol (½ mark each) IPR – Intellectual Property Rights (b) TELNET (1 mark) 24. (b) and (d) (1 mark) Maximum value of X: 2 (½ mark each) Minimum value of X: 1 OR 10 # 0 (Each line - ½ mark) 10 $ 20 1 # 0 1 $ 20 25. Delete - Data Manipulation Language (DML) command and used when you want to remove some or all the tuples from a relation Drop - Data Definition Language (DDL) command whichremoves the table from database Syntax: (Definition – 1 mark ; Syntax: 1 mark) Delete: DELETE FROM relation_name WHERE condition; Drop: Drop table tablename; OR SELECT department, avg(salary) from company Group by department; (2 marks) 26. Difference between equi join and natural join – 1 mark Each output – 1 mark OR
  • 203. 203 | P a g e (i) insert into House values (‘Tulip’,’Rajesh’,278); (1 mark) (ii) Each output ½ mark 27. def countwords( ): S= open(“Quotes.txt”, “r”) (Opening the file in correct mode and closing – 1 mark) f = S. read() ½ mark z= f.split( ) ½ mark for i in z: ½ mark count = count + 1 print(“Total number of words”, count) ½ mark S.close() OR def countlines(): file=open(“STORY.TXT”, “r”) (Opening the file in correct mode and closing – 1 mark) lines= file.readlines() ½ mark count=0 for w in lines: if w[0]== ‘A’ or w[0]== ‘a’: 1 mark count=count+1 print(“Total lines starting with A:”, count) ½ mark file.close() 28.(i) PID – int(11) ProdName – varchar(10) DateofManufacture – Date Price – float(7, 2) (ii) ALTER TABLE Customer MODIFY Address(30); 29. def INDEX_LIST(L): indexList=[] for i in range(len(L)): if L[i]!=0: indexList.append(i) return indexList (½ mark for correct function header 1 mark for correct loop 1 mark for correct if statement ½ mark for return statement) 30. def Push(Package): Empid=int(input(“Enter Id of Employee: ")) Ename=input(“Enter Name of employee”) Salary= int(input(“Enter Salary of an employee”)) T=(Empid, Ename ,Salary) Package.append(T) def Pop(Package): if (Package==[]): print( "Stack empty")
  • 204. 204 | P a g e else: print ("Deleted element:",Package.pop()) OR def PUSH(Arr,value): s=[] for x in range(0,len(Arr)): if Arr[x]%5 and Arr[x]%3==0: s.append(Arr[x]) if len(s)==0: print("Empty Stack") else: print(s) def popStack(st) : if len(st)==0: # If stack is empty print("Underflow") else: print(“Element deleted is”,st.pop( )) 31. (i) Block A (ii) Any correct cable layout – 1 mark (iii) (a) In all blocks (b) To be placed between blocks where distance is greater than 70m (iv) Radiowaves (v) LAN 32. (i) 9 60 P$R$S$ (ii) import mysql.connectoraspymysql dbcon=pymysql.connect(host=”localhost”, user=”root”, passwd=”sia@1928” ,database=” oraclenk”) if dbcon.isconnected()==False print(“Error in establishing connection:”) cur=dbcon.cursor() query=”select * from stmaster” cur.execute(query) resultset=cur.fetchmany(3) for row in resultset: print(row) dbcon.close() OR (i) In the function add() global c is increment due to use of global keyword. In the main program local c is printed as local takes precedence over global c. If global c is not used then c=c+2 will show error as there is no local variable c in function. (ii) (i) import mysql.connector (ii) execute () (iii)mysql.connector.connect(host=”192.168.11.111”,user=”root”,passwd=”Admin”,databa 146 se=”MYPROJECT”) 33. (i) writerow() – 1 mark
  • 205. 205 | P a g e writerows() – 1 mark (ii) Definition of add() – 1 mark Definition of search() – 1 mark Function call – 1 mark OR (i) seek() – 1 mark tell() – 1 mark (ii) Definition of ADD() – 1 mark Definition of COUNTR() – 1 mark Function call – 1 mark 34. Each SQL statement 1 mark 35. (i) pickle (1 mark for correct module) (ii) fout=open(‘updateemp.dat’, ‘wb’) (1 mark for correct statement) (iii) Statement 3: pickle.load(fin) Statement 4: pickle.dump(rec,fout) (1 mark for each correct statement) KENDRIYA VIDYALAYA SANGATHAN – CHENNAI REGION Class: XII Session: 2022-23 Computer Science (083) Sample Question Paper - II Maximum Marks: 70 Time Allowed: 3 hours 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 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 Q35 against part c only. 8. All programming questions are to be answered using Python Language only. SECTION A 1. State whether True or False: Variable names can begin with the _ symbol. 1 2. Identify which of the following is an invalid data type in Python: (a) int (b) float (c) super (d) None 1 3. Consider the following code: 1
  • 206. 206 | P a g e dict1 = {‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92, ‘Saritha’: 85} What suitable code should be written to return a list of values in dict1 ? 4. Consider the following expression: not True and False or not False Which of the following will be the output: a) True b) False c) None d) NULL 1 5. Select the correct output of the following code: >>>str1 = ‘India is a Great Country’ >>>str1.split(‘a’) a) [‘India’,’is’,’a’,’Great’,’Country’] b) [‘India’, ’is’, ’Great’, ’Country’] c) [‘Indi’, ’is’, ’Gre’, ’t Country’] d) [‘Indi’, ’is’, ’Gre’, ’t’, ‘Country’] 1 6. Which of the following is an invalid access mode for text files: a) w b) a+ c) ab d) r 1 7. Fill in the blanks: ___________ command is used to add a new column in the table in SQL 1 8. Which of the following will display all the tables in a database: a) SELECT * FROM <tablename>; b) DISPLAY TABLES; 1
  • 207. 207 | P a g e c) SHOW TABLES; d) USE TABLES; 9. Which of the following will be the output of the code: mySubject = “Computer Science” print(mySubject[:3] + mySubject[3:]) a) Com b) puter Science c) Computer Science d) Science Computer 1 10. Choose the correct option: __________ is the number of columns in a table and ________ is the number of rows in the table. a) Cardinality, Degree b) Degree, Cardinality c) Domain, Range d) Attribute, Tuple 1 11. The correct syntax of load( ) is: a) <objectvariable> = pickle.load(<fileobject>) b) pickle.load(<fileobject>, <objectvariable>) c) <fileobject>.load(<objectvariable>) d) <objectvariable> = <fileobject>.load( ) 1 12. The _________clause is used to display result of an SQL query in ascending or descending order with respect to specified attribute values 1 13. Fill in the blank: ________ is the protocol used for transferring files from one machine to another. a) HTTP 1
  • 208. 208 | P a g e b) FTP c) SMTP d) VOIP 14. How will the following expression be evaluated in Python? 2 + 9 * ( ( 3 * 12) – 8 ) / 10 a) 29.2 b) 25.2 c) 27.2 d) 27 1 15. Which function is used to display the sum of values in a specified column ? a) COUNT(column) b) TOTAL(column) c) SUM(column) d) ADD(column) 1 16. To open a connector to the MySQL database, which statement is used to connect with MySQL ? a) connector b) connect c) password d) username 1 Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as : (a) Both A and R are true and R is the correct explanation for A (b) Both A and R are true and R is not the correct explanation for A (c) A is True but R is False (d) A is False but R is True 17. Assertion (A) : A variable defined outside any function or any block is known as a global variable. Reason ( R ) : A variable defined inside any function or a block is known as a local variable. 1
  • 209. 209 | P a g e 18. Assertion (A ) : The tell( ) method returns an integer that specifies the current position of the file object in the file. Reason ( R) : Offset can have any of the three values – 0, 1 and 2 1 SECTION B 19. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with each correction underlined. DEF result_even( ): x = input(“Enter a number”) if (x % 2 = 0) : print (“You entered an even number”) else: print(“Number is odd”) even ( ) 2 20. Write two points of difference between LAN and WAN (OR) Write two points of difference between HTTP AND SMTP 2 21 (a) Given is a Python string declaration: str1="!!Welcome to Python!!" Write the output of: print(str1[::-2]) (b) Write the output of the code given below: dict1 = {"name": "Suman", "age": 36} dict1['age'] = 27 dict1['address'] = "Chennai" 1 1
  • 210. 210 | P a g e print(dict1.keys()) 22. Explain the use of Primary Key in a Relational Database Management System. Give an example to support your answer. 2 23. (a) Expand the following: i. XML ii. HTML (b) What is the use of PPP in computer networks ? 1 1 24. Predict the output of the following Python code: def Bigger(N1,N2): if N1>N2: return N1 else: return N2 L=[32,10,21,54,43] for c in range (4,0,-1): a=L[c] b=L[c-1] print(Bigger(a,b),'@', end=' ') (OR) Predict the output of the following Python code: tup1 = ("George","Anderson","Mike","Luke","Amanda") 2
  • 211. 211 | P a g e list1 =list(tup1) list2 = [] for i in list1: if i[-1]=="e": list2.append(i) tup2 = tuple(list2) print(tup2) 25. Differentiate between COUNT(*) and SUM( ) functions in SQL with appropriate example. (OR) Categorize the following commands as DDL or DML: CREATE, DROP, UPDATE, INSERT 2 SECTION C 26. (a) Consider the following tables Uniform and Cost: Table: Uniform UCode UName UColour 1 Shirt White 2 Pant Grey 3 Tie Black Table: Cost UCode Size Price 1 L 550 1 M 500 2 L 850 2 M 810 1+2
  • 212. 212 | P a g e What will be the output of the following statement? SELECT * FROM Uniform NATURAL JOIN Cost; (b) Write the output of the queries (i) to (iv) based on the tablegiven below: Table: Activity PID PARTICIPANT GRADE EVENT POINTS EVENTDATE HOUSE 101 Ajay Devgan A Running 200 2022-02-03 Gandhi 102 John Abraham Hopping Bag 300 2021-12-02 Bose 103 Sunny Deol B Skipping 200 2019-09-23 Gandhi 104 Akshay Kumar A Bean Bag 250 2020-11-14 Bhagat 105 Juhi Chawla A Obstacle 350 2022-03-17 Bose 106 Madhuri Dixit Egg & Spoon 200 2021-10-15 Bose (a) SELECT PARTICIPANT, POINTS FROM Activity ORDER BY POINTS DESC; (b) SELECT HOUSE, COUNT(PARTICIPANT) FROM Activity GROUP BY HOUSE; (c) SELECT DISTINCT POINTS FROM Activity; (d) SELECT PID,EVENTDATE FROM Activity WHERE EVENT=”Running” OR EVENT=”Skipping”; 27. Write a function in python to count the number lines in a text file ‘Country.txt’which is starting with an alphabet ‘W’ or ‘H’. If the file contents are as follows: Whose woods these are I think I know. His house is in the village though; He will not see me stopping here To watch his woods fill up with snow. The output of the function should be: W or w : 1 H or h : 2 3
  • 213. 213 | P a g e (OR) Write a user defined function countwords( ) to display the total number of words present inthe text file “Quotes.Txt”. If the text file has the following data written in it: Living a life you can be proud of doing your best Spending your time withpeople and activities that are important to you Standing up for things that areright even when it’s hard Becoming the best version of you The countwords() function should display the output as: Total number of words : 40 28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations Book and Issued given below: Table : Book Book_id Book_name Author_name Publisher Price Type Qty C0001 Fast Cook Latha Kapoor Oswaal 355 Cookery 5 F0001 The Tears William Hopkins First Publ 650 Fiction 20 T0001 My First Python Brain & Brooke Oswaal 350 Text 10 T0002 Python Brain Works A W Rossaine TDH 350 Text 15 F0002 Thunderbolts Anna Roberts First Publ 750 Fiction 50 Table: Issued Book_id Qty_Issued F0002 5 T0001 9 C0001 2 i. SELECT Type, MIN(Price) FROM Book GROUP BY Type; 3
  • 214. 214 | P a g e ii. SELECT Book_Name, Author_name FROM Book WHERE Price BETWEEN 300 AND 600; iii. SELECT Book.Book_id, Publisher, Qty FROM Book, Issued WHERE Book.Book_id = Issued.Book_id AND Qty > 10; iv. SELECT Book.Book_id, Book_name, Type FROM Book, Issued WHERE Book.Book_id = Issued.Book_id AND Publisher=”Oswaal”; (b) Write the command to view the structure of an already created table 29. Write a function LShift(arr,n) in python, which accepts a list of numbers and a numeric value by which all elements of the list are shifted to left. Sample Input data of the list Arr=[10,20,30,40,12,11] and n=2 Output Arr :[30,40,50,12,11,10,20] 3 30. (a)Write a function in python named PUSH(STACK, SET) where STACK is list ofsome numbers forming a stack and SET is a list of some numbers. The functionwill push all the EVEN elements from the SET into a STACK implemented byusing a list. Display the stack after push operation. (b)Write a function in python named POP(STACK) where STACK is a stackimplemented by a list of numbers. The function will display the popped elementafter function call.Also, display “Stack Empty” if there are no elements in the stack. (OR) A stackBook contains the following details of various books – [book_no, book_title, book_price].Write a function PushBook(Book)in Python that inputs the book details from the user and pushes into the stack. Also, display the stack elements. 3 SECTION D
  • 215. 215 | P a g e 31. Python University is setting up its academic blocks at Chennai and is planning to set up a network. The University has 3 academic blocks and one Human Resource Center as shown in the diagram below: Center to Center distances between various blocks/center is as follows: No. of computers in each block/center is given above. a) Suggest the most suitable place (i.e., Block/Center) toinstall the server of this University with a suitable reason. 5
  • 216. 216 | P a g e b)Suggest an ideal layout for connecting these blocks/centers for awired connectivity. c)Which device will you suggest to be placed/installed ineach of these blocks/centers to efficiently connect all thecomputers within these blocks/centers. d) Suggest the placement of a Repeater in thenetwork with justification. e) The university is planning to connect its admission officein Delhi, which is more than 1250km from university.Which type of network out of LAN, MAN, or WAN will beformed? Justify your answer. 32. (a) Write the output of the code given below: def check(n1=1, n2=2): n1=n1+n2 n2+=1 print(n1,n2) check( ) check(3) (b) The code given below inserts the following record in the table Employee: ENo – integer EName – string Dept – string Salary – integer Note the following to establish connectivity between Python and MYSQL: * Username is root * Password is tiger 2+3
  • 217. 217 | P a g e * The table exists in a MYSQL database named Company * The details (ENo, EName, Dept, Salary) 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 Employee. Statement 3- to add the record permanently in the database import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="root", password="tiger", database="Company") mycursor = _________ #Statement 1 eno=int(input("Enter Employee No :: ")) ename=input("Enter Name :: ") dept=input("Enter Dept :: ") salary=int(input("Enter Salary :: ")) query="insert into employee values({},'{}','{}',{})".format(eno,ename,dept,salary) ___________ #Statement 2 ____________ # Statement 3 print("Data Added successfully") (OR) (a) Predict the output of the code given below:
  • 218. 218 | P a g e s = 'mAhAtMaGaNdHi' i = 0 while i<len(s): if (s[i].islower()): print(s[i].upper(),end=' ') if (s[i].isupper()): print(s[i].lower(),end=' ') i += 1 (b) The code given below reads the following record from the table named Employee and displays only those records who have salary greater than 15,000: ENo – integer EName – string Dept – string Salary – 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 Company. Write the following missing statements to complete the code: Statement 1 – to form the cursor object Statement 2 – to execute the query that extracts records of those employees whose salary is greater than 15,000.
  • 219. 219 | P a g e Statement 3- to read the complete result of the query (records whose salary is greater than 15,000) into the object named data, from the table employee in the database. import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="root",password="tiger", database="Company") mycursor = __________ #Statement 1 print("Employees whose salary greater than 15000 are : ") ___________________ #Statement 2 data = __________________ #Statement 3 for i in data: print(i) print() 33. What is the role of newline argument in opening of CSV files ? Write a Program in Python that defines and calls the following user defined functions: a) ADD() – To accept and add data of a book to a CSV file ‘book.csv’. Each record consists of a list with field elements as bookid, title and price to store book id, book title and book price respectively. b) COUNTR() – To count the number of records present in the CSV file named ‘book.csv’. (OR) 5
  • 220. 220 | P a g e 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: (i) add() – To accept and add data of a toy store to a CSV file ‘toydata.csv’. Each record consists of a list with field elements as tid, tname and tprice to store toy id, toy name and toy price respectively. (ii) search()- To display the records of the toys whose price is more than 500. SECTION E 34. As part of Fit India Campaign, Suresh has started a juice shop that serves healthy juices. As his database administrator, answer the following questions based on the data given in the table below. Table : HEALTHYDRINKS (i) Identify the most appropriate column, which can be considered as Primary key. (ii) If two columns are added and 2 rows are deleted from the table result, what will be the new degree and cardinality of the 1+1+2
  • 221. 221 | P a g e above table? (iii) Write the statements to: a. Insert the following record into the table DrinkCode – 107, Dname – Santara Special, Price – 25.00, Calorie – 130 b. Increase the price of the juices by 3% whose name begins with ‘A’. OR (Option for part iii only) (iii) Write the statements to: a.Delete the record of those juices having calories more than 140. b. Add a column Vitamins in the table with datatype as varchar with 20 characters. 35. Rehaan is a Python programmer. He has written a code and created a binary file record.dat with student_id, sname and marks. The file contains 10 records. He now has to update a record based on the student_id entered by the user and update the marks. The updated record is then to be written in the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat. If the student_id is not found, an appropriate message should also be displayed. As a Python expert, help him to complete the following code based on the requirement given above: 1+1+2
  • 222. 222 | P a g e import _______ #Statement 1 def update_data(): rec={} fin=open("record.dat","rb") fout=open("_____________") #Statement 2 found=False sid=int(input("Enter student id to update their marks :: ")) while True: try: rec=______________ #Statement 3 if rec["Student_id"]==sid: found=True rec["Marks"]=int(input("Enter new marks :: ")) pickle.____________ #Statement 4 else: pickle.dump(rec,fout) except: break if found==True: print("The mark of student id ",sid," has been updated.") else: print("No student with such id is found") fin.close() fout.close() (i) Which module should be imported in the program? (Statement 1)
  • 223. 223 | P a g e (ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2) (iii) Which statement should Rehaan fill in Statement 3 to read the data from the binary filerecord.dat, and in Statement 4 to write the updated data in the file, temp.dat? Computer Science (083) Sample Question Paper - II Maximum Marks: 70 Time Allowed: 3 hours SECTION A (1 mark to be awarded for every correct answer) 1. State whether True or False: Variable names can begin with the _ symbol. Ans. True 1 2. Identify which of the following is an invalid data type in Python: (b) int (b) float (c) super (d) None Ans. (c ) super 1 3. Consider the following code: dict1 = {‘Mohan’: 95, ‘Ram’: 89, ‘Suhel’: 92, ‘Saritha’: 85} What suitable code should be written to return a list of values in dict1 ? Ans. dict1.values( ) 1 4. Consider the following expression: not True and False or not False 1
  • 224. 224 | P a g e Which of the following will be the output: e) True f) False g) None h) NULL Ans. a) True 5. Select the correct output of the following code: >>>str1 = ‘India is a Great Country’ >>>str1.split(‘a’) e) [‘India’, ’is’, ’a’,’ Great’, ’Country’] f) [‘India’, ’is’, ’Great’, ’Country’] g) [‘Indi’, ’is’, ’Gre’, ’t Country’] h) [‘Indi’, ’is’, ’Gre’, ’t’, ‘Country’] Ans. c) [‘Indi’, ’is’, ’Gre’, ’t Country’] 1 6. Which of the following is an invalid access mode for text files: e) w f) a+ g) ab h) r Ans. c) ab 1 7. Fill in the blanks: ___________ command is used to add a new column in the table in SQL Ans. ALTER TABLE 1 8. Which of the following will display all the tables in a database: e) SELECT * FROM <tablename>; f) DISPLAY TABLES; g) SHOW TABLES; h) USE TABLES; 1
  • 225. 225 | P a g e Ans. c) SHOW TABLES; 9. Which of the following will be the output of the code: mySubject = “Computer Science” print(mySubject[:3] + mySubject[3:]) e) Com f) puter Science g) Computer Science h) Science Computer Ans. c) Computer Science 1 10. Choose the correct option: __________ is the number of columns in a table and ________ is the number of rows in the table. e) Cardinality, Degree f) Degree, Cardinality g) Domain, Range h) Attribute, Tuple Ans. b) Degree, Cardinality 1 11. The correct syntax of load( ) is: e) <objectvariable> = pickle.load(<fileobject>) f) pickle.load(<fileobject>, <objectvariable>) g) <fileobject>.load(<objectvariable>) h) <objectvariable> = <fileobject>.load( ) Ans. a) <objectvariable> = pickle.load(<fileobject>) 1 12. The _________clause is used to display result of an SQL query in ascending or descending order with respect to specified attribute values. 1
  • 226. 226 | P a g e Ans. ORDER BY 13. Fill in the blank: ________ is the protocol used for transferring files from one machine to another. e) HTTP f) FTP g) SMTP h) VOIP Ans. b) FTP 1 14. How will the following expression be evaluated in Python? 2 + 9 * ( ( 3 * 12) – 8 ) / 10 e) 29.2 f) 25.2 g) 27.2 h) 27 Ans. c) 27.2 1 15. Which function is used to display the sum of values in a specified column ? e) COUNT(column) f) TOTAL(column) g) SUM(column) h) ADD(column) Ans. c) SUM(column) 1 16. To open a connector to the MySQL database, which statement is used to connect with MySQL ? e) connector 1
  • 227. 227 | P a g e f) connect g) password h) username Ans. b) connect 17. Assertion (A) : A variable defined outside any function or any block is known as a global variable. Reason ( R ) : A variable defined inside any function or a block is known as a local variable. Ans. b) Both A and R are true and R is not the correct explanation for A 1 18. Assertion (A ) : The tell( ) method returns an integer that specifies the current position of the file object in the file. Reason ( R) : Offset can have any of the three values – 0, 1 and 2 Ans. c) A is True but R is False 1 SECTION B 19. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with each correction underlined. DEF result_even( ): x = input(“Enter a number”) if (x % 2 = 0) : print (“You entered an even number”) else: print(“Number is odd”) even ( ) Ans. def result_even( ): x = int(input(“Enter a number”)) 2
  • 228. 228 | P a g e if (x % 2 = = 0) : print (“You entered an even number”) else: print(“Number is odd”) result_even ( ) (1/2 mark for each correction) 20. Write two points of difference between LAN and WAN (OR) Write two points of difference between HTTP AND SMTP Ans. (Any two relevant points of difference to be awarded 1 mark each) 2 21 (c) Given is a Python string declaration: str1="!!Welcome to Python!!" Write the output of: print(str1[::-2]) Ans. !nhy teolW! (b) Write the output of the code given below: dict1 = {"name": "Suman", "age": 36} dict1['age'] = 27 dict1['address'] = "Chennai" print(dict1.keys()) 2
  • 229. 229 | P a g e Ans. dict_keys(['name', 'age', 'address']) 22. Explain the use of Primary Key in a Relational Database Management System. Give an example to support your answer. Ans. Use of Primary Key – (1 mark) Any correct example – (1 mark) 2 23. (a) Expand the following: iii. XML iv. HTML Ans. i. eXtensible Markup Language (1/2 mark) ii. HyperText Markup Language (1/2 mark) (d) What is the use of PPP in computer networks ? Ans. Point to Point Protocol is the Internet standard for transmission of IP packets over serial lines. It is the best solution for dial-up Internet connections. (any 1 correct point, 1 mark) 2 24. Predict the output of the following Python code: def Bigger(N1,N2): if N1>N2: return N1 else: return N2 L=[32,10,21,54,43] for c in range (4,0,-1): 2
  • 230. 230 | P a g e a=L[c] b=L[c-1] print(Bigger(a,b),'@', end=' ') Ans. 54 @ 54 @ 21 @ 32 @ (OR) Predict the output of the following Python code: tup1 = ("George","Anderson","Mike","Luke","Amanda") list1 =list(tup1) list2 = [] for i in list1: if i[-1]=="e": list2.append(i) tup2 = tuple(list2) print(tup2) Ans. ('George', 'Mike', 'Luke') 25. Differentiate between COUNT(*) and SUM( ) functions in SQL with appropriate example. Ans. Any two valid differences – (1 mark) Any valid example – (1 mark) (OR) Categorize the following commands as DDL or DML: 2
  • 231. 231 | P a g e CREATE, DROP, UPDATE, INSERT Ans. DDL – DROP, CREATE (1 mark) DML – UPDATE, INSERT (1 mark) SECTION C 26. UCode UName UColour 1 Shirt White 2 Pant Grey 3 Tie Black Table: Uniform UCode Size Price 1 L 550 1 M 500 2 L 850 2 M 810 Table: Cost What will be the output of the following statement? SELECT * FROM Uniform NATURAL JOIN Cost; Ans. UCode UName UColour Size Price 1 Shirt White L 550 1 Shirt White M 500 2 Pant Grey L 850 2 Pant Grey M 810 1+2
  • 232. 232 | P a g e (1 mark for correct output) (b) Write the output of the queries (i) to (iv) based on the table given below: Table: Activity PID PARTICIPANT GRADE EVENT POINTS EVENTDATE HOUSE 101 Ajay Devgan A Running 200 2022-02-03 Gandhi 102 John Abraham Hopping Bag 300 2021-12-02 Bose 103 Sunny Deol B Skipping 200 2019-09-23 Gandhi 104 Akshay Kumar A Bean Bag 250 2020-11-14 Bhagat 105 Juhi Chawla A Obstacle 350 2022-03-17 Bose 106 Madhuri Dixit Egg & Spoon 200 2021-10-15 Bose (e) SELECT PARTICIPANT, POINTS FROM Activity ORDER BY POINTS DESC; Ans. PARTICIPANT POINTS Juhi Chawla 350 John Abraham 300 Akshay Kumar 250 Ajay Devgan 200 Sunny Deol 200 Madhuri Dixit 200 (f) SELECT HOUSE, COUNT(PARTICIPANT) FROM Activity GROUP BY HOUSE; Ans. HOUSE COUNT(PARTICIPANT) Gandhi 2 Bose 3
  • 233. 233 | P a g e Bhagat 1 (g) SELECT DISTINCT POINTS FROM Activity; Ans. POINTS 200 300 250 350 (d) SELECT PID, EVENTDATE FROM Activity WHERE EVENT = ”Running” OR EVENT =”Skipping”; Ans. PID EVENTDATE 101 2022-02-03 103 2019-09-23 27. Write a function in python to count the number lines in a text file ‘Country.txt’which is starting with an alphabet ‘W’ or ‘H’. If the file contents are as follows: Whose woods these are I think I know. His house is in the village though; He will not see me stopping here To watch his woods fill up with snow. The output of the function should be: W or w : 1 H or h : 2 3
  • 234. 234 | P a g e Ans. def count_W_H(): f = open (“Country.txt”, “r”) W,H = 0,0 r = f.read() for x in r: if x[0] == “W” or x[0] == “w”: W=W+1 elif x[0] == “H” or x[0] == “h”: H=H+1 f.close() print (“W or w :”, W) print (“H or h :”, H) (Note: Use of any correct code giving the same result is also accepted) Correct function header – ½ mark Correct open and close of file – ½ mark Correct for loop and condition checking – 1 mark Correct printing of output – 1 mark (OR) Write a user defined function countwords( ) to display the total number of words present inthe text file “Quotes.Txt”. If the text file has the following data written in it: Living a life you can be proud of doing your best Spending your time withpeople and activities that are important to you Standing up for things that areright even when it’s hard Becoming the best version of you
  • 235. 235 | P a g e The countwords() function should display the output as: Total number of words : 40 Ans. def countwords(): s = open("Quotes.txt","r") f = s.read() z = f.split() count = 0 for I in z: count = count + 1 print ("Total number of words:", count) f.close( ) (Note: Use of any correct code giving the same result is also accepted) Correct function header – ½ mark Correct open and close of file – ½ mark Correct use of split( ) – ½ mark Correct for loop and counter increment - 1 mark Correct printing of output – ½ mark 28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations Book and Issued given below: Table : Book Book_id Book_name Author_name Publisher Price Type Qty C0001 Fast Cook Latha Kapoor Oswaal 355 Cookery 5 F0001 The Tears William Hopkins First Publ 650 Fiction 20 T0001 My First Python Brain & Brooke Oswaal 350 Text 10 T0002 Python Brain Works A W Rossaine TDH 350 Text 15 3
  • 236. 236 | P a g e F0002 Thunderbolts Anna Roberts First Publ 750 Fiction 50 Table: Issued Book_id Qty_Issued F0002 5 T0001 9 C0001 2 v. SELECT Type, MIN(Price) FROM Book GROUP BY Type; Ans. +---------+------------+ | Type | MIN(Price) | +---------+------------+ | Cookery | 355 | | Fiction | 650 | | Text | 350 | +---------+------------+ vi. SELECT Book_Name, Author_name FROM Book WHERE Price BETWEEN 300 AND 600; Ans. +--------------------+----------------+ | Book_Name | Author_name | +--------------------+----------------+ | Fast Cook | Latha Kapoor | | My First Python | Brain & Brooke | | Python Brain Works | A W Rossaine | +--------------------+----------------+ vii. SELECT Book.Book_id, Publisher, Qty FROM Book, Issued WHERE Book.Book_id = Issued.Book_id AND Qty > 10; Ans. +---------+------------+------+ | Book_id | Publisher | Qty | +---------+------------+------+ | F0002 | First Publ | 50 | +---------+------------+------+ viii. SELECT Book.Book_id, Book_name, Type FROM Book, Issued WHERE Book.Book_id = Issued.Book_id AND Publisher=”Oswaal”;
  • 237. 237 | P a g e Ans. +---------+-----------------+---------+ | Book_id | Book_name | Type | +---------+-----------------+---------+ | T0001 | My First Python | Text | | C0001 | Fast Cook | Cookery | +---------+-----------------+---------+ (1/2 mark for each correct output) (c) Write the command to view the structure of an already created table Ans. DESCRIBE <tablename>; (1 mark for correct answer) 29. Write a function LShift(arr,n) in python, which accepts a list of numbers and a numeric value by which all elements of the list are shifted to left. Sample Input data of the list Arr=[10,20,30,40,12,11] and n=2 Output Arr :[30,40,50,12,11,10,20] Ans. 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) (Note : Using of any correct code giving the same result is also accepted.) 3
  • 238. 238 | P a g e 30. (a)Write a function in python named PUSH(STACK, SET) where STACK is list ofsome numbers forming a stack and SET is a list of some numbers. The functionwill push all the EVEN elements from the SET into a STACK implemented byusing a list. Display the stack after push operation. Ans. (1 ½ marks for correct code) (b)Write a function in python named POP(STACK) where STACK is a stackimplemented by a list of numbers. The function will display the popped elementafter function call.Also, display “Stack Empty” if there are no elements in the stack. Ans. (1 ½ marks for correct code) (OR) A stack Book contains the following details of various books – [book_no, book_title, book_price]. Write a function PushBook(Book)in Python that inputs the book details from the user and pushes into the stack. Also, display the stack elements. Ans. def PushBook(Book): 3
  • 239. 239 | P a g e book_id=int(input("Enter book id: ")) book_title=input("Enter book title: ") book_price = int(input("Enter price: ")) data=[book_id,book_title,book_price] Book.append(data) print("The stack: ",Book) Correct function header – ½ mark Correct input from user – 1 mark Correct use of append into Book – 1 mark Correct display of stack content – ½ mark (Note: Any other correct code giving same output can be accepted.) SECTION D 31. a)Suggest the most suitable place (i.e., Block/Center) to install the server of this University with a suitable reason. Ans. Most suitable place to install the server is HR center, as this center has maximum number of computers. b)Suggest an ideal layout for connecting these blocks/centers for awired connectivity. 5
  • 240. 240 | P a g e Ans. c)Which device will you suggest to be placed/installed ineach of these blocks/centers to efficiently connect all thecomputers within these blocks/centers. Ans.Hub / Switch d)Suggest the placement of a Repeater in the network with justification. Ans. Repeater may be placed when the distance between 2 buildings is more than 100 meters. e)The university is planning to connect its admission office in Delhi, which is more than 1250km from university. Which type of network out of LAN, MAN, or WAN will be formed? Justify your answer. Ans.WAN, as the given distance is more than the range of LAN and MAN. 32. (a) Write the output of the code given below: def check(n1=1, n2=2): n1=n1+n2 n2+=1 print(n1,n2) check( ) check(3) 2+3
  • 241. 241 | P a g e Ans. 3 3 5 3 (1 mark for 3 3 and 1 mark for 5 3) (b) Write the following missing statements to complete the code: import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="root", password="tiger", database="Company") mycursor = _________ #Statement 1 eno=int(input("Enter Employee No :: ")) ename=input("Enter Name :: ") dept=input("Enter Dept :: ") salary=int(input("Enter Salary :: ")) query="insert into employee values({},'{}','{}',{})".format(eno,ename,dept,salary) ___________ #Statement 2 ____________ # Statement 3 print("Data Added successfully") Statement 1 – to form the cursor object Ans. con1.cursor() Statement 2 – to execute the command that inserts the record in the table Employee. Ans. mycursor.execute(query)
  • 242. 242 | P a g e Statement 3- to add the record permanently in the database Ans. con1.commit() (1 mark for each correct answer) (OR) (b) Predict the output of the code given below: s = 'MoHaNdAs GaNdHi' i = 0 while i<len(s): if (s[i].islower()): print(s[i].upper(),end=' ') if (s[i].isupper()): print(s[i].lower(),end=' ') i += 1 Ans. m O h A n D a S g A n D h I (1 mark for first 7 characters, 1 mark for next 7 characters) (b) The code given below reads the following record from the table named Employee and displays only those records who have salary greater than 15,000: ENo – integer EName – string Dept – string
  • 243. 243 | P a g e Salary – 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 Company. Write the following missing statements to complete the code: Statement 1 – to form the cursor object Statement 2 – to execute the query that extracts records of those employees whose salary is greater than 15,000. Statement 3- to read the complete result of the query (records whose salary is greater than 15,000) into the object named data, from the table employee in the database. import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="root",password="tiger", database="Company") mycursor = __________ #Statement 1 print("Employees whose salary greater than 15000 are : ") ___________________ #Statement 2 data = __________________ #Statement 3 for i in data: print(i) print() Ans: Statement 1:
  • 244. 244 | P a g e con1.cursor() Statement 2: mycursor.execute("select * from employee where salary>15000") Statement 3: mycursor.fetchall() (1 mark for each correct statement) 33. What is the role of newline argument in opening of CSV files ? Ans. The role of newline argument is to specify how would Python handle newline characters while working with CSV files. newline=’’ will ensure that no translation of EOL character takes place. (1 mark for correct answer) Write a Program in Python that defines and calls the following user defined functions: a) ADD() – To accept and add data of a book to a CSV file ‘book.csv’. Each record consists of a list with field elements as bookid, title and price to store book id, book title and book price respectively. b) COUNTR() – To count the number of records present in the CSV file named ‘book.csv’. Ans. import csv def ADD(): fout=open("record.csv","a",newline="n") 5
  • 245. 245 | P a g e wr=csv.writer(fout) empid=int(input("Enter Employee id :: ")) name=input("Enter name :: ") mobile=int(input("Enter mobile number :: ")) lst=[empid,name,mobile] ---------1/2 mark wr.writerow(lst) ---------1/2 mark fout.close() def COUNTR(): fin=open("record.csv","r",newline="n") data=csv.reader(fin) d=list(data) print(len(d)) fin.close() ADD() COUNTR() (½ mark for importing csv module 1 ½ marks each for correct definition of ADD() and COUNTR() ½ mark for function call statements) (OR) Give any one point of difference between a binary file and a csv file. Ans. Difference between binary file and csv file: (Any one difference may be given) Binary file: • Extension is .dat • Not human readable • Stores data in the form of 0s and 1s CSV file • Extension is .csv
  • 246. 246 | P a g e • Human readable • Stores data like a text file (1 mark for correct difference) Write a Program in Python that defines and calls the following user defined functions: (i) add() – To accept and add data of a toystore to a CSV file ‘toydata.csv’. Each record consists of a list with field elements as tid, tname and tprice to store toy id, toy name and toy price respectively. (ii) search()- To display the records of the toys whose price is more than 500. Ans. import csv def add(): fout=open("toydata.csv","a",newline='n') wr=csv.writer(fout) tid=int(input("Enter Toy Id :: ")) tname=input("Enter toy name :: ") tprice=int(input("Enter toy price :: ")) TD=[tid,tname,tprice] wr.writerow(TD) fout.close() def search(): fin=open("toydata.csv","r",newline='n') data=csv.reader(fin) found=False print("The Details are: ")
  • 247. 247 | P a g e for i in data: if int(i[2])>500: found=True print(i[0],i[1],i[2]) if found==False: print("Record not found") fin.close() add() print("Now displaying") search() (½ mark for importing csv module 1 ½ marks each for correct definition of add() and search() ½ mark for function call statements) SECTION E 34. Table : HEALTHYDRINKS Based on the data given, answer the following questions: i. Identify the most appropriate column, which can be considered as Primary key. Ans: Drinkcode (1 mark for correct answer) 1+1+2
  • 248. 248 | P a g e ii. If two columns are added and 2 rows are deleted from the table result, what will be the new degree and cardinality of the above table? Ans: New Degree: 6 New Cardinality: 4 (1/2 mark for correct degree and ½ mark for correct cardinality) (iii) Write the statements to: a. Insert the following record into the table DrinkCode – 107, Dname – Santara Special, Price – 25.00, Calorie – 130 Ans. INSERT INTO HEALTHYDRINKS VALUES(107,”Santara Special”,25.00,130); b. Increase the price of the juices by 3% whose name begins with ‘A’. Ans. UPDATE HEALTHYDRINKS SET PRICE=PRICE + 3/100*PRICE WHERE DNAME LIKE “A%”; (1 mark for each correct statement) OR (Option for part iii only) (iii) Write the statements to: a.Delete the record of those juices having calories more than 140. Ans. DELETE FROM HEALTHYDRINKS WHERE CALORIE > 140; b. Add a column Vitamins in the table with datatype as varchar with 20 characters.
  • 249. 249 | P a g e Ans. ALTER TABLE HEALTHYDRINKS ADD Vitamins VARCHAR(20); (1 mark for each correct statement) 35. As a Python expert, help Rehaan to complete the following code based on the requirement given: import ____________ #Statement 1 def update_data(): rec={} fin=open("record.dat","rb") fout=open("_____________") #Statement 2 found=False sid=int(input("Enter student id to update their marks :: ")) while True: try: rec=______________ #Statement 3 if rec["Student_id"]==sid: found=True rec["Marks"]=int(input("Enter new marks :: ")) pickle.____________ #Statement 4 else: pickle.dump(rec,fout) except: break if found==True: print("The mark of student id ",sid," has been updated.") else: print("No student with such id is found") 1+1+2
  • 250. 250 | P a g e fin.close() fout.close() (i) Which module should be imported in the program? (Statement 1) (ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2) (iii) Which statement should Rehaan fill in Statement 3 to read the data from the binary filerecord.dat, and in Statement 4 to write the updated data in the file, temp.dat? Ans: (i) pickle(1 mark for correct module) (ii) fout=open(‘temp.dat’, ‘wb’) (1 mark for correct statement) (iii) pickle.load(fin) pickle.dump(rec,fout) (1 mark for each correct statement) KENDRIYA VIDYALAYA SANGATHAN-CHENNAI REGION Class: XII session 2022-23 Computer Science(083) Sample Question Paper - III Maximum Marks:70 Time Allowed: 3 hours 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 Q35 against part C only. 8. All programming questions are to be answered using Python Language only.
  • 251. 251 | P a g e SECTION A Marks 1. Find output generated by the following code: p=10 q=20 p*=q//3 q+=p=q**2 print(p,q) 1 2. A database can have only one table(True/False) 1 3. Which one of the following refers to the copies of the same data (or information) occupying the memory space at multiple places. a) Data Repository b)Data Inconsistency c)Data Mining d)Data Redundancy 1 4. MAC address is of ___________ a) 24 bits b) 36 bits c) 42 bits d) 48 bits 1 5. Read following statement about features of CSV file and select which statement is TRUE? Statement1: Only database can support import/export to CSV format Statement2: CSV file can be created and edited using any text editor Statement3: All the columns of CSV file can be separated by comma only a. Statement 1 and statement 2 b. Statement 2 and statement 3 c. Statement 2 d. Statement 3 1
  • 252. 252 | P a g e 6. What is the output of the following program if the student.csv file contains following data? Student.csv Ronit, 200 Akshaj, 400 import csv d = csv.reader(“student.csv”) next (d) for row in d: print (row); 1 7. The command used to skip a row in a CSV file is A. next() B. skip() C. omit() D. bounce() 1 8. Inspecting the value at the stack’s top without removing it. a) peak operation b) insert operation c) pop operation d) push operation 1 9. Stacks serve major role in ______________ a) Simulation of recursion b) Simulation of linked list c) Simulation of limited resource allocation d) Simulation of all data 1 10. Which statement will give the output as : True from the following : a) >>>not -5 b) >>>not 5 c) >>>not 0 d) >>>not(5-1) 1 1
  • 253. 253 | P a g e 11. Give the output of the following code: >>>import math >>>math.ceil(1.03)+math.floor(1.03) a) 3 b) -3.0 c) 3.0 d) None of the above 1 12. The input() function always returns a value of ……………..type. a) Integer b) float c) string d) Complex 1 13. Directions: In the following questions, A statement of Assertion (A) is followed by a statement of Reason (R). Mark the correct choice as. (A) Both A and R are true and R is the correct explanation for A. (B) Both A and R are true and R is not correct explanation for A. (C) A is true but R is false. (D) A is false but R is true. Question. Assertion (A): A referential integrity is a system of rules of DBMS. Reason (R): It ensures that user don't accidently delete or change related data. 1 14. Directions: In the following questions, A statement of Assertion (A) is followed by a statement of Reason (R). Mark the correct choice as.
  • 254. 254 | P a g e (A) Both A and R are true and R is the correct explanation for A. (B) Both A and R are true and R is not correct explanation for A. (C) A is true but R is false. (D) A is false but R is true. Question. Assertion (A): The keyword DISTINCT is used with SELECT command. Reason (R): DISTINCT keyword eliminates duplicate rows 15. To include non-graphic characters in python, which of the following is used? a. Special Literals b. Boolean Literals c. Escape Character Sequence d. Special Literal – None 1 16. 50. Which of the following statement creates a tuple? a) t=[1,2,3,4] b) t={1,2,3,4} c) t=<1,2,3,4> d) t=(1,2,3,4) 1 17. Which of the following operation is supported in python with respect to tuple t? a) t[1]=33 b) t.append(33) c) t=t+t d) t.sum() 1 1 18. A ………………is a virtual table that does not really exist in its own right but is instead derived from one or more underlying base table(s) in DBMS a)SQL b) map c) view d) query 1
  • 255. 255 | P a g e SECTION B 19. Littu wrote a code function to display Fibonacci series. Correct the errors and rewrite it. def Fibonacci() nterms = int(input("How many terms? "))# first two terms n1, n2 = 0, 1 count = 0 if nterms<= 0:# check if the number of terms is valid print("Please enter a positive integer"); elifnterms == 1:# if there is only one term, return n1 print("Fibonacci sequence upto",nterms,":") print(n1); else:# generate fibonacci sequence print("Fibonacci sequence:") while count >nterms: print(n1) nth = n1 + n2 n1 = n2# update values n2 = nth count -= 1 2 20. What Are Cookies? Why are protocols neededin networking? OR Why a switch is called an intelligent hub? 2 21. a)Predict the output of the following code fragments: keepgoing = True x=100 while keepgoing : print (x) x = x - 10 if x < 50 : keepgoing = False b)counter = {} defaddToCounter(country): if country in counter: counter[country] += 1 else: counter[country] = 1 2
  • 256. 256 | P a g e addToCounter('China') addToCounter('Japan') addToCounter('china') print (len(counter)) 22. The Mname Column of a table Members is given below Mname Aakash Hirav Vinayak Sheetal Rajeev (i) SELECT Mname FROM Members WHERE Mname ' “%v"; (ii) SELECT Mname FROM Members WHERE Mname LIKE "%e%"; 2 23. a. Give three examples of DDL & DML commands? b. What is the referential integrity constraint? 2 24. How is HAVING clause similar to WHERE clause? How is HAVING clause differentfrom WHEREclause? Explain with the help of examples of each. OR Give one difference between ROLLBACK and COMMIT commands used in MySql. 2 25. What are python modules? Name some commonly used built-in modules in Python? OR What is difference between tell() and seek() methods? 2 SECTION C 26. Write a method in python to write multiple line of text contents into a text file mylife.txt. 3
  • 257. 257 | P a g e OR Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word 'India'. For example, if the content of the file is: India is the fastest-growing economy. India is looking for more investments around the globe. The whole world is looking at India as great market. Most of the Indians can foresee the heights that India is capable of reaching. The output should be 4. 27. a)Define candidate key, Primary key and Foreign Key. b)Write the SQL commands for the given questions below based on the table STUDENT. No Name Age Dept DOJ Fee Sex 1 Anu 24 CS 10-01-19 250 M 2 Manu 21 EE 09-02-17 480 M 3 Vinu 25 CS 23-01-19 400 M 4 Pallavi 26 IT 22-05-17 260 F 5 Sai 30 EE 16-03-20 310 F 6 Appu 34 BE 15-06-17 250 F 7 Minnu 23 CS 29-01-18 480 M i)To count the number of students with age<26. ii)To list the names of female students who are in EE department. 1+2 28. I)Consider the table given below. Write the output of a)SELECTdistinct(color, fruit), sum(rating) FROM medleys; b)SELECT distinct(fruit,color) FROM medleys WHERE color =”blue”; c)SELECT DISTINCT fruit FROM medleys; d)SELECT medley_id FROM medleys WHERE rating>10; MEDLEYS 3
  • 258. 258 | P a g e medley_id | color | fruit | rating ============================ 1 red apple 25 2 blue pear 5 3 green apple 12 4 red apple 10 5 purple kiwi 5 6 purple kiwi 50 7 blue kiwi 3 8 blue pear 9 II) Write a COMMAND to delete the column DOP from the table VEHICLE. Table have five columns V_ID, OWNER_NAME, ADDRESS, MODEL_NO, COLOUR, DOP. 29. Write a python program using function to find the largest element in a list and then reverse the list contents and display it. Don’t use in-built functions for the program. 3 30. Write a code for the STACK PUSH and POP implementation. a)Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a player by considering them as push and pop operations in a stack.Write a function to display the stack elements. OR Vedika has created a dictionary containing names and marks as key-value pairs of 5 students. Write a program, with separate user-defined functions to perform the following operations: Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is greater than 70. Pop and display the content of the stack. The dictionary should be as follows: d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95} Then the output will be: Umesh Vishal Ishika 3
  • 259. 259 | P a g e SECTION D 31. a. TellAbout Consultants are setting up a secured network for their office campus at Gurgaon for their day-to-day office and web-based activities. They are planning to have connectivity between three buildings and the head office situated in Mumbai. Answer the questions (i) to (iv) after going through the building positions in the campus and other details, which are given below : The given building blocks are named as Green, Blue and Red i. Suggest the most suitable place (i.e., building) to house the server of this organization. Also give a reason to justify your suggested location. 5
  • 260. 260 | P a g e ii. Suggest the placement of the following devices with justification: a. Repeater. b. Switch. iii. Suggest a cable layout of connections between the buildings inside the campus. iv. The organization is planning to provide a high speed link with its head office situated in Mumbai using a wired connection. Which of the following cables will be most suitable for this job. • Optical Fiber • Co-axial Cable • Ethernet Cable v. While connecting the devices two modems are found to be defected. What is the function of modem? 32. a) Write the output of the code def L1(D): CNT = 3 TOTAL = 0 for C in [7,5,4,6]: T = D[CNT] TOTAL = float (T) + C print(TOTAL) CNT-=1 TXT = ["20","50","30","40"] L1(TXT) b)The program to illustrate Insertion of records to database in Python is given below. Note the following to establish connectivity between Python and MYSQL: • Username is root • Password is tiger • The table exists in a MYSQL database named Company. import mysql.connector as mysql try: det=ps.connect(host='localhost',user='root',password='tiger',database=' Company') cmd=_________ #Statement 1 pid=input("Enter Product Id:") pn=input("Enter Product Name:") pr = input("Enter Product Rate:") md = input("Enter Mf. Date:") query="insert into products values('{}','{}',{},'{}')" 2+3
  • 261. 261 | P a g e .format(pid,pn,pr, md) ____________ #Statement 2 ____________ #Statement 3 det.close() print("Record Submitted") except Exception as e: print(e) OR a) Write the output of the code 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) The code given below search for a record using ID in Python The employee table consists of the following details: Employee Name Salary Designation City Birth Date Note the following to establish connectivity between Python and MYSQL: • Username is root • Password is tiger • The table exists in a MYSQL database named Company. import mysql.connector as mysql try: db=mysql.connect(host="localhost",user="root",password='tiger', database="Company")
  • 262. 262 | P a g e cmd=________. # Statement1 id=input("Enter Id you Want to Search?") q="Select * from employee where employeeid={0}".format(id) ___________ #Statement2 row=_______ #Statement3 if(row): print("Employee Name:",row[1]) print("Salary:", row[2]) print("Designation:",row[3]) print("City:", row[4]) print("Birth Date:", row[5]) else: print("Record Not Found....") db.close() except Exception as e: print(e) 33. What is pickle module and why we use this module? The table given below have the details of customer. The name of the file is cust.csv , write a code to insert multiple rows in the csv file. SNo Customer Name City Amount 1 Dhaval Anand 1500 2 Anuj Ahmedabad 2400 3 Mohan Vadodara 1000 4 Sohan Surat 700 OR What is aBinary File? Give examples. The detail of marks of class XII are stored in file named RESULTS.CSV. Raman, the Maths teacher wants to search the details of one student. Write a program to search the details based on name . 5 SECTION E
  • 263. 263 | P a g e 34. Consider the following DEPT and WORKER tables. Write SQL queries for (i) to and (iv) find outputs for queries Šv) to (viii): (i) To display Wno, Name, Gender from the table WORKER in descending order of Wno. (ii) To display the Name of all the FEMALE workers from the table WORKER . (iii) Write statements a) To display the Wno and Name of those workers from the table WORKER who are born between '1987-01-01' and '1991-12-01'. b) To count and display MALE workers who have joined after '1986-01- 01".. OR(only for part iii) (iii) Write the output for the given statements a) SELECT COUNT(*), DCODE FROM WORKER GROUP BY DCODE HAVING COUNT(*) > 1; b) SELECT DISTINCT DEPARTMENT FROM DEPT; 4
  • 264. 264 | P a g e 35. Arun, during Practical Examination of Computer Science, has been assignedan incomplete search() function to search in a pickled file student.dat. The Filestudent.dat is created by his Teacher and the following information is knownabout the file. • File contains details of students in [roll_no,name,marks] format. • File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each student is written in the binary file using dump(). Arun has been assigned the task to complete the code and print details of rollnumber 1. def search(): f = open("student.dat",____)#Statement-1 ____: #Statement-2 while True: rec = pickle.____#Statement-3 if(____): #Statement-4 print(rec) except: pass f.close() I). In which mode Arun should open the file in Statement-1? a) r b) r+ c) rb d) wb II). Identify the suitable code to be used at blank space in line marked as Statement2 a) if(rec[0]==1) 4
  • 265. 265 | P a g e b) for i in range(10) c) try d) pass III). Identify the function (with argument), to be used at blank space in line marked as Statement-3. a) load() b) load(student.dat) c) load(f) d) load(fin) IV). What will be the suitable code for blank space in line marked as Statement-4. a) rec[0]==2 b) rec[1]==2 c) rec[2]==2 d) rec[0]==1 Computer Science(083) Sample Question Paper – III Marking Scheme Maximum Marks:70 Time Allowed: 3 hours SECTION A 1) Find output generated by the following code: p=10 q=20 p*=q//3 q+=p=q**2 print(p,q) Answer: 60,480 1 2) A database can have only one table(True/False) Answer False 1
  • 266. 266 | P a g e No, database does not have a limit on number of tables. It depends on the disk space. 3) Which one of the following refers to the copies of the same data (or information) occupying the memory space at multiple places. a) Data Repository b)Data Inconsistency c)Data Mining d)Data Redundancy Answer: d)Data Redundancy 1 4) MAC address is of ___________ a) 24 bits b) 36 bits c) 42 bits d) 48 bits Answer: c)d) 48 bits 1 5) Read following statement about features of CSV file and select which statement is TRUE? Statement1: Only database can support import/export to CSV format Statement2: CSV file can be created and edited using any text editor Statement3: All the columns of CSV file can be separated by comma only a. Statement 1 and statement 2 b. Statement 2 and statement 3 c. Statement 2 d. Statement 3 Answer: c. Statement 2 1
  • 267. 267 | P a g e 6) What is the output of the following program if the student.csv file contains following data? Student.csv Ronit, 200 Akshaj, 400 import csv d = csv.reader(“student.csv”) next (d) for row in d: print (row); Answer: Akshaj, 400 1 7) The command used to skip a row in a CSV file is A. next() B. skip() C. omit() D. bounce() Answer: A. next() 1 8) Inspecting the value at the stack’s top without removing it. a) peak operation b) insert operation c) pop operation d) push operation a) peak operation 1 9) Stacks serve major role in ______________ a) Simulation of recursion b) Simulation of linked list c) Simulation of limited resource allocation d) Simulation of all data Answer: a) Simulation of recursion 1 10) Which statement will give the output as : True from the following : 1
  • 268. 268 | P a g e a) >>>not -5 b) >>>not 5 c) >>>not 0 d) >>>not(5-1) ans >>>not 0 11) Give the output of the following code: >>>import math >>> math.ceil(1.03)+math.floor(1.03) a) 3 b) -3.0 c) 3.0 d) None of the above answer: a) 3 1 12) The input() function always returns a value of ……………..type. a) Integer b) float c) string d) Complex answer: c)string 1 13) Directions: In the following questions, A statement of Assertion (A) is followed by a statement of Reason (R). Mark the correct choice as. (A) Both A and R are true and R is the correct explanation for A. (B) Both A and R are true and R is not correct explanation for A. (C) A is true but R is false. (D) A is false but R is true. 1
  • 269. 269 | P a g e Question. Assertion (A): A referential integrity is a system of rules of DBMS. Reason (R): It ensures that user don't accidently delete or change related data. Answer: A 14) Question. Assertion (A): The keyword DISTINCT is used with SELECT command. Reason (R): DISTINCT keyword eliminates duplicate rows Answer: A 1 15) To include non-graphic characters in python, which of the following is used? a. Special Literals b. Boolean Literals c. Escape Character Sequence d. Special Literal – None Answer Escape Character Sequence 1 16) Tuples can have various types of elements. Which of the following statement creates a tuple? a) t=[1,,2,3,4] b) t={1,2,3,4} c) t=<1,2,3,4> d) t=(1,2,3,4) answer d) 1 17) Which of the following operation is supported in python with respect to tuple t? a) t[1]=33 b) t.append(33) c) t=t+t d) t.sum() 1
  • 270. 270 | P a g e answer: c)t=t+t 18) A ………………is a virtual table that does not really exist in its own right but is instead derived from one or more underlying base table(s) in DBMS a)SQLb)map c) view d) query Answer:c) view 1 SECTION B 19) Littu wrote a code to display Fibonacci series. Correct the errors and rewrite it. def Fibonacci(): nterms = int(input("How many terms? "))# first two terms n1, n2 = 0, 1 count = 0 if nterms <= 0:# check if the number of terms is valid print("Please enter a positive integer") elif nterms == 1:# if there is only one term, return n1 print("Fibonacci sequence upto",nterms,":") print(n1) else:# generate fibonacci sequence print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + n2 n1 = n2# update values n2 = nth count += 1 2 20) What Are Cookies? Why are protocols needed? Cookies are text files with small pieces of data — like a username and password — that are used to identify your computer as you use a computer network. Specific cookies known as HTTP cookies are used to identify specific users and improve your web browsing experience. Data stored in a cookie is created by the server upon your connection. This data is labeled with an ID unique to you and your computer.When the cookie is exchanged between your computer and the network server, the server reads the ID and knows what information to specifically serve to you. In networks, communication occurs between the entities in different systems. Two entities cannot just send bit streams to each other and expect 2
  • 271. 271 | P a g e to be understood. For communication, the entities must agree on a protocol. A protocol is a set of rules that govern data communication. OR Why a switch is called an intelligent hub? A switch is called an intelligent hub because before simply forwarding a packet it checks for the intended destination for the packet and forwards it to that destination only, this is called packet filtering. While a hub forwards a packet to all the workstations in a network but only destination computer keeps it, rest all the computers drops that packet. 21) a)Predict the output of the following code fragments: keepgoing = True x=100 while keepgoing : print (x) x = x - 10 if x < 50 : keepgoing = False b)counter = {} def addToCounter(country): if country in counter: counter[country] += 1 else: counter[country] = 1 addToCounter('China') addToCounter('Japan') addToCounter('china') print (len(counter)) a)Output: 100 90 80 70 60 50 1+1
  • 272. 272 | P a g e b)3 22) The Mname Column of a table Members is given below Mname Aakash Hirav Vinayak Sheetal Rajeev (i) SELECT Mname FROM Members WHERE Mname ' “%v"; (ii) SELECT Mname FROM Members WHERE Mname LIKE "%e%"; Answer: The output of given commands will be as follows (i) Hirav, Rajeev (ii) Sheetal, Rajeev 2 23) a. Give three examples of DDL & DML commands? b. What is the referential integrity constraint? Answer Data Definition Language (DDL) commands: CREATE table ALTER table DROP table Data Manipulation Language (DML) commands: INSERT table UPDATE table DELETE bAnswer Foreign key constraints or referential integrity constraints. A logical rule about the values in one or more columns in one or more tables is known as a foreign key constraint, also known as a referential constraint or a referential integrity constraint. 1+1 24) How is HAVING clause similar to WHERE clause? How is HAVING clause differentfrom WHEREclause? Explain with the help of examples of each. Similarity: Both HAVING and WHERE clause are used for checking condition(s). Difference: WHEREclause is used for simple condition(s). HAVINGclause is used for conditions with group of values. 2
  • 273. 273 | P a g e e.g. WHERE clause: SELECT * FROM EMP WHERE DEPT = “PHYSICS “ ; HAVING clause : SELECT SUM(SALARY), DEPT FROM EMP GROUP BYDEPT HAVING COUNT(*) > 3; OR Give one difference between ROLLBACK and COMMIT commands used in MySql. • ROLLBACK command is used to end the current transaction and undo all the changes we made since the current transaction began. • Rollback is used to revert the last transaction in the Sql. ➢ COMMIT command is used to make all the changes permanent to the underlying database which we made during the current transaction. ➢ Commit is used to save all the recent transactions. 25) What are python modules? Name some commonly used built-in modules in Python? Ans: Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code. Some of the commonly used built-in modules are: os sys math random data time JSON 2
  • 274. 274 | P a g e OR What is difference between tell() and seek() methods? tell() seek() It returns the current position of cursor in file. Change the cursor position by bytes as specified by the offset Example: fout=open(“story.txt”,”w”) fout.write(“Welcome Python”) print(fout.tell( )) fout.close( ) Example: fout=open(“story.txt”,”w”) fout.write(“Welcome Python”) fout.seek(5) print(fout.tell( )) fout.close( ) Output : 4 Output : 5 SECTION C 26) Write a method in python to write multiple line of text contents into a text file mylife.txt. OR Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word 'India'. For example, if the content of the file is: India is the fastest-growing economy. India is looking for more investments around the globe. The whole world is looking at India as a great market. Most of the Indians can foresee the heights that India is capable of reaching. The output should be 4. def writelines(): outfile = open('myfile.txt','w') while True: line = input('Enter line: ') line += 'n' 3
  • 275. 275 | P a g e outfile.write(line) choice = input('Are there more lines y/n? ') if choice == 'n': break outfile.close() # Call the writelines function. writelines() or def count_word(): file = open('india.txt','r') count = 0 for line in file: words = line.split() for word in words: if word == 'India': count += 1 print(count) file.close() # call the function count_word(). count_word() 27) a)Define candidate key, Primary key and Foreign Key. Primary Key: There can be more than one candidate key in relation out of which one can be chosen as the primary key. For Example, STUD_NO, as 1+2
  • 276. 276 | P a g e well as STUD_PHONE, are candidate keys for relation STUDENT but STUD_NO can be chosen as the primary key (only one out of many candidate keys). Primary Key: It is a unique key. It can identify only one tuple (a record) at a time. It has no duplicate values, it has unique values. It cannot be NULL. Primary keys are not necessarily to be a single column; more than one the column can also be a primary key for a table. Eg:- STUDENT table SNO is a primary key SNO SNAME ADDRESS PHONE Foreign Key: If an attribute can only take the values which are present as values of some other attribute, it will be a foreign key to the attribute to which it refers. The relation which is being referenced is called referenced relation and the corresponding attribute is called referenced attribute and the relation which refers to the referenced relation is called referencing relation and the corresponding attribute is called referencing attribute. The referenced attribute of the referenced relation should be the primary key to it. For Example, STUD_NO in STUDENT_COURSE is a foreign key to STUD_NO in STUDENT relation. It acts as a primary key in one table and it acts as secondary key in another table. It combines two or more relations (table) at a time. They act as a cross-reference between the tables. For example, DNO is a primary key in the DEPT table and a non-key in EMP b)Write the SQL commands for the given questions below based on the table STUDENT. No Name Age Dept DOJ Fee Sex 1 Anu 24 CS 10-01-19 250 M
  • 277. 277 | P a g e 2 Manu 21 EE 09-02-17 480 M 3 Vinu 25 CS 23-01-19 400 M 4 Pallavi 26 IT 22-05-17 260 F 5 Sai 30 EE 16-03-20 310 F 6 Appu 34 BE 15-06-17 250 F 7 Minnu 23 CS 29-01-18 480 M a)To count the number of students with age<26. b)To list the names of female students who are in EE department. a)SELECT COUNT(*) FROM STUDENT WHERE Age<26; b)SELECT Name FROM STUDENT WHERE Sex=”F” AND Dept=”EE”; 28) I) Consider the table given below. Write the output of the SQL queries (a to d). a)SELECTdistinct(color, fruit), sum(rating) FROM medleys; b)SELECT distinct(fruit,color) FROM medleys WHERE color =”blue”; c)SELECT DISTINCT fruit FROM medleys; d)SELECT medley_id FROM medleys WHERE rating>10; medley_id | color | fruit | rating ============================ 1 red apple 25 2 blue pear 5 3 green apple 12 4 red apple 10 5 purple kiwi 5 6 purple kiwi 50 7 blue kiwi 3 3
  • 278. 278 | P a g e 8 blue pear 9 Answers: a) color | fruit | sum red apple 3 blue pear 14 blue kiwi 3 green apple 12 purple kiwi 55 b) fruit | color ========== Pear blue Kiwi blue c) fruit ==== Apple Pear Kiwi d) medley_id ======== 1 3 6
  • 279. 279 | P a g e II)Write a COMMAND to deletethe column DOP from the table VEHICLE. Table have five columns V_ID, OWNER_NAME,ADDRESS, MODEL_NO, COLOUR, DOP. ALTER TABLE VEHICLE DROP COLUMN DOP; 29) Write a python program using function to find the largest element in a list and then reverse the list contents and display it. Don’t use in-built functions for the program. E.g. M = [10, 24, 45, 90, 98] Output Largest in the give n List is 98 Reverse list: [98,90,45,24,10] def largest(L,n) : max = L[0] for i in range(1, n) : if L[i] > max : max =L[i] return max M = [10, 24, 45, 90, 98] n = len(M) max= largest(M, n) print ("Largest in the given List is", max) #reverse the list for i in range(n//2): M[i],M[len(M)-1-i] = M[len(M)-1-i], M[i]#swapping elements print('Reverse list:', M) 3
  • 280. 280 | P a g e 30) Write a code for the STACK PUSH and POP implementation. a)Write functions AddPlayer(player) and DeletePlayer(player) in python to add and remove a player by considering them as push and pop operations in a stack.Write a function to display the stack elements. OR Vedika has created a dictionary containing names and marks as key-value pairs of 5 students. Write a program, with separate user-defined functions to perform the following operations: Push the keys (name of the student) of the dictionary into a stack, where the corresponding value (marks) is greater than 70. Pop and display the content of the stack. The dictionary should be as follows: d={“Ramesh”:58, “Umesh”:78, “Vishal”:90, “Khushi”:60, “Ishika”:95} Then the output will be: Umesh Vishal Ishika Answers def AddPlayer(player): pn=input("enter player name:") player.append(pn) def DeletePlayer(player): if player==[]: print("No player found") else: return player.pop() def display(player): if player==[]: print("Stack is Empty") else: top = len(player)-1 print(player[top],"-Top") for i in range(top-1,-1,-1): print(player[i]) ------------------------------------------------------- def push(stk,item): stk.append(item) def Pop(stk): if stk==[]: return None else: return stk.pop() 3
  • 281. 281 | P a g e stk=[] d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95} for i in d: if d[i]>70: push(stk,i) while True: if stk!=[]: print(Pop(stk),end=" ") else: break SECTION D 31) a) TellAbout Consultants are setting up a secured network for their office campus at Gurgaon for their day-to-day office and web-based activities. They are planning to have connectivity between three buildings and the head office situated in Mumbai. Answer the questions (i) to (iv) after going through the building positions in the campus and other details, which are given below : The given building blocks are named as Green, Blue and Red Distances between various buildings Building GREEN to RED 110 Building GREEN to BLUE 45 Building BLUE to RED 65 Gurgaon to Head office 1760 GREEN RED BLUE HEAD OFFICE MUMBAI GURGAON CAMPUS
  • 282. 282 | P a g e Computers in the buildings Building GREEN 32 Building RED 150 Building BLUE 45 HEAD OFFICE 45 i. Suggest the most suitable place (i.e., building) to house the server of this organization. Also give a reason to justify your suggested location. ii. Suggest the placement of the following devices with justification: Repeater. Switch. iii. Suggest a cable layout of connections between the buildings inside the campus. iv. The organization is planning to provide a high speed link with its head office situated in Mumbai using a wired connection. Which of the following cables will be most suitable for this job ? Optical Fiber Co-axial Cable Ethernet Cable v. While connecting the devices two modems are found to be defected. What is the function of modem Answers: i. The most suitable place to install server is building “RED” because this building have maximum computer which reduce communication delay ii. Since the cabling distance between buildings GREEN, BLUE and RED are quite large, so a repeater each, would ideally be need along their path to avoid loss of signals during the course of data flow in their routes. 1 1 1 1
  • 283. 283 | P a g e In the layout a switch each, would be needed in all the buildings, to interconnect the group of cables from the different computers in each building. switch switch switch iii. Cable Layout----Bus Topology 1 BLUE GREEN RED GURGAON CAMPUS
  • 284. 284 | P a g e iv. Optical Fiber v. The modem will do the modulation and demodulation process. That is, it converts digital signal to analog signal at senders side and analog to digital at receivers side, respectively. 32) a)Write the output of the code def L1(D): CNT = 3 TOTAL = 0 for C in [7,5,4,6]: T = D[CNT] TOTAL = float (T) + C print(TOTAL) CNT-=1 TXT = ["20","50","30","40"] L1(TXT) b)The program to illustrate Insertion of records to database in Python is given below. Note the following to establish connectivity between Python and MYSQL: • Username is root • Password is tiger 2+3
  • 285. 285 | P a g e • The table exists in a MYSQL database named Company. import mysql.connector as mysql try: det=ps.connect(host='localhost',user='root',password='tiger',databa se='Company') cmd=_________#Statement 1 pid=input("Enter Product Id:") pn=input("Enter Product Name:") pr = input("Enter Product Rate:") md = input("Enter Mf. Date:") query="insert into products values('{}','{}',{},'{}')" .format(pid,pn,pr,md) ____________#Statement 2 ____________ #Statement 3 det.close() print("Record Submitted") except Exception as e: print(e) OR a)Write the output of the code def fun(s): k=len(s) m=" " for i in range(0,k): if(s[i].isupper()): m=m+s[i].lower()
  • 286. 286 | P a g e elif s[i].isalpha(): m=m+s[i].upper() else: m=m+'bb' print(m) fun('school2@com') b)The code given below search for a record using ID in Python The employee table consists of the following details: Employee Name Salary Designation City Birth Date Note the following to establish connectivity between Python and MYSQL: • Username is root • Password is tiger • The table exists in a MYSQL database named Company. import mysql.connector as mysql try: db=mysql.connect(host="localhost",user="root",password='tiger', database="Company") cmd=________.# Statement1 id=input("Enter Id you Want to Search?") q="Select * from employee where employeeid={0}".format(id) ___________#Statement2 row=_______#Statement3 if(row):
  • 287. 287 | P a g e print("Employee Name:",row[1]) print("Salary:", row[2]) print("Designation:",row[3]) print("City:", row[4]) print("Birth Date:", row[5]) else: print("Record Not Found....") db.close() except Exception as e: print(e) Answers: a) 47.0 35.0 54.0 26.0 b)Answer: Statement 1---det.cursor() Statement 2---cmd.execute(query) Statement 2---det.commit() OR a)SCHOOLbb SCHOOLbbbb b)Answer:
  • 288. 288 | P a g e Statement1---db.cursor() Statement2---cmd. .execute(q) Statement3: cmd.fetchone() 33) What is pickle module and why we use this module? Thetablegiven below have the details of customer.The name of the file iscust.csv, write a code to insert multiple rows in the csv file. SNo Customer Name City Amount 1 Dhaval Anand 1500 2 Anuj Ahmedabad 2400 3 Mohan Vadodara 1000 4 Sohan Surat 700 Pickle module provides us the ability to serialize and deserialize objects that is, it helps to convertobjects into bitstreams that can be stored in files and later utilized to recreate the original objects. For us, writing different kinds of objects into the binary file and later, reading the file's content is really challenging.The fact that some of the objects may have changing lengths makes this a tedious task. So we use the pickle module to solve this issue since it can handle dictionaries, sets, lists, tuples, classes, and more.It can store lists, Tuples, dictionaries, sets, classes etc. Program from csv import writer with open("cust.csv","a",newline="n") as f: dt = writer(f) while True: sno= int(input("Enter Serial No:")) cust_name = input("Enter customer name:") city = input("Enter city:") amt = int(input("Enter amount:")) dt.writerow([sno, cust_name, city, amt]) print("Record has been added.") print("Want to add more record?Type YES!!!") ch = input() ch = ch.upper() if ch=="YES": print("*************************") else: break 5
  • 289. 289 | P a g e OR What is a Binary File? Give examples. The detail of marks of class XII are stored in file named RESULTS.CSV. Raman, the Maths teacher wants to search the details of one student. Write a program to search the details based on name . A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length.Binary Files contain raw data so are not in human readable format. It can be read by using some special tool or program. Document files: .pdf, .doc, .xls etc. Image files: .png, .jpg, .gif, .bmp etc. Video files: .mp4, .3gp, .mkv, .avi etc. Audio files: .mp3, .wav, .mka, .aac etc. Database files: .mdb, .accde, .frm, .sqlite etc. Archive files: .zip, .rar, .iso, .7z etc. Executable files: .exe, .dll, .class etc b) import csv def searchname(): fobj=open('RESULT.CSV') stulist=csv.reader(fobj) name=input('Name to search? ') found=0 for stu in stulist: if name.upper()==stu[1]: print(stu[0], stu[1], stu[2], sep='t') found=1 break fobj.close() if found==0: print(name,'not found in the file') SECTION E 34) Consider the following DEPT and WORKER tables. Write SQL queries for (i) to and (iv) find outputs for queries (v) to (viii): 1+1 +2
  • 290. 290 | P a g e Table: DEPT DCODE DEPARTMENT CITY D01 D02 D03 D05 D04 MEDIA MARKETING INFRASTRUCTURE FINANCE HUMAN RESOURCE DELHI DELHI MUMBAI KOLKATA MUMBAI Table: WORKER WNO NAME DOJ DOB GENDER DCODE 1001 1002 1003 1007 1004 1005 1006 George K Ryma Sen Mohitesh Anil Jha aya Priya Manilasahai R Sahay 2013-09-02 2012-12-11 2013-02-03 2014-01-17 2012-12-09 2013-11-18 2014-06-09 1991-09-01 1990-12-15 1987-09-04 1984-10-19 1986-11-14 1987-03-31 1985-06-23 MALE FEMALE MALE MALE FEMALE MALE FEMALE D01 D03 D05 D04 D01 D02 D05 DOJ refers to date of joining and DOB refers to date of birth of workers. (i) To display Wno, Name, Gender from the table WORKER in descending order of Wno. (ii) To display the Name of all the FEMALE workers from the table WORKER. (iii) Write statements a) To display the Wno and Name of those workers from the table WORKER who are born between '1987-01-01' and '1991-12-01'.
  • 291. 291 | P a g e b) To count and display MALE workers who have joined after '1986-01- 01".. OR (iii) Write the output for the given statements a) SELECT COUNT(*), DCODE FROM WORKER GROUP BY DCODE HAVING COUNT(*) > 1; b) SELECT DISTINCT DEPARTMENT FROM DEPT; Answers: i) SELECT WNO, NAME, Gender, FROM WORKER ORDER BY WNO Desc; ii) SELECT NAME FROM WORKER WHERE GENDER = 'FEMALE'; iii) a) SELECT WNO, NAME, FROM WORKER WHERE DOB BETWEEN '1987-01-01' AND '1991-12-01'; b) SELECT count(*) FROM WORKER WHERE GENDER = 'MALE' AND DOJ > '1986-01-01'; OR iii) a) COUNT(*) DCODE 2D01 2D05 b) DISTINCT DEPARTMENT MEDIA MARKETING INFRASTRUCTURE FINANCE HUMAN RESOURCE
  • 292. 292 | P a g e 35) Arun, during Practical Examination of Computer Science, has been assignedan incomplete search() function to search in a pickled file student.dat. The Filestudent.dat is created by his Teacher and the following information is knownabout the file. • File contains details of students in [roll_no,name,marks] format. • File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each student is written in the binary file using dump(). Arun has been assigned the task to complete the code and print details of rollnumber 1. def search(): f = open("student.dat",_________)#Statement-1 ____: #Statement-2 while True: rec = pickle.____#Statement-3 if(____): #Statement-4 print(rec) except: pass ____ #Statement-5 I). In which mode Arun should open the file in Statement-1? a) r b) r+ c) rb d) wb II). Identify the suitable code to be used at blank space in line marked as Statement2 a) if(rec[0]==1) b) for i in range(10) c) try d) pass III). Identify the function (with argument), to be used at blank space in line marked as Statement-3. a) load() b) load(student.dat) c) load(f) d) load(fin) IV). What will be the suitable code for blank space in line marked as Statement-4. a) rec[0]==2 b) rec[1]==2 c) rec[2]==2 d) rec[0]==1 Answers 1+1 +2
  • 293. 293 | P a g e KENDRIYA VIDYALAYA SANGATHAN-CHENNAI REGION CLASS: XII Session 2022-2023 COMPUTER SCIENCE (083) SAMPLE QUESTION PAPER - IV Max. Marks: 70 Time Allowed: 3 Hrs. General Instructions: 1. This question paper contains five sections, Section A to E. 2. All questions are compulsory. 3. Section A have 18 question 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 Q35 against part C only. 8. All programming questions are to be answered using Python Language only. SECTION-A 1 Which of the following is not a valid identifier in Python? a)KV2 b) _main c) Hello_Dear1 d) 7 Sisters 1 2 A variable created or defined in a function body is known as… a)local b) global c) built-in d) instance 1 3 Suppose list1 = [0.5 * x for x in range(0,4)], list1 is a) [0, 1, 2, 3] b) [0, 1, 2, 3, 4] c) [0.0, 0.5, 1.0, 1.5] d) [0.0, 0.5, 1.0, 1.5, 2.0] 1 4 Which statement is not correct a)The statement x = x + 10 is a valid statement b)List slice is a list itself. c)Lists are immutable while strings are mutable. d)Lists and strings in pythons support two way indexing. 1 5 What will be the output of following code snippet: msg = “Hello Friends” msg [ : : -1] 1 I. c II. c III. a load(f) IV. d. rec[0]==1
  • 294. 294 | P a g e a)Hello b) Hello Friend c) 'sdneirF olleH' d) Friend 6 Which of the following function is used to write data in binary mode? a) write ( ) b) output ( ) c) dump ( ) d) send ( ) 1 7 Suppose a tuple T1 is declared as T1 = (10, 20, 30, 40, 50) which of the following is incorrect? a)print(T[1]) b) T[2] = -29 c) print(max(T)) d) print(len(T)) 1 8 What will be output of following: d = {1 : “SUM”, 2 : “DIFF”, 3 : “PROD”} for i in d: print (i) a)1 b) SUM c) 1 d) 3 2 DIFF SUM SUM 3 PROD 2 3 DIFF DIFF 3 3 PROD PROD 1 9 What will be output of following code: X = 50 def funct(X): X = 2 funct (X) print(„X is now: „, X) a) X is now: 50 b) X is now: 2 c) Error d) None of the above 1 10 To read the next line from the file object fob, we can use: a)fob.read(2) b) fob.read( ) c) fob.readline( ) d) fob.readlines( ) 1 11 TCP/IP stands for a) Transmission Communication Protocol / Internet Protocol b) Transmission Control Protocol / Internet Protocol c) Transport Control Protocol / Interwork Protocol d) Transport Control Protocol / Internet Protocol 1 12 An attack that encrypts files in a computer and only gets decrypted after paying money to the attacker.. a) Botnet b) Trojan c) Ransomware d) Spam 1 13 Which is known as range operator in MySQL. a) IN b) BETWEEN c) IS d) DISTINCT 1 14 If column “salary” of table “EMP” contains the dataset {10000, 15000, 25000, 10000, 25000}, what will be the output of following SQL statement? SELECT SUM(DISTINCT SALARY) FROM EMP; a) 75000 b) 25000 c) 10000 d) 50000 1 15 Which of the following functions is used to find the largest value from the given data 1
  • 295. 295 | P a g e in MySQL? a) MAX ( ) b) MAXIMUM ( ) c) LARGEST ( ) d) BIG ( ) 16 Name the clause used in query to place the condition on groups in MySQL? 1 Q17 and 18 are Assertion and Reasoning based questions.Mark the correct choice as a)A is true R is false b) A is false and R is true c) Both A and R are correct and R is correct explanation of A d) Both A and R are correct and R is not correct explanation of A 1 7 Assertion : The number of addresses used in IPv6 addressing method is 128 Reason : IPv6 address is a 128 bit unique address 1 1 8 Assertion : Delete command is used to remove rows or records from table. Reason : This command is used to remove records along with structure of the table from database 1 SECTION B 1 9 Rewrite the following code after removing the syntactical error(if any).Underline each correction: X=input("Enter a Number") If x % 2 =0: for i range (2*x): print i loop else: print "#" 2 2 0 Write two points of difference between Client side script and Server side script OR Write two advantages of Twisted pair cable. 2 2 1 Write the output of the following python code: def func(b): global x print ('Global x=',x) y=x+b x=7 z=x-b print ('Local x=' ,x) print ('y=' ,y) print ('z=' ,z) x=5 func(10) 2 2 2 What is the purpose of BETWEEN clause? 2 2 3 a) What do the following top level domains signify? (i) .com (ii) .org b)What is the use of VoIP? 2 2 Write the output of the following python code: 2
  • 296. 296 | P a g e 4 x=7 def new(): x=70 print("x=",x) print("x=",x) new() print("x=",x) OR Write the output of the following python code: Numbers =[9,18,27,36] for num in Numbers: for N in range(1,num%8): print(N,"$",end="") print() 2 5 Differentiate between equi join and cross join function in SQL with a example OR Categorize the folowing commands as DML or TCL COMMIT ,UPDATE , DELETE ,SAVE POINT 2 SECTION –C 2 6 a)Observe the table ‘Club’ given below:Table: Club Member_id Member_name Address Age Fee M001 Sujith New delhi 20 2000 M002 Nisha Trichy 18 3500 M003 Tarun Chennai 22 2100 M004 Arjun Coimbatore 19 3200 What is the cardinality and Degree of above table b) Write the queries of the i to iv based on the table: Shop given below Table: Shop Code Iname Qty Price Company 101 Digital Pad 120 11000 Xenita 105 Pen Drive 64 GB 500 7000 Hp 103 LED Screen 40' 50 25000 Samsung 104 Car GPS system 20 9000 Digiclick i) To display the details of all the item in ascending order of item names ii)To display item name and price of all those items whose price in range of 10000 to 30000 iii) To display max and min price of the table iv)To display the total amount of digiclick company 3 2 7 Write a function show_word() in python to read the contant of a text file 'words.txt' and display the entire content in upper case.example,if the file contain "I love my country ,i am proud to be indian" 3
  • 297. 297 | P a g e Then the function should display the output as: I LOVE MY COUNTRY ,I AM PROUD TO BE INDIAN OR Write a function mycount() in python to read the text file 'file.txt' and count the number of times "i" occurs in the file. example,if the file is 'file.txt'contains: "I love my country ,i am proud to be indian" The mycount()function should display the output as: "i occurs 4 times". 2 8 a) Write the output of the SQL queries i to iv based on the relations CARHUB and CUSTOMER given below: Table :CARHUB Vcode Vehicle Name Make Color Capacity Charges 100 Innova Toyota White 7 15 102 SX4 Suzuki Blue 4 14 104 C Class Mercedes Red 4 35 105 A-star Suzuki White 3 14 108 Indigo Tata Silver 3 12 Table : CUSTOMER CCode CName Vcode 1 Rajesh 101 2 Leela 108 3 John 105 4 Feroza shah 104 i)select vehiclename from carhub where color='white'; ii)select max,min from carhub; iii)select count(*),make carhub; iv)select cname,vehiclename,from customer,carhub where customer.vcode=carhub.vcode; b)Write the command to view all the tables in a database. 3 2 9 Write a python program using function to demonstrate random() with dictionary. Should create the dictionary of 5 keys:valus random character as key and ASCII as its value. 3 3 0 A list contains following records of students: [Adm_no,SName,DOB,Mobile] Write the following user defined function to perform given operations on the stack named 'Admission': i)PUSH() To insert an object containing admission number,student name and Mobile of the students who's birth year is after 2008 to the stack. If stack holds more than 3 elements show "stack is full" ii) POP() To pop the object from the stack and display them in stack one by one. For Example: If the lists of students detail are : ["20221017","Guru","20-7-2008","9988779988"] ["20221018","Ragunath","06-8-2009","9977889988"] ["20221019","Jenifer","31-12-2007","9988996677"] ["20221020","Priya","21-10-2009","9966557864"] 3
  • 298. 298 | P a g e The stack should contain ["20221017","Guru","9988779988"] ["20221018","Ragunath","9977889988"] ["20221020","Priya","9966557864"] The output should contain ["20221017","Guru","9988779988"] ["20221018","Ragunath","9977889988"] ["20221020","Priya","9966557864"] Stack is full OR Write a function in python, makepush(var) and makepop(var) ,to add a new variable and delete a variable from list of variables description, considering them to act as push and pop operations of the stack data structure. SECTION-D 3 1 Uplifting Skills Hub India is a knowledge and skill community which has an aim to uplift the standard of knowledge and skills in the society. It is planning to setup its training centers 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 (a) to (d) keeping in mind the distances between various locations and other given parameters. Shortest distances between various locations: Village 1 To B_Town 2 KM Village 2 To B_Town 1.0 KM Village 3 To B_Town 1.5 KM Village 1 To Village 2 3.5 KM Village 1 To Village 3 4.5 KM Village 2 To Village 3 2.5 KM A_city Head office to B_HUB 25 KM Number of Computers installed at various locations are as follows: B_Town 120 Village 1 15 Village 1 10 Village 1 15 A_city Office 6 Note: In Villages, there are community centers, in which one room has been given as training center to this organization to install computers. The organization has got financial support from the government and top IT companies. (a) 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. 5
  • 299. 299 | P a g e (b) Suggest the best wired medium and draw the cable layout (location to location) to efficiently connect various locations within the B_HUB. (c) Which hardware device will you suggest to connect all the computers within each location of B_HUB? (d) Which service/protocol will be most helpful to conduct live interactions of Experts from Head Office and people at all locations of B_HUB (e) Which type of network would be formed if B_HUB is connected to their A_city 3 2 a) What will be the output of the following python code? v=25 def fun(ch): v=50 print (v ,end=ch) print(v, end="*") fun("!") print(v) b)The code given below insert the record in the table employee: Empno – integer Name – string Dept – string Salary – integer Note the following to establish connectivity between Python and MYSQL: ❖ Username is host ❖ Password is root ❖ The table exists in a MYSQL database named company. ❖ The details (eno, Name, Dept and Salary) 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 employee. Statement 3- to add the record permanently in the database import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="host", password="root", database="company") mycursor=_________________ #Statement 1 eno=int(input("Enter Employee Number :: ")) name=input("Enter name :: ") dept=input("Enter department :: ") salary=int(input("Enter salary :: ")) querry="insert into employee values({},'{}','{}',{})".format(eno,name,dept,salary) ______________________ #Statement 2 ______________________ # Statement 3 5
  • 300. 300 | P a g e print("Data Added successfully") OR a) Predict the output of the code given below: str1=input ("Enter a string: ") str2="aAeEiIoOuU" v,c=0,0 for i in str1: if i in str2: v+=1 else: c+=1 print ("The given string contains { } vowels and { } consonants".format(v,c)) b) The code given below reads the following record from the table named employee and displays only those records who have salary greater than 65000: Empno – integer Name – string Dept – string Salary – integer Note the following to establish connectivity between Python and MYSQL: ❖ Username is host ❖ Password is root ❖ The table exists in a MYSQL database named company. Write the following missing statements to complete the code: Statement 1 – to form the cursor object Statement 2 – to execute the query that extracts records of those employee whose salary are greater than 65000. Statement 3- to read the complete result of the query (records whose salary are greater than 65000) into the object named data, from the table employee in the database. import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="host", password="root", database="company") mycursor=_______________ #Statement 1 print("Employee with salary greater than 65000 are : ") _________________________ #Statement 2 data=__________________ #Statement 3 for i in data: print(i) print()
  • 301. 301 | P a g e 3 3 What are the merits of using a csv file for storage? Write a Program in Python that defines and calls the following user defined functions: (i) ADD() – To accept and add data of an Library to a CSV file ‘books.csv’. Each record consists of a list with field elements as bno, name,Author and type to store Book number id, Book name, Author Name and Type of Book respectively. OR Give any one point of difference between a text file and a csv file. Write a Program in Python that defines and calls the following user defined functions: (i) update() – To accept and update data of a student to a CSV file ‘mark.csv’. Each record consists of a list with field elements as sid, sname and sclass to store student id, student name and student class respectively. 5 SECTION-E 3 4 Write SQL commands for the following queries based on the relation Teacher given below: Table: Teacher N o Name Ag e Departme nt Date_of_jo in Salar y Se x 1 Jugal 34 Computer 10-01-1997 1200 0 M 2 Sharmil a 31 History 24-03-1998 2000 0 F 3 Sandee p 32 Maths 12-12-1996 3000 0 M 4 Sangeet a 35 History 01-07-1999 4000 0 F 5 Rakesh 42 Maths 05-09-1997 2500 0 M 6 Shyam 50 History 27-06-1998 3000 0 M 7 Shiv Om 44 Computer 25-02-1997 2100 0 M 8 Shalak ha 33 Maths 31-07-1997 2000 0 F (i) To show all information about the teacher of Computer department. (ii) To list the names of all teachers with their date of joining in descending order. (iii) Write the statements to a) Delete the record of teacher age greater than 45 b)Increase the salary of teachers by 15% whose department is history OR 4
  • 302. 302 | P a g e a) To count the number of teachers with age less than 35 b)Add column QUALIFICATION in the table with datatype as varchar with 50 characters. 3 5 Mr.Mathew is a Python programmer. who has recently joined the company and given a task to write a python code to perform update operation in binary file(stud.dat)which contain admno(Admission no) and fee(Fee paid by student). He has succeeded in writing partial code and has missed out certain statement ,you as an expect of python have to provide the missing statements. import _______ #Statement 1 St={} Flag=0 File=open("____________","rb+) #Statement 2 Search=int(input("Enter Admission number whose fee is to be updated :")) Amt=int(input("How much to be incresed:")) try: while True: Try: Pos=file.tell() St=pickle.load(file) If st['admno']==search: st['fee']+=amt file._________(pos) #Statement 3 pickle.__________(st.file) #Statement 4 print("Record Updated") flag=1 expect EOFError: if flag=0: print("Record not found") file.close() (i) Which module should be imported in the program? (Statement 1) (ii) Write the correct statement required to open binary file (Statement 2) (iii) Which statement should be fill in Statement 3 to place the file pointer at specified position and statement 4 used to store the data 4
  • 303. 303 | P a g e KENDRIYA VIDYALAYA SANGATHAN-CHENNAI REGION CLASS: XII Session 2022-2023 COMPUTER SCIENCE (083) SAMPLE PAPER - IV MARKING SCHEME Section-A 1. d) 7 Sisters 1 2. a) local 1 3. c) [0.0, 0.5, 1.0, 1.5] 1 4. c) Lists are immutable while strings are mutable. 1 5. c) 'sdneirF olleH' 1 6. c) dump ( ) 1 7. b) T[2] = -29 1 8. a) 1 2 3 1 9. a) X is now: 50 1 10. c)fob.readline( ) 1 11. b) Transmission Control Protocol / Internet Protocol 1 12. c) Ransomware 1 13. b) BETWEEN 1 14. d) 50000 1 15. a) MAX ( ) 1 16. HAVING Clause 1 17. c) Both A and R are correct and R is correct explanation of A 1 18. a)A is true R is false 1 SECTION-B 19 x=input("Enter a Number") if x % 2= =0: error 1 for i in range (2*x): error 2 print (i) error 3 else: print ("#") error 4 1 2 ⁄ mark for each correct correction made and underlined.) 20 Client Side Script Server Side Script It is downloaded and run t client end It run at server end and result is send to client end(browser).
  • 304. 304 | P a g e It is browser dependent. It is not browser dependent Eg:JavaScript ,VBScript Eg:ASP,JSP ( 1 mark for each correct point of difference) OR Advantages of Twisted Pair cable • It is easy to install and maintain • It is very inexpensive • It can be easily connected • It is flexible ( 1 mark for each correct point) 21 Global x=5 Local x=7 y=15 z=-3 ( 2 mark for correct output) 22 Between clause is used to filter the record by providing the range in a column which contains only a numeric value Text,Data can also be used with BETWEEN clause Eg: select * from student where age between 15 and 18; (1 mark for explanation and 1 mark for correct qurey) 23 a) (i) .com - commercial business (ii) .org - organization (non profit) (1 2 ⁄ mark for each answer) b) Voice over Internet Protocol Transmission of voice and multimedia content over internet protocol(IP) network is through VoIP (1 mark for correct answer) 24 X=7 X=70 X=7 (1 mark for correct answer) OR 1 $
  • 305. 305 | P a g e 1 $ 2 $ 1 $ 2 $ 3 $ (1 mark for correct answer) 25 Join clause is used to combine records from two or more tables in a database they can be in two ways Equi Join and Cross Join Equi Join Cross Join/Cartesian Product It returns data from the table with matching values A product of two or more sets that consists of all combinations of records from two tables are joined Syntax: Select column from table1,table2 where table1.common_col=table2.common_col Syntax: Select column from table1,table2 (1 mark for each difference) OR DML -UPDATE ,DELETE TCL - COMMIT ,SAVE POINT (1 mark for each category ) SECTION -C 26 (a) Cardinality: 4 Degree: 5 (1 mark for correct answer) (b) (i) select * from item order by iname; (ii) select iname,price from shop where price between 10000 and 30000; (iii) select max,min from shop; (iv)select price*qty from shop where code=104; (1 2 ⁄ mark for each correct query ) 27 def show_word(): file=open( "words.txt",'r') Lines=file.readlines()
  • 306. 306 | P a g e for L in Lines: Print(L.upper()) File.close() ( ½ mark for correctly opening and closing the file ½ for readlines() ½ mark for correct loop 1 mark for using proper functions ½ mark for displaying the correct output) OR def mycount(): f=open("file.txt",'r') count=0 x=f.read() word=x.split() for i in word: if i=="I": count =count +1 print("my occurs",count,"times") f.close() mycount() ( ½ mark for correctly opening and closing the file ½ for read() ½ mar for correct loop ½ for correct if statement ½ mark for correctly incrementing count ½ mark for displaying the correct output) 28 a) i) Innova A-Star ii) Max Min 35 12
  • 307. 307 | P a g e iii) count(*) 5 iv) Customer Name Vehicle Name Leela Indigo John A-star Feroza Shah C Class (½ mark for displaying the correct output) b) Show Tables; (1 mark for correct query) 29 import random def createDict(): a={ } for i in range(5): x=random.randint(65,90) x=chr(x) n=random.randint(10,99) a.update({x:n}) return a dict =createDict() print ("Dictionary :",dict) (½ mark for correct function header 1 mark for correct loop 1 mark for using correct function ½ mark for return statement) 30 status =[ ] def Push_ele(stud): if len(status) ≤ 3 if stud[2] ==2008: L1=[stud[0],stud[1]]
  • 308. 308 | P a g e Status.append(L1) Else: Print("Stack is Full") def pop_ele(): num=len(status) while len(status)!=0: dele=status.pop() print(dele) num=num-1 else: print("Stack Empty") (1.5 marks for correct push_element() and 1.5 marks for correct pop_element()) OR def makepush(var): a=int(input("Enter Variable name:")) var.append(a) def makepop(var): if (var ==[ ]): print(stack empty") else: print("Deleted Variable:",var.pop()) (1.5 marks for correct makepush() and 1.5 marks for correct makepop()) SECTION D 31 (a) B_TOWN. Since it has the maximum number of computers and is closest to all other locations. (b)
  • 309. 309 | P a g e (c) Switch OR Hub (d) Videoconferencing OR VoIP OR any other correct service/protocol (e ) MAN- Metropolitan Area Network (1 Mark for each correct answer) 32 a) Output: 25*50!100!25 b)Output: Statement 1: con1.cursor( ) Statement 2: mycursor.execute(querry) Statement 3: con1.commit( ) (1 mark for each correct answer) OR a) Output Entered string : Tamilnadu The given string contains 4 vowels and 5 consonants b) Output: Statement 1: con1.cursor( ) Statement 2: mycursor.execute("select * from employee where salary >65000") Statement 3: mycursor.fetchall( ) (1 mark for each correct answer) 33 Ans: Merits of a csv file: ❖ It is human readable – can be opened in Excel and Notepad applications ❖ It is just like text file ❖ Easy to extract data as required. Program def addrecord(): try: csvfile=open('e:datasetdata.csv','a',newline='') csvobj=csv.write(csvfile)
  • 310. 310 | P a g e while True: bno=int(input("Book Number:")) name=input("Title of the Book:") author=input("Author Name :") type=input("Type of the Book :") Line=[bno,name,author,type] csvobj.writerow(Line) ch=input("More (Y/N)?") if ch=='N': break expect: csvfile.close( ) addrecord() (1 mark for merits 1 mark for importing csv module 1½ mark for each correct definition of ADD() ½ mark for function call statement ½ mark for return statement) OR a) Binary file: ❖ Extension is .txt ❖ Default file type ❖ Used to store character data CSV file ❖ Extension is .csv ❖ Human readable ❖ Stores data like a text file b) Program def modifysid( ): csvfile=open('e:datasetmark.csv','r',newline='') csvobj=csv.reader(csvfile) n=input("Enter the Student ID to be searched") l=[ ] k=[ ] for Line in csvobj: if Line[0] ==n: print("Record Found‼!") t=input("Enter Class")
  • 311. 311 | P a g e k=[Line[0],Line[1],Line[2],t] l.append(k) print (Line) else: l.append(Line) else: print ("Record not found") print(l) csvfile.close( ) csvfile=open('e:datasetmark.csv','w',newline='') csvobj=csv.witer(csvfile) for i in l: csvobj.writerow(i) csvfile.close() modifysid() (1 mark for difference 1 mark for importing csv module 1½ mark for each correct definition of search statement ½ mark for function call statement ½ mark for append( ) statement) SECTION E 34 Output: i) SELECT * FROM TEACHER WHERE DEPARTMENT ="COMPUTER"; II)SELECT NAME FROM TEACHER ORDER BY DATE_OF_JOIN DESC iii) a) Delete From Teacher Where Age≥45 b) UPDATE TEACHER SET SALARY=SALARY +(SALARY*0.15) WHERE DEPARTMENT="HISTORY"; OR iii) a)SELECT COUNT(*) FROM TEACHER WHERE AGE ≤ 35; b) ALTER TABLE TEACHER ADD(QUALIFICATION VARCHAR(50)); (1 mark for each correct statement) 35 i) Statement 1: import pickle ii) Statement 2: file =open ("stud.dat","rb+") iii) Statement 3: file.seek(pos) Statement 4: pickle.dump(st,file) (1 mark for each correct statement)
  • 312. 312 | P a g e KENDRIYA VIDYALAYA SANGATHAN -CHENNAI REGION Class: XII Session: 2022-23 Computer Science (083) Sample Question Paper - V Maximum Marks: 70 Time Allowed: 3 hours 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 Q35 against part c only. 8. All programming questions are to be answered using Python Language only. SECTION A 1. State True or False “Python identifiers are dynamically typed.” 1 2. Which of the following is an invalid operator in Python? (a)- (b) //= (c)in (d) =% 1 3. Given the following dictionary employee={'salary':10000,'age':22,'name':'Mahesh'} employee.pop('age') print(employee) What is output? a. {‘age’:22} b. {'salary': 10000, 'name': 'Mahesh'} c. {'salary':10000,'age':22,'name':'Mahesh'} d. None of the above 1
  • 313. 313 | P a g e 4. Consider the given expression: True and False or Not True Which of the following will be correct output if the given expression is evaluated? (a) True (b) False (c) NONE (d) NULL 1 5. What will the following code print? print(max("zoo 145 com")) a. 145 b. 122 c. z d. zoo 1 6. Which of the following statements is incorrect regarding the file access modes? a. ‘r+’ opens a file for both reading and writing. File object points to its beginning. b. ‘w+’ opens a file for both writing and reading. Overwrites the existing file if it exists and creates a new one if it does not exist. c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates a new one if it does not exist. d. ‘a’ opens a file for appending. The file pointer is at the end of the file if the file exists. 1 7. All aggregate functions except ___________ ignore null values in their input collection. a) Count (attribute) b) Count (*) c) Avg () d) Sum () 1 8. Which of the following SQL commands will change the attribute value of an existing tuple in a table? (a) insert (b) update (c) alter (d) change 1
  • 314. 314 | P a g e 9. Consider the following code that inputs a string and removes all special characters from it after converting it to lowercase. s = input("Enter a string") s = s.lower() for c in ',.;:-?!()'"': _________________ print(s) For eg: if the input is 'I AM , WHAT I AM", it should print i am what i am Choose the correct option to complete the code . a. s = s.replace(c, '') b. s = s.replace(c, '0') c. s = s.replace(c, None) d. s = s.remove(c) 1 10. Fill in the blank: An attribute or set of attributes in a table that can become a primary key is termed as - -------------------- a) Alternate key b) Candidate key c) Foreign key d) Unique key 1 11. Observe the following code snippet file = open(“station.txt”,”r”) try: …….. except EOFError: # When will this line execute …….. When will the line underlined execute? a. When the file is closed. b. This is a text file. c. When the file pointer is at the beginning of the file. 1
  • 315. 315 | P a g e d. When the file pointer has reached the end of file. 12. Fill in the blank: The SELECT statement when combined with __________ clause, is used for pattern matching (a) Order by (b) distinct (c) like (d) between 1 13. ______is a standard network protocol used to transfer files from one host to another host over a TCP-based network, such as the Internet. a) TCP b) IP c) FTP d) SMTP 1 14. What will the following expression be evaluated to in Python? 2**3**2+15//3 a) 69 b) 517 c) 175 d) 65 1 15. Identify the invalid SQL aggregate function from the following a) sum b)max c)min d) add 1 16. Identify the invalid method to get the data from the result set of query fetched by a cursor object mycursor. a) mycursor.fetchone() b) mycursor.fetchall() c) mycursor.fetchmany() d) mycursor.fetchnow() 1 Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as (a) Both A and R are true and R is the correct explanation for A (b) Both A and R are true and R is not the correct explanation for A (c) A is True but R is False (d) A is false but R is True
  • 316. 316 | P a g e 17. Assertion (A):-global keyword is used inside a function to enable the function alter the value of a global variable. Reasoning (R):- A global variable can not be accessed by a function without the use of global keyword. 1 18. Assertion (A): The ‘with’ block clause is used to associate a file object to a file. Reason (R): It is used so that at the end of the ‘with’ block the file resource is automatically closed. 1 SECTION B 19. Shraddha wrote the code that, prints the sum of numbers between 1 and the number, for each number till 10.She could not get proper output. i = 1 while (i <= 10): # For every number i from 1 to 10 sum = 0 # Set sum to 0 for x in range(1,i+1): sum += x # Add every number from 1 to i print(i, sum) # print the result a) What is the error you have identified in this code ? b) Rewrite the code by underlining the correction/s. 2 20. Write two points of difference between star and bus topology. OR Differentiate Web browser and Webserver. 2 21. a) Write the output of the code snippet. txt = "Time, will it come back?" x = txt.find(",") y = txt.find("?") print(txt[x+2:y]) b) The score of a student in a test is stored as a Python tuple. The test had 3 questions, with some questions having subparts whose scores are recorded separately.Give the output of the code snippet. 1 1
  • 317. 317 | P a g e score = (6, (5, (2, 1), 8), (4, 3, (1, 3, 2))) print (score [2][2]) 22. What is a not null constraint in SQL? Give example to illustrate. 2 23. (a) Write the full forms of the following: (i) SMTP (ii) URL (b)Differentiate http and https protocols. 2 24. Predict the output of the Python code given below: value = 50 def display(N): global value value = 25 if N%7==0: value = value + N else: value = value - N print(value, end="#") display(20) print(value) OR Predict the output of the Python code given below: l=[] for i in range(4): l.append(2*i+1) print(l[::-1]) 2
  • 318. 318 | P a g e 25. Differentiate betweendrop anddelete commands in SQL with appropriate example. OR What is the use of order by clause in SQL ? Give example. 2 SECTION C 26 i) Considering the following table SALEORDER which stores the name of items sold on a day ,give the output of the query that follows:- DATE ITEM 12-09-2022 RICE 12-09-2022 RICE 12-09-2022 SUGAR 12-09-2022 RICE 12-09-2022 COFFEE 12-09-2022 COFFEE 12-09-2022 TEA SELECT ITEM,COUNT(*) FROM SALEORDER GROUP BY ITEM HAVING COUNT(*)>1; ii)Writethe outputofthequeries(a)to(d)basedonthetable BOOK,given below: (a) SELECT PUBLISHER,PRICE FROM BOOK WHERE QTY>=10; (b) SELECT BOOK_NAME, TYPE FROM BOOK WHERE BOOK_NAME LIKE 'T%'; (c) SELECT SUM(PRICE) FROM BOOK WHERE PUBLISHER IN (‘EPB’,’TMH’); (d) SELECT MIN(QTY) FROM BOOK WHERE PRICE>500; Book_Id Book_Name Publisher Price Type Qty F0001 The Tears EEE 750 Fiction 10 F0002 Thunderbolts EEE 700 Fiction 5 T0001 Let us C++ EPB 250 Text 10 T0002 C++ Brain TMH 325 Text 5 C0001 Fast Cook EPB 350 Cookery 8 1+2
  • 319. 319 | P a g e 27. Write a Python function which reads a text file “poem.txt” and prints the number of vowels in each line of that file, separately. Eg: if the content of the file “poem.txt” is The plates will still shift and the clouds will still spew. The sun will slowly rise and the moon will follow too. The output should be 6 7 6 9 OR Write a Python program that writes the reverse of each line in “input.txt” to another text file “output.txt”. Eg: if the content of input.txt is: The plates will still shift and the clouds will still spew. The sun will slowly rise and the moon will follow too. The content of “output.txt” should be: tfihs llits lliw setalp ehT .weps llits lliw sduolc eht dna esir ylwols lliw nus ehT .oot wollof lliw noom eht dna 3 28 (a) Write the outputs of the SQL queries (i) to (iii) based on the tables VEHICLES and TRAVELS Table: VEHICLE VCODE VEHICLETYPE PERKM V01 VOLVO BUS 150 3
  • 320. 320 | P a g e V02 AC DELUXE BUS 125 V03 ORDINARY BUS 80 V04 CAR 18 V05 SUV 30 Table: TRAVEL CNO CNAME TRAVELDATE KM VCODE NOP 101 Arun 2015-12-13 200 V01 32 102 Balaji 2016-06-21 120 V03 45 103 Vignesh 2016-04-23 450 V02 42 104 Selva 2016-01-13 80 V02 40 105 Anupam 2015-02-10 65 V04 2 106 Tarun 2016-04-06 90 V05 4 ● PERKM is Freight Charges per kilometer. ● Km is kilometers Travelled ● NOP is number of passengers travelling in vehicle. (i) SELECT VCODE, COUNT(*) AS NUMTRIPS FROM TRAVEL GROUP BY VCODE; (ii) SELECT CNAME, TRAVEL.VCODE, VEHICLETYPE FROM VEHICLE, TRAVEL WHERE VEHICLE.VCODE = TRAVEL.VCODE AND NOP >= 30; (iii) SELECT MAX(TRAVELDATE), MIN(TRAVELDATE) FROM TRAVEL ; (iv) SELECT VEHICLETYPE FROM VEHICLE WHERE VEHICLETYPE LIKE “%BUS”; (b) Write the command to view the structure of the table TRAVEL.
  • 321. 321 | P a g e 29 Write a function sumcube(L) to test if an element from list L is equal to the sum of the cubes of its digits ie it is an ”Armstrong number”. Print such numbers in the list. If L contains [67,153,311,96,370,405,371,955,407] The function should print 153,370,371,407 3 30 Vikram has a list containing 10 integers. You need to help him to create a program with separate user defined functions to perform the following operations based on this list. ● pushnum() to Traverse the content of the list and push the numbers that are divisible by 5 into a stack. ● popnum() to Pop and display the content of the stack and display “Stack underflow” if the stack is empty. For Example: If the sample Content of the list is as follows: N=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38] Sample Output of the code should be: 35 55 10 OR Write a function in Python, Push(Ride) where , Ride is a dictionary containing the details of Cab ride , Ride={driver: billamt }. The function should push the names of those driver names in the stack,INCENTIVE who have billed greater than 400. Also display the count of names pushed into the stack For example: If the dictionary contains the following data: Ride={‘Raghu’:389,’Anbu’:560,’Siraj’:768,’Syed’:450 }. The stack INCENTIVE should contain [‘Anbu’,’Siraj’,’Syed’] The output should be: The count of Drivers in the stack is 3 3 SECTION D
  • 322. 322 | P a g e 31 University of Correspondence in Allahabad is setting up the network between its different wings (units). There are four wings named as Science(S), Journalism(J), Arts(A) and Home Science(H). Distance between various wings Wing A to Wing S 100 m Wing A to Wing J 200 m Wing A to Wing H 400 m Wing S to Wing J 300 m Wing S to Wing H 100 m Wing J to Wing H 450 m Number of Computers in each wing Wing A 150 Wing S 10 Wing J5 Wing H 50 (a) Suggest the suitable topology and draw the cable layout to efficiently connect various blocks / wings of network. (b) Where should the server be housed ? justify your answer. (c) What kind of network (LAN/MAN/WAN) will be formed? (d) Suggest the fast and very effective wired communication medium to connect another sub office at Kanpur, 670 km far apart from above network. (e) Suggest the placement of the following devices in the network. i. Hub/ Switch ii. Repeater 5
  • 323. 323 | P a g e 32 (a) Find and write the output of the following Python code: def Display(str): m="" for i in range(0,len(str)): if(str[i].isupper()): m=m+str[i]+'*' elif str[i].islower(): m=m+'@' elif str[i]==' ' : m=m+'#' print(m) Display('LION king') (b) The code given below inserts the following record in the table Player: PNo – integer Name – string NoofGames– int Goals – integer Note the following to establish connectivity between Python and MYSQL: a. Username is root b. Password is sport c. The table exists in a MYSQL database named Football. d. The details (Pno,Name,NoofGames,Goals) are to be accepted from the user. Write the following missing statements to complete the code: (a)Statement 1 – to form the cursor object (b)Statement 2 – to execute the command that inserts the record in the table Player. (c) Statement 3- to add the record permanently in the database import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="root", password="sport", database="football") mycursor=_________________ #Statement 1 pno=int(input("Enter player Number :: ")) name=input("Enter player name :: ") noofgames=int(input("Enter no of games :: ")) goals=int(input("Enter Goals :: ")) querry="insert into player values({},'{}',{},{})".format(pno,name,noofgames,goals) ______________________ #Statement 2 2+3
  • 324. 324 | P a g e ______________________ # Statement 3 print("Data Added successfully") OR (a) Predict the output for the following code def repToInt(repString, base): decimal = 0 exponent = len(repString) - 1 for digit in repString: decimal = decimal + int(digit) * base ** exponent exponent -= 1 return decimal print(repToInt("100011",2)) (b) Considering a table Product stored in database Inventory,complete the Mysql connectivity code to delete the products whose name is beginning with “M” Product table has following attributes –(pno,pname,price,qty) Note the following to establish connectivity between Python and MYSQL: a. Username is root b. Password is stock Write the following missing statements to complete the code: (a)Statement 1 – to form the cursor object (b)Statement 2 – the query string to perform the required operation (c) Statement 3- to execute the query import mysql.connector as msc mydb = msc.connect(host = "localhost",user = "root",password = "stock", database = "inventory") crs =__________________ # Statement 1 query2=___________________________________________#Statement 2 crs.___________________________ #Statement 3 mydb.close()
  • 325. 325 | P a g e 33 a) Mention the advantage of csv files. b) Write the functions to performthe required operations on csv files and call the functions appropriately. i) Newgadget() to add the details of new gadgets in csv file gadget.csv which stores records in the format.Deviceno,name,price,brand Get the input from the user. ii) Countgadget() to read the csv file ‘gadget.csv’ and count the devices whose brand is “Samsung” OR a) Is CSV file a text file? b) Write the functions to perform the required operations on csv files and call the functions appropriately. i) Namelist() to add the participants for Music competition in a csv file “music.csv” where each record has the format Name,class,age ii) Display() to read the csv file ‘music.csv’ and display the participants under 15 years of age 5 SECTION E 34 In a database School, there are two tables given below: STUDENTS RNO NAME CLASS SEC ADDRESS ADMNO PHONE 1 MEERA 12 D A-26 1211 3245678 2 MEENA 12 A NULL 1213 NULL 3 KARISH 10 B AB-234 1214 4567890 4 SURAJ 11 C ZW12 1215 4345677 SPORTS ADMNO GAME COACHNAME GRADE 1215 CRICKET RAVI A 1213 VOLLEYBALL AMANDEEP B 1211 VOLLEYBALL GOWARDHAN A 1214 BASKET BALL TEJASWINI B Based on the given information answer the questions which follows, (i) Identify the attribute used as foreign key in table sports (ii) What is the degree of the table students? (iii) Write SQL statements to perform the following operations a) To display the name and game played by sports students b) To change the address and phonenumber of “Meena ” to B 54, 8864113 (OR only to subpart iii) 1+1 +2
  • 326. 326 | P a g e iii) a) To make the field class in table STUDENTS mandatory while inserting data b) To delete the game CRICKET from SPORTS TABLE. 35 Aditi is a Python programmer. He has written a code and created a binary file employee.dat with employeeid, ename and salary. The file contains 10 records. He now has to update a record based on the employee id entered by the user and update the salary. The updated record is then to be written in the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat. If the employee id is not found, an appropriate message should to be displayed. As a Python expert, help him to complete the following code based on the requirement given above: import _______ #Statement 1 def update_data(): rec={} fin=open("employee.dat","rb") fout=open("_____________") #Statement 2 found=False eid=int(input("Enter employee id to update their salary :: ")) while True: try: rec=______________ #Statement 3 if rec["Employee id"]==eid: found=True rec["Salary"]=int(input("Enter new salary :: ")) pickle.____________ #Statement 4 1+1 +2
  • 327. 327 | P a g e else: pickle.dump(rec,fout) except: break if found==True: print("The salary of employee id ",eid," has been updated.") else: print("No employee with such id is not found") fin.close() fout.close() (i) Which module should be imported in the program? (Statement 1) (ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2) (iii) Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat and in Statement 4 to write the updated data in the file, temp.dat?
  • 328. 328 | P a g e Computer Science (083) Sample Paper – V Marking scheme Maximum Marks: 70 Time Allowed: 3 hours 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 Q35 against part c only. 8. All programming questions are to be answered using Python Language only. SECTION A 1. State True or False “Python identifiers are dynamically typed.” Ans: True 1 2. Which of the following is an invalid operator in Python? (a)- (b) //= (c)in (d) =% Ans: d) =% 1 3. Given the following dictionary employee={'salary':10000,'age':22,'name':'Mahesh'} employee.pop('age') print(employee) What is output? a. {‘age’:22} b. {'salary': 10000, 'name': 'Mahesh'} c. {'salary':10000,'age':22,'name':'Mahesh'} d. None of the above Ans: b. {'salary': 10000, 'name': 'Mahesh'} 1
  • 329. 329 | P a g e 4. Consider the given expression: True and False or Not True Which of the following will be correct output if the given expression is evaluated? (e) True (f) False (g) NONE (h) NULL Ans:b)False 1 5. What will the following code print? print(max("zoo 145 com")) a. 145 b. 122 c. z d. zoo Ans: C )z 1 6. Which of the following statements is incorrect regarding the file access modes? a. ‘r+’ opens a file for both reading and writing. File object points to its beginning. b. ‘w+’ opens a file for both writing and reading. Overwrites the existing file if it exists and creates a new one if it does not exist. c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates a new one if it does not exist. d. ‘a’ opens a file for appending. The file pointer is at the end of the file if the file exists. Ans:c. . ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates a new one if it does not exist. 1 7. All aggregate functions except ___________ ignore null values in their input collection. a) Count (attribute) b) Count (*) c) Avg () d) Sum () Ans: b.Count(*) 1 8. Which of the following SQL commands will change the attribute value of an existing tuple in a table? (e) insert (f) update (g) alter (h) change Ans: b. update 1
  • 330. 330 | P a g e 9. Consider the following code that inputs a string and removes all special characters from it after converting it to lowercase. s = input("Enter a string") s = s.lower() for c in ',.;:-?!()'"': _________________ print(s) For eg: if the input is 'I AM , WHAT I AM", it should print i am what i am Choose the correct option to complete the code . a. s = s.replace(c, '') b. s = s.replace(c, '0') c. s = s.replace(c, None) d. s = s.remove(c) Ans: a. s = s.replace(c, '') 1 10. Fill in the blank: An attribute or set of attributes in a table that can become a primary key is termed as --------------------- e) Alternate key f) Candidate key g) Foreign key h) Unique key Ans: b.Candidate key 1 11. Observe the following code snippet file = open(“station.txt”,”r”) try: …….. except EOFError: # When will this line execute …….. When will the line underlined execute? 1
  • 331. 331 | P a g e a. When the file is closed. b. This is a text file. c. When the file pointer is at the beginning of the file. d. When the file pointer has reached the end of file. Ans: d.When the file pointer has reached the end of file 12. Fill in the blank: The SELECT statement when combined with __________ clause, is used for pattern matching (e) Order by (f) distinct (g) like (h) between Ans: c) like 1 13. ______is a standard network protocol used to transfer files from one host to another host over a TCP-based network, such as the Internet. e) TCP f) IP g) FTP h) SMTP Ans: FTP 1 14. What will the following expression be evaluated to in Python? 2**3**2+15//3 e) 69 f) 517 g) 175 h) 65 Ans: b) 517 1 15. Identify the invalid SQL aggregate function from the following b) sum b)max c)min d) add Ans:d.add 1
  • 332. 332 | P a g e 16. Identify the invalid method to get the data from the result set of query fetched by a cursor object mycursor. e) mycursor.fetchone() f) mycursor.fetchall() g) mycursor.fetchmany() h) mycursor.fetchnow() Ans: d. mycursor.fetchnow() 1 Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as (e) Both A and R are true and R is the correct explanation for A (f) Both A and R are true and R is not the correct explanation for A (g) A is True but R is False (h) A is false but R is True 17. Assertion (A):-global keyword is used inside a function to enable the function alter the value of a global variable. Reasoning (R):- A global variable can not be accessed by a function without the use of global keyword. Ans: c. A is True but R is False 1 18. Assertion (A): The ‘with’ block clause is used to associate a file object to a file. Reason (R): It is used so that at the end of the ‘with’ block the file resource is automatically closed. Ans: a) Both A and R are true and R is the correct explanation for A 1 SECTION B 19. Shraddha wrote the code that, prints the sum of numbers between 1 and the number, for each number till 10.She could not get proper output. i = 1 while (i <= 10): # For every number i from 1 to 10 sum = 0 # Set sum to 0 for x in range(1,i+1): sum += x # Add every number from 1 to i print(i, sum) # print the result c) What is the error you have identified in this code ? 2
  • 333. 333 | P a g e d) Rewrite the code by underlining the correction/s. Ans: a.The code will cause infinite loop b.Correction i = 1 while (i <= 10): # For every number i from 1 to 10 sum = 0 # Set sum to 0 for x in range(1,i+1): sum += x # Add every number from 1 to i print(i, sum) i+=1 (1 mark for error detection,1 mark for error correction) 20. Write two points of difference between star and bus topology. Bus Star In Bus topology all devices are connected to a common backbone wire known as Bus. All data is transmitted through the Bus. In star topology each device is connected to a central node, which is a networking device like a hub or a switch. Less easy to find faults in the network Easy to find and rectify fault Easy to install and configure High initial cost of wires Failure of bus brings the network down Failure of one line will not bring the entire network down. (1 mark each for any two difference) OR Differentiate Web browser and Webserver. WEBSERVER: A web server is a computer that runs websites. It's a computer program that distributes web pages as they are requisitioned. The basic objective of the web server is to store, process and deliver web pages to the users. This intercommunication is done using Hypertext Transfer Protocol (HTTP). WEB BROWSER: 2
  • 334. 334 | P a g e The web browser is the software application used to access resources on the internet. E.g. Chrome, Firefox,Internet Explorer etc. (1 mark each for correct difference) 21. a) Write the output of the code snippet. txt = "Time, will it come back?" x = txt.find(",") y = txt.find("?") print(txt[x+2:y]) Ans: will it come back (1 mark for correct answer) b) The score of a student in a test is stored as a Python tuple. The test had 3 questions, with some questions having subparts whose scores are recorded separately.Give the output of the code snippet. score = (6, (5, (2, 1), 8), (4, 3, (1, 3, 2))) print (score [2][2]) Ans: (1, 3, 2) (1 mark for correct answer) 1 1 22. What is a not null constraint in SQL? Give example to illustrate. A not null constraint is a restriction that does not allow a column to be left blank during insertion.In other words it makes the field a mandatory one. If a field pname is given a constraint pname varchar notnull , The value for the field should necessarily be provided in an insert query. (1 mark for explanation 1 for illustration) 2 23. (c) Write the full forms of the following: (i) SMTP (ii) URL 2
  • 335. 335 | P a g e Ans: Simple Mail Transfer Protocol Universal Resource Locator/Uniform resource locator) ½ mark for each correct abbreviation (d)Differentiate http and https protocols. Hyper text transfer protocol is used to transmit web pages over the internet.It does not provide encryption.(Insecure connection) Hyper text transfer protocol secure is used to transmit web pages over the internet.It provides encryption when data is transmitted between web client and server.It has Secure Sockets Layer certificate which provides encryption. (Secure connection) (1 mark for correct differentiation) 24. Predict the output of the Python code given below: value = 50 def display(N): global value value = 25 if N%7==0: value = value + N else: value = value - N print(value, end="#") display(20) print(value) Ans: 50#5 (1 mark for 50# and 1 mark for 5) OR Predict the output of the Python code given below: l=[] for i in range(4): l.append(2*i+1) print(l[::-1]) 2
  • 336. 336 | P a g e Ans:[7, 5, 3, 1] (1/2 mark for each correct values) 25. Differentiate betweendrop anddelete commands in SQL with appropriate example. Drop: DDL command used to remove a database object Syntax: Drop table tname; Delete:DML command used to remove rows from a table Syntax: Delete from tablename [ where Condn] (1 mark for difference ,1 mark for correct example) OR What is the use of order by clause in SQL ? Give example. The order by clause is used to arrange the table based on asc /desc order of a particular field. Syntax: select fn1,fn2 … from tablename order by fn1 [asc/desc]; Select name,marks from student order by marks asc; [any appropriate example] (1 mark for difference 1 mark for correct example) 2 SECTION C 26 j) Considering the following table SALEORDER which stores the name of items sold on a day ,give the output of the query that follows:- DATE ITEM 12-09-2022 RICE 12-09-2022 RICE 12-09-2022 SUGAR 12-09-2022 RICE 12-09-2022 COFFEE 12-09-2022 COFFEE 12-09-2022 TEA SELECT ITEM,COUNT(*) FROM SALEORDER GROUP BY ITEM HAVING COUNT(*)>1; ITEM COUNT(*) RICE 3 1+2
  • 337. 337 | P a g e COFFEE 2 1 MARK FOR CORRECT OUTPUT ii)Writethe outputofthequeries(a)to(d)basedonthetable BOOK,given below: (a) SELECT PUBLISHER,PRICE FROM BOOK WHERE QTY>=10; PUBLISHER PRICE EEE 750 EPB 250 (b)SELECT BOOK_NAME, TYPE FROM BOOK WHERE BOOK_NAME LIKE 'T%'; BOOK_NAME TYPE The Tears Fiction Thunderbolts Fiction (c)SELECT SUM(PRICE) FROM BOOK WHERE PUBLISHER IN (‘EPB’,’TMH’); SUM(price) 575 (d)SELECT MIN(QTY) FROM BOOK WHERE PRICE>500; MIN(QTY) 5 1/2 mark for each of the outputs Book_Id Book_Name Publisher Price Type Qty F0001 The Tears EEE 750 Fiction 10 F0002 Thunderbolts EEE 700 Fiction 5 T0001 Let us C++ EPB 250 Text 10 T0002 C++ Brain TMH 325 Text 5 C0001 Fast Cook EPB 350 Cookery 8 27. Write a Python function which reads a text file “poem.txt” and prints the number of vowels in each line of that file, separately. Eg: if the content of the file “poem.txt” is The plates will still shift and the clouds will still spew. The sun will slowly rise and the moon will follow too. The output should be 3
  • 338. 338 | P a g e 6 7 6 9 PROGRAM def vowelsinline(): f=open("poem.txt","r") l=f.readlines() vc=0 for i in l: vc=0 for c in i: if c.upper() in "AEIOU": vc+=1 print(vc) f.close() vowelsinline() Ans: ( ½ mark for correctly opening and closing the file ½ for readlines() ½ mar for correct loop ½ for correct if statement ½ mark for correctly incrementing count ½ mark for displaying the correct output) OR Write a Python program that writes the reverse of each line in “input.txt” to another text file “output.txt”. Eg: if the content of input.txt is: The plates will still shift and the clouds will still spew. The sun will slowly rise
  • 339. 339 | P a g e and the moon will follow too. The content of “output.txt” should be: tfihs llits lliw setalp ehT .weps llits lliw sduolc eht dna esir ylwols lliw nus ehT .oot wollof lliw noom eht dna PROGRAM def reverseline(): f=open("poem.txt","r") o=open("output.txt","w") l=f.readlines() for i in l: o.write(i[::-1]) f.close() o.close() reverseline() (½ mark for correctly opening and closing the file ½ for readlines() ½ mark for correct loops ½ for correct if statement ½ mark for correctly incrementing counts ½ mark for displaying the correct output)
  • 340. 340 | P a g e 28 (c) Write the outputs of the SQL queries (i) to (iii) based on the tables VEHICLES and TRAVELS Table: VEHICLE VCODE VEHICLETYPE PERKM V01 VOLVO BUS 150 V02 AC DELUXE BUS 125 V03 ORDINARY BUS 80 V04 CAR 18 V05 SUV 30 Table: TRAVEL CNO CNAME TRAVELDATE KM VCODE NOP 101 Arun 2015-12-13 200 V01 32 102 Balaji 2016-06-21 120 V03 45 103 Vignesh 2016-04-23 450 V02 42 104 Selva 2016-01-13 80 V02 40 105 Anupam 2015-02-10 65 V04 2 106 Tarun 2016-04-06 90 V05 4 ● PERKM is Freight Charges per kilometer. ● Km is kilometers Travelled ● NOP is number of passengers travelling in vehicle. (i) SELECT VCODE, COUNT(*) AS NUMTRIPS FROM TRAVEL GROUP BY VCODE; (ii) SELECT CNAME, TRAVEL.VCODE, VEHICLETYPE 3
  • 341. 341 | P a g e FROM VEHICLE, TRAVEL WHERE VEHICLE.VCODE = TRAVEL.VCODE AND NOP >= 30; (iii) SELECT MAX(TRAVELDATE), MIN(TRAVELDATE) FROM TRAVEL ; (iv) SELECT VEHICLETYPE FROM VEHICLE WHERE VEHICLETYPE LIKE “%BUS”; [1/2 mark for each correct output] (d) Write the command to view the structure of the table TRAVEL. Ans: DESC TRAVEL [1 mark for correct query] 29 Write a function sumcube(L) to test if an element from list L is equal to the sum of the cubes of its digits ie it is an ”Armstrong number”. Print such numbers in the list. If L contains [67,153,311,96,370,405,371,955,407] The function should print 153,370,371,407 Ans: def sumcube(L): for i in L: t=i s=0 while t: r=t%10 s=s+r**3 t=t//10 if s==i: print(i,end=' ') 3
  • 342. 342 | P a g e #main L=[67,153,311,96,370,405,371,955,407] sumcube(L) (½ mark for correct function header 1 mark for correct loop 1 mark for correct if statement ½ mark for return statement) Note: Any other relevant and correct code may be marked 30 Vikram has a list containing 10 integers. You need to help him to create a program with separate user defined functions to perform the following operations based on this list. ● pushnum() to Traverse the content of the list and push the numbers that are divisible by 5 into a stack. ● popnum() to Pop and display the content of the stack and display “Stack underflow” if the stack is empty. For Example: If the sample Content of the list is as follows: N=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38] Sample Output of the code should be: 35 55 10 Ans: def pushnum(Num,stk): for i in Num: if i%5==0: stk.append(i) def popnum(stk): if len(stk): print("The elements of Stack") while stk: print(stk.pop()) else: print("Stack Empty") 3
  • 343. 343 | P a g e L=[10, 13, 34, 55, 21, 79, 98, 22, 35, 38] stk=[] pushnum(L,stk) popnum(stk) (1.5 marks for correct push() and 1.5 marks for correct pop()) OR Write a function in Python, Push(Ride) where , Ride is a dictionary containing the details of Cab ride , Ride={driver: billamt }. The function should push the names of those driver names in the stack,INCENTIVE who have billed greater than 400. Also display the count of names pushed into the stack For example: If the dictionary contains the following data: Ride={‘Raghu’:389,’Anbu’:560,’Siraj’:768,’Syed’:450 }. The stack INCENTIVE should contain [‘Anbu’,’Siraj’,’Syed’] The output should be: The count of Drivers in the stack is 3 Ans: def push(Ride): for i in Ride: if Ride[i]>400: incentive.append(i) print("The count of drivers in the stack",len(incentive)) print("The stack is") for i in incentive[::-1]: print(i)
  • 344. 344 | P a g e #main Ride={'Raghu':389,'Anbu':560,'Siraj':768,'Syed':450 } incentive=[] push(Ride) (1 mark for correct function header 1 mark for correct loop ½ mark for correct If statement ½ mark for correct display of count) SECTION D 31 University of Correspondence in Allahabad is setting up the network between its different wings (units). There are four wings named as Science(S), Journalism(J), Arts(A) and Home Science(H). Distance between various wings Wing A to Wing S 100 m Wing A to Wing J 200 m Wing A to Wing H 400 m Wing S to Wing J 300 m Wing S to Wing H 100 m Wing J to Wing H 450 m Number of Computers in each wing Wing A 150 Wing S 10 Wing J 5 Wing H 50 (a) Suggest the suitable topology and draw the cable layout to efficiently connect various blocks / wings of network. Ans: Star topology 100m 100m 300 m 5 H S A J
  • 345. 345 | P a g e (1/2 mark for topology and ½ mark for layout) (b) Where should the server be housed ? justify your answer. Ans:Wing A ,as it has maximum number of computers(1/2 mark for correct wing and ½ mark for justification) (c) What kind of network (LAN/MAN/WAN) will be formed? Ans:LAN Ans: 1 mark for correct answer (d) Suggest the fast and very effective wired communication medium to connect another sub office at Kanpur, 670 km far apart from above network. Ans:Optical Fibre( 1 mark for correct answer) (e) Suggest the placement of the following devices in the network. i. Hub/ Switch ii. Repeater Ans: Hub/Switch In All Wings Repeater: Between S and J blocks as the distance is > 100m ( 1 mark for correct answer) 32 (c) Find and write the output of the following Python code: def Display(str): m="" for i in range(0,len(str)): if(str[i].isupper()): m=m+str[i]+'*' elif str[i].islower(): m=m+'@' elif str[i]==' ' : m=m+'#' print(m) Display('LION king') Ans:L*I*O*N*#@@@@ (1 marks for first 8 characters and 1 mark for consecutive 5 correct characters in the output) (d) The code given below inserts the following record in the table Player: PNo – integer Name – string NoofGames– int Goals – integer 2+3
  • 346. 346 | P a g e Note the following to establish connectivity between Python and MYSQL: a. Username is root b. Password is sport c. The table exists in a MYSQL database named Football. d. The details (Pno,Name,NoofGames,Goals) are to be accepted from the user. Write the following missing statements to complete the code: (a)Statement 1 – to form the cursor object (b)Statement 2 – to execute the command that inserts the record in the table Player. (C ) Statement 3- to add the record permanently in the database import mysql.connector as mysql def sql_data(): con1=mysql.connect(host="localhost",user="root", password="sport", database="football") mycursor=_________________ #Statement 1 pno=int(input("Enter player Number :: ")) name=input("Enter player name :: ") noofgames=int(input("Enter no of games :: ")) goals=int(input("Enter Goals :: ")) querry="insert into player values({},'{}',{},{})".format(pno,name,noofgames,goals) ______________________ #Statement 2 ______________________ # Statement 3 print("Data Added successfully") Ans: mycursor=con1.cursor() #Statement 1 mycursor.execute(querry) #Statement 2 con1.commit() #statement3 OR (c) Predict the output for the following code def repToInt(repString, base): decimal = 0 exponent = len(repString) - 1 for digit in repString: decimal = decimal + int(digit) * base ** exponent exponent -= 1 return decimal print(repToInt("100011",2)) Ans: 35 (2 marks for correct answer) (d) Considering a table Product stored in database Inventory,complete the Mysql connectivity code to delete the products whose name is beginning with “M”
  • 347. 347 | P a g e Product table has following attributes –(pno,pname,price,qty) Note the following to establish connectivity between Python and MYSQL: c. Username is root d. Password is stock Write the following missing statements to complete the code: (a)Statement 1 – to form the cursor object (b)Statement 2 – the query string to perform the required operation (c) Statement 3- to execute the query import mysql.connector as msc mydb = msc.connect(host = "localhost",user = "root",password = "stock", database = "inventory") crs =__________________ # Statement 1 query2=___________________________________________#Statement 2 crs.___________________________ #Statement 3 mydb.close() Ans: Statement1: mydb.cursor() Statement2: query2=”Delete from product where name like “M%”;” Statement 3: crs.execute(query2) (1 mark for each correct statement) 33 c) Mention the advantage of csv files. d) Write the functions to performthe required operations on csv files and call the functions appropriately. i) Newgadget() to add the details of new gadgets in csv file gadget.csv which stores records in the format, Deviceno,name,price,brandGet the input from the user. ii) Countgadget() to read the csv file ‘gadget.csv’ and count the devices whose brand is “Samsung” Ans: a) • CSV is human readable and easy to edit manually • CSV is processed by almost all existing applications. • CSV is smaller in size • CSV is considered to be standard format (Any 2 correct advantage 1 mark) b) import csv def Newgadget(): fout=open("gadget.csv","a",newline="n") wr=csv.writer(fout) devno=int(input("Enter Device no :: ")) name=input("Enter name :: ") price=int(input("Enter Price :: ")) 5
  • 348. 348 | P a g e brand=input("Enter brand :: ") lst=[devno,name,price,brand] ---------1/2 mark wr.writerow(lst) ---------1/2 mark fout.close() def Countgadget(): fin=open("gadget.csv","r",newline="n") data=csv.reader(fin) count=0 for i in data: if i[3].upper()=='SAMSUNG': count=count+1 print("Number of Samsung Gadgets",count) fin.close() #main Newgadget() Countgadget() (1 mark for advantage ½ mark for importing csv module 1 ½ marks each for correct definition of Newgadget() Countgadget(), ½ mark for function call statements) OR c) Is CSV file a text file? d) Write the functions to perform the required operations on csv files and call the functions appropriately. iv) Namelist() to add the participants for Music competition in a csv file “music.csv” where each record has the formatName,class,age v) Display() to read the csv file ‘gadget.csv’ and display the participants under 15 years of age Ans: a) Yes CSV is a special text file where each line represents a record with fields separated by commas. b) import csv def Namelist(): fout=open("music.csv","a",newline="n") wr=csv.writer(fout) name=input("Enter name :: ") clas=input("Enter Class :: ")) age=int(input("Enter age :: ") lst=[name,clas,age]--------1/2 mark wr.writerow(lst) ---------1/2 mark fout.close() def Display(): fin=open("music.csv","r",newline="n") data=csv.reader(fin)
  • 349. 349 | P a g e print("Participants under 15 years of age") for i in data: if int(i[2])<15: print(i) fin.close() #main Namelist() Display() (1 mark for difference ½ mark for importing csv module 1 ½ marks each for correct definition of Namelist() and display() ½ mark for function call statements ) SECTION E 34 In a database School, there are two tables given below: STUDENTS RNO NAME CLASS SEC ADDRESS ADMNO PHONE 1 MEERA 12 D A-26 1211 3245678 2 MEENA 12 A NULL 1213 NULL 3 KARISH 10 B AB-234 1214 4567890 4 SURAJ 11 C ZW12 1215 4345677 SPORTS ADMNO GAME COACHNAME GRADE 1215 CRICKET RAVI A 1213 VOLLEYBALL AMANDEEP B 1211 VOLLEYBALL GOWARDHAN A 1214 BASKET BALL TEJASWINI B Based on the given information answer the questions which follows, (iv) Identify the attribute used as foreign key in table sports (v) What is the degree of the table students? Ans: i) ADMNNO is used as foreign key in table sports ii) Degree of Student table-7 ( 1 mark each for each correct answer) (vi) Write SQL statements to perform the following operations 1+1 +2
  • 350. 350 | P a g e c) To display the name and game played by sports students d) To change the address and phonenumber of “Meena ” to B 54, 8864113 iii) a) Select NAME,GAME from STUDENTS S,SPORTS T where S.ADMNNO=T.ADMNNO b)update students set address=’B 54’ ,Phone=’ 8864113’ where name=”MEENA” (1 Mark each for correct query) (OR only to subpart iii) vi)a) To make the field class in table STUDENTS mandatory while inserting data b)To delete the game CRICKET from SPORTS TABLE. Ans: a) ALTER TABLE STUDENTS MODIFY CLASS VARCHAR(20) NOT NULL; b) DELETE FROM STUDENTS WHERE GAME=’CRICKET’ (1 Mark each for correct query) 35 Aditi is a Python programmer. He has written a code and created a binary file employee.dat with employeeid, ename and salary. The file contains 10 records. He now has to update a record based on the employee id entered by the user and update the salary. The updated record is then to be written in the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat. If the employee id is not found, an appropriate message should to be displayed. As a Python expert, help him to complete the following code based on the requirement given above: import _______ #Statement 1 def update_data(): rec={} fin=open("employee.dat","rb") fout=open("_____________") #Statement 2 found=False eid=int(input("Enter employee id to update their salary :: ")) while True: try: rec=______________ #Statement 3 if rec["Employee id"]==eid: found=True
  • 351. 351 | P a g e rec["Salary"]=int(input("Enter new salary :: ")) pickle.____________ #Statement 4 else: pickle.dump(rec,fout) except: break if found==True: print("The salary of employee id ",eid," has been updated.") else: print("No employee with such id is not found") fin.close() fout.close() (i) Which module should be imported in the program? (Statement 1) (ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2) (iii) Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat and in Statement 4 to write the updated data in the file, temp.dat? Ans: i) Pickle module(1 mark for correct module) ii) fout=open(“temp.dat”,”wb”)(1 mark for mode) iii) pickle.load(fin) pickle.dump(rec,fout) (1 mark each for correct statements) **********