0% found this document useful (0 votes)
12 views

12 Computer Science

Uploaded by

s1430.umang30574
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

12 Computer Science

Uploaded by

s1430.umang30574
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

KENDRIYA VIDYALAYA SANGATHAN

STUDENT SUPPORT MATERIAL


(Computer Science)
Class – XI
SESSION: 2024-25

Chief Patron : Ms. Nidhi Pandey, IIS


Commissioner, KVS , New Delhi
Patron : Shri Sardar Singh Chauhan,
Dy. Commissioner, KVS Delhi Region
Guidance : Shri Ghanshyam Panday,
Asstt. Commissioner, KVS Delhi Region
Co-ordinator : Shri Sandeep Arora,
Vice Principal, PM Shri KV JNU, Delhi

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

UNIT UNIT / CHAPTER NAME PAGE NO.


NO.

1. REVISION OF CLASS XI 7-26

2. PYTHON FUNCTIONS 26- 29

3. EXCEPTION HANDLING IN PYTHON 29-32

4. FILE HANDLING 33-51

5. DATA STRUCTURE 51-54

6. DATABASE CONCEPTS 55-90

COMPUTER NETWORKS
7. 91-113

8. SAMPLE QUESTION PAPER - I 114- 121

9. SAMPLE QUESTION PAPER – II 122-133

10. SAMPLE QUESTION PAPER – III 134-146

3|P age
Computer Science (2024-25)CLASS XII Code No. 083
Computer Science- Class XII

1. Learning Outcomes

Student should be able to


a) apply the concept of function.
b) explain and use the concept of file handling.
c) use basic data structure: Stacks
d) explain basics of computer networks.
e) use Database concepts, SQL along with connectivity between Python and SQL.

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

3. Unit wise Syllabus


Unit 1: Computational Thinking and Programming – 2
● Revision of Python topics covered in Class XI.
● Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default
parameters, positional parameters, function returning value(s), flow of execution, scope
of a variable (global scope, local scope)
● Exception Handling: Introduction, handling exceptions using try-except-finally blocks
● Introduction to files, types of files (Text file, Binary file, CSV file), relative and
absolute paths

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.

Unit 2: Computer Networks

● Evolution of networking: introduction to computer networks, evolution of networking


(ARPANET, NSFNET, INTERNET)
● Data communication terminologies: concept of communication, components of data
communication (sender,receiver, message, communication media, protocols),
measuring capacity of communication media (bandwidth, data transfer rate), IP
address, switching techniques (Circuit switching, Packet switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable,
Fiber-optic cable), Wireless media (Radio waves, Micro waves, Infrared waves)
● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway,
WIFI card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN),
networking topologies (Bus, Star, Tree)
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible
Markup Language (XML), domain names, URL, website, web browser, web servers,
web hosting
Unit 3: Database Management
● Database concepts: introduction to database concepts and its need
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys
(candidate key, primary key, alternate key, foreign key)
● Structured Query Language: introduction, Data Definition Language and Data Manipulation
Language, data type (char(n), varchar(n), int, float, date), constraints (not null, unique,
primary key), create database, use database, show databases, drop database, show
tables, create table, describe table, alter table (add and remove an attribute, add and
remove primary key), drop table, insert, delete, select, operators (mathematical, relational
and logical), aliasing, distinct clause, where clause, in, between, order by, meaning of
null, is null, is not null, like, update command, delete command, aggregate functions
(max, min, avg, sum, count), group by, having clause, joins: cartesian product on two tables,
equi-join and natural join
● Interface of python with an SQL database: connecting SQL with Python, performing

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)

2. SQL queries (4 queries based on one


or two tables) 4

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

3 Project (using concepts learnt in Classes 11 8


and 12)

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. ‘ “”” “”” ’

Python character set


 A character set is a set of valid characters supported by python programming language.
 Python supports all ASCII / Unicode characters that include:
 Alphabets: All capital (A-Z) and small (a-z) alphabets.
 Digits: All digits from 0-9.
 Special Symbols: Python supports all kinds of special symbols - " ' l ; : ! ~ @ # $ %
