12 Computer Science
12 Computer Science
Content Contributors
Sh. Deepak Chand PM SHRI, K V Tagore Grden
Mrs. Savita Chourisya , PGT CS PM SHRI, KV JNU
Mrs. Monika Rani K V AAI Rangpuri
Sh. Pawan Kumar Ruhela K V Shahdra
Mrs. Kanchan Khurana PM SHRI K V Sec-5 Dwarka
Sh. Pawanjeet Singh PM SHRI K V Delhi Cantt- 2
Sh. Tara Chand Meena PM SHRI KV Delhi Cantt-3
Sh. Vijay Chawala PM SHRI K V Pitampura
h. Aman Singh PM SHRI Sanik Vihar
Mrs. Vani Kochhar PM SHR I KV Arjangarh
2|Page
INDEX
COMPUTER NETWORKS
7. 91-113
3|P age
Computer Science (2024-25)CLASS XII Code No. 083
Computer Science- Class XII
1. Learning Outcomes
2. Distribution of Marks:
Periods
Unit No. Unit Name Marks
Theory Practical
1 Computational Thinking and 40 70 50
Programming – 2
2 Computer Networks 10 15 …
3 Database Management 20 25 20
Total 70 110 70
4|Page
● Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file,
opening a file using with clause, writing/appending data to a text file using write() and
writelines(), reading from a text file using read(), readline() and readlines(), seek and tell
methods, manipulation of data in a text file
● Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb,
wb+, ab, ab+), close a binary file, import pickle module, dump() and load() method,
read, write/create, search, append and update operations in a binary file
● CSV file: import csv module, open / close csv file, write into a csv file using
writer(),writerow(),writerows() and read from a csv file using reader()
● Data Structure: Stack, operations on stack (push & pop), implementation of stack using
list.
5|Page
insert, update, delete queries using cursor, display data by using connect(), cursor(),
execute(), commit(), fetchone(), fetchall(), rowcount, creating database connectivity
applications, use of %s format specifier or format() to perform queries
4. Practical
Marks
S.No Unit Name (Total=30)
Lab Test:
1. Python program (60% logic + 20% 8
1
documentation + 20% code quality)
Report file:
Minimum 15 Python programs.
2 SQL Queries – Minimum 5 sets 7
usingone table / two tables.
Minimum 4 programs based on
Python – SQL connectivity
4 Viva voce 3
6|Page
KENDRIYA VIDYALAYA SANGATHAN (DELHI REGION)
STUDENT SUPPORT MATERIAL
CLASS XII
SUBJECT: - COMPUTER SCIENCE (083)
REVISION OF CLASS XI
Some key features of Python Programming Language: -
Interpreter based programming language: - Python is an interpreter-based programming
language which execute the source code line by line.
Ease to code and read: - It is very easy to write the code in python and indented blocks also
make it easy to read.
Free and Open Source: - Python programming language is available free to use for commercial
purposes.
Portable: - The code written in Python can be executed on different machine.
Object Oriented Support: - It supports both procedural and OOPs.
Dynamic typing: - Variable data type can be decided at runtime.
Robust Standard library: - Extensive standard library available for anyone to use.
Different ways to run the python code: -
Interactive Mode: - Interactive mode is used when a user wants to run one single line or one
block of code within command line known as python shell.
Script Mode: - Script mode is used when a user is working with more than one single code or
block of code. The block of code is written within a text file with file extension “.py”
Indentation
Indentation refers to the blank spaces at the beginning of a code line. Generally indentation
indicates the starting of a block of an if……else , if…..elif, for……, while……… or user defined
function started with the keyword “def”.
Comments
In python programming language comments are a type of non-executable statement that is
used for documentation purpose. It is of two types: -
o Single line comment
o Multiline comment
7|Page
Single line comment: - Single line comment starts with the symbol “#”.
Multiline comment: - Multiline comments always enclosed with triple quotes i.e. ‘ “”” “”” ’
8|Page
15. global To declare a global variable
16. if To make a conditional statement
17. import To import a variable
18. in To check if a value is present in a list, tuple etc.
19. is To test if two variables are equal
20. lambda To create an anonymous function
21. None Represents a null value
22. nonlocal To declare a non-local variable
23. not A logical operator
24. or A logical operator
25. pass A null statement, a statement that will do nothing
26. raise To raise an exception
27. return To exit a function and return a value
28. True Boolean value, result of comparison operations
29. try To make a try...except statement
30. while To create a while loop
31. with Used to simplify exception handling
32. yield To return a list of values from a generator
Identifiers (Names):- Identifiers are the names given to different parts of the program viz
variables, objects, classes, functions, lists, dictionaries and so forth. Python is a case sensitive
language as it treats upper and lower-case characters differently.
The naming rules for Python identifiers are:-
It must only be a non-keyword with no space in between.
It must be made up of only letters, numbers, and underscore(_).
It cannot begin with a number, although they can contain numbers.
The following are some valid identifiers:-
Name DATE8_3_4 Age _DS
_amount ADD14 T2Z0T _STU
The following are some invalid identifiers:-
N-ame contains special character – (hyphen) other than A-Z, a-z and
_(underscore)
83Date Starting with a digit
break reserved word/ keyword
A.ge contains special character dot(.)
Literals:- Literals are the values supported by a python program and are often referred
to/ by an identifier. Python support following types of literals: -
String Literals: - A string literal is a sequence of characters surrounded by
quotes (single, double or triple). String literals can either be single or multi-line
strings.
9|Page
Escape Sequences: - In strings, you can include non-graphic characters through
escape sequences. Escape sequences are given in following tables: -
Relational Operators: - These are used to compare two values and returns a True or
False.
Operator Name Example
== Equal to/ comparison 20==20 is True
!= Not Equal to 20!=20 is False
> Greater than 20>7 is True
< Less than 20<7 is False
>= Greater than or Equal to 20>=7 is True
<= Less than or Equal to 20<=20 is True
Logical Operators: - Logical operators are generally used to combine two or more
conditions within if or loop and returns True or False.
Operator Description Example
and Returns True if both statements are 20==20 and 30>10
True It will return True
or Returns True if any or both the 20==20 and 30<10
statements are True It will return True
not Reverses the result not(22==22) is False
Membership Operators: - Python’s membership operators test for membership in a
sequence such as string, list or tuple. There are two membership operators as
explained below: -
Operator Description Example
in Returns True if a x = ["apple", "banana"]
sequence with the print("banana" in x)
specified value is present # returns True because a sequence
in the object with the value "banana" is in the list
not in Returns True if a x = ["apple", "banana"]
sequence with the print("pineapple" not in x)
specified value is not # returns True because a sequence
present in the object with the value "pineapple" is not in
the list
Identity Operators: - Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the same memory location:
Operator Description Example
is Returns True x = ["apple", "banana"]
if both y = ["apple", "banana"]
variables are z = x
the same print(x is z)
object # returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object
as y, even if they have the same content
print(x == y)
# to demonstrate the difference between "is"
11 | P a g e
and "==": this comparison returns True because
x is equal to y
is not Returns True x = ["apple", "banana"]
if both y = ["apple", "banana"]
variables are z = x
not the same print(x is not z)
object # returns False because z is the same object as
x
print(x is not y)
# returns True because x is not the same object
as y, even if they have the same content
print(x != y)
# to demonstrate the difference between "is
not" and "!=": this comparison returns False
because x is equal to y
Operator Precedence: - In a mathematical or logical expression, the operator
precedence plays an important role to decide which operator will be executed first.
The following table elaborates their precedence.
Operator Remarks
() Even though ( ) is not an operator but it plays an
important role in deciding which part of the
expression should be evaluated first.
** The unique feature of ** is that it is the only
operator that is evaluated from right to left.
*, /, //, % All the four have same precedence. Thus, left most
will be executed first if all come in an expression.
+, - Both have same precedence.
== != > >= < <= is is All the relational, identity and membership
not in not in operators
Not “Not” being a unary operator has precedence over
the logical operators “and/or”
And Have higher precedence over logical operator “or”
Punctuators: - Punctuators are symbols that are used in programming languages
to organize sentence structures, and indicates the rhythm and emphasis of
expressions, statements, and program structure.
Most common punctuators of Python programming language are:-
‘ “ # \ () [] {} @ , : . ` =
Expressions: - An expression is defined as a combination of constants, variables,
and operators. An expression always evaluates to a value. A value or a standalone
variable is also considered as an expression but a standalone operator is not an
expression.
(i) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"
Statement Flow Control: - The statement flow of control specifies that in what different the
statements of a program may be executed viz sequentially, selectively or iteratively. It may be of
three types: -
i. Sequential flow of control
ii. Selection flow of control
iii. Iteration flow of control
12 | P a g e
Sequential flow of control Program Output
The statements execute x=10 30
sequentially one after y=20
another, as written in print(x+y)
program.
The statements of a
program repeat for a given
number of times. It can be
of two types: -
1. while loop
2. for loop
Syntax of while loop: - n=1
while(condition): while(n<4): India India India
Statement/s print("India ", end=“ ")
n=n+1
Syntax of for loop: -
for value in sequence: for i in range(1,6):
Statement/s print(i, end=' ') 12345
13 | P a g e
range() example Output sequence
range(10) 0123456789
range(1,11) 1 2 3 4 5 6 7 8 9 10
range(1,11,2) 13579
range(10,0,-1) 10 9 8 7 6 5 4 3 2 1
Questions (MCQ):
Q.1 Which one of the following is not a valid identifier?
a) true
b) __init__
c) 20Decades
d) My_var
Q.2 Which of the following keywords is a python operator?
a) for
b) break
c) is
d) else
Q.3 What will be the output of the operation print("\\\\\\") ?
a) \\\\\\
b) \\\
c) \\
d) Error
Q.4 What will be the output of the expression print(10+20*10//2**3-5)
a) 30
b) 40
c) 1005
d) 130
Q.5 Evaluate the expression print(20%-3)?
a) -1
b) -2
c) 2
d) Error
Q.6 What will be the result of the expression True or False and not True or True
a) True
b) False
c) None
d) Error
Q.7 What will be the output of the following program?
a = {'A':10,'B':20}
b = {'B':20, 'A':10}
print(a==b and a is b)
14 | P a g e
a) True
b) False
c) None
d) Error
Q.8 Which of the following statements is false for python programming language?
a) Python is free and Open source.
b) Python is statically typed.
c) Python is portable.
d) Python is interpreted.
Q9. Which of the following is valid arithmetic operator in Python:
(i) //
(ii) ?
(iii) <
(iv) And
Q10. Find and write the output of the following python code:
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
15 | P a g e
Long answer type questions
Q1. Write a program to print one of the words negative, zero, or positive, according to whether
variable x is less than zero, zero or greater than zero, respectively.
Q2. Write a program that returns True if the input number is an even number, False otherwise.
Q3. Write a program that calculates and prints the number of seconds in a year.
Q4. Write a program that accepts two integers from the user and prints a message saying first number
is divisible by second number or not.
Q5. Write a program to calculate the factorial of any given number N.
Python String
Python strings are a set of characters enclosed in single quotes, double quotes, or triple quotes.
Python strings are immutable - Once a string is created, it cannot be changed. You can create a
new string with the desired modifications, but the original string remains unchanged.
Python Strings are ordered: Strings maintain the order of characters in the sequence.
This means that the characters in a string have a definite order, and this order will not change.
Python Strings are iterable. You can iterate over the characters in a string using loops like for
loops or comprehensions.
Characters in a String are indexable: Each character in a string can be accessed using an index.
Indexing starts from 0, so the first character of a string has an index of 0, the second character
has an index of 1, and so on.
String examples:
Accepting a string from user: We can use input() method to accept a string from the user.
String operations:
Concatenation: More than one string can be joined using the (+) operator to create a
new string.
16 | P a g e
Indexing: Each character of a string can be accessed using two types of indexing.
o Forward indexing: First character of a string has an index 0 and next has 1 and
so on.
o Reverse indexing: Last character of the string is having an index of -1 and last
but one has -2 and so on.
Traversal: We can traverse a string using iteration and specifically using for loop.
o Iterate using membership
String Methods: Python has a few built-in and string library methods (also built-in) to
manipulate strings. Some of them as elaborated below with examples.
o Global Methods/ functions: These functions accept string as a parameter –
Syntax:- methodName(string)
17 | P a g e
o String Library Methods: These methods have the syntax: -
string.methodName()
o Methods that return True or False:
isalnum() – Returns True is the string comprises of only alphabets and digits
19 | P a g e
Characteristics of List:-
Ordered collection of objects - Lists maintain the order of elements as they are
inserted.
Lists are mutable - Lists can be modified after creation. You can add, remove, or modify
elements freely.
Heterogenous - Lists can contain elements of different data types. For example, a list
can contain integers, strings, floats, and even other lists.
Dynamic - Lists in Python can grow or shrink in size dynamically. You can append new
elements, insert elements at specific positions, or remove elements as needed.
Indexed - Elements in a list are indexed with integers starting from 0. This allows for
easy access to individual elements using their index.
Nesting - Lists can contain other lists as elements, allowing for the creation of nested
data structures.
Built-in Methods - Python lists come with built-in methods for various operations like
sorting, reversing, searching, etc., making them versatile for a wide range of tasks.
Iterable - Lists can be used in iterations using loops (e.g., for loop)
Slicing - Lists support slicing operations, allowing you to extract sub-list by specifying a
range of indices.
# starting at 0 index
i=0
# giving an increment of 1 to i
i=i+1
21 | P a g e
Output:
USA
CHINA
BRAZIL
TURKEY
Python Tuple
A tuple is an ordered sequence of elements of different data types, such as integer, float, string,
list or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas. Like list and string, elements of a tuple can be accessed using index
values, starting from 0
o Indexing: - Elements of a tuple can be accessed in the same way as a list or string using
indexing and slicing.
o Tuple is Immutable: Tuple is an immutable data type. It means that the elements of a
tuple cannot be changed after it has been created. An attempt to do this would lead to an
error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
o Tuple operations:
Concatenation: - Python allows us to join tuples using concatenation operator
depicted by symbol +. We can also create a new tuple which contains the result of
this concatenation operation.
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2
#concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Repetition: - Repetition operation is depicted by the symbol *. It is used to
repeat elements of a tuple. We can repeat the tuple elements. The repetition
operator requires the first operand to be a tuple and the second operand to be an
integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
Membership: - The in operator checks if the element is present in the tuple and
returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
Slicing: - Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)
Python Dictionary
Python dictionaries are collection of key value pairs enclosed in {}. Python dictionaries are un-
ordered. Python dictionary keys are immutable (numbers, string, tuple). Python dictionary
values are mutable.
Dictionary Examples:
22 | P a g e
Dictionary Operations:
Displaying Values for a given Key: We can use dictName[key] to get the value.
Dictionary Methods: Like Strings and lists, dictionaries too have global and member
functions.
* Global functions: The global functions include len(), max(),
min(), sum() and
23 | P a g e
keys() – Returns a view object containing the keys of the dictionary, that can be
converted to list using a list() method.
values() - Returns a view object containing the values of the dictionary, that can
be converted to list using a list() method.
items() - Returns a view object containing the key-value pairs as tuples of the
dictionary, that can be converted to list of tuples using a list() method.
pop(key) – Removes a key-value pair from a dictionary and returns only the
value.
popitem() – Removes the last added key-value pair from the dictionary and returns
a tuple containing the removed key-value pair.
Questions (MCQ)
Q9. If the following code is executed, what will be the output of the following code?
str="KendriyaVidyalayaSangathan"
print(str[8:16])
Q10. Write a statement in Python to declare a dictionary whose keys are 1,2,3 and values
are Apple, Mango and Banana respectively.
26 | P a g e
Actual parameters: - When we call a function and pass some values to the function. These passed
values are called actual parameters.
Formal parameters: - The parameters declared in the header part of the function is called formal
parameters or the values received by the functions from its caller is called formal parameters.
Default parameters: - It is formal parameters with the assignment of values. These values are used if
the caller does not provide value to that parameter. Remember default parameters are written
after positional parameters (whose position is fixed while calling a function).
def < name of the function> (formal parameters):
function body is always written in tab indentation
code here
code here
out of scope of function. The function call can be placed after this part.
Example: -
def myfunction(a,b,c=10) : #a, b and c is formal parameter and c is with default values
print(a,b,c)
return (a+b+c)
total = myfunction(10,20,30) # 10 20 and 30 are actual parameter.
Questions (MCQ)
Q.1 What is the default return value for a function that does not return any value exp
(Q) None
(ii) int
(iii) double
(iv) null
Q.2 Which of the following items are present in function header?
a) function name only
b) both function name and parameter only
c) parameter list only
d) return value
Q.3 Which of the following keywords marks the beginning of the function block?
a) func
b) define
c) def
d) function
Q.4 What is a variable defined outside all the functions referred to as ?
a) A static variable
b) A global variable
c) A local variable
d) An automatic variable
Q.5 What is the result of this code?
def print_double(x):
print(2**x)
print_double(3)
a) 8
b) 6
c) 4
d) 10
Q.6 A void function also returns a ____________ value to its caller.
Q.7 def fun2(list1):
for x in list1:
27 | P a g e
print(x.upper(),end=”#”)
fun2([‘Rajesh’,’Kumar’])
Q.8 Consider the following function headers. Identify the correct statement: -
1) def correct(a=1,b=2,c):
2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3):
4) def correct(a=1,b,c):
Q9. What will be the output of the following code?
A=1
def f():
a=10
print(a)
Q10. Find and write the output of the following python code:
a=10
def call():
global a
a=15
call()
print(a)
Q. 2. What do you understand by local and global scope of variables? How can you access a global
variable inside the function, if function has a variable with same name.
Q. 3. What are the differences between parameters and arguments?
Q. 4. What are default arguments?
Q. 5. What are keyword arguments?
Q. 6. What are the advantages of keyword arguments?
Q. 7. What are the advantages of dividing a program into modules.
28 | P a g e
Q. 8. Differentiate between Built-in functions and user defined functions.
Q. 9. Differentiate between Built-in functions and functions defined in modules.
Q. 10. Write a generator function Generates () that displays the square roots of numbers from 100 to n
where n is passed as an argument.
Long Answer Type Questions
Q. 1. List a type of arguments and explain any 2 type of arguments.
Q. 2. Write a method in Python to find and display the prime number between 2 to N. Pass N as
argument to the method.
Q. 3. Write a program that uses a function which take two string arguments and returns the string
comparison result of the two passed strings.
Q. 4. Write definition of a function
1. OddSum(Numbers) to add Odd values in the list Numbers.
2. EvenSum(Numbers) to add Even values in the list Numbers.
Q.5. Define a function overlapping () that takes two lists and returns true if they have at least one
member in common, False otherwise.
Q.6. Write a program for nth multiple of Fibonacci Series. Also show proper documentation.
Q. 7. Write a Python program to reverse a string.
Q.8. A function checkMain() defined in module Allchecks.py is being used in two different programs
In program 1 as
Allchecks.checkMain(3,’A’)
and in program 2 as
checkMain(4,’Z’).
Why are the functions call statements different in each program?
Q. 9. Write a python program to find simple interest using a user defined function with parameters and
with return value.
Q. 10. Explain any three string functions with example?
29 | P a g e
ZeroDivisionError: - This exception is raised when an attempt is made to divide a
number by zero.
ImportError: - This exception is raised when an import statement fails to find or load a
module.
Example: -
Here in this code a s we are dividing the ‘marks’ by zero so a error will occur known as
‘ZeroDivisionError’
marks = 10000
a = marks / 0
print(a)
Output: -
In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
Note: Exception is the base class for all the exceptions in Python.
A = [1, 2, 3]
try:
print (“Second element = “, a[1])
print (“Fourth element = “(a[3]))
except:
print (“An error occurred”)
In the above example, the statements that can cause the error are placed inside the try
statement (second print statement in our case). The second print statement tries to access the fourth
element of the list which is not there and this throws an exception. This exception is then caught by the
except statement.
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and except blocks. The
final block always executes after the normal termination of the try block or after the try block
terminates due to some exception.
30 | P a g e
Example:
The code attempts to perform integer division by zero, resulting in a ZeroDivisionError. It
catches the exception and prints “Can’t divide by zero.” Regardless of the exception, the finally
block is executed and prints “This is always executed.”
try:
k = 5//0
print(k)
except ZeroDivisionError:
print (“Can’t divide by zero”)
finally:
print (‘This is always executed’)
Output:
Can’t divide by zero
This is always executed
Questions (MCQ)
Q.1 What is the purpose of the try block in Python error handling?
a) To define the block of code where an exception may occur
b) To catch and handle exceptions that occur within the block
c) To ensure that the code executes without any errors
d) To terminate the program if an exception occurs
Q.2 Which keyword is used to catch exceptions in Python?
a) try
b) catch
c) except
d) handle
Q.3 What is raised when a Python program encounters an error during execution?
a) Error
b) Exception
c) Fault
d) Bug
Q.4 Which of the following is NOT a standard Python exception?
a) KeyError
b) ValueException
c) IndexError
d) TypeError
31 | P a g e
Q.5 What does the finally block in Python error handling ensure?
a) It ensures the code within it will always execute, regardless of whether an
exception occurs or not.
b) It ensures the program will terminate if an exception occurs.
c) It ensures that the program will skip executing the code if an exception occurs.
d) It ensures that only the code within the finally block will execute if an exception
occurs.
Q.6 What is the output of the following code?
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero")
finally:
print("Finally block")
a) Division by zero
Finally block
b) Finally block
c) Division by zero
d) ZeroDivisionError
Q.7 Which of the following keywords is used to handle the exception block in Python?
a) hand
b) rescue
c) except
d) catch
Q8. Which of the following is NOT a common built-in exception in Python?
a) KeyError
b) FileNotFoundError
c) IndexError
d) SyntaxError
Q9. Which statement is true about handling exceptions in Python?
a) An exception handler can catch exceptions raised by functions it calls.
b) An exception handler cannot catch exceptions raised by functions it calls.
c) An exception handler only catches exceptions raised in the same block.
d) An exception handler can only catch exceptions of the same type.
Q10. What is the purpose of the finally block in Python error handling?
a) To handle exceptions
b) To raise exceptions
c) To ensure that certain code will always be executed
d) To terminate the program
32 | P a g e
FILE HANDLING
• Till now we have run programs on console , which run for a short period of time and give some output
and after that their data is disappeared. And when we again run those programs then we have to use new
data.
•This is because the data is entered in primary memory which is temporary memory and its data is
volatile.
•If we want to save the output, so that it can be used later on.We use the concept of File Handling.
•The meaning of File I/O (input-output) is to transfer the data from Primary memory to secondary
memory and vice-versa.
DATA FILE
A File is a collection of characters in which we can perform read and write functions. And also we can
save it in secondary storage. It contains data pertaining to a specific application, for later use.
The data files can be stored in the following ways: -
1. Text file
2. Binary file
3. CSV(Comma-separated values) file
1. OPEN FILE : Open the file for reading or writing by specifying filename and file opening
mode.
2. READ/WRITE : Once the file is open process the file as required
3. CLOSE FILE : Close the file after processing
OPENING A FILE
A file can be opened for – read, write or append data
Syntax:
Fileobject = open(“filename” , opening_mode)
Note: Default opening mode is read
f = open("school.txt") # opening mode not specified default file opening mode is read
Here ‘f’ is the file object/file handle/file pointer which holds reference to the file.
The disk file school.txt is loaded into memory and its reference is linked to ‘f’ object. Now onwards the
python program will access the data file “school.txt” through ‘f’ object. Here “school.txt” is stored in
33 | P a g e
the same folder where .py file is stored otherwise if the file stored in any other folder then filename is
specified with full path.
f=open("d:\\pyprograms\\school.txt" , “r”) # filename with full path
File opening modes
CLOSING A FILE
The close method of file object closes the file object i.e. releases the file. Python automatically closes a file
when the reference object of a file is reassigned to another file.
Fileobject.close( )
TEXT FILES
Text file stores information in ASCII or UNICODE character. Data is stored as a character for example the word
computer will take 8 bytes, 123.45 will take 6 bytes.
In text file each line is terminated with an EOL(End of Line) character.
Some translation takes place when this EOL character is read or written. This EOL character is ‘\n’ or ‘\r’ or
combination of both.
Reading data from Text file
1. read( ): reads and returns the entire data stored in the file, starting from current cursor position up to
the end of the file. The returned data forms one string.
2. read( n ): reads and returns n number of characters from the file starting from current cursor position.
The returned data forms one string
3. readline( ): reads and returns only one line from file, starting from current cursor position up to end of
line character. The returned data forms one string. A line is considered as a sequence of character up to new
line character(EOL).
4. readlines( ): reads and returns all the lines from the file starting from current cursor position in the
form of list of strings. Where each lines forms one string.
Every file maintains a file pointer which tells the current position in the file where read/write
operation will take place.
Each time read/write operation is performed two things happen
o read/write operation is performed at the current cursor position in the file.
o File pointer moves forward by the specified number of bytes.
While reading if no data is left in the file, then a blank string is returned.
# program 1: Read data from text file using read()
f=open("school.txt")
data=f.read() # read entire data starting from 1st character
34 | P a g e
print("first read::",data)
data=f.read(3) # Will return a blank list as End Of File has reached because of first read stmt
print("second read::",data)
data=f.read(5) # Will return a blank list as End Of File has already reached
print("third read::", data)
f.close()
35 | P a g e
for word in str:
if word[0]=='I' or word[0]=='i':
w=w+1
print("Total number of words starting with I or i : ",w)
file.close()
# Progarm 8: Define a function copytext() to copy all the lines from sample .txt that are ending with
‘a or ‘A’ to a new file temp.txt
def copytext():
f1=open("sample.txt")
f2=open("temp.txt", 'w')
list=[ ]
data=f1.readlines()
f2.writelines(list)
f1.close()
f2.close()
f=open("temp.txt" , "r")
print(f.read())
f.close()
# Progarm 11: Opening file in append mode and enter some data to it.
n=input("enter name of file") # Accept file name from the user
f=open(n , "a")
for i in range(3):
t=input("enter name:")
f.write(t)
f.write("\n")
f.close()
f=open("sample.txt","r")
print(f.read())
f.close()
>>>write() function cannot be used for writing sequence i.e. list, tuple etc
>>> writelines() is used to write sequence of strings to a file
37 | P a g e
# Progarm 14: Delete all the lines from the file sample.txt which are not starting with 'H' or 'I'
import os
f1=open("sample.txt")
f2=open("backup.txt", 'w')
d=f1.readlines()
for l in d:
if l[0]=='H' or l[0]=='I':
f2.writelines(l)
f1.close()
f2.close()
os.remove("sample.txt") #remove file sample.txt
os.rename("backup.txt","sample.txt") # rename backup.txt to sample.txt
f=open("sample.txt","r")
print(f.read())
f.close()
BINARY FILE
It stores information in the same format as in the memory, thus no translation occur.
There is no delimiter for a new line.
Binary files are faster and easier for a program to read and write than text files.
Data in binary files cannot be directly read it can be read only through python program for the same.
These files can represent the actual content such as image, audio, video, compressed versions of other
files, executable files, etc.
Example Code :
f = open("a.dat", 'wb')
line = ‘G20 Presidency\nOne Earth, One Family, One Future'
f.write(line)
f.close()
f = open("a.txt", 'rb+') print(f.tell())
print(f.read(7)) # read seven characters print(f.tell())
print(f.read())
print(f.tell())
f.seek(9,0) # moves to 9 position from beginning
print(f.read(5))
f.seek(4, 1) # moves to 4 position from current location
print (f.read(5))
f.seek(-5, 2) # Go to the 5th byte before the end
print(f.read(5))
f.close()
38 | P a g e
The Pickle Module :
We know that Python considers everything as an object. So, all data types including list, tuple,
dictionary, etc. are also considered as objects. During execution of a program, we may require to
store current state of variables so that we can retrieve them later to its present state.
To save any object structure along with data, Python provides a module called Pickle. The module
Pickle is used for serializing and de-serializing any Python object structure.
Pickling is a method of preserving food items by placing them in some solution, which increases
the shelf life. In other words, it is a methodto store food items for later consumption.
De-serialization or unpickling is the inverse of pickling process where a byte stream isconverted
back to Python object.
The pickle module deals with binary files. Here, data are not written but dumped and similarly,
data are not read but loaded. The Pickle Module must be imported to load and dump data. The
pickle module provides two methods - dump() and load() to work with binary files for pickling
and unpickling, respectively.
40 | P a g e
Program 4: Record modification in binary file
import pickle
emp=[ ]
f=open("employee.dat" , "rb")
emp=pickle.load(f)
print("Contents before modification\n",emp)
e=int(input("\nenter employee no you want to modify:"))
found=0
for d in emp:
if d[0]==e:
d[2]=d[2]+1000
found=1
break
if found==0:
print("record not found")
f.close()
f=open("employee.dat","wb")
pickle.dump(emp,f)
f.close()
e=[ ]
f=open("employee.dat","rb")
e=pickle.load(f) #returns data as list of lists each list represent one record
f.close()
if found==1:
print("Contents after modification\n",e)
CSV File:
CSV (Comma Separated Values) format is one of the most simple and common ways to store data
in tabular form. Each record consists of one or more fields separated by commas. To represent a
CSV file, it must be saved with the .csv file extension. It is a file format for data storage which
looks like a text file. The information is organized with one record in each line and each field is
separated by comma.
● It is a plain text file that contains the comma-separated data.
● These files are often used for exchanging data between different applications.
● CSV files are usually created by programs that handle huge amounts of data. They are used
to export data from spreadsheets (ex:- excel file) and databases (Ex:- Oracle, MySQL). It
can be used to import data into a spreadsheet or a database.
42 | P a g e
Why Use CSV Files? / Advantages of CSV Files:
• CSV is faster to handle.
• CSV 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.
CSV Files Disadvantages:
• No standard way to represent binary data.
• There is no distinction between text and numeric values.
• 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.
• Problems with importing CSV into SQL (no distinction between NULL and quotes)
Working with csv file: csv files are used to store a large number of variables or data. They
are incredibly simplified spreadsheets. Each line in a csv file is a data record.
(iii) Write into a CSV File using csv.writerow(): To write an existing file, you must
first open the file in one of writing modes (w, a or r+) first. then writerow()
function is used to write items in a sequence (list, tuple or string) separating them
by comma.
(iv) Writerows():If we need to write the content of 2-Dimensional list into csv file , instead of
using writerow() function many times, we can write use object.writerows()method.
Example:-
# writerow()
import csv
row=['Nikhil', 'CEO', '2', '9.0']
f=open("myfile.csv", 'w')
w_obj = csv.writer(f)
w_obj.writerow(row)
f.close()
43 | P a g e
# writerows()
import csv
rows = ['Nikhil','CEO','2','9.0'],
['Sanchit','CEO','2','9.1']]
f=open("myfile.csv",'w')
w_obj = csv.writer(f)
w_obj.writerows(rows)
f.close()
# reader()
import csv
f=open("myfile.csv",'r')
r_obj = csv.reader(f)
for data in r_obj:
print(data))
f.close()
If we consider the sample.csv file given below in the CSV file structure the output of the above code will
be:
## OUTPUT:
['Name', 'DOB', 'City']
['Ram', '12-Jul-2001', 'Delhi']
['Mohan', '23-Jan-2005', 'Delhi']
['Suraj', '17-Dec-2002', 'Kolkata']
EXERCISE
MCQ:
1. ____ file format are faster and easier for a program to read and write than other fileformat.
a. Text file b. Binary file c. Doc file d. None of the above
Answer b. Binary file
2. The command for opening a file in Python file handling is .
a. open() b. update() c. both a) and b) d. None of the above
Answer a. open()
3. The command for closing a file in Python file handling is .
a. close() b. closing() c. object() d. None of the above
Answer ⟵ a. close()
4. text file mode is used to read data from file.
a. ‘r’ b. ‘rb’ c. ‘r+’ d. None of the above
Answer a. ‘r’
5. text file mode is used to append data in the file using file handling.
a. ‘w’ b. ‘ab’ c. ‘a’ d. None of the above
Answer c. ‘a’
6. Out of the followings which mode is used for both reading and writing in binary format infile?
44 | P a g e
a) wb b) wb+ c) w d) w+
Ans: b) wb+
7. Which of the following is not true about binary files?
a) Binary files are store in terms of bytes
b) When you open binary file in text editor will show garbage values
c) Binary files represent ASCII value of characters
d) All of the above
Ans: c) Binary files represent ASCII value of characters
3. Assertion(A): pickle.dump() function is used to store the object data to the file.
45 | P a g e
Reason(R): pickle.load() function is used to retrieve pickled data.
Ans: ii. Both A and R are true but R is not the correct explanation for A
5. Assertion(A): ab+ mode is used for both appending and reading binary files and move file
pointer at end.
Reason(R): ab+ mode, if the file does not exist, it does not create a new file for reading andwriting.
Ans: iii. A is True but R is False
3. A binary file “student.dat” has structure [rollno, name, marks]. Write a user definedfunction
insertRec() to input data for a student and add to student.dat.
Ans:
import pickle def insertRec():
f=open(‘student.dat’,’ab’)
rollno = int (input(‘Enter Roll Number :’))
name=input("Enter Name :")
marks = int(input(‘Enter Marks :’))
rec = [rollno, name, marks ]
pickle.dump( rec, f )
f.close()
SA-2(3-Marks Questions)
1. A binary file “student.dat” has structure [rollno, name, marks]. Write a function
searchRollNo( r ) in python which accepts the student’s rollno as parameter and searches
the record in the file “student.dat” and shows the details of student i.e. rollno, name and
marks (if found) otherwise shows the message as ‘No record found’.
Ans:
def searchRollNo( r ):
f=open("student.dat","rb")
flag = False
while True:
try:
rec=pickle.load(f)
if rec[0] == r :
print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag == True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
47 | P a g e
print(rec[0], rec[1], rec[2])
num = num + 1
except:
f.close()
return num
A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post, Salary].
Create a binary file “EMP.dat” that stores the records of employees and display them one by one.
Also display the records of all those employees who are gettingsalaries between 25000 to 30000.
Ans:
import pickle
f1 = open('emp.dat','rb')
try:
while True:
e = pickle.load(f1)
print(e)
except:
f1.close()
f1 = open('emp.dat','rb')
try:
while True:
e = pickle.load(f1)
if(e[3]>=25000 and e[3]<=30000):
print(e)
except:
f1.close()
3. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. Write a function
CountRec(Author) in Python which accepts the Author name as parameter and count and return
number of books by the given Author are stored in the binary file “Book.dat”.
Ans:
import pickle
def CountRec(Author):
f=open("Book.dat","rb")num = 0
try:
while True:
rec=pickle.load(f)
if Author==rec[2]:
num = num + 1
except:
f.close()
return num
4. Consider a binary file emp.dat having records in the form of dictionary. E.g {eno:1,
name:”Rahul”, sal: 5000} write a python function to display the records of above file for those
employees who get salary between 25000 and 30000.
Ans:
import pickle
def search():
f=open(“emp.dat”,”rb”)
while True:
try:
d=pickle.load(f)
if(d[‘sal’]>=25000 and d[‘sal’]<=30000):
print(d)
48 | P a g e
except EOFError:
break
f.close()
# statement 1
def addrecords():
fw= #statement 2
dict={}
ch=’y’
while ch==’y’:
eno=int(input(“enter employee number”))
nm= input(“enter employee name”)
sal=int(input(“enter employee salary”))
dict={‘empno’:eno,’name’:nm,’salary’:sal}
# statement 3
ch=input(“add more record”)
fw.close()
# function to display records
def display():
dict={}
fr= # statement 4
dict= # statement 5
fr.close()
print(“data :”,dict)
Answer questions (i)-(v) based on above case study
(i). Help Ramesh to import the module to perform binary file operation in statement 1.
a) csv b) random c) pickle d) file
Ans: c) pickle
(ii). Which statement is used from the following for statement 2 to open the binary file inwrite
mode?
a) open(“employee.dat”,’w’) b) open(“employee.dat”,’wb’)
c) open(“employee.dat”,’w+’) d) open(“employee.dat”,’r’)
Ans: b) open(“employee.dat”,’wb’)
(iii). Which statement is used from the following for statement 3 to write dictionary datacreated
in above code, namely dict, is written in binary file employee.dat file?
a) pickle.dump(dict,fw) b) pickle.write(dict,fw)
c) pickle.save(dict,fw) d) pickle.store(dict)
Ans: a) pickle.dump(dict,fw)
(iv). Which statement is used from the following for statement 4 to open the binary file inread
mode?
a) open(“employee.dat”,’r’) b) open(“employee.dat”,’r+’)
c) open(“employee.dat”,’a’) d) open(“employee.dat”,’rb’)
49 | P a g e
Ans: d) open(“employee.dat”,’rb’)
(v). Complete statement 5 to read data in dictionary namely dict from the openedbinary file?
a) dict=pk.read(fr) b) dict=pickle.load(fr)
c) pickle.load(dict,fr) d) none of these
Ans: b) dict=pickle.load(fr)
Incomplete Code
import _______________________________________________________ #Statement 1
fh = open( , , newline=‘ ’) #Statement 2
stuwriter = csv. data = [ ] #Statement 3
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(“Class : ”)
section = input(“Enter Section : ”)
rec = [ ] #Statement 4
data.append(rec)
stuwriter. (data) #Statement 5
fh.close()
51 | P a g e
6. If top=-1 go to step 7 else go to step 4
7. Stop
ANSWER:
R={'OM':76, 'JAI':45, 'BOB':89, 'ALI':65, 'ANU':90, 'TOM':82}
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[ ]:
return S.pop( )
else:
print('Underflow')
ST=[ ]
for k in R:
if R[k]>=75:
PUSH(ST,k)
while True:
if ST!=[ ]:
print (POP(ST), end=' ')
else:
break
Q2. Alarm has a list containing 10 integers. You need to help him create a program with separateuser
defined functions to perform the following operations based on this list.
Traverse the content of the list and push the even numbers into a stack.
Pop and display the content of the stack.
For Example: If the sample content of the list is as follows:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output of the code should be: 38 22 98 56 34 12
ANSWER:
N=[12,13,34,56,21,79,98,22,35,38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[ ]:
return S.pop( )
else:
print('Underflow')
ST=[ ]
for k in N:
53 | P a g e
if k%2==0:
PUSH(ST,k)
while True:
if ST!=[ ]:
print(POP(ST), end=" ")
else:
break
Q3. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all
numbers divisible by 5 into a stack implemented by using a list. Display the stack if it has at least
one element, otherwise display appropriate error message.
ANSWER:
s=[25,40,27,34 ]
def PUSH( Arr, value):
for x in range(0, len(Arr)):
if(Arr[x]%5--0):
s.append(Arr[x])
if(len(s)==0):
print("Empty stack")
else:
print(s)
Q4 . Write functions in python for Push(List) and for PopS(List) for performing Push and Pop
operations with a stack of list containing integers.
ANSWER:
List=[1,2,3]
def PushS(List):
N=int(input('Enter Integer'))
List.append(N)
def PopS(List):
if (List==[]):
print('UnderFlow!!')
else:
print('Deleted Value: ',List.pop())
PushS(List)
print(List)
PopS(List)
Q5 . A list, NList contains following record as list elements:[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined
functions in Python to perform the specified operations on the stack named travel.
Push_element(NList): It takes the nested list as an argument and pushes a list object containing
name of the city and country, which are not in India and distance is less than3500 km from Delhi.
Pop_element(): It pops the objects from the stack and displays them. Also, the function should
display “Stack Empty” when there are no elements in the stack.
ANSWER:
travel=[]
def Push_element(NList):
for L in NList:
if(L[1] != 'India' and L[2]<3500):
travel.append([L[0],L[1]])
def Pop_element():
if travel !=[]:
print(POP(ST),end=" ")
else:
print(“stack empty”)
break
54 | P a g e
DATABASE CONCEPTS
1. DATABASE: A Database is defined as an organized collection of interrelated data that serves
many applications.
2. DATABASE MANAGEMENT SYSTEM: A Database Management System (DBMS) is a general
purpose software system that facilitates the process of defining, constructing and
manipulating databases for various applications.
3. NEED FOR DBMS
1) Helps store data in a structured manner.
2) Query the Database(i.e. ask questions about the data)
3) Sort and Manipulate the Data in the Database
4) Validate the Data Entered and check for inconsistencies
5) Produce Flexible Reports
4. ADVANTAGES OF DBMS
1) Elimination of Data Redundancy/Duplication
2) Data Consistency
3) Sharing of Data
4) Reduced Programming Effort
5) Improved Data Integrity
6) Privacy and Security
7) Improved backup and recovery system
8) Economical
5. TYPES OF DBMS
1) Hierarchical DBMS
2) Network Based DBMS
3) Object Based DBMS
4) Relational DBMS
DIFFERENT DATA MODELS
A data model refers to a set of concepts to describe the structure of a database, and certain
constraints (restrictions) that the database should obey. The four data model that are used for
database management are:
1.Relational data model
2. Hierarchical data model
3. Network data model
4. Object Oriented data model
In Relational data model, the data is organized into tables (i.e. rows and columns). These tables
are called relations.
RELATIONAL MODEL TERMINOLOGY
1. Relation : A table storing logically related data is called a Relation.
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.
55 | P a g e
KEYS IN A DATABASE
1. PRIMARY KEY – An Attribute or a set of Attributes, which uniquely identifies each tuple in the
Relation is known as Primary Key.
2. CANDIDATE KEY – An Attribute or a set of Attributes that has the ability to uniquely identify each
tuple in the Relation is known as a Candidate Key.
3. ALTERNATE KEY – All the Candidate Keys which were not chosen to be Primary Key are also
known as Alternate Keys.
4. FOREIGN KEY - An Attribute or a Set of Attributes in one relation which refer to the Primary Key
of any other Relation is known as the Foreign Key of the Relation. They are used to establish
relationships between Tables.
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.
Tips to Remember regarding Keys in a Database
One can always relate the Keys in a Relation to be like the Representatives of Each Political Party
during an Election.
All representatives are those who promise to uniquely identify the problems of each voter
in the country. They are the Candidates for the Election. In a similar way, Candidate Keys
can uniquely identify each tuple.
After the Elections One Candidate among all the Candidates are elected as the Prime
Minister of the Country. Similarly, any one of the Candidate Keys which has been chosen
by the Database Developer to uniquely identify each tuple is the Primary Key of the
Relation.
All those Candidates who could not become the Prime Minister, become the member of
the Opposition. Similarly, all the Candidate Keys which were not chosen to be Primary Key
are also known as Alternate Keys of the Relation.
The Prime Minister of the Country often sends Foreign Ministers to represent the Prime
Minster in other countries. Similarly, a Foreign Key are attributes in a relation which
refers to the Primary Key of some other Relation.
MIND MAP
56 | P a g e
Check Your Progress:
57 | P a g e
Question 10: What is a foreign key in the relational data model?
(A) A set of attributes in one relation that references the primary key of another relation
(B) A set of attributes in one relation that references the candidate key of another relation
(C) A set of attributes in one relation that references the foreign key of another relation
(D) None of the above
Answer: (A)
Question 1:
Assertion (A): A database is a collection of organized data.
Reason (R): A database can be used to store a wide variety of data types, including text,
numbers, images, and videos.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).
Question 2:
Assertion (A): The relational data model is a type of database model that stores data in
tables.
Reason (R): The relational data model is the most popular type of database model used
today.
Answer: Both (A) and (R) are correct and (R) is not the correct explanation of (A).
Question 3:
Assertion (A): A relation in the relational data model is a set of tuples.
Reason (R): A tuple is a column in a table.
Answer: Assertion (A) is True and Reason (R) is False.
Question 4:
Assertion (A): A foreign key in the relational data model is a set of attributes in one
relation that references the primary key of another relation.
Reason (R): Foreign keys are used to establish relationships between tables.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).
Question 5:
Assertion (A): A candidate key in the relational data model is a set of attributes that
uniquely identifies a tuple in a relation.
Reason (R): A primary key is a candidate key that is chosen to be the unique identifier for
tuples in a relation.
Answer: Both (A) and (R) are correct and (R) is the correct explanation of (A).
58 | P a g e
SHORT ANSWER QUESTIONS (2 MARKS)
Q1 Mention the various advantages of DBMS.
Ans. The following are some of the advantages of DBMS:-
1. Elimination of Data Redundancy/Duplication
2. Data Consistency
3. Sharing of Data
4. Reduced Programming Effort etc.
Q2. What is the difference between an attribute and tuple?
Ans. The columns of the table are known as Attributes and the rows in the table which store the record
is known as tuples.
Q3. Define Degree and Cardinality.
Ans. DEGREE OF A RELATION – The total number of Attributes in a relation is known as the Degree
of the Relation.
CARDINALITY OF A RELATION – The total number of Tuples / Records in a relation (excluding the
Top Row, which contains the Attribute Headers) is known as the Cardinality of the Relation.
Q4. Given a Table Employee (EID, EName, Department, Salary). The Table contains details of 10
Employees. A User inserts 4 more Employee records. 2 Employees resign and their data are
deleted from the table. The developer also adds a Gender Column to the table. What is the
Degree and Cardinality of the Table? Also mention which column can be used as a Primary Key.
Ans. Degree – 5 and Cardinality – 12 , Primary Key – EID
Q5. Differentiate between Primary Key and Foreign Key.
Ans. An Attribute or a set of Attributes, which uniquely identifies each tuple in the Relation is known
as Primary Key whereas an Attribute or a Set of Attributes in one relation which refer to the Primary
Key of any other Relation is known as the Foreign Key of the Relation. They are used to establish
relationships between Tables. There can only be 1 Primary Key however, there can be multiple
Foreign Keys from multiple Tables.
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 is a language that enables you to create and operate on relational databases, which are sets of
related information stored in tables.
59 | P a g e
CLASSIFICATION OF SQL STATEMENTS
MySQL ELEMENTS
LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type.
For example, ‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all
numeric literals. Numeric literals can either be integer literals i.e., without any decimal or be
real literals i.e. with a decimal point e.g. 17 is an integer literal but 17.0 and 17.5 are real
literals.
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 Data Type
1. int – used for number without decimal.
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 Data Type
60 | P a g e
1. date – used to store date in YYYY-MM-DD format.
2. time – used to store time in HH:MM:SS format.
String Data Types
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.
DIFFERENCE BETWEEN CHAR AND VARCHAR DATA TYPE
1. It specifies a fixed length character String. It specifies a variable length character string.
DATABASE COMMNADS
In order to insert another row in EMPLOYEE table , we write again INSERT command :
INSERT INTO employee VALUES (1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);
62 | P a g e
ECODE ENAME GENDER GRADE GROSS
DISTINCT(GENDER)
M
F
64 | P a g e
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
ECODE ENAME GRADE
1001 Ravi E4
1006 Ruby A1
- The NOT IN operator finds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
ECODE ENAME GENDE GRADE GROSS
R
1001 Ravi M E4 50000
1004 Neela F B2 38965
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%’ ;
Output will be :
to display the names of those students whose marks is NULL, we use the command :
SELECT Name
FROM EMPLOYEE
WHERE Marks IS NULL ;
Output will be :
Name
ARUN
SANJAY
SORTING RESULTS
Whenever the SELECT query is executed , the resulting rows appear in a predecided order.
The ORDER BY clause allow sorting of query result. The sorting can be done either in
ascending or descending order, the default is ascending.
66 | P a g e
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME FROM EMPLOYEE WHERE GROSS > 40000 ORDER BY ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema
DROPPING TABLES
The DROP TABLE command lets you drop a table from the database. The syntax of DROP TABLE
command is :
67 | P a g e
DROP TABLE <tablename> ;
e.g. to drop a table employee, we need to write :
DROP TABLE employee ;
Once this command is given, the table name is no longer recognized and no more commands can be
given on that table.
After this command is executed, all the data in the table along with table structure will be deleted.
S.NO. DELETE COMMAND DROP TABLE COMMAND
1 It is a DML command. It is a DDL Command.
2 This command is used to delete only This command is used to delete all the data of the
rows of data from a table table along with the structure of the table. The table
is no
longer recognized when this command gets executed.
3 Syntax of DELETE command is: Syntax of DROP command is :
DELETE FROM <tablename> DROP TABLE <tablename> ;
WHERE <condition> ;
However if you specify NOT NULL constraint while adding a new column, MySQL adds the new
column with the default value of that datatype e.g. for INT type it will add 0 , for CHAR types, it will
add a space, and so on.
e.g. Given a table namely Testt with the following data in it.
Col1 Col2
1 A
2 G
68 | P a g e
Now following commands are given for the table. Predict the table contents after each of the
following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testt ADD col6 VARCHAR(3);
MODIFYING COLUMNS
Column name and data type of column can be changed as per following syntax :
ALTER TABLE <table name> CHANGE <old column name> <new column name> <new datatype>;
If Only data type of column need to be changed, then
ALTER TABLE <table name> MODIFY <column name> <new datatype>;
e.g.1. In table EMPLOYEE, change the column GROSS to SALARY.
ALTER TABLE EMPLOYEE CHANGE GROSS SALARY INTEGER;
e.g.2. In table EMPLOYEE , change the column ENAME to EM_NAME and data type from
VARCHAR(20) to VARCHAR(30).
ALTER TABLE EMPLOYEE CHANGE ENAME EM_NAME VARCHAR(30);
e.g.3. In table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to VARCHAR(2).
ALTER TABLE EMPLOYEE MODIFY GRADE VARCHAR(2);
DELETING COLUMNS
To delete a column from a table, the ALTER TABLE command takes the following form :
DEFAULT CONSTRAINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value. E.g.
CREATE TABLE Student ( Student_ID integer , Name varchar(30) , Score integer DEFAULT 80);
When following SQL statement is executed on table created above:
INSERT INTO Student
no value has been provided for score field.
VALUES (10 , ‘Ravi’ );
Then table Student looks like the following:
Student_ID Name Score
10 Ravi 80 score field has got the default
value
UNIQUE CONSTRAINT
The UNIQUE constraint ensures that all values in a column are distinct. In other words,
no two rows can hold the same value for a column with UNIQUE constraint. e.g.
CREATE TABLE Customer
( SID integer Unique , Last_Name varchar(30) , First_Name varchar(30) ) ;
Column SID has a unique constraint, and hence cannot include duplicate values. So, if the
70 | P a g e
table already contains the following rows :
SID Last_Name First_Name
1 Kumar Ravi
2 Sharma Ajay
3 Devi Raj
CHECK CONSTRAINT
- The CHECK constraint ensures that all values in a column satisfy certain conditions. Once
defined, the table will only insert a new row or update an existing row if the new value
satisfies the CHECK constraint. e.g.
CREATE TABLE Customer ( SID integer CHECK (SID > 0), Last_Name varchar(30) , First_Name
varchar(30) ) ;
So, attempting to execute the following statement :
INSERT INTO Customer VALUES (-2 , ‘Kapoor’ , ‘Raj’);
will result in an error because the values for SID must be greater than 0.
71 | P a g e
e.g.
Parent Table
TABLE: STUDENT
ROLL_NO NAME CLASS
Primary key
1 ABC XI
2 DEF XII
Child
3 Table XYZ XI
TABLE: SCORE
ROLL_NO MARKS
1 55
2 83
3 90
Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its
values from Primary key (ROLL_NO) of STUDENT table.(Parent Key).
REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs in the
parent table. Referencing action with ON UPDATE clause determines what to do in case of a UPDATE
occurs in the parent table.
Actions:
1. CASCADE : This action states that if a DELETE or UPDATE operation affects a row
from the parent table, then automatically delete or update the matching rows in
the child table i.e., cascade the action to child table.
2. SET NULL : This action states that if a DELETE or UPDATE operation affects a row from the
parent table, then set the foreign key column in the child table to NULL.
3. NO ACTION : Any attempt for DELETE or UPDATE in parent table is not allowed.
4. RESTRICT : This action rejects the DELETE or UPDATE operation for the parent table.
73 | P a g e
AVG(SAL)
6051.6
Output
2. COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows
where COLUMN is not null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
e.g. SELECT COUNT(*) FROM EMPL ;
Output
COUNT(*)
5
COUNT(JOB)
4
3. MAX( )
This function returns the maximum value from a given column or expression.
e.g. SELECT MAX(SAL) FROM EMPL ;
Output
MAX(SAL)
9870
4. MIN( )
This function returns the minimum value from a given column or expression.
e.g. SELECT MIN(SAL) FROM EMPL ;
MIN(SAL)
2985
Output
5. SUM( )
This function returns the sum of values in given column or expression.
e.g. SELECT SUM(SAL) FROM EMPL ;
SUM(SAL)
30258
Output
74 | P a g e
8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
Sol:
** One thing that you should keep in mind is that while grouping , you should include only
those values in the SELECT list that either have the same value for a group or contain a
group(aggregate) function. Like in e.g. 2 given above, DEPTNO column has one(same)
value for a group and the other expression SUM(SAL) contains a group function.
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiple fields in
the GROUP BY expression. e.g. To group records job wise within Deptno wise, you need
to issue a query statement like:
SELECT DEPTNO, JOB, COUNT(EMPNO) FROM EMPL GROUP BY
DEPTNO, JOB ;
Output
DEPTNO JOB COUNT(EMPNO)
10 CLERK 1
20 SALESMAN 1
20 MANAGER 1
30 SALESMAN 1
JOIN
A Join is a Query that combine rows from two or more tables. In a join Query, more than one tables
are listed in FROM Clause.
The function of combining data from multiple tables is called joining.
Joins are used when we have to select data from multiple tables is called joining. Join are used to
extract data from two tables, when we need a relationship between certain columns in these
tables.
There are different kind of SQL joins
1) Equi Join: Equi Join is a simple SQL join condition that uses equal sign as comparison operator.
Syntax
Select col1,col2,col3 from table1 and table2 Where table1.col1=table2.col1
2) Natural Join
The Natural Join is a type of equi join and it structured in such a way that, columns with same
name of associated tables will appear only once.
Syntax
Select * from table1 NATURAL JOIN table2.
In this no need to give the joining condition. It will automatically make the condition based on the
common column in both the tables.
TRANSACTION CONTROL COMMANDS (TCL)
The TCL of MySQL consists of following commands :
MIND MAP
76 | P a g e
Check Your Progress :
MCQ
1. In a table STUDENT in MySQL database, an attribute NAME of data type VARCHAR(20) has
the value “ASEEMA SAHU”. Another attribute SUBJECT of data type CHAR(10) has value
“CS”. How many characters are occupied by attribute
NAME and attribute SUBJECT respectively?
A. 11, 10
B. 11, 2
C. 12, 3
D. 20, 10
2. Identify the MySQL Commands that belongs to DML category :
A. ALTER
B. DROP
C. DELETE
D. CREATE
3. Consider the following Statements :
Statement – 1 : UNIQUE constraint ensures that all the values in a column are distinct
/ unique.
Statement – 2 : MySQL is an open-source relational database management system.
A. Only Statement-1 is True
B. Only Statement-2 is True
C. Both Statements are True.
D. Both Statements are False.
4. Fill in the blank:
___________________________ are used to define the different structures in a database.
A. Data Definition Language (DDL) Statement
77 | P a g e
B. Data Manipulation Language (DML) Statement
C. Transaction Control Statement
D. Session Control Statement
5. Naresh wants to create an attribute for admission number. Which will be the most
suitable data type for admission number which can accommodate admission numbers with
4 digits ?
A. VARCHAR(2)
B. CHAR(3)
C. INT
D. DATE
6. “The column which can uniquely identify each row or record in a table.”
The above Statement refers to which constraints in MySQL ?
A. NOT NULL
B. UNIQUE
C. PRIMARY KEY
D. DEFAULT
7. Identify the Statement which is NOT CORRECT ?
A. It is mandatory to define constraint for each attribute of a table.
B. Constraints are certain types of restrictions on the data values that an attribute can
have.
C. Constraints are used to ensure the accuracy and reliability of data.
D. It is not mandatory to define constraint for each attribute of a table.
8. Choose the correct MySQL statement to create a database named TARGET100.
A. CREATE TARGET100;
B. CREATE DATABASE TARGET100;
C. CREATE DATABASES TARGET100;
D. Database TARGET100 is not a valid database name. Hence, it cannot be created.
9. Prapti is presently working in the database SUBJECT. She wants to change and go to
the database RECORD. Choose the correct statement in MySQL to go to the database
RECORD.
A. GO TO DATABASE RECORD;
B. USE DATABASE RECORD;
C. CHANGE DATABASE RECORD;
D. USE RECORD;
10. Smiti has entered the following statements in MySQL. But it shows an error as
mentioned below. Help her to identify the reason for such error ?
mysql> CREATE TABLE PRACTICAL(
-> SUBJECT VARCHAR(20),
-> MARKS INT,
-> ROLL INT,
-> NAME VARCHAR(30));
mysql> ERROR 1046 (3D000): No database selected
A. She has to first USE an available database or create a new database and then USE it.
B. Wrong syntax for CREATE TABLE
C. Wrong data type declaration
D. PRACTCAL named table already exists.
ASSERTION – REASONING
Q.11, 12, 13, 14 and 15 are ASSERTION(A) AND REASONING(R) based questions. Mark the
correct choice as
A. Both A and R are true and R is the correct explanation for A
B. Both A and R are true and R is not the correct explanation for A
C. A is True but R is False
D. A is false but R is True
78 | P a g e
11 A table REMEDIAL is created with following attributes, datatype and constraints:
The first record inserted in the table REMEDIAL successfully is as follows :
Field Datatype Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY
SNAME ROLL FEES ADMN
AZAD SARKAR 10 3500 4585
12 Assertion(A): The MySQL statement :
INSERT INTO REMEDIAL (ROLL, FEES, ADMN) VALUES (11, 1800, 4986);
will generate an ERROR and record will not be inserted.
Reasoning(R):
Field 'SNAME' cannot be an empty or NULL value as the Constraint assign is NOT NULL.
13. Assertion(A): The MySQL statement :
INSERT INTO REMEDIAL VALUES ('PAROMITA DOGRA', 10, 3000, 5500);
will generate an ERROR and record will not be inserted.
Reasoning(R): Duplicate entry '10' for the field 'ROLL'. The Constraint assign is UNIQUE
which restricts the duplicate entry.
14. Assertion(A): The MySQL statement :
INSERT INTO REMEDIAL VALUES ('NEHA JAIN', 25, 3500, 4585);
will generate an ERROR and record will not be inserted.
Reasoning(R): Duplicate entry '3500' for the field 'FEES'.
15. Assertion(A): The MySQL statement :
INSERT INTO REMEDIAL VALUES ('NEHA JAIN', 25, 3500, 4585);
will generate an ERROR and record will not be inserted.
Reasoning(R): Duplicate entry '4585' for the field ADMN. The Constraint assign is PRIMARY
KEY which restricts the duplicate entry.
True False: State True or False for Q.16 to Q20:
16. MySQL is an open-source relational database management system.
17. All Candidate Keys are Primary Keys but all Primary keys are not Candidate Keys.
18. MySQL statement to delete a table STUDENT from the database SCHOOL is
DELETE TABLE STUDENT;
19. ALTER TABLE statement is used to make changes in the structure of a table like
adding, removing or, changing datatype of column(s).
20. DDL (Data Definition Language) includes SQL statements such as, CREATE
TABLE, ALTER TABLE and DROP TABLE.
Short Answer Type Questions
21. Write MySQL statements for the following:
i. To create a database named SCHOOL.
ii. To create a table named REMEDIAL based on the following specification:
Field Datatype Constraints
SNAME VARCHAR(20) NOT NULL
ROLL INT UNIQUE
FEES FLOAT
ADMN INT PRIMARY KEY
22. Mr. Kareem Sen has just created a table named “STUDENT” containing columns SNAME,
SUBJECT and FEES. After creating the table, he realized that he has forgotten to add a
PRIMARY KEY column in the table. Help him in writing an SQL command to add a
PRIMARY KEY column ADMN of integer type to the table
Employee.
79 | P a g e
23. Zenith is working in a database named SCHOOL, in which she has created a table named
“STUDENT” containing columns ADMN, SNAME, GENDER and CATEGORY. After creating
the table, she realized that the attribute, GENDER has to be deleted from the table and a
new attribute FEES of data type FLOAT has to be added. This attribute FEES cannot be
left blank. Help Zenith to write the commands
to complete both the tasks.
24. (i) State one difference between DDL and DML statements in MySQL.
(ii) Write the MySQL statement to delete the database named “SCHOOL”.
25. Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP
80 | P a g e
Answer :
MCQ
1. (A)
2. (C)
3. (C)
4. (A)
5. (C)
6. (C)
7. (A)
8. (B)
9. (A)
10. (A)
11. (A)
12. (A)
13. (D)
14. (B)
15. (A)
16. True
17. False
18. False
19. True
20. True
21. i. CREATE DATABASE SCHOOL;
ii.
CREATE TABLE REMEDIAL( SNAME VARCHAR(20) NOT NULL, ROLL INT
UNIQUE, FEES FLOAT ADMN INT PRIMARY KEY);
22. ALTER TABLE STUDENT ADD ADMN INT PRIMARY KEY;
23. ALTER TABLE STUDENT DROP GENDER;
ALTER TABLE STUDENT ADD FEES FLOAT NOT NULL;
24. (i)
DDL (Data Definition Language) DML (Data Manipulation Language)
DDL statements are used to DML statements are used to access
create and
structure of a table, modify manipulate data in existing tables
the which
existing structure of the table includes inserting data into tables,
and
remove the existing table. deleting data from the tables,
retrieving
data and modifying the existing data.
81 | P a g e
INTERFACE OF PYTHON WITH AN SQL DATABASE
In order to connect to a database from within Python, you need a library(mysql connector)
that provides connectivity functionality. Steps for Creating Database Connectivity
Applications There are mainly seven steps that must be followed in order to create a
database connectivity application.
Step 1 : Start Python.
Step 2 : Import the packages required for database programming.
Step 3 : Open a connection to 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.
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
CODE FOR SELECTING AND PRINTING DATA FROM A MYSQL TABLE THROUGH PYTHON
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="mohana", password="mohana",
database="mydatabase”)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM
customers") myresult = mycursor.fetchall()
for x in myresult:
print(x)
CODE FOR DELETING A RECORD FROM MYSQL TABLE USING PYTHON
import
mysql.connector
82 | P a g e
mydb =
mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",
database="mydatabase")
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE name = 'XYZ'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
MIND MAP
MCQ
Q-1: Looking at the code below, what would this line do?
INSERT INTO Cats (name, breed) VALUES ('Petunia', 'American Shorthair')
A. Add a table to the Cats database with the name "Petunia" and breed "American Shorthair".
B. Add a row to the Cats table with the name "Petunia" and the breed "American
Shorthair".
C. Create the table Cats.
D. Add a row to the Cats table with the name "American Shorthair" and the breed "Petunia".
83 | P a g e
Ans: B
Q-2: Looking at the code below, what would this line do to the table Cats?
cur.execute('DROP TABLE IF EXISTS Cats ')
A. It will remove the row "Cats".
B. It will move "Cats" to the end of the database.
C. It will remove the column "Cats".
D. It will remove the table "Cats".
Ans : B
Q-3 True or False? A cursor is used to create a database.
A. True
B. False
Ans : B
Q-4 Which of the following is true about The PYTHONPATH Variable?
A. The PYTHONPATH is an environment variable
B. It consists of a list of directories
C. The syntax of PYTHONPATH is the same as that of the shell variable PATH
D. All of the
above Ans.D
Q-5 CONNECT() function in SQL is used for:
A. To connect to database. B. To open database
C. To create database D. All of the
above Ans.D
Q-6 which method is used to retrieve N number of records
A. fetchone() B. fetchall() C. fetchmany() D.
fetchN() Ans.C
Q-7 Which of the following is not the function of the MYSQL in python ?
A. .connect() B. .close() C. .execute() D.
.raw() Ans.D
Q-8 Which keyword we use to fetch the data from the table in database ?
A. fetch B. select C. raw D. All of the above
Ans.B
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
Q1. Assertion(A): A database constraint can be added or removed any time from database
tables.
Reasoning(R): Alter table command is used to change the structure of table.
84 | P a g e
Ans. a
Q2. Assertion(A): SQL has efficient mechanisms to retrieve data stored in multiple tables in a
MySQL database.
Reasoning(R): The SQL statements CREATE is used to retrieve data from the tables in a
database and is also called query statement.
Ans. c
Q3. Assertion(A): The resultset refers to a logical set of records that are fetched from the database
by
executing an SQL query.
Reason(R): Resultset stored in a cursor object can be extracted by using fetch(...) functions.
Ans. a
Q4. . Assertion(A): MySqldb is an interface for connecting to a MySql database servers to
Python
Reason(R)::exit() function is used to close the connection to a database
Ans. c
Q5. Assertion(A): fetchone() returns the next row as a query of the sequence
Reason(R): fetchone() raises an exception if there is no resultset
Ans. c
B. TRUE FALSE QUESTION ON MYSQL DATABASE CONNECTIVITY
1. To create a database in MySQL, use the "CREATE DATABASE" statement
(TRUE)
2. You can check if a database exist by listing all databases in your system by
using the "SHOW DATABASES"(TRUE)
3. You can check if a table exist by listing all tables in your database with the
"SHOW TABLES" statement(TRUE)
4. When creating a table, you MUST create a column with a unique key for
each record. (FALSE)
5. To fill a table in MySQL, use the "INSERT ONTO" statement.(FALSE)
D. SA-1(2 MARKS) -5
1. How can you use Python with MySQL?
ANS. Python can be used with MySQL in a number of ways. One way is to use the mysql-
connector-python library, which is a MySQL driver written in Python. This library can be used
to connect to a MySQL database and perform various operations, such as creating and
executing SQL queries.
85 | P a g e
5. How do you disconnect from the database?
ANS. Use t h e close() method. db.close() closes the connection from the database.
E. SA -II
1. What is database connectivity?
Ans: Database connectivity refers to connection and communication between an application
and a database system.
2. What is connection? What is its role?
Ans: A Connection (represented through a connection object) is the session between the
application program and the database. To do anything with database, one must have a
connection object.
3. What is a result set?
Ans: A result set refers to a logical set of records that are fetched from the database by
executing a query and made available to the application-program.
4. Which package must be imported in Python to create a database connectivity
application?
Ans: There are multiple packages available through which database connectivity
applications can be created in Python. One such package is mysql.connector.
5. Explain the following 'results' retrieval methods
A. fetchone () B. rowcount () C. fetchall ()
Ans: (A) fetchone() :- The fetchone() method will return only one row from the result set
in the form of tuple containing a record.
(B) rowcount() :- cursor.rowcount() that always return how many records have been
retrieved so for using any of the fetch..() methods.
(C) fetchall() :- The fetchall() method return all the rows from the result set in the form of a
tuple congaing the records.
86 | P a g e
Answer :-
import mysql.connector
db1 = mysql.connector.connect (host = "localhost", user = "root", password =
"pathwalla", database = "company")
cursor = db1.cursor()
sql = "SELECT FROM EMP WHERE SALARY> 70000;"
try:
cursor.execute(sql)
resultset =
cursor.fetchall () for
row in resultset:
empno =
row [0]
ename =
row [1]
salary =
row [2]
print (("empno-3d, ename=%s, salary-8f") % (empno, ename,
salary)) except:
print ("Error: unable to fetch data")
db1.close()
- ‘%s` Format Specifier or format( ) : Used to dynamically insert values into SQL queries.
- Enhances query flexibility and security by preventing SQL injection attacks.
Example python Code : for connecting a database named ‘mydb’ having user name as ‘User’
, password as ‘password’ , host as ‘localhost’ and database port as 5432
87 | P a g e
conn = psycopg2.connect(database="mydb", user="user", password="password",
host="localhost", port="5432")
# Creating a cursor object to execute
queries cur = conn.cursor()
# Executing a query using %s format specifier
cur.execute("INSERT INTO table_name (column1, column2) VALUES (%s, %s)", (value1,
value2))
# Fetching data using fetchone() or
fetchall() data = cur.fetchone()
# Committing changes and closing the
connection conn.commit()
conn.close()
Correct Answer: B
2. Which function is used to execute SQL commands in Python's database connectivity?
A. `executeSQL()` B. `runSQL()` C. `execute()` D.
`sendSQL()` Correct Answer: C
3. What does the `fetchone()` function do in database connectivity?
A. Fetches the first row of the query result B. Fetches all rows of the query result
C. Fetches a specific row based on the index D. Fetches the last row of the query result
Correct Answer: A
4. What is the purpose of the `rowcount` attribute in Python's database connectivity?
A. Number of rows affected by the last executed command
B. Total number of rows in the database
C. Total number of columns in the database
D. Number of tables in the database
Correct Answer: A
88 | P a g e
`fetchall()` Correct Answer: D
8. What is the primary purpose of the `cursor()` function in database connectivity?
A. Connects to the database B. Executes SQL commands
C. Fetches data from the database D. Creates a cursor object to execute SQL
queries Correct Answer: D
9. In Python's database connectivity, what does SQL injection refer to?
A. A way to securely connect to the database
B. A method to execute multiple SQL commands in one go
C. A code injection technique where malicious SQL statements are inserted into a query
D. A function to fetch rows from the
database Correct Answer: C
10. Which function is used to close the database connection in Python?
A. close() B. disconnect() C. end() D.
finish() Correct Answer: A
Assertion Reason Questions :
1. Assertion: `fetchall()` retrieves only the first row of the query result.
Reason: `fetchall()` function fetches all rows of the query result set.
Correct Answer: False. Assertion is incorrect, and the Reason is incorrect.
2. Assertion:The `rowcount` attribute is used to get the number of rows affected
by the last executed command.
Reason: It helps in determining the number of columns in the query
result. Correct Answer: True. Assertion is correct, and the Reason is
correct.
3. Assertion: `commit()` is essential after executing SQL commands to save the changes
made during the transaction.
Reason: It is necessary to close the database connection.
Correct Answer: True. Both Assertion and Reason are correct, and the Reason is the correct
explanation of the Assertion.
4. Assertion: `%s` format specifier in SQL queries helps prevent SQL injection attacks.
Reason: It dynamically inserts values into queries, enhancing flexibility and security.
Correct Answer: True. Both Assertion and Reason are correct, and the Reason is the correct
explanation of the Assertion.
5. Assertion: `connect()` function creates a cursor object for executing SQL commands.
Reason: `cursor()` function establishes a connection to the database.
Correct Answer: False. Assertion is incorrect, and the Reason is incorrect.
True/False Questions :
1. The `fetchone()` function retrieves all rows of a query result set. (False )
2. The `execute()` function is used for executing SQL commands in Python's database
connectivity. (True)
3. `commit()` function is used to save the changes made during the transaction. (True)
4. SQL injection is a technique to securely connect to the database. (False)
5. The `%s` format specifier or `format()` is used to dynamically insert values into SQL
queries. (True)
89 | P a g e
Short Answer (SA-1) Questions :
1. Discuss the steps involved in creating a database connectivity application using Python.
2. Compare and contrast `fetchone()` and `fetchall()` functions in Python's database
connectivity.
3. Explain the importance of using placeholders like `%s` in SQL queries with examples.
4. Describe the use of `format()` function in dynamically inserting values into SQL queries.
Provide an example.
5. How can the `rowcount` attribute be used to determine the success of an SQL query in
Python?
6. Discuss two common security risks associated with database connectivity in Python
and how to mitigate them.
7. Explain the process of creating a cursor object and its significance in database
operations using Python.
8. How does `commit()` function contribute to data integrity in database transactions?
9. What is the role of the `rollback()` function in database transactions? Provide an
example scenario.
10. Explain how exceptions are handled in Python's database connectivity to
manage errors in SQL queries.
90 | P a g e
Computer Networks
Mind Map
Computer Network
It is a group of computers connected with each other through wires, optical fibres or optical links
so that various devices can interact with each other through a network.
The aim of the computer network is the sharing of resources among various devices.
In the case of computer network technology, there are several types of networks that vary from
simple to complex level.
Brief History of Network-
91 | P a g e
In 1967, ARPA (Advance Research Project Agency by Department of Defence) proposed
the idea of ARPANET – a small network of computers.
By 1969, ARPANET became reality that connect four nodes at University of California at
Los Angeles (UCLA), University of California at Santa Barbara (UCSB), Stanford Research
Institute (SRI) and University of Utah via IMPs ( Interface Message Processor – a
specialized computer).
In 1973, Vint Cerf and Bob Kahn presented paper outlined the protocol (
Transmission Control Protocol) to achieve end-to-end delivery of packets.
Network Terminology:
Node: Any device connected to a network, such as a computer, printer, or router.
Protocol: A set of rules and standards that define how devices on a network communicate
with each other.
IP Address: A unique numerical identifier assigned to each device on a network, used to
identify and communicate with other devices.
TCP/ IP: Transmission Control Protocol/Internet Protocol. TCP/IP is a set of standardized rules
that allow computers to communicate on a network such as the internet
Network Interface Card or Unit (Network Adapter or LAN card) - It is hardware that allows a
computer (or device) to connect to network.
MAC (Media Access Control) address – Each NIC is assigned a unique 12 digit hexadecimal
number, known a MAC address, is used as network address in communication. The format for the
MAC address is
MM : MM : MM : SS : SS : SS
Manufacturer ID Card Id
Channel – It is communication path through which data is actually transmitted.
Communication Media- It is allows data or signal to be communicated across the devices. It is
means of communication.
92 | P a g e
Data – Information stored within the computer system in form of ‘0’ and ‘1’
Bit rate – It defines the amount of data transferred. It is defined as number of bits per second
(bps). [Bps – Bytes per Second]
Baud – The number of changes in signal per second.
Bandwidth – It is difference between the highest and the lowest frequencies contained in the
signal.
Difference Between MAC Address and IP Address:
Switching Technique
In computer networking, Switching is the process of transferring data packets from one
device to another in a network, or from one network to another, using specific devices
called switches.
Types of Switching: There are three types of switching methods:
Message Switching
Circuit Switching
Packet Switching
Circuit Vs Packet Switching
93 | P a g e
Network Devices
RJ 45 Connector: RJ45 stands for Registered Jack 45 and is the most commonly used connector
in wired networks. The jacks are mainly used to connect to the Local Area Network (LAN).
Ethernet Card: An Ethernet card enables a computer to access the Internet by means of an
Ethernet cable. An Ethernet port is necessary to connect the cable to the computer. Ethernet
cards are internal and come standard on most new computers - both laptops and desktops.
Wi-Fi Card:iIt may be internal or external with built-in wireless radio and antenna. The
most common Wi-Fi card used in desktop computer are PCI-Express Wi-Fi card made it
fit the PCI-Express card slots on the motherboard. It allows to connect our device to
hotspot available. Advantage is that it allows computer to become part of network without
being physically connected through wire and can be placed anywhere.
94 | P a g e
Types of Computer Networks
There are following main types of Computer Networks: -
LAN (Local Area Network) – Systems connected in a small network like in a building or a small
office
It is inexpensive
It uses Ethernet
Two or more personal computers can be connected through wires or cables acting as
nodes
Transfer of data is fast.
MAN (Metropolitan Area Network) – A network that can be connected within a city, for
example, cable TV Connection
It has a higher range
This type of network can be used to connect citizens with the various Organizations.
WAN (Wide Area Network) – A network which covers over a country or a larger range of people
Telephonic lines are also connected through WAN
Internet is the biggest WAN in the world
Mostly used by Government Organizations to manage data and information.
Network Media
Network media usually refers to the various means of communication and the transmission of
information over computer networks, such as the Internet.
Types of Network Media
o Guided or Wired
Telephone (T1) cable
Twisted pair cable
STP (Shielded Twisted Pair)
UTP (Unshielded Twisted Pair)
Co-axial cable
Optical Fiber/Fibre
o Unguided or Wireless
Infrared
Radio Wave
Microwave
Bluetooth
Satellite
Advantages:
95 | P a g e
It is the least expensive medium of transmission for short distances.
It is relatively easy to implement and terminate.
It is flexible and lightweight.
It is easy to set up and install.
Less susceptible to electrical interference caused by nearby equipment or uses of wires.
Disadvantages:
Attenuation is very high.
It offers poor noise immunity as the result signal distortion is too much more.
STP called shielded twisted pair cable is more difficult to connect to a terminating block.
Susceptible to noise and interference.
Co-axial Cable
Coaxial cabling has a single copper conductor at its center, and a plastic layer thatprovides
insulation between the center conductor and a braided metal shield.
Connector: BNC (Bayonet Neill-Concelman)
Advantages:
The cost of a coaxial cable is less.
Highly resistant to physical damage.
Great channel capacity.
The transmission rate is high.
It is less susceptible to noise interference compare to twisted pair.
It is easy to wire and easy to expand to flexibility.
It support high bandwidth signal transmission compare to twisted pair.
It requires fewer repeater than twisted pair.
Disadvantage:
It is bulky.
It has a more security problem.
It does not support high-speed transmission.
It must be grounded to prevent interference.
In case of failure in one cable, the entire It is expensive to install.
Cost maintenance is also high.
Inflexible construction.
Unsupported by newer network will be down by using this wire.
Optical Fibre
An optical fiber is a flexible, transparent fiber made by drawing glass or plastic to a
diameter slightly thicker than that of a human hair.
It uses light for data transmission using total internal reflection.
Advantages:
Higher bandwidth
Less signal attenuation
Immune to cross-talk
Optical fiber have long life more than 100 or above years
Resistance to corrosive material
Long distance transmission is possible
Immunity to electromagnetic interference
Disadvantages:
Unidirectional propagation
High initial cost
Optical fiber more tensile stress than copper cables
96 | P a g e
Installation and maintenance
Fiber joining process is very costly and require skilled menpower
Difficult to splice (join)
Difficult to find error
Radio Wave
Frequency – 3KHz – 1GHz
Omni-Directional
Penetrate obstacle
Antenna of sender and receiver should not be aligned
Infrared
300GHz to 400THz
Line of sight- antenna of sender and receiver must be aligned
Short distance communication
It cannot penetrate obstacle – best suited for indoor
Secure
Support high data rate
TV Remote
Microwave
1GHz to 300 GHz
Line of sight- antenna of sender and receiver must be aligned
Cannot penetrate obstacles
Rain or other disturbance cause issue with Microwave
Types of microwave propagation
Terrestrial Microwave propagation
Satellite Microwave propagation
Bluetooth
It also uses radio waves
2.4 GHz
Range 10mtr
Short distance
Network Topology
A Network Topology is the arrangement with which computer systems or network devices are
connected to each other. Topologies may define both physical and logical aspect of the network.
Both logical and physical topologies could be same or different in a same network.
Point-to-Point
Point-to-point networks contains exactly two hosts such as computer, switches or routers,
servers connected back to back using a single piece of cable. Often, the receiving end of one host
is connected to sending end of the other and vice-versa.
97 | P a g e
If the hosts are connected point-to-point logically, then may have multiple intermediate devices.
But the end hosts are unaware of underlying network and see each other as if they are connected
directly.
Bus Topology
In case of Bus topology, all devices share single communication line or cable.Bus topology may
have problem while multiple hosts sending data at the same time. Therefore, Bus topology either
uses CSMA/CD technology or recognizes one host as Bus Master to solve the issue. It is one of the
simple forms of networking where a failure of a device does not affect the other devices. But
failure of the shared communication line can make all other devices stop functioning.
Both ends of the shared channel have line terminator. The data is sent in only one direction and
as soon as it reaches the extreme end, the terminator removes the data from the line.
Star Topology
All hosts in Star topology are connected to a central device, known as hub device, using a point-
to-point connection. That is, there exists a point to point connection between hosts and hub
98 | P a g e
As in Bus topology, hub acts as single point of failure. If hub fails, connectivity of all hosts to all
other hosts fails. Every communication between hosts, takes place through only the hub. Star
topology is not expensive as to connect one more host, only one cable is required and
configuration is simple.
Advantages –Star Topology
Reliable
Robust
Failure of node does not affect the working of the network.
Fault detection and isolation is easy.
Maintenance of the network is easy.
It doesn’t create bottlenecks where data collisions occur.
Ring Topology
In ring topology, each host machine connects to exactly two other machines, creating a circular
network structure. When one host tries to communicate or send message to a host which is not
adjacent to it, the data travels through all intermediate hosts. To connect one more host in the
existing structure, the administrator may need only one more extra cable.
Failure of any host results in failure of the whole ring. Thus, every connection in the ring is a
point of failure. There are methods which employ one more backup ring.
Advantage – Ring Topology
It is easy to connect a device to the network.
It requires less cable length.
Low setup cost
There is no need of Hub/Switch
Minimum collision
Suitable for Optical Fibre Network
99 | P a g e
Disadvantage – Ring Topology
Failure of one node can shutdown entire network
There is a limit on central cable length and number of nodes that can be connected.
Difficult to find and correct errors.
Maintenance costs can get higher with time.
Not suitable for Big network.
Low Security due to broadcasting of data.
Mesh Topology
In this type of topology, a host is connected to one or multiple hosts. This topology has hosts in
point-to-point connection with every other host or may also have hosts which are in point-to-
point connection to few hosts only.
Hosts in Mesh topology also work as relay for other hosts which do not have direct point-to-point
links.
Tree Topology
Also known as Hierarchical Topology, this is the most common form of network topology in use
presently. This topology imitates as extended Star topology and inherits properties of bus
topology.
This topology divides the network in to multiple levels/layers of network. Mainly in LANs, a
network is bifurcated into three types of network devices. The lowermost is access-layer where
computers are attached. The middle layer is known as distribution layer, which works as
mediator between upper layer and lower layer. The highest layer is known as core layer, and is
central point of the network, i.e. root of the tree from which all nodes fork.
All neighboring hosts have point-to-point connection between them. Similar to the Bus topology,
if the root goes down, then the entire network suffers even though it is not the single point of
failure. Every connection serves as point of failure, failing of which divides the network into
unreachable segment.
Advantages- Tree Topology
100 | P a g e
It is a combination of bus and star topology
Other nodes in a network are not affected, if one of their nodes get damaged
It provides easy maintenance and fault identification.
Point-to-point wiring for individual segments.
Disadvantages -Tree Topology
Large cabling is required as compared to star and bus topology.
On the failure of a hub, the entire network fails.
Tree network is very difficult to configure than other network topologies.
Hybrid Topology
A network structure whose design contains more than one topology is said to be hybrid topology.
Hybrid topology inherits merits and demerits of all the incorporating topologies.
The above picture represents an arbitrarily hybrid topology. The combining topologies may
contain attributes of Star, Ring, Bus, and Daisy-chain topologies. Most WANs are connected by
means of Dual-Ring topology and networks connected to them are mostly Star topology
networks. Internet is the best example of largest Hybrid topology
Protocol
It is set of rules or standard that governs communication.
Types of Protocol
HTTP
FTP
FTP
PPP
SMTP
TCP/IP
POP3
HTTPS
Remote Access Protocol(Telnet)
VoIP
101 | P a g e
It works on application layer of OSI model.
It is used to transfer the files on internet.
Making projects being on long distance is possible with transferring files using this
protocol.
FTP ensures to use different conventions while naming files.
It provides secure login method for effective transfer of files.
It provides the different directory structure for different files.
102 | P a g e
Remote Access Protocol (Telnet)
This protocol helps a user (Telnet Client) to log in at a remote computer (Telnet Server) and
function as if he/she were connected directly to that computer. Telnet is the main internet
protocol for creating a connection with a remote machine. It allows you to connect to remote
computers (called remote hosts) over a TCP/IP network (such as the Internet). Once your telnet
client establishes a connection to the remote host, your client becomes a virtual terminal,
allowing you to communicate with the remote host from your computer with whatever privileges
you may have been granted to the specific application and data on that host computer.
VoIP
VOIP: Voice over Internet Protocol (Voice over IP, VoIP and IP telephony) is a group of
technologies for the delivery of voice communications and multimedia sessions over Internet.
The terms Internet telephony, broadband telephony, and broadband phone service specifically
refer to the provisioning of communications services (voice, fax, SMS, voice-messaging) over the
public Internet, rather than via the public switched telephone network (PSTN). This method of
making phone calls is much cheaper than convectional way because the service of
Telecommunication Company is not used.
Application of Internet
Web 2.0 :
The term web 2.0 is used to refer to a new generation of websites that are supposed to let
people to publish and share information online.
It aims to encourage the sharing of information and views, creativity that can be consume
by the other users. E.g: Youtube
The Main characteristics of web 2.0:
o Makes web more interactive through online social media web- based forums,
communities, social networking sites.
o It is a website design and development world which aim to encourage sharing of
information and views, creativity and user interactivity between the users.
o Video sharing possible in the websites
Web 3.0
It refers to the 3rd Generation of web where user will interact by using artificial
intelligence and with 3-D portals.
Web 3.0 supports semantic web which improves web technologies to create, connect and
share content through the intelligent search and the analysis based on the meaning of the
words, instead of on the keywords and numbers.
103 | P a g e
Domain Names:
Every computer on the network has a unique numeric address assigned to it which is a
combination of four numbers from 0-255 separated by a dot. For example, 59.177.134.72 since it
is practically impossible for a person to remember the IP addresses. A system has been
developed which assigns domain names to web servers and maintains a database of these names
and corresponding IP addresses on DNS (Domain Name Service) server.
Examples of some domain names are cbse.nic.in, indianrailway.gov.in etc. A domain name usually
has more than one part for example, in the domain name www.cbse.nic.in
in is the primary domain name
nic is the sub-domain of in
cbse is the sub-domain of nic
www indicates the server is on world wide web.
URL (Uniform resource locator): A URL is a formatted text string used to identify a network
resource on the Internet. Network resources can be plain Web pages, text documents, graphics,
downloadable files, services or programs. Every network resource on the web has a unique URL
in the following format:
Protocol: // domain name /path / file name
Network Protocol: The network protocol identifies the protocol to be used to access the
network resource. These strings are short names followed by the three characters ': //’. Some
examples of protocols include http, gopher, ftp and mailto.
Domain name: It identifies the host/server that holds the resource. For example: www.
School.com is a domain name.
Resource Location: It consists of the path or directory and the file name of resource. For
example in the URL :
http://www.school.com/syllabus/preprimary/nursery.htm the file nursery.htm is stored in the
sub directory preprimary, of the directory syllabus on the server www.school.com
Web hosting: Web hosting is the process of uploading/saving the web content on a web server to
make it available on WWW. In case an individual or a company wants to make its website
available on the internet, it should be hosted on a web server.
Web page
A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera,
Microsoft Edge, or Apple Safari. These are also often called just "pages."
104 | P a g e
Difference between Static web page and Dynamic web page
Static web page: A web page which Dynamic web page: An interactive web
displays same kind of information page is a dynamic webpage. A dynamic
whenever a user visits it is known as web page uses scripting languages to
a static web page. A static web page display changing content on the web
generally has .htm or .html as page. Such a page generally has .php,
Extension .asp or .jspas extension.
Website:
A collection of web pages which are grouped together and usually connected together in various
ways. Often called a "website" or a "site."
Web server
A web server is a computer hosting one or more websites. "Hosting" means that all the web
pages and their supporting files are available on that computer. The web server will send any web
page from the website it is hosting to any user's browser, per user request.
Abbreviations:
1 NIU Network Interface Unit
2 MAC Media Access Control
3 TCP/IP Transmission Control Protocol/Internet Protocol
4 PAN Personal Area Network
5 LAN Local Area Network
6 MAN Metropolitan Area Network
7 WAN Wide Area Network
8 UTP Unshielded Twisted Pair
9 STP Shielded Twisted Pair
10 Mbps Mega bits per sec
11 EMI Electro Magnetic Interference
12 RJ Registered Jack
13 Wi-Fi Wireless Fidelity
14 VPN Virtual Private Network
15 IAAS Infrastructure As A Service
16 PAAS Platform As A Service
17 SAAS Software As A Service
18 DAAS Desktop As A Service
19 IOT Internet Of Things
20 NIC Network Interface Card
21 CSMA/CD Carrier Sense Multiple Access/Collision Detection
22 CSMA/CA Carrier Sense Multiple Access/Collision Avoidance
23 DNS Domain Name System
24 DHCP Dynamic Host Configuration Protocol
25 ISP Internet Service Provider
26 URL Uniform Resource Locator
27 HTTP Hyper Text Transfer Protocol
28 FTP File Transfer Protocol
29 FDMA Frequency Division Multiple Access
105 | P a g e
30 TDMA Time division Multiple Access
31 CDMA Code Division Multiple Access
32 SIM Subscriber Identity Module
33 EDGE Enhanced Data rates for GSM Evolution
34 UMTS Universal Mobile Telecommunications System
35 LTE Long Term Evolution
36 GPRS General Packet Radio Service
37 ICMP Internet Control Message Protocol
38 OSI Open Systems Interconnection
39 SMTP Simple Mail Transfer Protocol
40 VoIP Voice Over Internet Protocol
41 SIP Session Initiation Protocol
42 QoS Quality of Service
43 POP Post Office Protocol
44 IMAP Internet Mail Access Protocol
45 SCP Secure Copy Protocol
46 SSH Secure Shell
47 IEEE Institute of Electrical & ElectronicEngineering
48 NFC Near-Field Communication
49 NFS Network File System
50 NTP Network Time Protocol
51 SLIP Serial Line Internet Protocol
52 PPP Point to Point Protocol
53 UDP User Datagram Protocol
54 SNMP Simple Network Management Protocol
106 | P a g e
Ans: (c)
Q 9. Rahul is in India and he wants to communicate with his friend in America. He wants to show
him his new gadgets without going to America. Which protocol out of the following will be
suitable for the same?
a) POP3 (b) VoIP (c) SMTP (4) HTTP
Ans: (b)
Q 10. In which type of switching technique, the resources are allocated on demand?
a) Packet Switching (b) Line Switching
(c) Parallel Switching (c) Circuit Switching
Ans: (a)
107 | P a g e
Ans: Switch
Q 7. Give two examples of Instant messenger.
Ans: Skype, Facebook Messenger, WhatsApp
Q 8. What is Error 404?
Ans: If the server is not able to locate the page, it sends a page containing the error message
(Error 404-page not found) to the client’s post.
Q 9. Name an open source web browser?
Ans. Mozilla Firefox is an open source web browser.
Q 10. Packet switching is based on _______ principle.
Ans: Store and Forward
SHORT QUESTIONS
Q1. Expand following –
HTTPS, TDMA
Ans: HTTPS- Hypertext Transfer Protocol Secure
TDMA-Time division multiple access
Q 2. Name two transmission media for networking
Ans: Optical Fibre , Satellite
Q 3. What is the name of earliest for m of Internet. Also expand it.
Ans: ARPANET (Advanced Research Project Agency Network)
Q 4. Why switch is known as intelligent hub?
Ans: Switch filters the incoming packets and finds the destination node from the MAC Table. It
transmits data only to intended node.
Q 5. What is a protocol? Which protocol is used to search information from Internet using an
Internet browser? .
Ans: Protocol refers to the rules which are applicable for a network. These protocols define the
standardised format for data packets to be transmitted over the network, techniques for
detecting errors and correcting them etc.
The protocol used to search the information from Internet using browser is Hyper Text Transfer
Protocol (HTTP).
108 | P a g e
Q 6. What is an IP address?
Ans: An Internet Protocol address (IP address) is a numerical unique address of a device in a
network. IP is a datagram-oriented connectionless protocol, therefore each packet must contain a
header with the source IP address, the destination IP address, and other data in order to be
delivered successfully.
Q 7. Write two differences between HUB AND Switch.
Ans : Differences are:
1. W
h
i
c
h
w
i
l
l
b
e the most appropriate block, where TTC should plan to install their server?
2. Draw a block to block 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 set up of offices in Bangalore with its London based office.
i. Satellite Link
ii. Infrared
iii. Ethernet
4. Which of the following device will be suggested by you to connect each computer in each
of the buildings?
109 | P a g e
Switch, Modem, Gateway
Ans:
1. TTC should install its server in finance block as it is having maximum number of computers.
2.
The above layout is based on minimum cable length required, which is 120 metres in the above
case.
3. Satellite Link.
4. Switch
Q 2. Freshminds University of India is starting its first campus in Ana Nagar of South India with
its centre admission office in Kolkata. The university has three major blocks comprising of Office
block, Science Block and commerce block is in 5 km area campus.
As a network expert, you need to suggest the network plan as per (i) to (iv) to the authorities
keeping in mind the distance and other given parameters
1. Suggest the authorities, the cable layout amongst various blocks inside university campus
for connecting the blocks.
2. Suggest the most suitable place (i.e. block) to house the server for this university with a
suitable reason.
3. Suggest an efficient device form the following to be installed in each of the block to
connect all the computers: (a) Modem (b) Switch (c) Gateway
110 | P a g e
4. Suggest the most suitable (very high speed) service to provide data connectivity between
admission office located in Kolkata and the campus located in Ana Nagar form the
following options:
Telephone line
Fixedline dial-up connection
Co-axial cable network
GSM
Leased line
Satellite connection
Ans: 1.
2. The most suitable place to house the server is Science Block as it has maximum number of
computers. Thus, reducing the cabling cost and increases efficiency of network.
3. (b) Switch is the device to be installed in each of the blocks to connect all the computers.
4. Satellite Connection
Q 3. Learn Together is an educational NGO. It is setting up its new campus at Jabalpur for its web-
based activities. The campus has four compounds as shown in the diagram below:
Аnswer: 1.
2. The most suitable place to house the server is Training Compound as it has a maximum
number of computers.
3. (a) Repeater As per one layout (shown in (1)), the repeater can be avoided as all distances
between the compounds are <=100 m.
(b) Hub/Switch Training compound as it is hosting the server.
4. (b) Optical fibre.
1. Suggest the type of networking (LAN, MAN, WAN) for connecting Lib Wing to Admin
Wing. Justify your answer.
2. Suggest the most suitable place (i.e. wing) to house the server, with a suitable reason.
3. Suggest and placement of the following devices with reasons.
(a) Repeater
(b) Switch
4. The Institute is planning to link its study centre situated in Delhi. Suggest an economic
way to connect it with reasonably high speed. Justify your answer.
Аnswer:
1. Since, the distance between Lib Wing and Admin Wing is small. So type of networking is
small, i.e. LAN.
2. Since, maximum number of computers are in Student Wing, so suitable place to house the
server is Student Wing.
3. (a)Repeater should be installed between Student Wing and Admin Wing as distance is
more than 60 m.
(b) Switch should be installed in each wing to connect several computers.
4. Broadband connection as it is between economical and speedy
112 | P a g e
Q 5. Vidya for All is an educational NGO. It is setting up its new campus at Jaipur for its web-
based activities. The campus has four buildings as shown in the diagram below:
1.
2. The most suitable place to house the server for this NGO is Training Building because it has the
maximum number of computers.
3. (a) Repeater As per one layout (shown in (i)), the repeater can be avoided as all distances
between the compounds are <= 100 m.
(b) Hub/Switch Training building as it is hosting the server.
4. (b) Optical fibre.
113 | P a g e
KENDRIYA VIDYALAYA SANGATHAN, DELHI REGION
Sample Question Paper 2024-25
Class- XII Subject- COMPUTER SCIENCE (083)
M.M.- 70 Time Allowed- 3 Hours
General Instructions:
Please check this question paper contains 35 questions.
The paper is divided into 5 Sections- A, B, C, D and E.
Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
All programming questions are to be answered using Python Language only.
a) bring#it#ON b) bring#it#on
c) Bring#it#On d) bring#it#On
5 In MYSQL database, if a table EVENTS has degree 6 and cardinality 9 and another 1
table ORGANISERS has degree 4 and cardinality 5 what will be the degree and
cardinality of the Cartesian product of both table?
a) 24, 14 b) 30, 13 c) 10, 45 d) 36, 11
6 An organization has three offices at Gurgaon, Bangalore and Mumbai which are 1
connected to form a network. Which type of network will be formed?
a) LAN b) PAN c) WAN d) MAN
7 What will be the output of the following python dictionary operation?
data = {'A':2000, 'B':2500, 'C':3000, 'A':4000}
print(data)
a) {'A':2000, 'B':2500, 'C':3000, 'A':4000}
b) {'A':2000, 'B':2500, 'C':3000}
c) {'A':4000, 'B':2500, 'C':3000}
d) Error
8 Which of the following operations on a string will generate an error? 1
a. "DELHI"*4 b. "DELHI" + "400"
c. "DELHI" + 40 d. "DELHI" + "DELHI"
9 Which of the following statement(s) would give an error after executing the 1
114 | P a g e
following code?
D={'rno':32,'name':'Ms Archana','subject':['hindi','english'],'marks':(85,75)} #S1
print(D) #S2
D['subject'][1]='IP' #S3
D['marks'][1]=80 #S4
print(D) #S5
(A) S1 (B) S3
(C) S4 (D) S3 and S4
10 import random 1
List=["Delhi","Mumbai","Chennai","Kolkata"]
for y in range(4):
x = random.randrange(1,3)
print(List[x],end="#")
a. Delhi#Mumbai#Chennai#Kolkata#
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi#
d. Mumbai# Mumbai #Chennai # Mumbai
11 Select the network device from the following, which connects, networks with 1
different protocols
call()
print(a)
a. 10 b. 20 c. 15 d. 25
13 State whether the following statement is True or False 1
“Every syntax error is an exception but every exception cannot be a syntax error”
14 Which of the following is not true? 1
a)A set of more than one attribute cannot be a key.
b)Foreign key is an attribute value of which is derived from the primary key
of another table.
c)Combination of Primary Key with any other attribute is an alternate key.
d)A Key can comprise of more than one attributes
15 Fill in the blank: In case of _____________ switching, before a communication starts, 1
a dedicated path is identified between the sender and the receiver.
16 Which of the following functions changes the position of file pointer and 1
returns its new position?
a. flush( ) b. tell( )
c. seek( ) d. offset( )
Q 17 and 18 are ASSERTION AND REASONING based questions. Mark the
correct choice as
115 | P a g e
a)Both A and R are true and R is the correct explanation for A
b)Both A and R are true and R is not the correct explanation for A
c)A is True but R is False
d)A is False but R is True
17 Assertion (A): Dictionary is an immutable data type 1
Reasoning (R): Item assignment or in-place changes in an object of immutable
data type after its creation results in error.
18 Assertion(A):Key word arguments are related to the function calls 1
Reason(R): When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
116 | P a g e
return l1,l2
a,b=show("FUN",'DAY')
print(a,b)
23 Write the Python statement for each of the following tasks using BUILT-IN 2
functions/methods only:
i. To return index position of substring in given string.
ii. To delete first occurrence of an item in the list
OR
A list named stu_marks stores marks of students of a class. Write the Python
command to import the required module and display the average of the marks in
the list.
24 Mr. Sarthak has just created a table name ‘Wrestling’ containing columns Pname, 2
Style, WeightCategory. After creating the table he realized that he has forgotten to
add a primary key column in the table. Help him in writing an SQL command to
add a primary key column PlayerId of integer type to the table Wrestling.
Thereafter write the command to insert the following record in the table:
PlayerId – 999, Pname – Tyler, Style – BJJ, WeightCategory – 75
OR
Manan is working in a database named Vehicle in which he has created a table
name ‘Car’ containing columns CarId, BrandName, Model and MfgYear.
After creating the table he realized that the attribute Model has to be deleted
from the table and a new attribute Variant of data type string of size 20 has to be
added. This attribute Variant cannot be left blank. Help Manan write the
commands to complete both the tasks.
x,y = 200, 20
x = trap(x, y)
print(x, y, sep=‘#’)
y = trap(x, y)
print(y, x, sep=‘#’)
117 | P a g e
print(m)
Display('[email protected]')
27 Consider the table BANK given below and write the output of the SQL queries 3
that follow.
28 Write a function in Python to count the number of lines in a text fie ‘EXAM.txt’ 3
which start with an alphabet ‘T’ .
OR
Write a function in Python that count the number of “can” words present in a
text file “DETAILS.txt” .
Based on the given table write SQL queries for the following:
i. Change the Flavour of the chips to “black salt “ for those chips whose flavour is
“SALTY”.
ii. Display the Brand_Name ,Flavour and Total amount(price*quantity) of those
chips whose Brandname ends with ‘s’. Total Amount column name should also be
displayed.
iii. Delete the records of those chips whose quantity is less than 10.
Each of these records are nested together to form a nested list. Write the
following user defined functions in Python to perform the specified operations
on the stack named MustGo.
118 | P a g e
(i) Push_element(FJList, MustGo): It takes the nested list as an argument and
pushes a list object containing name of FoodJoint and its Cuisine is other than
Chinese and has rating more than 4.
119 | P a g e
33 TechCloud is an educational organization. It is planning to setup its campus at 5
Jaipur with its head office at Delhi. The Jaipur campus has 4 main buildings –
ADMIN, FINANCE, STUDIO and DATA CENTER.
a) Suggest and draw the cable layout to efficiently connect various blocks of
buildings within the Jaipur campus.
b) In which block should the server be placed and why?
c) Suggest the placement of following devices:
i) Switch/hub
ii)Repeater
d) Which cost efficient wired medium should be used to connect the computers
in Jaipur campus?
e) Which type of network is formed by connecting Delhi Head Office with
Jaipur Campus?
34 (i) Differentiate between r+ and w+ file modes in Python. 2+3
(ii) Consider a file Company.dat containing records of the following structure:
[ CompanyName, Type, No_members ]
Write a function copyData() that reads contents form the file Company.dat and
copies the records with Type “EduTech” to the file name EduTechs.dat. The
function should return the total number of records copied to the file
EduTechs.dat.
OR
(i) Write two differences between binary and text files.
(ii) A binary file multiplex.dat has the following structure:
{ screeenNo : [movieName,genre]}
Write a user defined function findType(type) that accepts type as parameter and
displays all the records from the binary file multiplex.dat that have the genre as
value provided in type.
35 (i) Define the term Domain with respect to RDBMS. 5
(ii) Shreyaan wants to write a program in Python to insert the following record
in the table named Tours in MySQL database TRAVELS:
● TourId – integer
● Destination – string
● Departure – date
● Price – float
Note the following to establish connectivity between Python and MySQL
● Username – admin
● Password – passkey
120 | P a g e
● Host – localhost
The value of the fields TourId, Destination, Departure and Price has to be
accepted form the user. Help Shreyaan to write the program in Python.
OR
(i) Give one difference between primary key and unique.
(ii) Yuvin has created a table named Courses in MySQL database PyAcademy
with following structure:
● Cid – integer
● Cname – string
● StartDate – date
● Fee – float
Note the following to establish connectivity between Python and MySQL
● Username – admin
● Password – passkey
● Host – localhost
Yuvin now wants to display the records of courses fees of which is greater than
5000. Help Yuvin to write the program in Python.
121 | P a g e
KENDRIYA VIDYALAYA SANGATHAN, DELHI REGION
Sample Question Paper 2024-25
Class- XII Subject- COMPUTER SCIENCE (083)
M.M.- 70 Time- 3 Hours
MARKING SCHEME
SECTION A (1 MARK QUESTIONS)
1 State True or False: 1
“Python has a set of keywords that can be used to declare variables”
Ans False
2 In a table in MYSQL database, an attribute A of data-type varchar(20) has the 1
value “Manan”. The attribute B of data-type char(20) has value “Shreyaan”.
How many characters are occupied by attribute A and attribute B?
a) 20,8 b) 5,20 c) 20,20 d) 5,8
Ans b) 5,20
3 Evaluate the following expression and identify the correct answer. 1
16 - 4 + 2 * 5 + 2**3 * 4
a. 54 b. 46 c. 18 d. 32
Ans a) 54
4 Select the output of the code: 1
s = “Bring it on”
l = s.split()
s_new = “#”.join([l[0].lower(), l[1], l[2]])
print(s_new)
a) bring#it#ON b) bring#it#on
c) Bring#it#On d) bring#it#On
Ans d) bring#it#On
5 In MYSQL database, if a table EVENTS has degree 6 and cardinality 9 and 1
another table ORGANISERS has degree 4 and cardinality 5 what will be the
degree and cardinality of the Cartesian product of both table?
a) 24, 14 b) 30, 13 c) 10, 45 d) 36, 11
Ans c) 10,45
6 An organization has three offices at Gurgaon, Bangalore and Mumbai which are 1
connected to form a network. Which type of network will be formed?
a) LAN b) PAN c) WAN d) MAN
Ans c) WAN
7 What will be the output of the following python dictionary operation?
data = {'A':2000, 'B':2500, 'C':3000, 'A':4000}
print(data)
a) {'A':2000, 'B':2500, 'C':3000, 'A':4000}
b) {'A':2000, 'B':2500, 'C':3000}
c) {'A':4000, 'B':2500, 'C':3000}
d) Error
Ans c) {'A': 4000, 'B': 2500, 'C': 3000}
8 Which of the following operations on a string will generate an error? 1
a. "DELHI"*4 b. "DELHI" + "400"
c. "DELHI" + 40 d. "DELHI" + "DELHI"
Ans c. "DELHI" + 40
9 Which of the following statement(s) would give an error after executing the 1
following code?
122 | P a g e
D={'rno':32,'name':'Ms Archana','subject':['hindi','english'],'marks':(85,75)} #S1
print(D) #S2
D['subject'][1]='IP' #S3
D['marks'][1]=80 #S4
print(D) #S5
(A) S1 (B) S3
(C) S4 (D) S3 and S4
Ans (C) S4
10 import random 1
List=["Delhi","Mumbai","Chennai","Kolkata"]
for y in range(4):
x = random.randrange(1,3)
print(List[x],end="#")
a. Delhi#Mumbai#Chennai#Kolkata#
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai# Mumbai #Mumbai # Delhi#
d. Mumbai# Mumbai #Chennai # Mumbai#
Ans d. Mumbai# Mumbai #Chennai # Mumbai
11 Select the network device from the following, which connects, networks with 1
different protocols
a) Bridge b)Gateway c)Hub d) Router
Ans b)Gateway
12 Find and write the output of the following python code: 1
a=10
def call():
global a
a=15
b=20
call()
print(a)
a. 10 b. 20 c. 15 d. 25
Ans c. 15
13 State whether the following statement is True or False 1
“Every syntax error is an exception but every exception cannot be a syntax
error”
Ans True
14 Which of the following is not true? 1
a)A set of more than one attribute cannot be a key.
b)Foreign key is an attribute value of which is derived from the primary key
of another table.
c)Combination of Primary Key with any other attribute is an alternate key.
d)A Key can comprise of more than one attributes
Ans a)A set of more than one attribute cannot be a key.
15 Fill in the blank: In case of _____________ switching, before a communication starts, 1
a dedicated path is identified between the sender and the receiver.
Ans Circuit Switching
16 Which of the following functions changes the position of file pointer and 1
returns its new position?
123 | P a g e
a. flush( ) b. tell( )
c. seek( ) d. offset( )
Ans c) seek()
Q 17 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): Dictionary is an immutable data type 1
Reasoning (R): Item assignment or in-place changes in an object of immutable
data type after its creation results in error.
Ans d) A is False but R is True
18 Assertion(A):Key word arguments are related to the function calls. 1
Reason(R): When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
Ans a. Both A and R are true and R is the correct explanation for A
SECTION B (2 MARKS QUESTIONS)
19 i) Expand the following : 2
a) SMTP b) VoIP
ii) Give one disadvantage of Star topology
OR
i) What is a web browser ?
ii) Define the term MAC Address
Ans i) Expand the following :
20 The code given below accepts a number as an argument and returns the list of 2
all prime numbers upto that number. Observe the following code carefully and
rewrite it after removing all syntax and logical errors. Underline all the
124 | P a g e
corrections made.
define prime(num):
for i in range(2,n/2+1,1)
if num%i=0:
print(‘Not prime’)
Break
else:
print(‘Prime’)
Ans def prime(num):
for i in range(2,n//2+1,1):
if num%i==0:
print(‘Not prime’)
break
else:
print(‘Prime’)
(1/2 Mark for each correct error)
21 Write a function distinction(marks) in Python, that takes the dictionary marks 2
as an argument and displays the subjects (in upper case) for which marks is
greater than or equal to 75.
For example, consider the following dictionary
marks = {‘eng’:78, ‘phy’:69, ‘chem’:74, ‘math’:75, ‘cs’:84}
The output should be:
ENG MATH CS
OR
Write a function countAlpha(String) that takes a string as an argument and
returns a dictionary containing count of each letter in String.
For example, if the String is ‘Peter Parker’
The dictionary will have
{‘P’:2, ‘e’:3, ‘t’:1, ‘r’:3, ‘ ’:1, ‘a’:1, ‘k’:1}
Ans def distinction(marks):
for i in marks:
if marks[i]>=75:
print(i.upper(),end=“ ”)
2 marks for correct answer
OR
def countAlpha(String):
d={}
for i in String:
if i in d:
d[i]+=1
else:
d[i]=0
return d
2 marks for correct answer
22 Predict the output of the following code: 2
def show(s1,s2):
l1=[ ]
l2=[]
for x in s1:
l1.append(x)
for x in s2:
125 | P a g e
l2.append(x)
return l1,l2
a,b=show("FUN",'DAY')
print(a,b)
Ans ['F', 'U', 'N'] ['D', 'A', 'Y']
Each list correctly written will fetch 1 mark.
23 Write the Python statement for each of the following tasks using BUILT-IN 2
functions/methods only:
i. To return index position of substring in given string.
ii. To delete first occurrence of an item in the list
OR
A list named stu_marks stores marks of students of a class. Write the Python
command to import the required module and display the average of the marks
in the list.
Ans i-find( )
ii – remove( )
1 mark for each correct answer
(OR)
import statistics
stu_marks =[45,60,70,85,40]
print(statistics.mean(stu_marks))
1 mark for correct import statement
1 mark for correct command with mean() and print()
24 Mr. Sarthak has just created a table name ‘Wrestling’ containing columns Pname, 2
Style, WeightCategory. After creating the table he realized that he has forgotten
to add a primary key column in the table. Help him in writing an SQL command
to add a primary key column PlayerId of integer type to the table Wrestling.
Thereafter write the command to insert the following record in the table:
PlayerId – 999, Pname – Tyler, Style – BJJ, WeightCategory – 75
OR
Mohan is working in a database named Vehicle in which he has created a table
name ‘Car’ containing columns CarId, BrandName, Model and MfgYear.
After creating the table, he realized that the attribute Model has to be deleted
from the table and a new attribute Variant of data type string of size 20 has to
be added. This attribute Variant cannot be left blank. Help Mohan to write the
commands to complete both the tasks.
Ans alter table Wrestling add PlayerId int primary key;
insert into Wrestling values(999,’ Tyler ‘,’BJJ’,75);
1 mark for each correct answer
OR
alter table car drop model;
alter table car add variant char(25) not null;
1 mark for each correct answer
25 Predict the output of the following code: 2
def trap(x, y=10):
x = x//y
y = x*y
return x
x,y = 200, 20
126 | P a g e
x = trap(x, y)
print(x, y, sep=‘#’)
y = trap(x, y)
print(y, x, sep=‘#’)
Ans 10#20
0#10
1 Mark for each correct line of output
SECTION C (3 MARKS QUESTIONS)
26 Predict the output of the following code: 3
def Display(str):
m=" "
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Display('[email protected]')
Ans fUN#pYTHONn#X
(3 Marks for correct answer)
27 Consider the table BANK given below and write the output of the SQL queries 3
that follow.
127 | P a g e
Gauri Current
Himani Savings
Jyoti Deposit
(iii) SELECT NAME, AGE, BALANCE FROM BANK WHERE
GENDER=‘F’ AND BALANCE BETWEEN 6000 AND 7000;
Name Age Balance
Rashi 20 7000
Himani 18 6750
Jyoti 17 6000
(1 Mark for each correct answer)
28 Write a function COUNT_T( ) in Python to count the number of lines in a text fie 3
‘EXAM.txt’ which start with an alphabet ‘T’ .
OR
Write a function CAN_WORDS ( ) in Python that count the number of “can”
words present in a text file “DETAILS.txt”.
Based on the given table write SQL queries for the following:
i. Change the Flavour of the chips to “black salt “ for those chips whose flavour is
“SALTY”.
ii. Display the Brand_Name ,Flavour and Total amount(price*quantity) of those
chips whose Brandname ends with ‘s’. Total Amount column name should also
be displayed.
iii. Delete the records of those chips whose quantity is less than 10.
Ans i. UPDATE CHIPS SET FLAVOUR =”BLACK SALT” WHERE FLAVOUR=”SALTY”
ii. SELECT BRAND_NAME,FLAVOUR,PRICE*QUANTITY AS “TOTAL AMOUNT”
WHERE BRAND_NAME LIKE “S%”;
iii. DELETE FROM CHIPS WHERE QUANTITY <10;
(1 mark for each correct answer)
30 A list FJList contains following record as list elements: 3
[FoodJoint, Cuisine, Rating]
Each of these records are nested together to form a nested list. Write the
following user defined functions in Python to perform the specified operations
128 | P a g e
on the stack named MustGo.
(i) Push_element(FJList, MustGo): It takes the nested list as an
argument and pushes a list object containing name of FoodJoint and its
Cuisine is other than Chinese and has rating more than 4.
(ii) Pop_element(MustGo): It pops the objects from the stack passed as
an argument and displays them one by one. Also, the function should
display ‘Stack Empty’ when there are no elements in the stack.
For example: If the nested list contains the following data:
FJList = [ [‘Divine Palace’, ‘Indian’, 4.8],
[‘Ching’, ‘Chinese’, 4.2], [‘The Lama’, ‘Thai’, 3.9],
[‘Le Cirque’, ‘French’, 4.5]]
The stack should contain:
[[‘Divine Palace’, ‘Indian’, 4.8],
[‘Le Cirque’, ‘French’, 4.5]]
The output should be:
[‘Le Cirque’, ‘French’, 4.5]
[‘Divine Palace’, ‘Indian’, 4.8]
Stack Empty
Ans (i) def Push_element(FJList, MustGo):
for i in FJList:
if i[1]!=‘Chinese’ and i[2]>4:
MustGo.append(i)
(ii)def Pop_element(MustGo):
while MustGo:
print(MustGo.pop())
else:
print(“Stack Empty”)
(1 Mark for each correct function)
1/2
129 | P a g e
(iv) Select name from student s, club c where s.clubid=c.clubid and clubic=
‘Ram’;
(1 mark each for correct answer)
32 Vedant is a Python programmer working in a institution which hosted a 2+2
technical festival. He has created a csv file named Participants.csv to store the
results of various competitions held in the festival. The structure of
Participants.csv is :
[Id, Name, Event]
where data type of Id is integer, Names is string and Event is string.
For efficiently maintaining data of the participants Vedant wants to write the
following user defined functions:
Accept() – to accept a record form the user and add it to the file
Participants.csv. The column headings should also be added on top of the csv
file.
EventCount() – to count and display the number of participants in the event
‘Robocon’
As a Python expert help him complete the task.
130 | P a g e
a) Suggest and draw the cable layout to efficiently connect various blocks of
buildings within the Jaipur campus.
b) In which block should the server be placed and why?
c) Suggest the placement of following devices:
i) Switch/hub
ii)Repeater
d) Which cost efficient wired medium should be used to connect the computers
in Jaipur campus?
e) Which type of network is formed by connecting Delhi Head Office with
Jaipur Campus?
Ans a) Star topology with ADMIN as center or any other suitable topology.
b) In ADMIN block because of maximum no of computers.
c) Suggest the placement of following devices:
i) Switch/hub – in all blocks
ii)Repeater – where distance is greater than 100 mts between ADMIN and
STUDIO
d) Ethernet cable
e) WAN
(1 Mark for each correct answer)
34 (i) Differentiate between r+ and w+ file modes in Python. 2+3
(ii) Consider a file Company.dat containing records of the following structure:
[ CompanyName, Type, No_members ]
Write a function copyData() that reads contents form the file Company.dat and
copies the records with Type “EduTech” to the file name EduTechs.dat. The
function should return the total number of records copied to the file
EduTechs.dat.
OR
(i) Write two differences between binary and text files.
(ii) A binary file multiplex.dat has the following structure:
{ screeenNo : [movieName,genre]}
Write a user defined function findType(type) that accepts type as parameter and
displays all the records from the binary file multiplex.dat that have the genre as
value provided in type.
Ans (i) r+ gives error if file doesn’t exist but w+ creates file if it doesn’t exist.
r+ doesn’t overwrite but w+ does.
(2 Marks for correct answer)
(ii)
def copyData();
131 | P a g e
import pickle
fr=open(‘Company.dat’, ‘rb’)
fw=open(‘EduTechs.dat’, ‘wb’)
c=0
try:
r=pickle.load(fr)
if r[1]== ‘EduTech’:
pickle.dump(r,fw)
c+=1
except:
fw.close()
fr.close()
return c
(3 Marks for correct answer)
35 (i) Define the term Domain with respect to RDBMS. 5
(ii) Shreyaan wants to write a program in Python to insert the following record
in the table named Tours in MySQL database TRAVELS:
● TourId – integer
● Destination – string
● Departure – date
● Price – float
Note the following to establish connectivity between Python and MySQL
● Username – admin
● Password – passkey
● Host – localhost
The value of the fields TourId, Destination, Departure and Price has to be
accepted form the user. Help Shreyaan to write the program in Python.
OR
(i) Give one difference between primary key and unique.
(ii) Yuvin has created a table named Courses in MySQL database PyAcademy
with following structure:
● Cid – integer
● Cname – string
● StartDate – date
● Fee – float
Note the following to establish connectivity between Python and MySQL
● Username – admin
● Password – passkey
● Host – localhost
Yuvin now wants to display the records of courses fees of which is greater than
5000. Help Yuvin to write the program in Python.
Ans (i) Domain is a pool of values from which a column can derive value for a tuple.
(1 Mark for each correct answer)
(ii)
import mysql.connector as sql
con=sql.connect(user= ‘admin’, passwd= ‘passkey’,host= ‘localhost’, database=
‘travels’)
cur=con.cursor()
tid=int(input(“Enter tour id”))
d=input(“Enter destination”)
dep=input(“Enter departure date(yyyy/mm/dd)”)
132 | P a g e
p=float(input(“Enter price”))
cur.execute(‘insert into tours values (%s, %s, %s, %s)’, [tid, d, dep, p])
con.commit()
(1 Mark for import, 1 mark for connection, 1 mark for input data, 1 mark for
execute)
OR
(i) There can be only one primary key but more than one unique constraints.
(1 Mark for correct answer)
(ii)
import mysql.connector as sql
con=sql.connect(user= ‘admin’, passwd= ‘passkey’, host= ‘localhost’, database=
‘PyAcademy’)
cur=con.cursor()
cur.execute(‘select * from courses where fee>5000’)
for i in cur.fetchall():
print(i)
(1 Mark for import, 1 mark for connection, 1 mark for execute, 1 mark for
fetchall)
133 | P a g e
KENDRIYA VIDYALAYA SANGATHAN
DELHI REGION
COMPUTER SCIENCE (083)
SAMPLE QUESTION PAPER 2
Class-XII
Max Marks-70 Time: 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 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 02 Long Answer type questions carrying 04 marks each.
7. Section E has 03 questions carrying 05 marks each.
8. All programming questions are to be answered using Python Language only.
SECTION A
1 Identify the invalid Python statement from the following. 1
(a) _b=1 (b) __b1= 1 (c) b_=1 (d) 1 = _b
2 Which of the following is an invalid identifier in Python? 1
(a)Max_marks (b) Max–marks (c)Maxmarks (d)_Max_Marks
3 If Statement in Python is __ 1
(a) looping statement (b) selection statement (c) iterative (d) sequential
4 Consider the given expression: 1
not 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
5 Choose the most correct statement among the following – 1
(a) a dictionary is a sequential set of elements
(b) a dictionary is a set of key-value pairs
(c) a dictionary is a sequential collection of elements key-value pairs
(d) a dictionary is a non-sequential collection of elements
6 Which of the following mode in file opening statement results or generates an 1
error if the file does not exist?
(a)r+ (b) a+ (c)w+ (d)None of the above
7 What will be the output of the following lines of Python code? 1
if not False:
print(10)
else:
print(20)
134 | P a g e
(c) Candidate Key
(d) Alternate Key
11 A table has initially 5 columns and 8 rows. Consider the following sequence of 1
operations performed on the table –
i. 8 rows are added
ii. 2 columns are added
iii. 3 rows are deleted
iv. 1 column is added
What will be the cardinality and degree of the table at the end of above operations?
18 Assertion (A): CSV files are used to store the data generated by various social media 1
platforms.
Reason (R): CSV file can be opened with MS Excel.
SECTION – B
19 Find error in the following code(if any) and correct code by rewriting code and 2
underline the correction;-
135 | P a g e
d = {"name": "Akash", "age": 16}
d['age'] = 27
d['city'] = "New Delhi"
print(d.items())
21 Write a function calc(NAMES) in Python, that takes the dictionary, NAMES as an 2
argument and displays the names (in lowercase)of the names having number of
character less than 5.
For example, Consider the following dictionary
NAMES={6:"Amit",9:"Rohan",6:"Supriya",3:"Ritu"}
The output should be:
Amit
Ritu
OR
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]
22 Predict output of the following code fragment – 2
24 Write the Python statement for each of the following tasks using BUILT-IN 2
functions/methods only:
136 | P a g e
(i) To insert an element 15 at the forth position, in the list List1.
(ii) To check whether a string named, Str ends with a full stop / period or not
25 Mr. Avnisha has just created a table named “Student” containing columns Sname, Class 2
and Marks.
After creating the table, she realized that she has forgotten to add a primary key column
in the table. Help her in writing an SQL command to add a primary key column SId of
integer type to the table Student.
Thereafter, write the command to insert the following record in the table:
SId-1045
Sname- Suman
Class: XII
Marks: 90
OR
Write the SQL commands to perform the following tasks:
(i) view the list of databases
(ii) view the structure of the table, school
SECTION - C
26 Find the output of the following: 3
28 Write the outputs of the SQL queries (a) to (c) based on the relation Furniture 3
137 | P a g e
12 Old Fox Sofa 20/02/2003 17000 20
13 Micky Baby Cot 21/02/2003 7500 15
138 | P a g e
32 4
Write the SQL queries based on the relations Teacher and Placement Tables given below :
Table : Teacher
Table: Placement
SECTION – E
5
33 India Tech Solutions (ITS) 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 (v) below.
FINANCE BLOCK
(i)Which will be the most appropriate block, where TTC should plan to install their
server?
139 | P a g e
(ii) Draw a block to block cable layout to connect all the buildings in the most
appropriate manner for efficient communication.
(iii)What will be the best possible connectivity out of the following, you will suggest to
connect the new set up of offices in Bengalore with its London based office.
Satellite Link
Infrared
Ethernet
(iv)Which of the following device will be suggested by you to connect each computer in
each of the buildings?
Switch
Modem
Gateway
(v) Company is planning to connect its offices in Hyderabad which is less than 1 km.
Which type of network will be formed?
34 (i) Give one difference between alternate key and candidate key.
(ii) Suhana has created a table named STUDENT in MYSQL database, VIDYALAYA: 1+4
RN (Roll number) - integer =5
SNAME(Name of Student)-string
DOB (Date of birth) – Date
FEE–float
Note the following to establish connectivity between Python and MySQL:
Username - root Password - tiger Host – localhost
Suhana, now wants to display the records of students whose fee is more than 5000.
Help Suhana to write the program in Python
OR
(i) Define the term Domain with respect to RDBMS. Give suitable example.
(ii) Rohan wants to write a program in Python to insert the following records in
the table named STUDENT in MYSQL database SCHOOL.
RNO – integer
NAME- string
SUBJECT–string
MARKS– integer
The values of RNO, NAME, SUBJECT, MARKS has to be accepted from the user. Help
Rohan to write the program in python.
35 (i) How are text files different from binary files? 2+3
(ii) Consider a file, BOOK.DAT, containing records of the following structure: =5
[BookName, Price, Publication]
Write a function, copyData(),that reads contents from the file BOOK.DAT and copies
the records with Book name as “PYTHON” to the file named PYTHON.DAT. The
function should return the total number of records copied to the file PYTHON.DAT.
OR
(i) Differentiate between r+ and w+ file modes in Python.
(ii) A Binary file, TRAIN.DAT has the following structure:
[TNO,TNAME, TTYPE ]
Where TNO – Train Number
TNAME–TrainName
TTYPE is Train Type.
Write a user defined function, find Type(ttype), that accepts ttype as parameter and
displays all the records from the binary file TRAIN.DAT,that have the value of Train Type
as ttype.
140 | P a g e
KENDRIYA VIDYALAYA SANGATHAN
DELHI REGION
COMPUTER SCIENCE (083)
SAMPLE QUESTION PAPER
Class-XII
MAX MARKS-70 TIME: 3hrs
MARKING SCHEME
SECTION A
1 (d) 1 = _b 1
2 (b)Max–marks 1
3 (b) selection statement 1
4 (b)False 1
5 (b) a dictionary is a set of key-value pairs 1
6 (a)r+ 1
7 (a) 10 1
8 (c)INSERT 1
9 d) d=f.readlines() 1
10 (a)Foreign Key 1
11 (a) 13,8 1
12 (a)file_object.seek(offset[,reference_point]) 1
13 (b) describe 1
14 (a)129 1
15 (a) fp.seek(offset, 0) 1
16 (b)connect() 1
17 (a) Both A and R are true and R is the correct explanation for A 1
18 (b) Both A and R are true and R is not the correct explanation for A 1
SECTION – B
19 Correct code:- 2
x= int(input(“Enter value of x:”))
for in range (0,10):
if x==y:
print( x+y)
else:
print (x-y)
141 | P a g e
return indexList
½ mark for function header
½ mark for correct for loop
½ mark for correct if statement
½ mark for return statement
22 250 # 150 2
250 # 100
130 # 100
OR
(22,44,66)
23 i. Network Interface Card 2
ii. Transmission Control Protocol/ Internet Protocol
iii. Post Office Protocol
iv. Simple Mail Transfer Protocol
½ mark for each expansion
OR
Circuit Switching Packet Switching
In-circuit switching, each data unit In Packet switching, each data unit just
knows the entire path address which is knows the final destination address
provided by the source. intermediate path is decided by the routers.
The delay between data units in circuit The delay between data units in packet
switching is uniform. switching is not uniform.
SECTION – C
26 Output is: 3
22
27 def SHOWWORD () : 3
c=0
142 | P a g e
file=open(‘STORY.TXT,'r')
line = file.read()
word = line.split()
for w in word:
if len(w)<5:
print( w)
file.close()
(½ Mark for opening the file)
(½ Mark for reading line and/or splitting)
(½ Mark for checking condition)
(½ Mark for printing word)
OR
def count H( ):
f = open (“para.txt” , “r” )
lines =0
l=f. readlines ()
for i in L:
if i [0]== ‘H’:
lines +=1
print (“No. of lines are: “ , lines)
def Pop(Book):
if (Book = =[ ]):
print(“Stack empty”)
else:
print(“Deleted element :”)
Book.pop()
SECTION – D
31 (i) ADD()Function: 4
import csv
def ADD():
with open('furniture.csv', 'a', newline='') as f:
fid=input("Enter furniture ID: ")
desc=input("Enter Description: ")
143 | P a g e
pr=input("Enter Price: ")
disc=input("Enter discount:")
rec=[fid,desc,pr,disc]
w=csv.writer(f)
w.writerow(rec)
(ii) COUNTR()Function:
import csv
def COUNTR():
with open('furniture.csv') as f:
r=csv.reader(f)
c=0
for rec in r:
if eval(rec[2])<5000:
c+=1
print("Number of such records=",c)
32 (i) SELECT DEPARTMENT, MAX (SALARY) FROM TEACHER GROUP BY DEPARTMENT; 4
(ii)SELECT NAME, SALARY, DEPARTMENT, PLACE FROM TEACHER, PLACEMENT
WHERE TEACHER.DEPARTMENT = PLACEMENT.DEPARTMENT AND DEPARTMENT =
“HISTORY”;
(iii)SELECT NAME, PLACE FROM TEACHER NATURAL JOIN PLACEMENT WHERE
GENDER='F';
(iv)SELECT * FROM TEACHER WHERE GENDER = ‘M’ AND DOJ < “2019-01-31”;
SECTION – E
33 (i) TTC should install its server in finance block as it is having maximum number of 5
computers.
(ii) Any suitable layout
(iii) Satellite Link.
(iv) Switch.
(v) LAN
34 (i)All keys that have the properties to become a primary key are candidate keys.The 2
candidate keys that do not become primary keys are alternate keys.
(ii)
import mysql.connector
mydb=mysql.connector.connect (host="localhost",user="root", passwd
="tiger", database="VIDYALAYA")
mycursor=mydb.cursor()
sql="SELECT*FROM STUDENT WHERE FEE>5000"
mycursor.execute(sql)
data=mycursor.fetchall()
print("The required data are:")
for row in data:
print(row)
mydb.close()
(½mark for importing correct module +1mark for correct connect() +1markfor
correctly executing the query+½ mark for correctly using fetchall() + 1 mark for
display data )
OR
(i) Domain is a set of values from which an attribute can take value in each row.
144 | P a g e
For example, roll no field can have only integer values and so its domain is a set of
integer values.
(½ mark for correctdefinition+½ for correct example)
(ii)
import mysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", passwd
="tiger", database="SCHOOL")
mycursor=mydb.cursor()
rno = int (input (“Enter Roll Number :”))
name=input(“Enter Name of Student:”))
sub = input (“Enter Subject :”))
marks=input(“EnterMarks:”))
sql="INSERT INTO STUDENT VALUES ({},‘{}’,‘{}’,{})".format(rno,name,sub,marks)
mycursor.execute(sql)
mydb.commit()
print("Student Records inserted successfully")
mydb.close()
(½ mark for importing correct module + 1 mark for correct connect() + ½ mark for
correctly accepting the input +1½ mark for correctly executing the query+½ mark for
correctly using commit() )
35 (i)
Text files:
1. Extension is .txt
2. Data is stored in ASCII format that is human readable
3. HasEOLcharacterthatterminateseachlineofdatastoredinthe text files
Binary Files :
1.Extension is .dat
2. Dataisstoredinbinaryform(0sand1s),that is not human readable.
(ii)
Def copyData():
f=open(“BOOK.DAT”,“rb”)
fp=open(“PYTHON.DAT”,“wb”)
Count=0
try :
while True:
data=pickle.load(f) print
(data)
if data[0] == “PYTHON” :
pickle.dump(data,fp)
Count = Count +1
except:
f.close()
fp.close()
return Count
(½markforopeningFiles&closing+½mark fortry–except+½markforloop+1 mark for
copying correct data + ½ for return the count
OR
(i) 2 marks
r+ mode:
1. Primary function is reading
2. File pointer is at beginning of file
145 | P a g e
3. If the file does not exist, it results in an error
w+ mode:
1. primary function is writing
2. if the file does not exist, it creates a new file.
3. If the file exists, previous data is overwritten
4. File pointer is at the beginning of file
(ii)
def findtype(ttype):
f=open(“TRAIN.DAT”,“rb”)
try:
while True:
data=pickle.load(f)
if data[2] ==ttype:
print(“Train Number :”,data[0])
print (“Train Name :”, data[1] )
print (“Train Type :”, data[2] )
exceptEOFError:
f.close()
(½mark for opening Files & closing+½ mark for try–except + ½ mark for loop +
½for correct if statement+1mark for display)
146 | P a g e