^`&*()_+–={}[]\.
 White Spaces: White spaces like tab space, blank space, newline, and carriage
return.
 Other: All ASCII and UNICODE characters are supported by Python that
constitutes the Python character set.
Python Tokens: - The smallest individual unit in a program is known as a Token or a lexical unit.
Python has following tokens:-
i. Keywords
ii. Identifiers (Names)
iii. Literals
iv. Operators
v. Punctuators
Keywords:- Python has a set of keywords that are reserved words and cannot be used as variable
names, or any other identifiers:-
S. No. Name of Description
Keyword
1. And A logical operator
2. As To create an alias
3. Assert For debugging
4. class To define a class
5. Continue To continue to the next iteration of a loop
6. Def To define a function
7. del To delete an object
8. elif Used in conditional statements, same as else if
9. Else Used in conditional statements
10. Except Used with exceptions, what to do when an exception occurs
11. False Boolean value, result of comparison operations
12. finally Used with exceptions, a block of code that will be executed
no matter if there is an exception or not
13. for To create a for loop
14. from To import specific parts of a module

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: -

 Numeric Literals: - A number represented in various forms is a numeric literal.


o Integer Literal: It includes both positive and negative numbers along with 0.
It doesn’t include fractional parts. It can also include binary, decimal, octal,
hexadecimal literal.
o Float Literal: It includes both positive and negative real numbers. It also
includes fractional parts. 99.62, 0.35E-7 are valid float literals.
o Complex Literal: It includes a+bj numeral, here a represents the real part
and b represents the complex part.
 Boolean Literals: - A Boolean literal in Python is used to represent one of the
two Boolean values i.e. True (Boolean true) or False (Boolean false).
 Special Literal None: - Python has one special literal, which is None literal and is
used to indicate absence of value.

Operators: - Operators are responsible for performing various operations in Python.


The operators are of two types Unary (Operates on single operand) and Binary Operators (operates on
two operands).
 Arithmetic Operators: Arithmetic operators are used with numeric values to
perform common mathematical operations:
Operators Name Example
+ Addition 30+90 gives 120
- Subtraction 90-30 gives 60
10 | P a g e
* Multiplication 40*10 gives 400
/ Division 12/3 gives 4.0
// Floor Division 10//3 gives 3
10.0 //3 gives 3.0
% Modulus 20%3 gives 2
** Exponentiation 4**2 gives 16

 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.

Selection flow of control Program Output


The statements execution a=int(input("Enter any integer Enter any integer
depends upon some number :")) number: 5
conditions. It contains if(a==0):
decision making statements print("Number is Zero") Number is Positive
(if, elif, else) elif(a>0):
print("Number is Positive")
if condition: else:
Statement/s print("Number is negative")
elif condition:
Statement/s
else:
Statement/s
Iteration flow of control Program Output

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

Jump Statements Program Output


(break, continue, pass)
for i in range(1,11): 1 2 hello 4 6 7
Syntax if(i==3):
for val in sequence: print("hello", end=' ')
if (val== i): continue
break if(i==8):
if (val== j): break
continue if(i==5):
if (val== k): pass
pass else:
print(i, end=’ ‘);
 range () function in python: The range() function returns a sequence of numbers, starting
from 0 by default, and increment by 1 (by default), and stops before the specified number.

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 = " ")

Very Short answer type questions


Q1. What are the tokens in Python?
Q2. How are keywords different from identifiers?
Q3. What are literals in python? How many types of literals are allowed in Python?
Q4. How are string literals represented and implemented in Python?
Q5. What are operators? What is their function?
Q6. What are variables? How are they important for a program?
Q7. What is entry control loop?
Q8. What is exit control loop?
Q9. What is mutable data type?
Q10. What is immutable data type?
Short answer type questions
Q1. What is the difference between a keyword and an identifier?
Q2. What are literals in Python? How many types of literals are allowed in python?
Q3. What is None literal?
Q4. What are data types? What are python built-in data types?
Q5. What is the role of comment and indentation in a program?
Q6. What is a statement? What is the significance of an empty statement?
Q7. What do you mean by term iteration?
Q8. Rewrite the following code after removing all the syntax error (s):
30=T
for K in range (0,To):
IF k%4 == 0:
print(K*4)
Else:
print(K+3)
Q9. Write a program that asks the user to input number of seconds and then expresses it in terms of
minutes and seconds it contains.
Q10. How many types of strings are supported in Python?

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.

 Replication: A string can be multiplied by a number to create replicated 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.

We can access any element of the string using indexing.

 Slicing: A substring can be acquired from


an existing string using the slicing
operation.

 Traversal: We can traverse a string using iteration and specifically using for loop.
o Iterate using membership

o Iterate using indexing

 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

isalpha() – Returns True if all the characters are Alphabets

isdigit() – Returns True if all the characters are digits.

isspace() – Returns True if all the characters are spaces

isupper() – Returns True if all the characters are upper-case alphabets

islower() – Returns True if all the characters are lowercase alphabets

startswith(substr) – Returns True if a string starts with the given substring.

endswith(substr) – Returns True if a string ends with the given substring.

o Methods that return a number based on the requirement:


18 | P a g e
count(substr) – counts the occurrence of a substring inside a string.
The general format of this function is count(substr, start, stop) where stop
index is not included. Both start and stop are optional.

index(substr) – Returns the index of the first occurrence of a substring inside


a given String. The general format of this method is index(substr, start, stop)
where stop index is not included. Both start and stop are optional.

find(substr) – Returns the index of the first occurrence of a substring inside a


given String. The general format of this method is find(substr, start, stop) where
stop index is not included. Both start and stop are optional. This is same as
index()
index(substr) find(substr)
This function throws a This function returns -1
ValueError if the if the substring is missing
substring is missing from the string.
from the string.
Python List

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.

 List operations (concatenation, repetition, membership & slicing) :


 Concatenation: - Python allows us to join two or more lists using concatenation
operator depicted by the symbol +.
#list1 is list of first five odd integers
>>> list1 = [1,3,5,7,9]
#list2 is list of first five even integers
>>> list2 = [2,4,6,8,10]
#elements of list1 followed by list2
20 | P a g e
>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']
 Repetition: - Python allows us to replicate a list using repetition operator depicted by
symbol *.
>>> list1 = ['Hello']
#elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
 Membership: - Like strings, the membership operators in checks if the element is
present in the list and returns True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
 Slicing: - Like strings, the slicing operation can also be applied to lists.
>>> list1 = ['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
 Traversing a list using loops: - We can access each element of the list or traverse a list
using a for loop or a while loop.
o List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
o List Traversal Using while Loop:
# creating a list
countries = ["USA", "CHINA", "BRAZIL", "TURKEY"]

# starting at 0 index
i=0

# using a while loop


while i < len(countries):
print(countries[i])

# 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.

 Adding a Key-Value pair to a dictionary: We can add a key-value pair to a dictionary


using the syntax dictName[key]=value. In case we are trying to add an existing key, then
the latest value will replace the old value of the existing key without adding a new key
value pair.

 Dictionary Methods: Like Strings and lists, dictionaries too have global and member
functions.
* Global functions: The global functions include len(), max(),
min(), sum() and

* Dictionary Member Methods: These methods are called


using the syntax dictName.methodName()
clear() – Removes all the elements from the dictionary and makes it empty.
copy() – Creates a copy of the existing dictionary.
get(key) – Returns the value for a given key.

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.

update() – Used to add the contents of one dictionary as key-value pairs in


another dictionary.

pop(key) – Removes a key-value pair from a dictionary and returns only the
value.

popitem() – Removes the last added key-value pair from the dictionary and returns
a tuple containing the removed key-value pair.

Questions (MCQ)

Q.1 Which is the correct form of declaration of dictionary?


(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
Q.2 Identify the valid declaration of L:
L = [1, 23, ‘hi’, 6].
a) list
b) dictionary
c) array
d) tuple
24 | P a g e
Q.3 Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80),
which of the following is incorrect?
a) print(Tup[1])
b) Tup[2] = 90
c) print(min(Tup))
d) print(len(Tup))
Q.4 What will be the output of the following python statement?
s = "HOME ALONE"
p = s.split("O")
print(p[1][:2]+p[-1])
a) ALNE
b) MENE
c) MEONE
d) MEAL
Q.5 What is the output of print("hello".find('E'))?
a) 1
b) 2
c) -1
d) Error
Q.6 For the given list
d=[10,30,20,15,45,50,80,90]
what will be the output of the following slicing operation:
d[2:7:2]
a) [20,15,45]
b) [20, 45, 80]
c) [30, 15, 50]
d) [20, 45]
Q.7 What will be the output of the following?
d = {"A":10, "B":20, "C":30, "A":40}
print(d)
a) {"A":10, "B":20, "C":30, "A":40}
b) {"A":40, "B":20, "C":30}
c) {"A":50, "B":20, "C":30}
d) KeyError
Q.8 Given the lists L=[“H”, “T”, “W”, “P”, “N”]
Write the output of print(L[3:4])

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.

Very Short type Questions

Q1. What is the internal structure of Python String?


Q2. Discuss the utility and significance of list, briefly.
Q3. What is the difference between a list and tuple?
Q4. What is the difference between (30) and (30,)?
Q5. Why a dictionary is termed as an unordered collection of object?
Q6. Write a python script that traverses through an input string and print its characters in different
lines.
Q7. What do you mean by mutability? What does “in place” task mean?
25 | P a g e
Q9. What type of objects can be used as keys in dictionary?
Q10. Discuss the utility and significance of a tuple.

Short type Questions


Q1. What is indexing in context to python string? Why is it also called two-way indexing?
Q2. What is string slice? How is it useful?
Q3. Find and write the output of the following python code:
x=”abcdef”
i=”a”
while i in x:
print(i, end=” “)
Q4. How are lists different from strings when both are sequences?
Q5. What will be the output of the following code snippet?
values=[]
for i in range(1,4):
values.append(i)
print(values)

Q6. What will be the output of the following code?


rec={“Name” : “Python”, “Age”:”20”}
r= rec.copy()
print(id(r)==id(rec))
Q7. How are tuples different from lists when both are sequences?
Q8. How can you say that a tuple is an ordered list of objects?
Q9. How are dictionaries different from lists?
Q10. When are dictionaries more useful than lists?

Long answer type questions


Q1. Write a program to print all even elements available within a list L.
Q2. Write a program to find out and element’s index/position in a tuple WITHOUT using index().
Q3. Write a program that checks for presence of a value inside a dictionary and prints its key.
info={‘Riya’: ‘CS’, ‘Mark’:’Eco’, ‘Ishpreet’: ‘Eng’, ‘Kamal’: ‘EVS’}
Q4. Write a program that creates a list of all integers less than 100 that are multiples of 3 or 5.
Q5. Write a program to that creates a tuple storing firs 9 terms of Fibonacci Series.
Python Functions
Python Function: - Functions is a block of code that perform a task and is identified by its name. A
function can be executed by calling it. Writing the name of the function will call a function. Functions
are internally declared in a separate memory area. So, a function can declare variables with the same
as declared in the outer part of the program.
Type of function: - i. Built-in function (all functions defined by python min( ), max( ), len( ) etc,
ii. User-defined functions (defined by the user)
Advantage of function: -
1. Reduces the size of the program
2. Improves reusability of code
3. Easy debugging
def keyword: - def keyword declares a user defined function followed by parameters and terminated
with a colon.
Return keyword: - Whenever the return keyword is executed inside a function it returns the control
back to its caller along with some value if passed explicitly. Writing return is not compulsory and we
can write as many return keywords as needed but only one return keyword is executed.

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)

Very Short Answer Type Questions


Q.1. What do you mean by modularity?
Q.2. What is a function call?
Q.3. Name the three categories of functions.
Q.4. What is the role of an argument of a function?
Q.5. What are docstrings?
Q.6. What are docstring conventions?
Q.7. Name the constant available in math module.
Q.8. Write two ways in which you are able to use constant pi in your programs.
Q.9. What is a function?
Short Answer Type Questions
Q. 1. Find and write the output of the following Python code:
def fun(s):
k= len(s)
m=””
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+’bb’
print(m)
fun(‘school2@com’)

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?

EXCEPTION HANDLING IN PYTHON


Introduction: - Exception in python is nothing but a run time error due to which the program will
stop the execution. On the other hand, exceptions are raised when some internal events occur which
change the normal flow of the program.
Here are some of the most common types of exceptions in Python: -
 SyntaxError:- This exception is raised when the interpreter encounters a syntax error
in the code, such as a misspelled keyword, a missing colon, or an unbalanced
parenthesis.
 TypeError:- This exception is raised when an operation or function is applied to an
object of the wrong type, such as adding a string to an integer.
 NameError:- This exception is raised when a variable or function name is not found in
the current scope.
 IndexError:- This exception is raised when an index is out of range for a list, tuple, or
other sequence types.
 KeyError:- This exception is raised when a key is not found in a dictionary.
 ValueError:- This exception is raised when a function or method is called with an
invalid argument or input, such as trying to convert a string to an integer when the
string does not represent a valid integer.
 AttributeError:- This exception is raised when an attribute or method is not found on
an object, such as trying to access a non-existent attribute of a class instance.
 IOError: - This exception is raised when an I/O operation, such as reading or writing a
file, fails due to an input/output error.

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.

Try and except Statement – Catching Exceptions


Try and except statements are used to catch and handle exceptions in Python. Statements that
can raise exceptions are kept inside the try clause and the statements that handle the exception
are written inside except clause.
Example: Here we are trying to access the array element whose index is out of bound and
handle the corresponding exception.

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

STEPS IN DATA FILE HANDLING

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()

# program 2: Read data from text file using readlines()


read all the lines from file in the form of list of lists where each list represents a line in the file
f=open("school.txt")
data=f.readlines()
print(data)
f.close()

# program 3: display data using file object


f=open("school.txt")
for i in f:
print(i)
f.close()
PROGRAMS RELATED TEXT FILES
# Progarm 4: DISPLAY TOTAL NO OF CHARACTERS, WORDS
f=open("school.txt" , "r")
d=f.read()
c=len(d)
str=d.split() # to convert a string into list of strings
w=len(str)
print("No of characters= ",c)
print("No of words= ",w)
f.close()

# Progarm 5: COUNT AND DISPLAY TOTAL NO OF OCCURENCE OF WORD 'and'


file=open("school.txt" , "r")
w=0
data=file.readlines()
for d in data:
str=d.split() # to convert a string into list of strings
for s in str:
if s=="and":
w=w+1
print("word 'and' found in the file: ", w," times")
file.close()
# Progarm 6: TO COUNT TOTAL NUMBER OF WORDS STARTING WITH 'I' or 'i'
file=open("school.txt" , "r")
d=file.read()
str=d.split()
w=0

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 7: DISPLAY LINES STARTING WITH 'I' OR 'H'


file=open("school.txt" , "r")
l=0
d=file.readlines()
for data in d:
if data[0]=='I' or data[0]=='H':
print(data)
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()

for line in data:


s=len(line)-2 # last character is at size -1 index and we have to check 2nd last
character
if line[s]=='a' or line[s]=='A':
list.append(line)

f2.writelines(list)

f1.close()
f2.close()

f=open("temp.txt" , "r")
print(f.read())
f.close()

WRITING DATA INTO TEXT FILE


# Progarm 9: Using \n to separate data
f=open("sample.txt" , "w")
f.write("INDIA\n")
f.write("NEW DELHI\n")
f.write("end")
print("Data written to file")
f.close()
36 | P a g e
# Progarm 10: Accepting data from user
f=open("sample.txt" , "w")
text=input("Enter Subject name:")
f.write(text)
f.write("\n")
mm=80
f.write(str(mm)) #numeric data is converted to string
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

# Program 12: Writing data using writelines ()


f=open("sample.txt","w")
l=["neem " , "tulsi " , "mint "]
f.writelines(l)
f.close()
f=open("sample.txt","r")
print(f.read())
f.close()

# Progarm 13: CREATE A FILE BY COPYING THE CONTENTS OF FILE SCHOOL.TXT TO


BACKUP.TXT
f1=open("school.txt")
f2=open("backup.txt", 'w')
d=f1.readlines()
f2.writelines(d)
f1.close()
f2.close()

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.

The tell() Function


The tell() method of python tells us the current position of the cursor within the file.

The seek() Function


The seek(offset, from) method changes the current file position.
If from is 0, the beginning ofthe file to seek. If it is set to 1, the current position is used. If it is set to 2
then the end of the file would be taken as seek position.
The offset argument indicates the number of bytes to be moved.

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.

Serialization is the process of transforming data or an object in memory (RAM) to a stream of


bytes called byte streams. These byte streams in a binary file can then be stored in a disk or in a
database or sent through a network. Serialization process is also called pickling.

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.

The dump() method:


This method is used to convert (pickling) Python objects for writing data in a binary file. Thefile in
which data are to be dumped, needs to be opened in binary write mode (wb).

Syntax of dump() is as follows:


dump(data_object, file_object)
where data_object is the object that has to be dumped to the file with the file handle named
file_object. For example, following Program writes the record of a student (roll_no, name, gender
and marks) in the binary file named mybinary.dat using the dump(). We need to closethe file after
pickling.

#Pickling data in Python


import pickle listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb")
pickle.dump(listvalues,fileobject)
fileobject.close()
The load() method
This method is used to load (unpickling) data from a binary file. The file to be loaded isopened in
binary read (rb) mode. Syntax of load() is as follows:
Store_object = load(file_object)
Here, the pickled Python object is loaded from the file having a file handle named file_object and is
stored in a new file handle called store_object. The following program demonstrates how to read data
from the file mybinary.dat using the load().
#Unpickling data in Python
import pickle
39 | P a g e
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)
Output of Program:
The data that were stored in fi le are:
[1, 'Geetika', 'F', 26]

#Program 1: Writing data into a binary file


import pickle
emp=[ ] # create an empty list
f=open("employee.dat" , "wb") #open file for writing in binary mode
# to append data(i.e. to add more records, instead of 'w' write 'a'
ans='y'
while ans=='y': # loop will run till value of ans is 'y'
eno=int(input("Enter employee number:"))
name=input("Enter employee name:")
sal=int(input("Enter salary:"))
emp.append([eno,name,sal]) #emp is created as list of lists by appending list to it
ans=input("Want to enter more records-press 'y':")
pickle.dump(emp, f) #write list emp to file using file object f
f.close()
>>>>>the list will be created and stored in file in the following form
>>>>>[ [1, 'gopi', 100786], [5, 'hina', 90675], [7, 'tia', 90876] ]

# Program 2: Reading data from file


import pickle
emp=[ ]
f=open("employee.dat","rb")
emp=pickle.load(f) #returns data as list of lists each list represent one record
print(emp)f.close()

# Program 3: searching a record from file


import pickle
emp=[ ]
f=open("employee.dat" , "rb")
e=int(input("enter employee no you want to search:"))
emp=pickle.load(f)
found=0
for d in emp:
if d[0]==e:
print(d)
found=1
break
if found==0:
print("record not found")
f.close()

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)

# Program 5: Deleting record in binary file


import pickle
f=open("employee.dat","rb")
emp=[ ]
emp=pickle.load(f)
f.close()
print("Contents before deletion",emp)
f=open("employee.dat","wb")
e=int(input("enter employee no you want to delete:"))
l=[ ]
found=0
for d in emp:
if d[0]!=e:
l.append(d)
else:
found=1
if found==0:
print("record not found")
41 | P a g e
pickle.dump(l,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 deletion",e)

Absolute and Relative path


The absolute path is the full path to some place on your computer.
For example:
C:/users/admin/docs/staff.txt
The relative path is the path to some file/folder with respect to the current working directory

Display name of current `working directory:


import os
D=os.getcwd()
print(D)
It will display a string containing the path of the current working directory
OUTPUT:
'C:\\Users\\TNINE\\AppData\\Local\\Programs\\Python\\Python36-32'

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.

CSV File Characteristics:


• One line for each record
• Comma separated fields
• Space-characters adjacent to commas are ignored
• Fields with in-built commas are separated by double quote characters.
When Use CSV:
• When data has a strict tabular structure
• To transfer large database between programs
• To import and export data to office applications.
• To store, manage and modify shopping cart catalogue

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)

Python CSV Module:


● CSV Module is available in Python Standard Library.
● The CSV module contains classes that are used to read and write tabular form
of data into CSV format.
● To work with CSV Files, programmer have to import CSV Module.

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.

(i) Read from CSV File:


Using csv.reader(): To read data from csv files, you must use the reader()
function to generate a reader object. This function returns a reader object
which is an iterator of lines in the csv file.
Syntax: csv.reader()
(ii) csv.writer (): The csv.writer(file object) function returns a writer object that
converts the user’s data into delimiter string.

(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:

Name, DOB, City


Ram, 12-Jul-2001, Delhi
Mohan, 23-Jan-2005, Delhi
Suraj, 17-Dec-2002, Kolkata

## 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

8. What is the difference between wb and wb+ mode?


a) wb mode is used to open binary file in write mode and wb+ mode open binary file both forread
and write operation.
b) In wb mode file open in write mode and wb+ in read mode
c) File pointer is at beginning of file in wb mode and in wb+ at the end of file
d) No difference
Ans: a) wb mode is used to open binary file in write mode and wb+ mode open binary fileboth for read
and write operation.

9. The pickle module in Python is used for:


a) Serializing any Python object structure b) De-serializing Python object structure
c) Both a and b d) None of these
Ans: c) Both a and b
10. Which method is used to convert Python objects for writing data in binary file?
a) write() b) load() c) store() d) dump()
Ans: d) dump()
11. seek() function is used for .

a) positions the file object at the specified location.


b) It returns the current position of the file object
c) It writes the data in binary file
d) None of these
Ans: a) positions the file object at the specified location.

12. Which is not the valid mode for binary files?


a) r b) rb c) wb d) wb+
Ans: a) r

(ASSERTION AND REASONING based questions)Mark the correct choice as:


i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true but R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True
1. Assertion (A): A binary file stores the data in the same way as stored in the memory.
Reason (R): Binary file in python does not have line delimiter
Ans: ii. Both A and R are true but R is not the correct explanation for A

2. Assertion(A): an open file can be close using close() function.


Reason(R): sometimes the data written onto files is held in memory until the file is closed.
Ans: i. Both A and R are true and R is the correct explanation for A

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

4. Assertion(A): The seek(offset,from) method changes the current file position.


Reason(R): If from is 0, the beginning of the file to seek. If it is set to 1, the current positionis used. If it
is set to 2 then the end of the file would be taken as seek position. The offset argument indicates the
number of bytes to be moved.
Ans: i. Both A and R are true and R is 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

Short Answer Type Questions ( 2-Marks Questions )


1. Identify the error in the following code:
import pickle
data=[‘one’, 2, [3, 4, 5]]
with open(‘data2.dat’, ‘rb’) as f:
pickle.dump(data, f)
Ans: The file is opened in read mode and dump() function tries to write onto file, hence thereis error
line 3.
Correct code : with open(‘data2.dat’, ‘wb’) as f:
2. Any recipe uses some ingredients. Write a program to store the list of ingredients in abinary file
recipe.dat .
Ans: import pickle
ingredients= [‘cucumber’, ‘pumpkin’, ‘carrot’, ‘peas’]
with open(‘recipe.dat’, ‘wb’) as fout:
pickle.dump(ingredient, fout)

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()

4. Considering the following definition of dictionary MULTIPLEX, write a method inpython to


search and display all the content in a pickled file CINEMA.DAT, where MTYPE key of the
dictionary is matching with the value ‘Comedy’.
MULTIPLEX = {‘MNO’ : , ‘MNAME’: , ‘MTYPE’: }
Ans:
import pickledef search():
file=open('CINEMA.DAT', 'rb')try:
while True:
46 | P a g e
MULTIPLEX=pickle.load(file)
if(MULTIPLEX['MTYPE']=='Comedy'):
print(MULTIPLEX)
except EOFError:
f.close()
5 What will be the output of following code:
import pickle
names=['First', 'Second', 'Third', 'Fourth', 'Fifth']
lst=[ ]
for i in range(-1, -5, -1):
lst.append(names[i])
fout= open('test.dat', 'wb')
pickle.dump(lst, fout)
fout.close()
fin= open('test.dat', 'rb')
nlist=pickle.load(fin)
fin.close()
print(nlist)
Ans: ['Fifth', 'Fourth', 'Third', 'Second']

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()

2. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a


function countrec() in Python that would read contents of the file“STUDENT.DAT” and display the
details and total number of those students whose percentage is above 75.
Ans:
import pickle
def CountRec():
f=open("STUDENT.DAT","rb")
num = 0try:
while True:
rec=pickle.load(f)if rec[2] > 75:

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()

Case Study Based Question-1


Ramesh loves programming. He joined an institute for learning. He is learning python. He learned all
the python concepts like strings, lists, tuple, dictionaries etc. but he wants to learn file handling in
python. He is trying to learn binary file handling. His teacher gave him partialcode to write and read
data from employee.dat having structure empno, name, salary. Help Ramesh to complete the code:

# 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)

Case Study Based Question-2


Mohit, a student of Class 12th, is learning CSV File Module in Python. During examination, he has been
assigned an incomplete Python code (shown below) to create a CSV File ‘Student.csv’ (content shown
below). Help him in completing the code which creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A

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()

Answer the questions from the above mentioned program:


(i) Identify the suitable code for blank space in line marked as Statement 1.
(a) csv file (b) CSV (c) csv (d) Csv
Ans: (c) csv
(ii) Identify the missing code for blank space in line marked as Statement 2.
(a) “School.csv”,“w” (b) “Student.csv”,“w” (c) “Student.csv”,“r” (d) “School.csv”,“r”
Ans: (b) “Student.csv”,“w”
# It opens a file student.csv in write mode because append( ) method is using.
(iii) Choose the function name (with argument) that should be used in the blank space of line
marked as Statement 3.
(a) reader(fh) (b) reader(MyFile) (c) writer(fh) (d) writer(MyFile)
Ans: (c) writer(fh) #csv. writer is used to insert data to the CSV file.
(iv) Identify the suitable code for blank space in line marked as Statement 4.
(a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’ (b) ROLL_NO, NAME, CLASS, SECTION
(a) ‘roll_no’,‘name’,‘class’,‘section’ (d) roll_no,name,class,section
(b) Ans: (d) roll_no,name,class,section
50 | P a g e
(v) Choose the function name that should be used in the blank space of line marked as Statement 5
to create the desired CSV file?
(a) dump( ) (b) load( ) (c) writerows( ) (d) writerow( )
Ans: (c) writerows( )
#writerows() writes each sequence in a list as a comma separated line of items in file.

DATA STRUCTURE ( STACK)


Stack: A stack is a data structure whose elements are accessed according to the Last-In First-Out (LIFO)
principle. This is because in a stack, insertion and deletion of elements can only take placeat one end,
called top of the stack. Consider the following examples of stacks:
1. Ten glass plates placed one above another. (The plate that is kept last must be taken out first).
2. The tennis balls in a container. (You cannot remove more than one ball at a time)
3. A pile of books.
4. Stack of coins
The Significance of Stack Top : If we want to remove any coin from the stack, the coin on the top of
the stack has to be removed first. That means, the coin that In the above picture coins are kept one
above the other and if any additional coin is to be added, it can be added only on was kept last in the
stack has to be taken out first.
Note: Stack Work on LIFO (Last In First Out) principle.
Operations on Stack :
We can perform two operations on stack are: Push and Pop

Push (Add/Insert): Adding an element in stack is called Push operation.


When the stack is empty, the value of top is Basically, an empty stack is initialized with an invalid
subscript. Whenever a Push operation is performed, the top is incremented by one and then the new
value is inserted on the top of the list till the time the value of top is less than or equal to the size of the
stack.
The algorithm for Push operation on a stack:
1. Start 2. Initialize top with -1 3. Input the new element
4. Increment top by one. 5. Stack[top]=new element. 6. Print “Item inserted” 7. Stop

Pop (Removing (deleting) an element from the stack.


Removing existing elements from the stack list is called pop operation. Here we must check if the stack is
empty by checking the value of top. If the value of top is -1, then the stack is empty and such a
situation is called Underflow. Otherwise, Pop operation can be performed in the stack. The top is
decremented by one if an element is deleted from the list.
The algorithm for pop operation is as follows:
1. Start.
2. If the value of top is -1 go to step 3 else go to step 4
3.Print “Stack Empty” and go to step 7
4. Deleted item =Stack[top]
5. Decrement top by 1
6. Print “Item Deleted”.
7. Stop
Traversal in a stack: Traversal is moving through the elements of the stack. If you want to display all
the elements of the stack, the algorithm will be as follows:
1. Start
2. Check the value of top. If top=-1 go to step 3 else go to step 4
3.Print “Stack is Empty” and go to step7
4. Print the top element of the stack
5. Decrement top by 1

51 | P a g e
6. If top=-1 go to step 7 else go to step 4
7. Stop

Stack implementation using list with function definition


import sys
def Push(stack):
N=int(input("enter no of record you want to ADD"))
for i in range(N):
data=input("enter name")stack.append(data)
def Pop(stack
if(stack==[]):
print("stack is empty")
else:
N=int(input("enter no of record you want to DELETE"))
for i in range(N):
print("elements to be deleted",stack.pop())
def display(stack):
if(stack==[]):
print("no element for deletion")
else:
top=len(stack)-1
for i in range(top,-1,-1):
print(stack[i])
s=[]
while(True):
print("MENU \n 1-PUSH in STACK \n 2-POP \n 3-DISPLAY \n 4.exit \n")
ch=int(input("enter your choice 1-4"))
if(ch==1):
Push(s)
print("elemnets in stack after push operation",s)
if(ch==2):
Pop(s)
print("element in stack after pop",s)
if(ch==3):
display(s)
if(ch==4):
print("Thank You")
exit()

Check Your Progress :


MCQ:-
1. Which end we use in stack to perform Push and Pop operation?
A. Front B. Rear C. Top D. Sop
2. Which principle followed by Stack?
A. FIFO B. LIFO C. FIOF D. TIPO
3. Which operation take place by stack?
A. Push B. Pop C. Traversal D. All of these
4. Which method we use to add an element in stack using list?
A. insert B. append C. add D. None of these
5. When we delete an element, the value of top will be
A. increment B. decrement C Both A&B D. None of these
ANSWERS: 1. C 2. A 3. D 4.B 5. B
52 | P a g e
TRUE/FALSE:
1. LIFO stands for Last in First Out.
2. We can perform Pop operation if stack is empty.
3. if size of stack is 5 we can Push 6 element in stack.
4. len() method used to find the size of stack.
5. Stack is a linear data structure.
ANSWERS: 1. T 2. F 3. F 4.T 5. T
Q1. Julie has created a dictionary containing names and marks as key value pairs of 6 students. Write a
program, with separate user defined functions to perform the following operations: -
 Push the keys (name of the student) of the dictionary into a stack, where the corresponding
value (marks) is greater than 75.
 Pop and display the content of the stack.
For example: If the sample content of the dictionary is as follows:
R={“OM”:76, “JAI”:45, “BOB”:89,“ALI”:65, “ANU”:90, “TOM”:82}
The output from the program should be: TOM ANU BOB OM

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:

MULTIPLE CHOICE QUESTIONS


Question 1: What is a database?
(A) A collection of organized data (B) A software program used to manage data
(C) A hardware device used to store data (D) All of the above
Answer: (A)
Question 2: What are the benefits of using a database?
(A) Improved data organization and efficiency (B) Reduced data redundancy
(C) Improved data integrity (D) Improved data security
(E) All of the above
Answer: (E)
Question 3: What is the relational data model?
(A) A type of database model that stores data in tables
(B) A type of database model that stores data in hierarchies
(C) A type of database model that stores data in networks
(D) All of the above
Answer: (A)
Question 4: What is a relation in the relational data model?
(A) A table (B) A row in a table (C) A column in a table (D) None of the above
Answer: (A)
Question 5: What is an attribute in the relational data model?
(A) A column in a table (B) A row in a table (C) A table (D) None of the above
Answer: (A)
Question 6: What is the domain of an attribute?
(A) The set of possible values that the attribute can take
(B) The name of the attribute
(C) The data type of the attribute (D) None of the above
Answer: (A)
Question 7: What is the degree of a relation?
(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above
Answer:(A)
Question 8: What is the cardinality of a relation?
(A) The number of attributes in the relation (B) The number of rows in the relation
(C) The number of tables in the relation (D) None of the above
Answer: (B)
Question 9: What is a key in the relational data model?
(A) A set of attributes that uniquely identifies a tuple in a relation
(B) A set of attributes that is used to sort the tuples in a relation
(C) A set of attributes that is used to filter the tuples in a relation
(D) None of the above
Answer: (A)

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)

ASSERTION REASONING QUESTIONS

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).

TRUE FALSE QUESTIONS


1: A database is a collection of organized data. (True)
2: The relational data model is a type of database model that stores data in hierarchies. (False)
3: A relation in the relational data model is a row in a table. (False)
4: A foreign key in the relational data model is a set of attributes in one relation that references the
primary key of another relation. (True)
5: A candidate key in the relational data model is a set of attributes that can uniquely identifies a row
in a table. (True)

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.

SHORT ANSWER QUESTIONS (3 MARKS)


1.Mention 3 Limitations of DBMS.
Ans. The following are three Limitations of DBMS:-
a. High Cost – DBMS requires various software, hardware and highly intelligent people, for
operating and maintaining the database system, which adds cost.
b. Database Failure – If Database is corrupted due to power failure or any other reason, our
valuable data may be lost.
c. Data Quality – With increased number of users directly accessing data from a Database,
there are enormous opportunities for data damage.

MYSQL

It is freely available open source Relational Database Management System (RDBMS) that uses
Structured Query Language(SQL). In MySQL database , information is stored in Tables. A single
MySQL database can contain many tables at once and store thousands of individual records.

SQL (Structured Query Language)

SQL is a language that enables you to create and operate on relational databases, which are sets of
related information stored in tables.

59 | P a g e
CLASSIFICATION OF SQL STATEMENTS

SQL commands can be mainly divided into following categories:

1. Data Definition Language(DDL) Commands


Commands that allow you to perform task, related to data definition e.g;
∙ Creating, altering and dropping.
∙ Granting and revoking privileges and roles.
∙ Maintenance commands.
2. Data Manipulation Language(DML) Commands
Commands that allow you to perform data manipulation e.g., retrieval, insertion, deletion and
modification of data stored in a database.

3. Transaction Control Language(TCL) Commands


Commands that allow you to manage and control the transactions e.g.,
∙ Making changes to database, permanent
∙ Undoing changes to database, permanent
∙ Creating savepoints
∙ Setting properties for current transactions.

MySQL ELEMENTS

1. Literals 2. Datatypes 3. Nulls 4. Comments

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

S.NO. Char Datatype Varchar Datatype

1. It specifies a fixed length character String. It specifies a variable length character string.

2. When a column is given datatype as CHAR(n), When a column is given datatype as


then MySQL ensures that all values stored in VARCHAR(n), then the maximum size a value in
that column have this length i.e. n bytes. If a this column can have is n bytes. Each value that
value is shorter than this length n then blanks is stored in this column store exactly as you
are added, but the size of value remains n specify it i.e. no blanks are added if the length is
bytes. shorter than maximum length n.
NULL VALUE
If a column in a row has no value, then column is said to be null , or to contain a null. You should
use a null value when the actual value is not known or when a value would not be meaningful.
COMMENTS
Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.
Comments begins from a # character to the end of the line or from a -- sequence to the end of the line.

DATABASE COMMNADS

1. VIEW EXISTING DATABASE


To view existing database names, the command is :
SHOW DATABASES ;
2. CREATING DATABASE IN MYSQL
For creating the database in MySQL, we write the following command :
CREATE DATABASE <databasename> ;
e.g. In order to create a database Student, command is :
CREATE DATABASE Student ;
3. ACCESSING DATABASE
For accessing already existing database, we write :
USE <databasename> ;
e.g. to access a database named Student , we write command as :
USE Student ;
4. DELETING DATABASE
For deleting any existing database, the command is :
DROP DATABASE <databasename> ;
e.g. to delete a database , say student, we write command as ;
61 | P a g e
DROP DATABASE Student;
5. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database, command is:
SHOW TABLES ;

CREATING TABLES IN MYSQL


- Tables are created with the CREATE TABLE command. When a table is created, its columns are
named, data types and sizes are supplied for each column.
Syntax of CREATE TABLE command is :
CREATE TABLE <table-name>
( <column name> <data type> ,
<column name> <data type> ,
………
<column name> <data type> ) ;
E.g. in order to create table EMPLOYEE given below :

ECODE ENAME GENDER GRADE GROSS

We write the following command :


CREATE TABLE employee
( ECODE integer ,
ENAME varchar(20) ,
GENDER char(1) ,
GRADE char(2) ,
GROSS integer ) ;
INSERTING DATA INTO TABLE
- The rows are added to relations(table) using INSERT command of SQL. Syntax of INSERT is :
INSERT INTO <tablename> [<column list>] VALUES ( <value1> , <value2> , …..) ;
e.g. to enter a row into EMPLOYEE table (created above), we write command as:
INSERT INTO employee VALUES (1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS) VALUES(1001 , ‘Ravi’ , ‘M’
, ‘E4’ , 50000);

ECODE ENAME GENDER GRADE GROSS

1001 Ravi M E4 50000

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

1001 Ravi M E4 50000

1002 Akash M A1 35000


INSERTING NULL VALUES - To insert value NULL in a specific column, we can type NULL without
quotes and NULL will be inserted in that column. E.g. in order to insert NULL value in ENAME column
of above table, we write INSERT command as :
INSERT INTO EMPLOYEE VALUES (1004 , NULL , ‘M’ , ‘B2’ , 38965 ) ;

ECODE ENAME GENDER GRADE GROSS

1001 Ravi M E4 50000

1002 Akash M A1 35000

1004 NULL M B2 38965

SIMPLE QUERY USING SELECT COMMAND


- The SELECT command is used to retrieve information from a table. Syntax of SELECT
command is :
SELECT <column name>,<column name> FROM <tablename> WHERE <condition name> ;
SELECTING ALL DATA
- In order to retrieve everything (all columns) from a table, SELECT command is used as :
SELECT * FROM <tablename> ;
e.g. In order to retrieve everything from Employee table, we write SELECT command as :
SELECT * FROM Employee;
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965

SELECTING PARTICULAR COLUMNS


EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 Neela F B2 38965
1005 Sunny M A2 30000
1006 Ruby F A1 45000
1009 Neema F A2 52000
- A particular column from a table can be selected by specifying column-names with SELECT
command. E.g. in above table, if we want to select ECODE and ENAME column, then
command is :
SELECT ECODE , ENAME FROM EMPLOYEE ;
E.g.2 in order to select only ENAME, GRADE and GROSS column, the command is :
SELECT ENAME , GRADE , GROSS FROM EMPLOYEE ;
63 | P a g e
SELECTING PARTICULAR ROWS
We can select particular rows from a table by specifying a condition through WHERE clause along
with SELECT statement. E.g. In employee table if we want to select rows where Gender is female,
then command is :
SELECT * FROM EMPLOYEE WHERE GENDER = ‘F’ ;
E.g.2. in order to select rows where salary is greater than 48000, then command is :
SELECT * FROM EMPLOYEE WHERE GROSS > 48000 ;

ELIMINATING REDUNDANT DATA


The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement. For
example SELECT GENDER FROM EMPLOYEE ;
Gender
M
M
F
M
M
F
SELECT DISTINCT(GENDER) FROM EMPLOYEE ;

DISTINCT(GENDER)
M
F

VIEWING STRUCTURE OF A TABLE


- If we want to know the structure of a table, we can use DESCRIBE or DESC
command, as per following syntax : DESCRIBE | DESC <tablename> ;
e.g. to view the structure of table EMPLOYEE, command is :
DESCRIBE EMPLOYEE ;
OR
DESC EMPLOYEE ;

USING COLUMN ALIASES


- The columns that we select in a query can be given a different name, i.e. column alias name for
output purpose. Syntax :
SELECT <columnname> AS column alias , <columnname> AS column alias ... FROM <tablename> ;
e.g. In output, suppose we want to display ECODE column as EMPLOYEE_CODE in output , then
command is :
SELECT ECODE AS “EMPLOYEE_CODE” FROM EMPLOYEE ;
CONDITION BASED ON A RANGE
- The BETWEEN operator defines a range of values that the column values must fall in to make
the condition true. The range include both lower value and upper value.
e.g. to display ECODE, ENAME and GRADE of those employees whose salary is between 40000
and 50000, command is:
SELECT ECODE , ENAME ,GRADE FROM EMPLOYEE

64 | P a g e
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
ECODE ENAME GRADE
1001 Ravi E4
1006 Ruby A1

CONDITION BASED ON A LIST


- To specify a list of values, IN operator is used. The IN operator selects value that match
any value in a given list of values. E.g.
SELECT * FROM EMPLOYEE WHERE GRADE IN (‘A1’ , ‘A2’);
Output will be :
ECODE ENAME GENDE GRADE GROSS
R
1002 Akash M A1 35000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
1009 Neema F A2 52000

- 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

CONDITION BASED ON PATTERN MATCHES


- LIKE operator is used for pattern matching in SQL. Patterns are described using two special
wildcard characters:
1. percent(%) – The % character matches any substring.
2. underscore(_) – The _ character matches any character.

e.g. to display names of employee whose name starts with R in EMPLOYEE table, the command is :
SELECT ENAME FROM EMPLOYEE WHERE ENAME LIKE ‘R%’ ;
Output will be :

e.g. to display details of employee whose second character in name is ‘e’.

SELECT * FROM EMPLOYEE WHERE ENAME LIKE ‘_e%’ ;


Output will be :
ECODE ENAME GENDE GRADE GROSS
R
1004 Neela F B2 38965
1009 Neema F A2 52000
65 | P a g e
e.g. to display details of employee whose name ends with ‘y’.

SELECT * FROM EMPLOYEE WHERE ENAME LIKE ‘%y’ ;


Output will be :
ECODE ENAME GENDE GRADE GROSS
R
1005 Sunny M A2 30000
1006 Ruby F A1 45000

SEARCHING FOR NULL


- The NULL value in a column can be searched for in a table using IS NULL in the WHERE
clause. E.g. to list employee details whose salary contain NULL, we use the command :
SELECT * FROM EMPLOYEE WHERE GROSS IS NULL ;
e.g.
STUDENT
Roll_No Name Marks
1 ARUN NULL
2 RAVI 56
4 SANJAY NULL

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.

The ORDER BY clause is used as :


SELECT <column name> , <column name>…. FROM <tablename>
WHERE <condition> ORDER BY <column name> ;
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use
command :
SELECT * FROM EMPLOYEE ORDER BY ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000

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

MODIFYING DATA IN TABLES


you can modify data in tables using UPDATE command of SQL. The UPDATE command specifies the
rows to be changed using the WHERE clause, and the new data using the SET keyword. Syntax of
update command is :
UPDATE <tablename> SET <columnname>=value , <columnname>=value WHERE <condition> ;
e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to
55000.
UPDATE EMPLOYEE SET GROSS = 55000 WHERE ECODE = 1009 ;
UPDATING MORE THAN ONE COLUMNS
e.g. to update the salary to 58000 and grade to B2 for employees whose employee code is 1001.
UPDATE EMPLOYEE SET GROSS = 58000, GRADE=’B2’ WHERE ECODE = 1009 ;
OTHER EXAMPLES
e.g.1. Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE SET GROSS = GROSS +100 ;
e.g.2. Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE SET GROSS = GROSS * 2
WHERE GRADE=’A1’ OR GRADE=’A2’ ;
e.g.3. Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is
Neela.
UPDATE EMPLOYEE SET GRADE=’A2’
WHERE ECODE=1004 AND GRADE=’NEELA’ ;
DELETING DATA FROM TABLES
To delete some data from tables, DELETE command is used. The DELETE command
removes rows from a table. The syntax of DELETE command is :
DELETE FROM <tablename> WHERE <condition> ;
For example, to remove the details of those employee from EMPLOYEE table whose grade is A1.
DELETE FROM EMPLOYEE WHERE GRADE =’A1’ ;
TO DELETE ALL THE CONTENTS FROM A TABLE
DELETE FROM EMPLOYEE ;
So if we do not specify any condition with WHERE clause, then all the rows of the table will be
deleted. Thus above line will delete all rows from employee table.

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> ;

ALTER TABLE COMMAND


The ALTER TABLE command is used to change definitions of existing tables. (adding columns,
deleting columns etc.). The ALTER TABLE command is used for :
1. adding columns to a table
2. Modifying column-definitions of a table.
3. Deleting columns of a table.
4. Adding constraints to table.
5. Enabling/Disabling constraints.

ADDING COLUMNS TO TABLE


To add a column to a table, ALTER TABLE command can be used as per following syntax:

ALTER TABLE <tablename> ADD <Column name> <datatype> <constraint> ;


e.g. to add a new column ADDRESS to the EMPLOYEE table, we can write command as :
ALTER TABLE EMPLOYEE ADD ADDRESS VARCHAR(50);
A new column by the name ADDRESS will be added to the table, where each row
will contain NULL value for the new column.
ECODE ENAME GENDER GRADE GROSS ADDRESS
1001 Ravi M E4 50000 NULL
1002 Akash M A1 35000 NULL
1004 Neela F B2 38965 NULL
1005 Sunny M A2 30000 NULL
1006 Ruby F A1 45000 NULL
1009 Neema F A2 52000 NULL

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 :

ALTER TABLE <table name> DROP <column name>;


e.g. to delete column GRADE from table EMPLOYEE, we will write :
ALTER TABLE EMPLOYEE DROP GRADE ;

ADDING/REMOVING CONSTRAINTS TO A TABLE


ALTER TABLE statement can be used to add constraints to your existing table by using it in
following manner:
TO ADD PRIMARY KEY CONSTRAINT
ALTER TABLE <table name> ADD PRIMARY KEY (Column name);
e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command is :
ALTER TABLE EMPLOYEE ADD PRIMARY KEY (ECODE) ;

TO ADD FOREIGN KEY CONSTRAINT


ALTER TABLE <table name> ADD FOREIGN KEY (Column name) REFERENCES Parent
Table (Primary key of Parent Table);
REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command as :
ALTER TABLE <table name> DROP PRIMARY KEY ;
- To remove foreign key constraint from a table, we use ALTER TABLE command as :
ALTER TABLE <table name> DROP FOREIGN KEY ;
INTEGRITY CONSTRAINTS/CONSTRAINTS
69 | P a g e
- A constraint is a condition or check applicable on a field(column) or set of fields(columns).
- Common types of constraints include :

S.No. Constraints Description


1 NOT NULL Ensures that a column cannot have NULL value
2 DEFAULT Provides a default value for a column when none is specified
3 UNIQUE Ensures that all values in a column are different
4 CHECK Makes sure that all values in a column satisfy certain criteria
5 PRIMARY KEY Used to uniquely identify a row in the table
6 FOREIGN KEY Used to ensure referential integrity of the data

NOT NULL CONSTRAINT


By default, a column can hold NULL. It you not want to allow NULL value in a column, then NOT
NULL constraint must be applied on that column. E.g.
CREATE TABLE Customer
( SID integer NOT NULL,
Last_Name varchar(30) NOT NULL,
First_Name varchar(30)
);
Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.

An attempt to execute the following SQL statement,


INSERT INTO Customer VALUES (NULL , ‘Kumar’ , ‘Ajay’);
will result in an error because this will lead to column SID being NULL, which violates the
NOT NULL constraint on that column.

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

The executing the following SQL statement,


INSERT INTO Customer VALUES (‘3’ , ‘Cyrus‘ , ‘Grace’) ;
will result in an error because the value 3 already exist in the SID column, thus trying to
insert another row with that value violates the UNIQUE constraint.

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.

PRIMARY KEY CONSTRAINT


- A primary key is used to identify each row in a table. A primary key can consist of one or
more fields(column) on a table. When multiple fields are used as a primary key, they are
called a composite key.
- You can define a primary key in CREATE TABLE command through keywords PRIMARY KEY.
e.g.
CREATE TABLE Customer ( SID integer NOT NULL PRIMARY KEY,
Last_Name varchar(30) , First_Name varchar(30) ) ;
Or
CREATE TABLE Customer ( SID integer, Last_Name varchar(30) ,
First_Name varchar(30), PRIMARY KEY (SID) ) ;
- The latter way is useful if you want to specify a composite primary key, e.g.
CREATE TABLE Customer ( Branch integer NOT NULL, SID integer NOT NULL ,
Last_Name varchar(30) , First_Name varchar(30),
PRIMARY KEY (Branch , SID) ) ;
FOREIGN KEY CONSTRAINT
- Foreign key is a non key column of a table (child table) that draws its values from
primary key of another table(parent table).
- The table in which a foreign key is defined is called a referencing table or child table.
A table to which a foreign key points is called referenced table or parent table.

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).

CREATE TABLE STUDENT


( ROLL_NO integer NOT NULL PRIMARY KEY ,
NAME VARCHAR(30) , CLASS VARCHAR(3) );
CREATE TABLE SCORE
( ROLL_NO integer , MARKS integer ,
FOREIGN KEY(ROLL_NO) REFERNCES STUDENT(ROLL_NO) ) ;

* Foreign key is always defined in the child table.


Syntax for using foreign key
FOREIGN KEY(column name) REFERENCES Parent_Table(PK of Parent Table);

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.

Q: Create two tables


Customer(customer_id, name)
Customer_sales(transaction_id, amount , customer_id)
Underlined columns indicate primary keys and bold column names indicate foreign key.
Make sure that no action should take place in case of a DELETE or UPDATE in the parent table.
72 | P a g e
Sol : CREATE TABLE Customer (
customer_id int Not Null Primary Key ,
name varchar(30) ) ;

CREATE TABLE Customer_sales


( transaction_id Not Null Primary Key ,
amount int , customer_id int ,
FOREIGN KEY(customer_id) REFERENCES Customer (customer_id) ON DELETE NO
ACTION ON UPDATE NO ACTION );

Q: Distinguish between a Primary Key and a Unique key in a table.

S.NO. PRIMARY KEY UNIQUE KEY


1. Column having Primary key can’t Column having Unique Key can contain
contain NULL value NULL value
2. There can be only one primary key in Many columns can be defined as Unique
Table. key

Q: Distinguish between ALTER Command and UPDATE command of SQL.

S.NO. ALTER COMMAND UPDATE COMMAND


1. It is a DDL Command It is a DML command
2. It is used to change the definition of It is used to modify the data values present
existing table, i.e. adding column, in the rows of the table.
deleting column, etc.
3. Syntax for adding column in a table: Syntax for using UPDATE command:
ALTER TABLE <tablename> UPDATE <Tablename>
ADD <Column name><Datatype> ; SET <Columnname>=value
WHERE <Condition> ;

AGGREGATE / GROUP FUNCTIONS


Aggregate / Group functions work upon groups of rows , rather than on single row, and return one
single output. Different aggregate functions are : COUNT( ) , AVG( ) , MIN( ) , MAX( ) , SUM ( )
Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
8912 SUR NULL 3000 10
1. AVG( )
This function computes the average of given data. e.g.
SELECT AVG(SAL) FROM EMPL ;

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

e.g. SELECT COUNT(JOB) FROM EMPL ;


Output

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

GROUPING RESULT – GROUP BY


The GROUP BY clause combines all those records(row) that have identical values in a particular
field(column) or a group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the
aggregate produces a value for each group.
Table : EMPL

EMPNO ENAME JOB SAL DEPTNO

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

e.g. Calculate the number of employees in each grade.


SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB ;
Output
JOB COUNT(*)
CLERK 1
SALESMAN 2
MANAGER 1

e.g.2. Calculate the sum of salary for each department.


SELECT DEPTNO , SUM(SAL) FROM EMPL GROUP BY DEPTNO ;
Output
DEPTNO SUM(SAL)
10 2985
20 15513
30 8760
e.g.3. find the average salary of each department.

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

PLACING CONDITION ON GROUPS – HAVING CLAUSE


- The HAVING clause places conditions on groups in contrast to WHERE clause that
places condition on individual rows. While WHERE conditions cannot include
aggregate functions, HAVING conditions can do so.
- e.g. To display the jobs where the number of employees is less than 2,
- SELECT JOB, COUNT(*) FROM EMPL GROUP BY JOB HAVING COUNT(*) < 2 ;
75 | P a g e
Output
JOB COUNT(*)
CLERK 1
MANAGER 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 :

1. BEGIN or START TRANSACTION – marks the beginning of a transaction.


2. COMMIT – Ends the current transaction by saving database changes and starts a new transaction.
3. ROLLBACK – Ends the current transaction by discarding database changes and starts a new
transaction.
4. SAVEPOINT – Define breakpoints for the transaction to allow partial rollbacks.
5. SET AUTOCOMMIT – Enables or disables the default auto commit mode

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.

(ii) DROP DATABASE SCHOOL;


25. DDL - ALTER, DROP
DML - INSERT, UPDATE

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.

CODE FOR CREATING A MYSQL DATABASE THROUGH PYTHON


import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="mohana", password="mohana")

mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")

CODE FOR CREATING A TABLE IN MYSQL THROUGH PYTHON


import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="mohana",password="mohana",
database="mydatabase")
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")

CODE FOR INSERTING DATA IN A MYSQL TABLE THROUGH PYTHON


import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="mohana",password="mohana",
database="mydatabase")
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("Tom", "ABCD")
mycursor.execute(sql,
val) mydb.commit()
print(mycursor.rowcount, "record inserted.")

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")

CODE FOR UPDATING A RECORD FROM MYSQL TABLE USING PYTHON


import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",
database="mydatabase”)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley
345'" mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

MIND MAP

Check Your Progress :

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

Q-9 In python, connect() returns .


A. Connection object. B. Database object C. Database name D. Connector
class Ans.A

Q-10 In python, execute() method can execute only .


A. Only DQL & DML statements B. Only DML statements
C. Only DQL statements. D. DDL, DML & DQL
statements. Ans.D

A. 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

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.

2. What is a cursor in the context of MySQL?


ANS. A cursor is a pointer that points to a specific location in a database table. In MySQL,
cursors are used to iterate through the rows of a table and retrieve data from them.

3. What’s the difference between autocommit and commit?


ANS. Autocommit is a database feature that automatically commits changes to the database as
soon as they are made. This means that changes are immediately visible to other users and
there is no need to explicitly call the commit() method. Commit, on the other hand, is a
database feature that allows changes to be made to the database and then explicitly committed
by the user. This allows the user to control when changes are made visible to other users.

4. How can you check if a table exists in MySQL?


ANS. You can check if a table exists in MySQL by using the SHOW TABLES command. This will
show you a list of all the tables in the database. If the table you are looking for is not in the list,
then it does not exist.

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.

F. CASE STUDY BASED QUESTIONS

Q1. A STUDENT HAS WRITTEN THE FOLLOWING CODE


Explain what the following query will do?
import mysql.connector
db =
mysql.connector.connect(….)
cursor = db.cursor()
person_id = input("Enter required person id")
lastname = input("Enter required lastname")
db.execute("INSERT INTO staff (person_id, lastname) VALUES ({}, ‘{}’) ". format
(person_id, lastname))
db.commit()
db.close()
ANS. This above program insert a new records in table staff such that person_id and lastname
are input by user.
Q2. ABC Infotech Pvt. Ltd. needs to store, retrieve and delete the records of its employees.
Develop an interface that provides front-end interaction through Python, and stores and
updates records using MySQL.
The operations on MySQL table "emp" involve reading, searching, updating and deleting
the records of employees.
Program to read and fetch all the records from EMP table having salary more than 70000.

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()

IMPORTANT CONNECTIVITY METHODS :

Connectivity Basics: Important functions and its purpose :


- connect( ): Establishes a connection to the database.
- cursor( ): Creates a cursor object to execute SQL queries.
- execute( ): Executes SQL commands.
- commit( ): Saves changes made during the transaction.
1. Fetching Data:
- fetchone( ): Retrieves the next row of a query result set.
- fetchall( ): Fetches all rows of a query result set.
- rowcount: Returns the number of rows affected by the last executed command.
2. Creating Database Applications:
Developing applications involves connecting to the database, executing queries, and
processing results.
Utilize `connect()`, `cursor()`, and `execute()` for database operations.
3. Query Formatting:

- ‘%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

# import the mysql-python connector module


import mysql.connector
# Establishing a connection to the database

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()

Check your Progress :

Multiple Choice Questions (MCQ) :


1. What does the `connect()` function do in database connectivity?
A. Closes the database connection B. Establishes a connection to the database
C. Deletes the database D. Fetches data from the database

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

5. How is dynamic insertion of values achieved in SQL queries?


A. Using `execute()` B. Using `dynamicValues()`
C. Using `%s` format specifier or `format()` D. Using `insertValues()`
Correct Answer: C
6. What does the `commit()` function do in database connectivity?
A. Rolls back the transaction B. Commits the changes made during the transaction
C. Closes the cursor. D. Fetches all rows of the query
result Correct Answer: B
7. Which function retrieves all rows of a query result set in Python's database
connectivity?

A. `fetch()` B. `fetchone()` C. `fetchset()` D.

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. Explain the purpose of the `fetchall()` function in Python's database connectivity.


2. How is the `rowcount` attribute helpful while working with database connectivity?
3. Describe the role of the `execute()` function in executing SQL queries.
4. What does SQL injection mean, and how can it be prevented in Python's
database applications?
5. Briefly explain the significance of the `commit()` function in database transactions.

Short Answer (SA-2) 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.

Advantages of Computer Network-


 Resource sharing,
 Centralized data management,
 Scalability,
 Remote access,
 Automation,
 Enhanced security,
 Reduced costs,

Disadvantages of Computer Network


 Expensive
 Virus and Malware
 Management of the network

Components of Data Communication:


 Message – The information to be communicated
 Sender – The device which send the message
 Receiver – The device which receive the message
 Transmission media – It is physical path by which message travel from sender toreceiver
 Protocol – It is set of rules that governs data communication. Actually, it is agreement
between the sender and receiver regarding various communicationparameter.

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.

PAN (Personal Area Network) – The smallest computer network


 Devices may be connected through Bluetooth or other infra-red enables devices
 It has a connectivity range of up to 10 meters.
 Personal devices belonging to a single person can be connected to each other using PAN

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

Twisted Pair Cable


 A twisted pair cable comprises of two separate insulated copper wires, which are twisted
together and run in parallel.
o STP (Shielded Twisted Pair) cable has a fine wire mesh surrounding the wires to
protect the transmission
o UTP (Unshielded Twisted Pair) cable does not has a fine wire mess.
 It is also known as Cat# cable where # denote number. e.g. Cat 6
 Connector: RJ 45

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

Unguided Media or Wireless Media


 No Physical media is used
 Less Secure
 Relatively low speed
 Can be used for longer distance
 Best suited for difficult terrain
 There is no need to acquire land rights

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.

There are many types of topologies: -

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.

Advantage – Bus 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.
 It can be extended easily.

Disadvantage – Bus 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
 Terminator is required.
 Maintenance costs can get higher with time.
 Not suitable for Big network.
 Low Security due to broadcasting of data.

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.

Disadvantages – Star Topology


 Require more cable length
 Central Device dependency
 More costly
 Performance depend on Hub/Switch

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

HTTP (Hyper Text Transfer Protocol)


 It is an application level protocol.
 It provide communication between web browser and web server.
 It is client server protocol ie. request is sent by browser and hyperemedia documents will
be provided by server.
 It can work as generic protocol.
 It is used to deliver data (HTML files, image files, query results, etc.) on the different
websites.

FTP (File Transfer Protocol)

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.

Point to Point Protocol (PPP)


 It works on data link layer of OSI model.
 It establishes direct and dedicate connection between two devices .
 Example – Two routers direct communicate using PPP.
 Our home computer when connects to internet with ISP through modem then there PPP
protocol is used.
 For using PPP duplex mode is required for communicating devices , it also ensures data
integrity and security , failing which using acknowledge method it resends the lost or
damaged data .

Simple Mail Transfer Protocol (SMTP)


 SMTP works on application layer of OSI model.
 It is used for email services .
 It is not concerned with message of email , it only uses the information contained in email
header .
 Outgoing emails are collected in queue .
 SMTP takes emails one by one from queue and send messages to destination as per
address mentioned in header of the mail .
 After sending the mail to destination it removes the messages from outgoing queue , and
same time it also removes the receiver’s address from mails destination list.
 At receiving end SMTP receiver program sends the mails mail to their corresponding mail
boxes .

Transmission control protocol / Internet Protocol ( TCP / IP )


 TCP / IP works with 4 layers i.e. Network , Internet , Transport and Application.
 It uses client – server model of communication .
 TCP breaks the messages in packets .
 IP decides the destination addresses for packets .
 Packets are sent on internet they reach at destination by routing various
intermediate nodes and paths .
 Different packets of same message will travel through different paths depending on traffic
at particular path.
 TCP is responsible for ordering the packets at receiving and destination.

Post office Protocol Version 3 (POP 3)


 It works on application layer of OSI model .
 It is used to transferring messages from email server to email client .
 It is used to access the remote serve email and receive and filters the email at appropriate
user folders.
 Messages are downloaded from mail server to hard disk using this protocol.

Hypertext Transfer Protocol Secure (HTTPS)


Hyper Text Transfer Protocol Secure (HTTPS) is the secure version of HTTP, the protocol over
which data is sent between your browser and the website that you are connected to. The 'S'
at the end of HTTPS stands for 'Secure'. It means all communications between your browser and
the website are encrypted.

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.

Introduction to Web Services:


WWW (World Wide Web): WWW is a network of web servers. It can be defined as a hypertext
information retrieval system on the Internet. It is the universe of the information available on the
internet. All the web pages on WWW use HTTP for making hypertext jumps.

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.

Difference between HTML AND XML:


HTML XML
HTML stands for Hyper Text Markup XML stands for Extensible Markup
Language. Language.
HTML is static in nature. XML is dynamic in nature.
It was developed by WHATWG. It was developed by Worldwide Web
Consortium.
It is termed as a presentation language. It is neither termed as a presentation nor a
programming language.
HTML is not Case sensitive. XML is Case sensitive.
HTML tags are predefined tags. XML tags are user-defined tags.

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.

Top level domains are further divided into two categories:


Generic Domain Names: Country Specific Domain Names:
·com - commercial business .in - India
·edu - Educational institutions ·au - Australia
·gov - Government agencies ·ca - Canada
·mil – Military .ch - China
·net - Network organizations .nz - New Zealand
·org - Organizations (non-profit .pk - Pakistan
.jp - Japan
.us - United States of America

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

The URL text string consists of three parts:

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

Multiple choice Questions:


Q1. What does PoP stand for?
a) Pre Office Protocol b) Post Office Protocol
c) Protocol of Post d) None
Ans: (b)

Q2. What does a set of rules define?


a) SMTP b) FTP
c) IMAP d) Protocol
Ans: (d)

Q3. The physical address assigned by NIC manufacturer is called--------------address.


(a)IP (b) MAC (c) TCP (d) URL
Ans:- (b) MAC

Q 4. What is the full form of HTTP?


a) Hypertext Transfer Protocol b) Hypertext Transfer Procedure
c) Hyperlink Transfer Protocol d) Hyperlink Transfer Procedure
Ans: (c)

Q 5. URL stands for


a) unique reference label b)uniform reference label
c) uniform resource locator d) unique resource locator

106 | P a g e
Ans: (c)

Q 6. Google Chrome is a good –


a) Web server.
b) Web browser.
c) Web protocol.
d) Subset of website sent from the root server to other root servers
Ans: (b)

Q 7. The participating computers in a network are referred to as:


a) Clients
b) Servers
c) Nodes
d) CPUs
Ans: (c)

Q 8. A collection of hyperlinked documents on the internet forms the ?


a) World Wide Web (WWW) b) E-mail system
c) Mailing list d) Hypertext markup language
Ans: World Wide Web (WWW)

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)

COMPETENCY BASED QUESTIONS


Q1. State two reasons for which you may like to have a network of computers instead of having
standalone computers.
Ans. 1. It helps the user to share data files.
2. It allows the user to communicate
Q 2. Given below two addresses
(i) 59.177.134.72
(ii) http://www.bb.nic.in/welcome.htm
Identify which one of the above is an IP address and which one is a URL?
Ans4 i) IP Address 59.177.134.72
URL http://www.bb.nic.in/welcome.htm
Q 3. Raj is working as a tech support engineer and sometimes he wants to work on cient’s
computer from home. Tell the traditional protocol used for this purpose.
Ans. Telnet
Q 4. Uploading photos from mobile to laptop is an example of ______.
Ans: PAN
Q 5. Which type of Guided media is not susceptible to external interference
Ans: Fiber Optic
Q 6. Identify me-
I am a networking device used to connect multiple computers. I send the data to only intended
node.

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

VERY SHORT QUESTIONS


Q1. _____ sends data to every connected node.
Ans: HUB
Q2. Name any two most popularly used search engines.
Ans: Two most popular search engines are Google and Mozilla firefox
Q 3. A local telephone line network is an example of __________ .
Ans: Circuit Switching
Q 4. Identify the Domain name and URL from the following:
http://www.income.in/home.aboutus.hml
Answer: Domain name – income.in
URL – http://www.income.in/home.aboutus.hml.
Q 5. Which of the following is not a unit for data transfer rate?
1. bps 2. Abps 3. gbps 4. Kbps
Ans: Abps
Q 6. Which device is used to connect all computers inside a lab?
Ans: Hub
Q 7. Which of the transmission is suitable to send data from one place to anywhere in the world
Ans: Satellite
Q 8. Which connector is used to connect Ethernet cable to LAN Card.
Ans: RJ 45
Q9. Wi-Fi stands for ______
Ans: Wireless fidelity
Q 10. Data communication spanning states, countries or the whole world is ______
Ans: WAN

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:

Q 8. What is the difference between HTTP and FTP?


Ans: FTP is a protocol used to upload files from a workstation to a FTP server or download files
from FTP Server to a workstation
HTTP is a protocol used to transfer files from a web server onto a browser in order to view a web
page that is on the internet.
Q 9. Write two advantages of Star topology.
Ans. 1. Easy to detect fault
2. Easy to install
Q 10. Write any one disadvantages of VoIP.
Ans: The disadvantage of VoIP is that its call quality is dependent on internet connection speed.
Slow internet connections will lead to poor quality voice calls.

LONG QUESTIONS / CASE STUDY BASED QUESTIONS


Q 1. Trine Tech Corporation (TTC) is a professional consultancy company. The company is
planning to set up their new offices in India with its hub at Hyderabad. As a network adviser, you
have to understand their requirement and suggest them the best available solutions. Their
queries are

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:

1. Suggest a cable layout of connections between the compounds.


2. Suggest the most suitable place (i.e compound) to house the server for this NGO. Also,
provide a suitable reason for your suggestion.
3. Suggest the placement of the following devices with justification:
(a) Repeater (b) Hub/Switch
4. The NGO is planning to connect its international office situated in Mumbai, which out of
the following wired communication link, will you suggest for a very high speed
111 | P a g e
connectivity?
(a) Telephone analog line
(b) Optical fibre
(c) Ethernet cable.

А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.

Q 4. Institute of Distance Learning is located in Pune and is planning to go in for networking of


four wings for better interaction. The details are shown
below: Delhi 2009C

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. Suggest a cable layout of connection between the buildings.


2. Suggest the most suitable place (i.e. building) to house the server for this NGO. Also,
provide a suitable reason for your suggestion.
3. Suggest the placement of the following devices with justification:
(a) Repeater
(b) Hub/Switch.
4. The NGO is planning to connect its international office situated in Delhi. Which out of the
following wired communication links, will you suggest for a very high speed connectivity?
(a) Telephone analog line
(b) Optical fibre
(c) Ethernet cable
Аnswer:

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.

SECTION A (1 MARK QUESTIONS)


1 State True or False: 1
“Python has a set of keywords that can be used to declare variables”
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
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
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
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

a) Bridge b)Gateway c)Hub d) Router


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
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.

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
20 The code given below accepts a number as an argument and returns the list of all 2
prime numbers upto that number. Observe the following code carefully and
rewrite it after removing all syntax and logical errors. Underline all the
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’)
21 Write a function distinction(marks) in Python, that takes the dictionary marks as 2
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}
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:
l2.append(x)

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.

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
x = trap(x, y)
print(x, y, sep=‘#’)
y = trap(x, y)
print(y, x, sep=‘#’)

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+"#"

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.

(i) SELECT DISTINCT TYPE FROM BANK;


(ii) SELECT NAME, TYPE FROM BANK
WHERE CREATEDON <‘2006/12/31’ AND NAME LIKE ‘%I’;
(iii) SELECT NAME, AGE, BALANCE FROM BANK
WHERE GENDER=‘F’ AND BALANCE BETWEEN 6000 AND 7000;

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” .

29 Consider the table CHIPS given below:’ 3

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.

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
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.

(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

SECTION D (4 MARKS QUESTIONS)


31 Consider the tables STUDENT and CLUB given below: 4

Write SQL queries for the following:


(i) Display Name and Club Name from the tables STUDENT and CLUB.
(ii) Display the structure of the table STUDENT
(iii) Display the average marks of Each class.
(iv) Display the name of all students from the club where ClubIC is Ram.
32 Vedant is a Python programmer working in a institution which hosted a technical 2+2
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.
SECTION E (5 MARKS QUESTIONS)

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 :

a) SMTP : Simple Mail Transfer Protocol


b) VoIP : Voice Over Internet Protocol
ii) Give one disadvantage of Star topology
Star topology has a single point of failure. If the central hub or switch fails,
the entire network will be down. This can be a major problem for networks
that require high availability. Or any other dis advantage.
(1 Mark each for correct answer)
OR
i) What is a web browser ?
A software application used to access information on the World Wide Web is
called a Web Browser. When a user requests some information, the web
browser
fetches the data from a web server and then displays the webpage on the user's
screen.
ii) Define the term MAC Address
A MAC address (media access control address) is a 12-digit hexadecimal
number assigned to each device connected to the network. Primarily specified
as a unique identifier during device manufacturing, the MAC address is often
found on a device's network interface card (NIC).
(1 Mark each for correct answer)

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.

(i) SELECT DISTINCT TYPE FROM BANK;


(ii) SELECT NAME, TYPE FROM BANK
WHERE CREATEDON <‘2006/12/31’ AND NAME LIKE ‘%I’;
(iii) SELECT NAME, AGE, BALANCE FROM BANK
WHERE GENDER=‘F’ AND BALANCE BETWEEN 6000 AND 7000;
Ans (i) SELECT DISTINCT TYPE FROM BANK;
Distinct Type
Savings
Current
Deposit
(ii) SELECT NAME, TYPE FROM BANK WHERE
CREATEDON <‘2006/12/31’ AND NAME LIKE ‘%I’;
Name Type
Rashi Current

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”.

Ans Correct function prototype 1⁄2 mark


Correct opening text file statement 1⁄2 mark
Correct logic 1 and 1⁄2 marks
Closing the file 1⁄2 mark
OR
Correct function prototype 1⁄2 mark
Correct opening text file statement 1⁄2 mark
Correct logic 11⁄2 marks
Closing the file 1⁄2 mark
29 Consider the table CHIPS given below:’ 3

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

SECTION D (4 MARKS QUESTIONS)

31 Consider the tables STUDENT and CLUB given below: 4

Write SQL queries for the following:


(i) Display Name and Club Name from the tables STUDENT and CLUB.
(ii) Display the structure of the table STUDENT
(iii) Display the average marks of Each class.
(iv) Display the name of all students from the club where ClubIC is Ram.
Ans (i) select Name, ClubName from student s, club c where s.clubid=c.slubid;
(ii) desc student;
(iii) select class, avg(marks) from student group by class;

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.

Ans import csv


def Accept( ):
f=open(‘Participants.csv’,‘a’,newline=‘’)
wo=csv.writer(f)
if not f.seek():
wo.writerow([‘Id’, ‘Name’, ‘Event’])
Id=int(input(“Enter id”)
name=input(“Enter name”)
event=input(“Enter event”)
wo.writerow([id, name, event])
print(“Data written successfully”)
f.close( )
def EventCount( ):
f=open(‘Participants.csv’,’r’)
ro=csv.reader(f)
c=0
for i in ro:
if i[2]==‘Robocon’:
c+=1
print(c)
f.close( )
(2 Marks for each correct function)
SECTION E (5 MARKS QUESTIONS)
33 TechCloud is an educational organization. It is planning to setup its campus at 1+2+
Jaipur with its head office at Delhi. The Jaipur campus has 4 main buildings – 2
ADMIN, FINANCE, STUDIO and DATA CENTER.

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)

(a) 10 (b) 20 (c) True (d) False


8 Which of the following is a DML command? 1
(a)CREATE (b)ALTER (c)INSERT (d)DROP
9 Which of the following function returns a list datatype? 1
a) d=f.read() b) d=f.read(10) c) d=f.readline() d) d=f.readlines()
10 Fill in the blank: 1
is a non-key attribute, whose values are derived from the primary
key of some other table.
(a) Foreign Key
(b) Primary Key

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?

(a) 13,8 (b) 8, 13 (c) 14,5 (d) 5,8


12 The correct syntax of seek() is: 1
(a) file_object.seek(offset[,reference_point])
(b) seek(offset[,reference_point])
(c) seek(offset,file_object)
(d) seek.file_object(offset)
13 The structure of the table/relation can be displayed using __________ command. 1
(a) view (b) describe (c) show (d) select
14 What will the following expression be evaluated to in Python? 1
print(2**3+(5+6)**(1 +1))
(a)129 (b)8 (c) 121 (d) None
15 How do you change the file position to an offset value from the start? 1
(a) fp.seek(offset, 0) (b) fp.seek(offset, 1) (c) fp.seek(offset, 2) (d) None
of them
16 Which of the following function is used to establish connection between Python and 1
MySQL database–
(a)connection() (b)connect() (c)Connect() (d)None
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
17 Assertion (A): The function definition calculate(a, b, c=1,d) will give error. 1
Reason (R): All the non-default arguments must precede the default arguments.

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;-

x= int(“Enter value of x:”)


for in range [0,10]:
if x=y
print( x + y)
else:
print( x-y)

20 (a) Given is a Python string declaration: 2


str="CBSE Examination@2022"
Write the output of: print(str[-1:-15:-2])

(b) Write the output of the code given below:

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

def Change(P ,Q=30):


P=P+Q
Q=P-Q
print(P,"#",Q)
return(P)
R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
OR
Predict output of the following code fragment –

tuple1 = (11, 22, 33, 44, 55 ,66)


list1 =list(tuple1)
new_list = []
for i in list1:
if i%2==0:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
23 Expand the following terms: 2
i. NIC
ii. TCP/IP
iii. POP
iv. SMTP
OR
Differentiate between Packet Switching and Circuit switching.

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

fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']


fruit_list2 = fruit_list1
fruit_list3 = fruit_list1[:]
fruit_list2[0] = 'Guava'
fruit_list3[1] = 'Kiwi'
sum = 0
for ls in (fruit_list1, fruit_list2, fruit_list3):
if ls[0] == 'Guava':
sum += 1
if ls[1] == 'Kiwi':
sum += 20
print (sum)
27 Define a function SHOWWORD () in python to read lines from a text file STORY.TXT, and 3
display those words, whose length is less than 5.
OR
Write a user defined function in python that displays the number of lines starting with
'H' in the file para.txt

28 Write the outputs of the SQL queries (a) to (c) based on the relation Furniture 3

No Itemname Type Dateofstock Price Discount


1 White lotus Double Bed 23/02/2002 30000 25
2 Pink feather Baby Cot 20/01/2002 7000 20
3 Dolphin Baby Cot 19/02/2002 9500 20
4 Decent Office Table 01/01/2002 25000 30
5 Comfort Zone Double Bed 12/01/2002 25000 25
6 Donald Baby Cot 24/02/2002 6500 15
7 Royal finish Office Table 20/02/2002 18000 30
8 Royal tiger Sofa 22/02/2002 31000 30
9 Econo sitting Sofa 13/12/2001 9500 25
10 Paradise Dining Table 19/02/2002 11500 25
11 Wood Comfort Double Bed 23/03/2003 25000 25

137 | P a g e
12 Old Fox Sofa 20/02/2003 17000 20
13 Micky Baby Cot 21/02/2003 7500 15

(a) SELECT Itemname FROM Furniture WHERE Type="Double Bed";


(b) SELECT MONTHNAME(Dateofstock) FROM Furniture WHERE Type="Sofa";
(c) SELECT Price*Discount FROM Furniture WHERE Dateofstock>31/12/02;
29 Consider the following table GAMES 3

GCode GameName Number PrizeMoney ScheduleDate


101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004
Write the output for the following queries :
(i) SELECT COUNT(DISTINCT Number) FROM GAMES;
(ii) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(iii) SELECT SUM(PrizeMoney) FROM GAMES;

30 Write PushOn(Book) and Pop(Book) methods/functions in Python to add a new Book 3


and delete a Book from a list of Book titles, considering them to act as push and pop
operations of the Stack data structure.
SECTION – D
31 Aryanis a Python programmer working in Infotech Ltd. For the Ambica Furniture, he 4
has created a csv file named furniture.csv, to store the data of different furniture.

Write User Defined Functions in Python as per following requirements:


(i) ADD()–To accept and add data of an item to a CSV file ‘furniture.csv’. Each record
consists of Fur_id, Description, Price, and Discount.
(ii)COUNTR()–To count the number of records present in ‘furniture.csv’ whose price is
less than 5000.

138 | P a g e
32 4
Write the SQL queries based on the relations Teacher and Placement Tables given below :
Table : Teacher

T_ID Name Age Department DOJ Salary Gender


1 Randeep 32 Mathematics 2020-12-12 30000 M
2 Samira 35 History 2018-07-01 40000 F
3 Arun 34 Comp Sci 2019-01-10 12000 M
4 Shyam 50 History 2019-06-27 30000 M
5 Shalakha 33 Mathematics 2018-07-31 20000 F
6 Shiv 44 Comp Sci 2019-02-25 21000 M
7 Saman 31 History 2017-03-24 20000 M
8 Raman 42 Mathematics 2021-09-05 25000 M

Table: Placement

P_ID Department Place


1 History Ahmedabad
2 Mathematics Jaipur
3 Comp Sci Nagpur
(i) Display department wise maximum salary from the Teacher Table.
(ii) Display Name, Salary, Department and Place for the teachers whose department
is History.
(iii) Display Name and Place for female teachers.
(iv) Display details of male teachers who joined the Vidyalaya before 31.01.2019.

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.

Physical locations of the blocks of TTC

HR BLOCK MEETING BLOCK

FINANCE BLOCK

Block to block distance (in m)


Block (From) Block (To) Distance
HR Block MEETING 110
HR Block Finance 40
MEETING Finance 80
Expected number of computers
Block Computers
HR 25
Finance 120
MEETING 90

(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

Note the following to establish connectivity between Python and MySQL:


Username-root Password- tiger Host– localhost

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)

½ mark for each correction


20 (a) 20@otnm 2
(1 mark for the correct answer)

(b) dict_items([('name', 'Akash'), ('age', 27), ('city', 'New Delhi')])


(1 mark for the correct answer)
21 NAMES={6:"Amit",9:"Rohan",6:"Supriya",3:"Ritu"} 2
def calc(NAMES):
for N in NAMES.value():
if len(N) < 5:
print(N.lower())
calc(NAMES)
OR
def INDEX_LIST(L):
indexList=[]
for i in range len(L):
if L[i]!=0:
indexList.append(i)

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 has there are 3


phases:
In Packet switching directly data transfer
i) Connection Establishment.
takes place.
ii) Data Transfer.
iii) Connection Released.

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.

In Packet switching, data is processed at all


In-Circuit switching, data is processed at
intermediate nodes including the source
the source system only
system.

The delay between data units in circuit The delay between data units in packet
switching is uniform. switching is not uniform.

1 mark for each correct difference


24 (i) L1.insert(3,15) 2
(ii) Str.endswith('.')
25 ALTER TABLE Student 2
ADD SId INTEGER PRIMARY KEY;
As the primary key is added as the last field, the command for inserting data will be:
INSERT INTO Student
VALUES("Suman","XII",90,1045);
Or
(i) show databases
(ii) desc school or describe school

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)

(½ Mark for opening the file)


(½ Mark for reading line and/or splitting)
(½ Mark for checking condition)
(½ Mark for printing word)
28 3
(a) (b) (c)
Itemane MONTHNAME(Dateofstock) Price*DIscount
White lotus February 625000
Comfort Zone December 340000
Wood Comfort February 112500

(1 mark for correct Answer)


29 (i) 2 3
(ii) 19-Mar-2004 12-Dec-2003
(iii)59000
30 def PushOn(Book): 3
a=input(“enter book title :”)
Book.append(a)

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

You might also like