0% found this document useful (0 votes)
745 views305 pages

Xii Cs Study Material (2022-23)

Uploaded by

Arun Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
745 views305 pages

Xii Cs Study Material (2022-23)

Uploaded by

Arun Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 305

केन्द्रीय विद्यालय संगठन

KENDRIYA VIDYALAYA SANGATHAN


जम्मू संभाग
JAMMU REGION

अध्ययन सामग्री
STUDY MATERIAL
कक्षा बारहिी ं
CLASS: XII
SUBJECT: COMPUTER SCIENCE (083)
सत्र 2022-23

SESSION 2022-23
Our Inspiration

Dr. D. Manjunath
Deputy Commissioner, KVS RO Jammu

Sh. G.S. Mehta


Sh. Assistant Commissioner, KVS RO jammu

SUBJECT CONVENOR

Sh. K.S Pathania


Principal KV KARGIL
CONTENT CONTRIBUTORS:

SH VISHAL GUPTA, PGT CS K.V NO.1 AKHNOOR


SH SANDEEP SAINI, PGT CS K V BHADARWAH
SMT SHALINI KAJOTRA, PGT CS KV KATHUA
SMT. VIJAYLAKSHMI, PGT CS KV MIRAN SAHIB
SH. PARDEEP SWAMI, PGT CS KV SAMBA

MODERATION BY:

SH. TARSAM KUMAR


PGT CS KV NO.2 JAMMU CANTT

SMT. SONIKA CHIB,


PGT CS KV SUNJUWAN
Computer Science
CLASS-XII
CURRICULUM 2022-23

Code No. 083


1. Prerequisites
Computer Science- Class XI

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

3. Distribution of Marks:

Unit Unit Name Marks Periods


No.
Theory Practical

Computational Thinking and Programming 40 70 50


I
- 2
II Computer Networks 10 15 ---
III Database Management 20 25 20
Total 70 110 70

4. Unit wise Syllabus

Unit I: 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)
 Introduction to files, types of files (Text file, Binary file, CSV file), relative and
absolute paths
 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
csv.writer() and read from a csv file using csv.reader( )
 Data Structure: Stack, operations on stack (push & pop), implementation of stack
using list.

Unit II: Computer Networks

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


networking (ARPANET, NSFNET, INTERNET)
● Data communication terminologies: the 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, Microwaves, 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 III: 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 insert, update, delete queries using cursor, display data
by using fetchone(), fetchall(), rowcount, creating database connectivity
applications
5. Practical

S.No Marks
Unit (Total=30)
Name
1 Lab Test:

1. Python program (60% logic + 20% 8

documentation + 20% code quality)


2. A stub program with Python SQL 4
connectivity must be provided with blanks
(4 blanks) to be filled by the student
with the desired SQL query.
2 Report file: 7
 Minimum 15 Python programs.
 SQL Queries – Minimum 5 sets using
one table / two tables.
 Minimum 4 programs based on
Python - SQL connectivity
3 Project (using concepts learnt in Classes 11 8
and 12)
4 Viva voce 3

6. Suggested Practical List:


Python Programming

● Read a text file line by line and display each word separated by a #.
● Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
● Remove all the lines that contain the character 'a' in a file and write it to
another file.
● Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
● Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
● Write a random number generator that generates random numbers between
1 and 6 (simulates a dice).
● Write a Python program to implement a stack using list.
● Create a CSV file by entering user-id and password, read and search the
password for given user- id.

Database Management
 Create a student table and insert data. Implement the following SQL
commands on the
student table:
 ALTER table to add new attributes / modify data type / drop attribute
 UPDATE table to modify dataORDER By to display data in ascending /
descending order
 DELETE to remove tuple(s)
 GROUP BY and find the min, max, sum, count and average
 Similar exercise may be framed for other cases.
 Integrate SQL with Python by importing suitable module.

7. Suggested Reading Material


 NCERT Textbook for COMPUTER SCIENCE (Class XII)
 Support Materials on the CBSE website.

8. Project

The aim of the class project is to create something that is tangible and useful using
Python file handling/ Python-SQL connectivity. This should be done in groups of two to
three students and should be started by students at least 6 months before the submission
deadline. The aim here is to find a real world problem that is worthwhile to solve.

Students are encouraged to visit local businesses and ask them about the problems
that they are facing. For example, if a business is finding it hard to create invoices for
filing GST claims, then students can do a project that takes the raw data (list of
transactions), groups the transactions by category, accounts for the GST tax rates, and
creates invoices in the appropriate format. Students can be extremely creative here.
They can use a wide variety of Python libraries to create user friendly applications such
as games, software for their school, software for their disabled fellow students, and
mobile applications, of course to do some of these projects, some additional learning is
required; this should be encouraged. Students should know how to teach themselves.

The students should be sensitised to avoid plagiarism and violations of copyright issues
while working on projects. Teachers should take necessary measures for this.

UNIT -1: COMPUTATIONAL THINKING AND


PROGRAMMING -2

Revision of Python topics covered in Class XI


Introduction:

Python was developed by Guido Van Rossum in early 1990s, has


become very popular programming language among beginners as well
as developers.

It is a case sensitive as it treats upper- and lower-case characters


differently.

Python is a high-level, general-purpose and a very popular programming


language. Python programming language (latest Python 3) is being used
in web development, Machine Learning applications, along with all cutting-
edge technology in Software Industry. Python Programming Language is
very well suited for Beginners, also for experienced programmers with
other programming languages like C++ and Java.

a) Python is currently the most widely used multi-purpose, high-


level programming language.
b) Python allows programming in Object-Oriented and Procedural
paradigms.
c) Python programs generally are smaller than other programming
languages like Java. Programmers have to type relatively less
and indentation requirement of the language, makes them
readable all the time.
d) Python language is being used by almost all tech-giant
companies like – Google, Amazon, Facebook, Instagram,
Dropbox, Uber… etc.
e) The biggest strength of Python is huge collection of standard
libraries which can be used for the following:
1. Machine Learning
2. GUI Applications (like Kivy, Tkinter, PyQtetc.)
3. Web frameworks like Django (used by YouTube, Instagram,
Dropbox)
4. Image processing (like OpenCV, Pillow)
5. Web scraping (like Scrapy, BeautifulSoup, Selenium)
6. Test frameworks
7. Multimedia
8. Scientific computing
9. Text processing and many more.

TOKEN:
Python breaks each logical line into a sequence of elementary lexical
components known as tokens. Each token corresponds to a substring
of the logical line. The normal token types are identifiers, keywords,
operators, delimiters, and literals.
A token is the smallest individual unit in a python program. All
statements and instructions in a program are built with tokens. The
various tokens in python are:
1. Keywords: Keywords are words that have some special meaning
or significance in a programming language
2. Identifiers(Name): Identifiers are the names given to different parts
of the program viz. variables, objects, classes, functions, lists,
dictionaries.
3. Literals: Literals are data that have a fixed / constant value.
4. Operators: Operators are token that trigger some computational/
action when applied to variables and other objects in an
expression.
5. Punctuators: Punctuators are symbols that are used in
programming languages to organize sentence structures.

The barebones of python program are

1. Expressions,
2. Statements,
3. Comments,
4. Functions,
5. Block and Indentation.

VARIBLES AND ASSIGNMENTS:

In python to create variables, just assign to its name the


value of appropriate
type.
e.g. name=‘Arun’
age = 18

Dynamic Typing : A variable referring to a value of its type and


also we can
reassign a value of other type to same variable is called dynamic
typing Datatype
e.g x=20
print(x)

x=“Hello World”
print(x)

Output : 20
Hello World

Multiple Assignment:
i) Assigning same value to multiple variables
a=b=c=10 -- it means assign value 10 to
variables a,b,c,
ii) Assigning multiple values to multiple variables :
a,b,c,=20,30,40 - it means assigning 20 to a, 30
to b, 40 to c

 swaping two variables: a,b=b,a

DATA TYPES

A data type, in programming, is a classification that specifies which


type of value a variable has and what type of mathematical,
relational or logical operations can be applied to it without causing an
error
Python Data Types offers following data types :

Primitive Data types :


a) Numbers : int, float, complex
b) Boolean
c) Stirngs
a)Numbers :
i) int : whole number, no matter what the size is
a=23

b=999999999999999999

ii) float : This is not arbitrary size. It is machine level double


precision floating point numbers(15 digits precision).

p=3.14 1592

iii) Complex :
c=4+5j  4 real part and 5j is imaginary
part
or
c=complex(4,5)
b) Boolean :It represent truth values True or False.
t=True
f= not t
print(f or t)

Result : True

c) String: - Any thing within quotes is string!

‘This is a string’  single quotes


“This too!”  Double quotes
“ “ “ This is one string” ” ” triple quoted string
‘ ‘ ‘ This is one more’ ’ ’
 Only difference is that single and double quotes are used to
create single line
string, where as triple quotes are used to create multiline string.
text= “Computer Sciecne”
text = ‘ ‘ ‘Computer science
with python
programming’ ’ ’

List: - Like string, list is a sequence of values. A list is a data


structure
in Python that is a mutable, or changeable, ordered sequence of
elements. Each
element or value that is inside of a list is called an item. Just as
strings
are defined as characters between quotes, lists are defined by
having values
between square brackets []

List Creation:
L=[] #empty list
L=[10,20,30,40,50,60,70,80] # List of
numbers
L=[‘apple’,’banana’,’orange’] # list of strings
L=list(‘apple’) # Converting string into a list of
# characters by list() method
L=[‘a’,1,3,4,’zero’] # list of mixed type i.e characters ,digits
etc.
Tuples in Python : A tuple is an immutable sequence of Python
objects. Tuples are
sequences, just like lists. The differences between tuples and lists
are, the tuples
cannot be changed unlike lists and tuples use parentheses, whereas
lists use square
brackets. Creating a tuple is as simple as putting different comma-
separated values.
Optionally you can put these comma-separated values between
parentheses also.
For example −

tup1 = ('physics', 'chemistry', 1997,


2000);
tup2 = (1, 2, 3, 4, 5);
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing
nothing −:
tup1 = ();
To write a tuple containing a single value you have to
include a comma, even
though there is only one value −
tup1 = (50,);
Set: - Sets are used to store multiple items in a single variable. Set
is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Tuple, and Dictionary, all with different
qualities and usage. A set is a collection that is unordered,
unchangeable*, and unindexed
Dictionary in Python: Dictionaries are a way of storing elements just
like in a Python list. But, rather than accessing elements using its
index, you assign a fixed key to it and access the element using the
key. So, Dictionary in Python deal with an unordered “key-value" pair,
which are written with curly brackets {}.

--Unlike lists, string and tuple, a dictionary is not a sequence


because it is unordered.
--Like List, a dictionary is mutable, i.e we can change the value of
a key, “in place” using assignment operator.

Dictionary Creations:
d={ } # empty dictionary
d = {'apple': 'fruit', 'beetroot': 'vegetable', 'cake': 'dessert'}
print(d)
a = {'one': 1, 'two': 'to', 'three': 3.0, 'four': [4,4.0]}
print(a)
# items in dictionary can have any data type

EXPRESSION: - An expression is a combination of operators and


operands that is interpreted to produce some other value.

MATH LIBRARY
The Python Math Library provides us access to some common math
functions and constants in Python, which we can use throughout our
code for more complex mathematical computations.

Import math is used to access math functions in math module.

Method Description

Returns the mantissa and the exponent, of


math.frexp()
a specified number
Returns the sum of all items in any iterable
math.fsum()
(tuples, arrays, lists, etc.)

math.gamma() Returns the gamma function at x

Returns the greatest common divisor of two


math.gcd()
integers

STATEMENT FLOW CONTROL:

Program's control flow is the order in which the program's code


executes. The control flow of a Python program is regulated
by conditional statements, loops, and function calls.
Flow of control through any given program is implemented with three
basic types of control structures:
SEQUENCE:- Program always execute in sequence from beginning
statement till end of program statement.
SELECTION: The selection statements are also known as Decision
control statements or branching statements. The selection statement
allows a program to test several conditions and execute instructions
based on which condition is true.
Python Selection Statements

 if statement.
 if-else statement.
 if-elif statement.

Conditional Statement Construct: if/elif/else


a) if statement tests a particular condition, if condition is true,
set of statement/
statements are executed. If condition is false it does
nothing.
The syntax is :
if age>=18 : (: colon is compulsory to write with
if/elif/else)
print(“you are eligible to vote”)
statement is indented, because indentation create a block
/compound of
statements to executed under if.

b) if-else statement: This form if statement tests a particular


condition, if condition is
true, set of statement/ statements are executed. If condition is
false it execute
statements indented below else.
The syntax is:
if age>=18 :
print(“you are eligible to vote”)
else:
print (“you are not eligible to vote”)

c) if-elif-else ladder: This statement is used whenever we have to


check multiple
conditions/ perform multiple decisions

Example of if-elif-else ladder:


x=int(input(“Enter number”))
if x<0 :
print(“be positive”)
elif x==0:
print(“Zero”)
elif x==1:
print(“Single”)
else:
print(“More”)

LOOPING: Looping means repeating something over and over until


a particular condition is satisfied. A for loop in Python is a control
flow statement that is used to repeatedly execute a group of
statements as long as the condition is satisfied. Such a type of
statement is also known as an iterative statement.

Loop Types

while Loop : While Loop: It is conditional loop that will repeat


instruction within itself as long as condition remains true.
Syntax :
while <condition>:
loop-body

This loop is preferred when we don’t know the no. of times to


executed beforehand.

e.g c=1 # initialization i.e. starting


point
while c<=9: # condition
print(c,end=‘ ‘)
c=c+1 # step of
increment
output: 1 2 3 4 5 6 7 8 9
For Loop:
For loop in Python repeats group of statements for specified number
of times. The for loop provides a syntax where following information
is provided.

 Initial Value of the counting variable.


 Boolean Condition (Terminating condition)
 Incrementation of the counting variable.

Syntax:

for variable in <range>: (colon))

statement1

statement2

…………..

Nested Loops.
Loops may contain another loop in its body is called nested
loop. The inner
loop must terminates before the outer loop.
e.g. i) for i in range(1,5): #
outer loop
for j in range(1,i+1): #
inner loop
print(“*”,end = ‘ ‘)
print()

output : 1
1 2
1 2 3
1 2 3 4

JUMP STATEMENTS: Jump statements cause an unconditional jump


to another statement elsewhere in the code. They are used primarily
to interrupt switch statements and loops. The jump statements are the
goto statement, the continue statement, the break statement, and the
return statement.
In Python, there are three types of Jump statements.

 break.
 continue.
 pass.

FUNCTION IN PYTHON

WHY WE NEED A FUNCTION:

Function provides the feature to divide the large and complex program
into smaller and simple modules/ sub-program called function. If
required, the subprogram can further be divided into smaller sub-
programs and the process of dividing the program into a set of smaller
sub-program can be continued up to any appropriate level. Therefore
function provides a systematic way of problem solving by dividing the
given problem into several sub-problems, finding their individual
solution, and integrating the solutions of individual problem to solve the
original/main problem.

WHAT IS FUNCTION ?
Function is a name given to group of statement for the purpose of
performing specific task. Function can be invoked(called) anywhere in
the program any no. of times.

A function is a subprogram that acts on data and often returns a


value. A function is a block of code which only runs when it is
called. We can pass data, known as parameters, into a function. A
function can return data as a result. In Python a function is defined
using the def keyword:

Example

def my_function ():


print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function ():


print("Hello from a function")

my_function()

A function definition consists of following components:

1. Keyword def marks the start of function header.


2. A Function name to uniquely identify it. Function naming
follows the same rules as rules of writing identifiers.
3. Parameters (arguments) through which we pass values to a
function. They are optional.
4. A colon (: ) mark the end of the function header.
5. Optional documents string to describe what the function
does.
6. One or more valid python statements that make up the
function body.
7. An optional return statement to return from the function.

Types of Function:

Function can be categorize into three types:


i) Built-in
ii) Modules
iii) User Defined

BUILT-IN :

These are predefined function that already available in python


standard library and we don’t have to import any module for using
them. There are many built-in functions which we have already used
in programming.

These are :
1) Type Conversion :
a) int() - to convert into an integer
c) float() – to convert into float type
b) str() - to convert into string type
2) Input() – It enables us to accept input as string from user from
keyboard at run-time without evaluating it.
3) eval() – This function is used to evaluate the value of string. eval()
takes string as argument, evaluate this string as number and
return numeric value as result.
e.g. >>> x=eval('34+5')
>>> x
39
4) max() & min() – These function is used to find maximum and
minimum
values respectively out of several values
e.g. >>> max(9,10,20,34,6)
34
>>>min(9,10,20,34,6)
6
>>>max('a','A','B','c')
'c‘
5) abs() function : This function returns absolute value of a number.
It means it
return always positive value.
e.g. >>> abs(-60)
60
6)type() : This function determine the type of a vsriable .
e.g. >>> x='Hello'
>>> type(x)
<class 'str'> . It means x is of type string
7)len() function : This function is used to find length of string, tuple,
list and
dictionary.
e.g. >>> x=[20,30,40,50,60,70]
>>> len(x)
6
8) round() function: It is used to get the result up to specified
number of digits. In other words this function rounds a given floating
point number to the specified number of digits and return.
Syntax : round(n,p)  n means number to be rounded and
p is the number of digits upto which n to be rounded.
e.g. i) if p is not specified, then it round up to 0 decimal and result
is an integer
>>> x=15.456
>>> y=15.567
>>> round(x) output : 15
>>> round(y) output: 16
ii) if p=0, then it round up to 0 decimal place and result is float
>>> round(x,0) output :15.0
iii) if p is positive integer, then round up to p digits after decimal and
result is
float
>>> round(x,1) output: 15.5
>>> round(x,2) output : 15.46
iv) if p is negative integer, then round upto p digits before decimal
place and result is float.
>>> x=1534.56
>>> round(x,-1) output: 1530.0
>>>round(x,-2) output 1500.0
8) range() function: It is used to define series of numbers and
particularly useful
in for loops.
>>> x=range(7)
>>> x
range(0, 7)
>>> x=list(range(7))
>>> x
[0, 1, 2, 3, 4, 5, 6]

>>> x=list(range(2,20,2))
>>> x
[2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> x=list(range(20,2,-2))
>>> x
[20, 18, 16, 14, 12, 10, 8, 6, 4]

MODULE IN PYTHON:
A module is a file containing functions and also variables of all types
(array, dictionary objects etc). It means if we hava e written set of
functions tis neededneed in several programs, we can place those
functions in a module. Then we can import the module in each
program that needs to call one of the functions.

Python language provides two important methods to import modules


in a program.

i) import statement: This is used to import the entire module

ii) rom : This is used to import all


functions or selected one.

Syntax: import module1,module2 ….


e.g Import math
To use math module we write at top of our program
import math
Then we can use functions of math module as :
i) ceil(x) : return smallest integer that is greater than or equal to x
>>> import math
>>> x=5.4
>>> math. ceil(x)
6
ii) floor(x): Return largest integer that is less than or equal to x
>>> x=5.4
>>> math.floor(x)
5
iii) pow(x,y) : It return x raise to power y.
vii)sin(x) : Return the sine of x in radians.
>>> x=20
>>>math.sin(0)
>>> math.pow(x,2)
0.0
400.0
iv) sqrt(x): It reutrns square root of x.
viii) tan(x): Returns the tangent of x in radians
>>> x=400
>>> math.tan(0)
>>> math.sqrt(x)
0.0
20.0
v)log10(x) : Return the base 10 logarithm of x.
>>> x=400
>>> math.log10(x)
2.6020599913279625
vi) cos(x): Return the cosine of x in radians.
>>> math.cos(0)
1.0
RANDOM MODULE IN PYTHON
To generate random numbers in python we have to invoke random
module explicitly as :

import random

Various function associated with this module are as :


i) randrange() : This method generate a random number (integer)
from specified
range.
Syntax : random.randrange(start,stop,step)
start : Optional argument, by default is 0
stop : Required an integer to specify end
step : An integer specifying its step of increment. It is Optional
argument, by
default it is 1.
For example :
>>> import random
>>> x=random.randrange(20)
>>>x=random.randrange(2,40,5)
>>> x output : 0
>>>x output : 22
>>> x=random.randrange(20)
>>>x=random.randrange(2,40,5)
>>> x output : 4
>>>x output :17
>>> x=random.randrange(20)
>>> x output: 17
ii) random() function : This function Generates a random float
number between 0.0
to 1.0. The function doesn't need any
arguments.
For example : >>>import random
>>>random.random()
0.645173684807533
For example : Write code to generate random floating point
numbers
between 10 and 30.
import random
x=random.random()*20+10
print( ‘random number is’, x)
iii) randint(). This function generate a random integer between
specified integers.
>>> x=random.randint(0,2)
>>> x output :2
>>> x=random.randint(0,2)
>>> x output: 1
>>> x=random.randint(0,2)
>>> x output: 2
This means randint generate integers between 0-2 i.e 0,1,2 i.e it
includes lower and upper limit

How to Create User-Defined Functions in Python


Syntax :
def function_name(parameters):
“””function docstring“””
statement1
statement2
...
...
return [expr]

def  keyword for defining function


function_name  name of function, it is an identifier as we
write variable name.
Parameters : List of variables separated by comma, which are
used by function. Parameters are
optional, it
means sometime it may be function with
no parameters.
:(colon) : Colon mark the end of function header
Statement1 Body of function, written after indentation
Statement2 space. Also called block of code
return : It is a keyword. This statement is optional ,
used as per requirement of function.
Doctstring : It is optional, this statement briefly explain what a
function does.

Examples :

i) Function without parameters :


# Def is keyword
def display(): #display is name of function , having
no parameters
print(“Welcome to class 12th”)
print(“We are learning functions”)

display()  Function call


display()
Note :
• If there is no return statement, then implicitly python return
none
• None is also built-in immutable data type
ii) Use of return statement:-
Python function can return single value as well as multiple values.
Example :
def sum(x,y):
return x+y
def sumdiff(x,y):
return x+y,x-y
z=sum(10,20)
print(z)
s=sumdiff(30,10)
print(s)
OUTPUT : 30
(40, 20)

Passing Arguments and Parameters:

Python support four types of parameters :


i) Positional arguments (Required arguments)

ii) Default arguments


iii) Keyword (or named) arguments .
iv) Variable Length arguments (Arbitrary Arguments)

i) Positional arguments : Example ii) discussed above is of positional


arguments. This mean when function call statement must match the
number and order of argument as define in the function definition, is
called positional arguments.
ii) Default Arguments : It means that at time of function call if we
omit default argument then value of that argument will be taken by
default.
For example :
def area(r=5): #Default argument, means value will be given
to formal
argument in function definition
“Function to calculate area of circle”
ar=3.14*r*r
return ar
a=area()  Here argument is omitted, and hence it calculate
with default value of radius 5
print(‘Area of circle is’, a)
a=area(4)  Here it calculate area with value of radius 4.
print(‘Area of circle is’, a)

Note: In function header any parameter cannot have default value


unless all parameters appearing on its right have their default value
For example :

def simple_interest(principal, rate, time=1): #correct


definition
def simple_interest(principal,rate=6,time): # illegal
definition (error)
def simple_interest(principal,rate=6,time=1): #correct
definition
def simple_interest(principal=3000,rate=6,time=1): #correct definition

Practice Question :
Write a function power() , to calculate raise to the power. The
function take two arguments base ‘m’ and raise to power ‘n’. The
second argument raise to power n will be taken by default 2 i.e. if
in the function call if second argument n is omitted, then it will find
its square.

iii) Keyword Arguments: Keywords arguments are named arguments.


We have to use these keyword argument in function call. Arguments
which are preceded with a variable name followed by a '=' sign (e.g.
var_name=") in function call are called keyword arguments.
All the keyword arguments passed must match one of the arguments
accepted by the function. You may change the order of appearance
of the keyword. See the following example.
Def welcome( greet, name=“world”):
print(greet,name)
welcome(“Hello”)
welcome(“hi”, name=“Guido”)
welcome(name=“Guido”,greet=“Hey”)
welcome(name=“Guido”, “Hey”)  error because we cannot take
non keyword argument after keyword argument.

SCOPE AND LIFETIME OF VARIABLES IN FUNCTION


Scope of a variable is the portion of a program where the variable is
recognized. Parameters and variables defined inside a function are
not visible from outside the function. Hence, they have a local scope.

The lifetime of a variable is the period throughout which the variable


exits in the memory. The lifetime of variables inside a function is as
long as the function executes.

They are destroyed once we return from the function. Hence, a


function does not remember the value of a variable from its previous
calls.

On Other hand variables which are declared outside function is


having global scope. There life time and scope is up to program
execution.

Here is an example to illustrate the scope of a variable inside a


function.

def my_func():

x = 10 # x has local scope

print("Value inside function:",x)

my_func()

print("Value outside function:",x)

Note: scope of x is local to func(), but outside this scope it is not


accessible , hence error in print statement after function call.

Here is another example to illustrate the scope of a variable inside a


function.

x=20
def my_func():

x = 10 # x has local scope

print("Value inside function:",x)

my_func()

print("Value outside function:",x)

Note: -Again scope of x inside func() is local, it wil print inside


function 10.

-But outside after function call it will print 20

Another Example :
x=20
def my_func():
x=x+10
print(‘Value of x inside function’, x)
my_func()
print(‘Value of x outside function’, x)

To make it working inside function we use global keyword

x=20
def my_func():
global x
x=x+10
print(‘value inside function’, x)
my_func()

print(‘value outside function’,x)

MUTABLE ARGUMENTS :
In Python, Mutable arguments are always passed by reference. The
following snippet will confirm this:

def myFun(x): # Here x is a new reference to same list lst

x[0] = 20 # Driver Code (Note that lst is modified )

# after function call.

lst = [10, 11, 12, 13, 14, 15]

myFun(lst);

print(lst) output :[20, 11, 12, 13, 14, 15]

Note : When we pass a reference and change the received reference


to something else, the connection between passed and received
parameter is broken. For example, consider below program.

def myFun(x):

x = [20, 30, 40] # New object x is created which is


local to myFun

# after function call.

lst = [10, 11, 12, 13, 14, 15]

myFun(lst);

print(lst) output : [10, 11, 12, 13, 14, 15]

IMMUTABLE ARGUMENTS:

To understand this let us consider the following code :


n=20
def change(x)
x=x+20
print(‘Value of x:’,x)
change(n)

print(‘value of n is’,n)

Output : value of x :40

value of n: 20

When we, pass argument n to function, the function has


local variable x referred to same object

n 20

Now comes to interesting part x=x+20, since integer is


immutable, so we are not able to modify by adding 20,
so it create new object by adding 20 i.e 40
x 40

Hence n referred to same object 20

n 20
SOLVED QUESTIONS:-
Q1

What are tokens in Python? How many types of tokens are allowed in
Python? Exemplify your ANS.

ANS:

The smallest individual unit in a program is known as a Token. Python has


following tokens:

1. Keywords — Examples are import, for, in, while, etc.


2. Identifiers — Examples are MyFile, _DS, DATE_9_7_77, etc.
3. Literals — Examples are "abc", 5, 28.5, etc.
4. Operators — Examples are +, -, >, or, etc.
5. Punctuators — ' " # () etc.

Q 2

How are keywords different from identifiers?

ANS:
Keywords are reserved words carrying special meaning and purpose to the
language compiler/interpreter. For example, if, elif, etc. are keywords. Identifiers
are user defined names for different parts of the program like variables,
objects, classes, functions, etc. Identifiers are not reserved. They can have
letters, digits and underscore. They must begin with either a letter or
underscore. For example, _chk, chess, trail, etc.

Q 3

What are literals in Python? How many types of literals are allowed in Python?

ANS:

Literals are data items that have a fixed value. The different types of literals
allowed in Python are:

1. String literals
2. Numeric literals
3. Boolean literals
4. Special literal None
5. Literal collections

Q4

Out of the following, find those identifiers, which cannot be used for naming
Variables or Functions in a Python program:

 Price*Qty
 class
 For
 do
 4thCol
 totally
 Row31
 _Amount
ANS:

 Price*Qty ⇒ Contains special character *


 class ⇒ It is a keyword
 4thCol ⇒ Begins with a digit

Q5

What is an expression and a statement?

ANS.

An expression is any legal combination of symbols that represents a value. For


example, 2.9, a + 5, (3 + 5) / 4.
A statement is a programming instruction that does something i.e. some action
takes place. For example:
print("Hello")
a = 15
b = a – 10

Q6

What are immutable and mutable types? List immutable and mutable types of
Python.

ANS.

Mutable types are those whose values can be changed in place whereas
Immutable types are those that can never change their value in place.

 Mutable types in Python are:

1. Lists
2. Dictionaries
3. Sets

 Immutable types in Python are:


1. Integers
2. Floating-Point numbers
3. Booleans
4. Strings
5. Tuples

Q 7

Explain the use of the pass statement. Illustrate it with an example.

ANS.

The pass statement of Python is a do nothing statement i.e. empty statement


or null operation statement. It is useful in scenarios where syntax of the
language requires the presence of a statement but the logic of the program
does not. For example,

for i in range(10):

if i == 2:

pass

else:

print("i =", i)

OUTPUT :-

i = 0

i = 1

i = 3

i = 4

i = 5
i = 6

i = 7

i = 8

i = 9

Q 8

Predict the output of the following code fragments:

count = 0
while count < 10:
print ("Hello")
count += 1

ANS.

OUTPUT:-

Hello

Hello

Hello

Hello

Hello

Hello

Hello

Hello
Hello

Hello

Q 9

Predict the output of the following code fragments:

x = 10
y = 0
while x > y:
print (x, y)
x = x - 1
y = y + 1
ANS.

OUTPUT:-

10 0
9 1
8 2
7 3
6 4

Explanation

X y Output Remarks

10 0 10 0 1st Iteration

10 0
9 1 2nd Iteration
9 1
X y Output Remarks

10 0
8 2 9 1 3rd Iteration
8 2

10 0
9 1
7 3 4th Iteration
8 2
7 3

10 0
9 1
6 4 8 2 5th Iteration
7 3
6 4

Q 10

Predict the output of the following code fragments:

keepgoing = True
x=100
while keepgoing :
print (x)
x = x - 10
if x < 50 :
keepgoing = False
ANS.
Output

100
90
80
70
60
50

Explanation

Inside while loop, the line x = x - 10 is decreasing x by 10 so after 5


iterations of while loop x will become 40. When x becomes 40, the condition if
x < 50 becomes true so keepgoing is set to False due to which the while loop
stops iterating.

Q 11

Predict the output of the following code fragments:

c = 0
for x in range(10):
for y in range(5):
c += 1
print (c)

ANS.
OUTPUT:-

50
Explanation

Outer loop executes 10 times. For each iteration of outer loop, inner loop
executes 5 times. Thus, the statement c += 1 is executed 10 * 5 = 50 times.
c is incremented by 1 in each execution so final value of c becomes 50.

Q 12

Predict the output of the following code fragments:

for x in 'lamp':
print(str.upper(x))

ANS.

OUTPUT:-

L
A
M
P

Q 13

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

ANS.
x = int(input("Enter x: "))

if x < 0:
print("negative")
elif x > 0:
print("positive")
else:
print("zero")

OUTPUT:-
Enter x: -5
negative

Enter x: 0
zero

Enter x: 5
positive

Q 14

Write a program that returns True if the input number is an even number,
False otherwise.

ANS.

x = int(input("Enter a number: "))

if x % 2 == 0:
print("True")
else:
print("False")

OUTPUT:-
Enter a number: 10
True

Enter a number: 5
False

OUESTION 15

Write a Python program that calculates and prints the number of seconds in a
year.

ANS.

days = 365
hours = 24
mins = 60
secs = 60
secsInYear = days * hours * mins * secs
print("Number of seconds in a year =", secsInYear)

OUTPUT:-

Number of seconds in a year = 31536000

Q 16

Write a Python program that accepts two integers from the user and prints a
message saying if first number is divisible by second number or if it is not.
Write a Python program that accepts two integers from the user and prints a
message saying if first number is divisible by second number or if it is not.

ANS
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a % b == 0:
print(a, "is divisible by", b)
else:
print(a, "is not divisible by", b)

OUTPUT:-

Enter first number: 15


Enter second number: 5
15 is divisible by 5

Enter first number: 13


Enter second number: 7
13 is not divisible by 7

Q 17

Write a program that reads a date as an integer in the format MMDDYYYY.


The program will call a function that prints print out the date in the format
<Month Name> <day>, <year>.

Sample run :

Enter date : 12252019


December 25, 2019

ANS.

months = ["January", "February", "March", "April", "May", "June",


"July", "August", "September", "October", "November", "December"]

dateStr = input("Enter date in MMDDYYYY format: ")


monthIndex = int(dateStr[:2]) - 1
month = months[monthIndex]
day = dateStr[2:4]
year = dateStr[4:]

newDateStr = month + ' ' + day + ', ' + year


print(newDateStr)

OUTPUT:-

Enter date in MMDDYYYY format: 12252019


December 25, 2019

Q 18

Write a program that prints a table on two columns — table that helps
converting miles into kilometres.

ANS.

print('Miles | Kilometres')
print(1, "\t", 1.60934)
for i in range(10, 101, 10):
print(i, "\t", i * 1.60934)

OUTPUT:-

Miles | Kilometres
1 1.60934
10 16.0934
20 32.1868
30 48.2802
40 64.3736
50 80.467
60 96.5604
70 112.6538
80 128.7472
90 144.8406
100 160.934

Q 19

Write a short Python code segment that prints the longest word in a list of
words.

ANS.

# code

L=[‘no’,country’, ‘for’, ‘old’, ‘men]

M=0

W=None

for i in range(len(L):

if len([L[i])>m:

word=L[i]

M=len(L[i])
Print(Longest word in the list is’, word)

OUTPUT:-

Longest word in the list is country

Q 20

Write a Python program that creates a tuple storing first 9 terms of Fibonacci
series.
ANS.

n=int(input("enter a number"))

i=1

f=0

s=1

print(f)

print(s)

while (i<=n):

t=f+s

print(t)

f=s

s=t

i+=1

OUTPUT:-
enter a number5

Q 21

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

ANS

#CODE

if x<10:

print(‘negative’)

elif x==0:

print(‘Zero’)

else

print(Positive;)

Q 22
Differentiate between list and tuple.

ANS

Tuple is immutable whereas list is mutable i.e tuple cannot be modified at run-
time whereas list can change / modify at runtime.Tuples use parentheses,
whereas lists use square brackets.

Q 23

What is a tuple?

ANS

A tuple is an immutable sequence of values which can be of any type and are
indexed by an integer.

Q 24

How many types of strings are supported in Python?

ANS

Python allows two string types:

1. Single line Strings: - Strings that are terminated in a single line.


2. Multi-line Strings: - Strings storing multiple lines of text.

Q 25

When are dictionaries more useful than lists?

ANS

Dictionaries can be much more useful than lists. For example, suppose we
wanted to store all our friends' cell-phone numbers. We could create a list of
pairs (name of friend, phone number), but once this list becomes long enough
searching this list for a specific phone number will get time-consuming. Better
would be if we could index the list by our friend's name. This is precisely what
a dictionary does.

Q 26

How are lists different from strings when both are sequences?

ANS

The lists and strings are different in following ways:

(i) The lists are mutable sequences while strings are immutable.
(ii) In consecutive locations, a string stores the individual characters while a list
stores the references of its elements.
(iii) Strings store single type of elements - all characters while lists can store
elements belonging to different types

Q 27

Write a program that reads a string and checks whether it is a palindrome


string or not.

ANS

string = input("Enter a string :")


length = len(string)
mid = int(length / 2)
rev = -1
for a in range (mid) :
if string[a] == string[rev] :
a += 1
rev -= 1
else :
print(string, "is not a palindrome")
break
else :
print(string, "is a palindrome")
Q 28

What do you understand by the term Iteration?

ANS

Iteration refers to repetition of a set of statements for a sequence of values or


as long as a condition is true.

Q 29

What is the difference between interactive mode and script mode in Python?

ANS

In interactive mode, instructions are given in front of Python prompt (>>>) in


Python Shell, Python carries out the given instructions and shows the result
there itself.

In script mode, Python instructions are stored in a file, generally with.py


extension, and executed together in one go as a unit. The saved instructions are
known as Python script or Python program.

Q 30

Write a Python program to sort a dictionary by key.

ANS

dic = eval(input("Enter dictionary :- "))


newdic = {}
lst = list(dic.keys())
lst.sort()
for i in lst :
newdic [ i ] = dic[ i ]

print(newdic)
Q 31

Program to Convert Celsius To Fahrenheit

ANS

# Python program for converting celsius to fahrenheit temperature.


# given temp in celsius
celsiusTemp = 42.5
# converting the given temp in celsius to fahrenheit temperature
fahrenheitTemp = (celsiusTemp * 1.8) + 32
# print the converted temperature value
print('Converting the given temp in celsius =',
celsiusTemp, " to Fahrenhiet = ", fahrenheitTemp)

OUTPUT

Converting the given temp in celsius = 42.5 to Fahrenhiet = 108.5

Q 32

Python Program to Check if a Number is Positive, Negative or zero

ANS

def checkNumber(given_Num):
# checking if the given number is positive number
if(given_Num > 0):
print("The given number", given_Num, "is positive")
# checking if the given number is negative number
elif(given_Num < 0):
print("The given number", given_Num, "is negative")
# if the above conditions are not satisfied then the given number is zero
else:
print("The given number", given_Num, "is zero")

given_num1 = 169
given_num1 = -374
checkNumber(given_num1)
given_num1 = 0
checkNumber(given_num1)

OUTPUT
The given number 169 is positive

The given number -374 is negative

The given number 0 is zero

Q 33

Python Program to Check if a Number is Odd or Even

ANS

n=int(input("enter a number "))

if (n%2==0):

print("number is even ")

else:

print("number is odd ")

OUTPUT

enter a number 45

number is odd

Q 34
PROGRAM TO FIND THE DAY OF THE WEEK

ANS

n=int(input("enter day of "))

if n==1:

print("day is sunday ")

elif n==2:

print("day is monday")

elif n==3:

print("day is tuesday ")

elif n==4:

print("day is wednesday")

elif n==5:

print ("day is thursday ")

elif n==6:

print ("day is friday ")

elif n==7:

print("day is saturday")

else:

print ("day does not exist ")

OUTPUT

>>>enter day of 2

day is Monday

>>>enter day of 5

day is thursday
>>> enter day of 8

day does not exist

Q 35

Write a program for calculator

ANS

a=int(input("enter a number "))

b=int(input("enter a another number"))

op=input("enter a character")

if op=='+':

res=a+b

elif op=='-':

res=a-b

elif op=='*':

res=a*b

elif op=='/':

res=a/b

elif op=='%':

res=a%b

else:

print('operator not available')

print("result is ",res)

OUTPUT

enter a number 4
enter a another number34

enter a character*

result is 136

Q 36

Program to calculate the time take by car at distance at 450 km

ANS

# program to calculate time taken by car with distance is 450 km

dis=450km

average=20

time =dis/average

print (" total time taken", time )

OUTPUT

total time taken 22.5

Q 37

Program to calculate the average marks of 5 subjects

ANS

n1 =int(input("enter marks in subject 1-"))

n2 = int ( input("enter marks in subject 2-"))

n3 =int ( input (" enter marks in subject 3-"))

n4= int ( input ( "enter marks in subject 4- "))

n5 = int ( input( "enter marks in subject 5-"))

avg = n1+n2+n3+n4+n5/5

print (" average of S subject- ",avg )


OUTPUT

enter marks in subject 1- 67

enter marks in subject 2- 87

enter marks in subject 3- 90

enter marks in subject 4- 89

enter marks in subject 5- 97

average of S subject- 352.4

Q 38

Program to calculate the simple interest

ANS

p=2000

r=5

t=6.5

s = p*r*t/100

print ("simple interest is ",s)

Output

simple interest is 650.0

Q 39

Program to calculate the square root

ANS

for i in range (1,11):

print("square root of ",i,"is",i**0.5)

OUTPUT

square root of 1 is 1.0


square root of 2 is 1.4142135623730951

square root of 3 is 1.7320508075688772

square root of 4 is 2.0

square root of 5 is 2.23606797749979

square root of 6 is 2.449489742783178

square root of 7 is 2.6457513110645907

square root of 8 is 2.8284271247461903

square root of 9 is 3.0

square root of 10 is 3.1622776601683795

Q 40

Program to slice the character of your name

ANS

s=input ("enter a first name \t")

s1=input("enter your last name \t")

print("name is")

s2=s+s1

print(s2)

l=len(s2)

print("slice",s2[-2:-9:-2])

OUTPUT

enter a first name HARSIMRAN

enter your last name SINGH

name is

HARSIMRANSINGH
slice GINR

Q 41

Write a Python function to find the Max of three numbers.

ANS

def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))

OUTPUT

Q 42

Write a Python function to multiply all the numbers in a list.

def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7)))

OUTPUT

-336

Q 43
Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument.
ANS

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

OUTPUT

Input a number to compute the factiorial : 4


24

Q 44

Write a Python function that takes a list and returns a new list with unique
elements of the first list.

ANS

def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x

print(unique_list([1,2,3,3,3,3,4,5]))

OUTPUT

[1, 2, 3, 4, 5]

Q 45

Write a Python function that checks whether a passed string is palindrome or


not.

def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1

while right_pos >= left_pos:


if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))

OUTPUT

True
Q 46

Write a Python function to create and print a list where the values are square of
numbers between 1 and 30 (both included).

ANS

def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l)

printValues()

OUTPUT

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324,
361, 400]

Q 47

Write a Python program to access a function inside a function.

ANS
def test(a):
def add(b):
nonlocal a
a += 1
return a+b
return add
func= test(4)
print(func(4))

OUTPUT

Q 48

Write a Python program to print the even numbers from a given list.

ANS

def is_even_num(l):
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))

OUTPUT

[2, 4, 6, 8]

Q 49

Write a Python function that takes a number as a parameter and check the
number is prime or not.

Note : A prime number (or a prime) is a natural number greater than 1 and that
has no positive divisors other than 1 and itself.

ANS

def test_prime(n):

if (n==1):
return False

elif (n==2):

return True;

else:

for x in range(2,n):

if(n % x==0):

return False

return True

print(test_prime(9))

OUTPUT

False

Q 50

Write a Python function that accepts a string and calculate the number of upper
case letters and lower case letters.

def string_test(s):

d={"UPPER_CASE":0, "LOWER_CASE":0}

for c in s:

if c.isupper():

d["UPPER_CASE"]+=1

elif c.islower():

d["LOWER_CASE"]+=1

else:
pass

print ("Original String : ", s)

print ("No. of Upper case characters : ", d["UPPER_CASE"])

print ("No. of Lower case Characters : ", d["LOWER_CASE"])

string_test('The quick Brown Fox')

OUTPUT

Original String : The quick Brow Fox


No. of Upper case characters : 3
No. of Lower case Characters : 13

Q 51.

PROGRAM TO CALCULATE THE SUM OF TWO NUMBERS USING FUNCTION

#Program to work with user defined functions

def sum(x,y):#function defination

z=x+y

print("sum of two numbers",z)

#main

sum(12,56)#function calling

OUTPUT

sum of two numbers 68

Q 52.
Write aprogram to calculate the basic calculate roots of a quadratic equation
using function

def qdf(a,b,c):

d=(b*b-4*a*c)**0.5

return(-b+d)/(2*a),(-b-d)/(2*a)

#main

a=int(input("enter a number"))

b=int(input("enter b number"))

c=int(input("enter c number"))

s,t=qdf(a,b,c)

print(s,'\t',t)

OUTPUT

enter a number 5

enter b number 8

enter c number 9

(-0.7999999999999999+1.0770329614269007j) (-0.8-1.0770329614269007j)

Q 53.

Write a program to calculate sum of n numbers with function

def sum(*n):

total=0

for i in n:
total=total+i

print("sum is",total)

#main

sum()

sum(20,30)

sum(78,67,89)

sum(12,34,56,67)

OUTPUT

sum is 0

sum is 50

sum is 234

sum is 169

Q 54.

Write a program to pass list in a function

def listadd(lst):

sum=0

l=len(lst)

for i in lst:

sum=sum+i

print(sum)

#main
list=eval(input("enter list"))

listadd(list)

OUTPUT

enter list [90,78,65,32]

265

Q 55.

#passing array/list to a function

def list_avg(lst):

sum=0

for i in lst:

sum+=i

return sum/i

#main

a=eval(input("enter list"))

avg=list_avg(a)

print("average of list",avg)

OUTPUT

enter list[ 12,34,56,78,90]

average of list 3.0

Q 56.
#program to calculate factorial using function

def fact(num):#function defination

result=1

while num>=1:

result=result*num

num=num-1

print(result)

#main

fact(8)#function calling

OUTPUT

40320

Q 57.

#program to calculate simple interest

def simpleint(p,r,t):

si=p*r*t/100

print("simple interest is",si)

#main

simpleint(1000,5,6)

OUTPUT

simple interest is 300.0

Q 58.

#subtraction of two numbers


def sub(x, y=10):#defination of function

z=x-y

print("sub is",z)

#main

sub(70)#calling of funtion

OUTPUT

sub is 60

Q 58.

#program to work with recursion

def recur_sum(n):

if n<=1:

return n

else:

return n+recur_sum(n-1)

#main

num=int(input("enter a number"))

if num<0:

print("enter a positive number")

else:

print("tne sum is",recur_sum(num))

OUTPUT

enter a number 9

tne sum is 45
Q 59.

#program to work with keyword argument

def greet_msg(name,msg):

print("hello",name,msg)

#main

greet_msg(name="vivek",msg="good afternoon")

OUTPUT

hello vivek good afternoon

Q 60.

#program to work with calculator

def calc(a,b):

add=a+b

sub=a-b

mul=a*b

div=a/b

return add,sub,mul,div

#main

result=calc(45,67)

print("the result obtained are:")

for i in result:

print(i)

OUTPUT
the result obtained are:

112

-22

3015

0.6716417910447762

FILE HANDLING IN PYTHON

A file in itself is a bunch of bytes stored on some storage device like hard
disk, thumb drive etc.
TYPES OF FILE:
1. TEXT FILE
 A text file stores information in ASCII or unicode characters.
 Each line of text is terminated, (delimited) with a special character
known as EOL.
 Translation is required from text to binary form for processing.
2. BINARY FILE
 A binary file is just a file that contains information in the same
format in which the information is held in memory i.e the file content
that is returned to you is raw.
 There is no delimiter for a line
 No translation occurs in binary file
 Binary files are faster and easier for a program to read and write
than are text files.
 Binary files are the best way to store program information.

3. CSV (Comma Separated Values) FILE


 CSV format is one of the most simple and common ways to store
data in tabular form.
 Each line of the file is a data record and each record consists of
one or more fields separated by commas.
 To represent a CSV file, it must be saved with the .csv extension.
Steps to process a FILE:
 Determine the type of file usage
 Open the file and assign its references to a file object or file handle
 Process as required
 Close the file

OPENING AND CLOSING A FILE:


1) open(): open() function is used to open a file
Syntax:
File_object=open(file_name,access mode)
Example
F= open('abc.txt’,'w')
this statement opens abc.txt in write mode
Note : if file mode is not mentioned in open function then default file mode, i.e
'r' is used

2) close() : the close() method of a file object flushes any unwritten information
and close the file object after which no more writing can be done.
SYNTAX:
File_object.close()

FILE MODES
It defines how the file will be accessed
Text Binary Description Notes
File File
Mode Mode

‘r’ ‘rb’ Read only *If the file does not exist,
then error is raised

‘w’ ‘wb’ Write only *If the file does not


exist,file is created.

*If the file exists, python


will truncate existing data
and overwrite in the file.

‘a’ ‘ab’ Append *File is in write only


mode.

*if the file exists, the data


in the file is retained and
new data being written
will be appended to the
end.

*if the file does not


exist,python will create a
new file.

‘r+’ ‘r+b’ Read and *File must exist otherwise


or write error is raised.
‘rb+’
*Both reading and writing
operations can take place.

‘w+’ ‘w+b’ Write and *File is created if doesn’t


or read exist.
‘wb+’
*If the file exists, file is
truncated(past data is
lost).

*Both reading and writing


operations can take place.

‘a+’ ‘a+b’ Write and *File is created if does


or read not exist.
‘ab+’
*If file exists, existing
data is retained ; new
data is appended.

*Both reading and writing


operations can take place.

TEXT FILE HANDLING


Methods to read data from files
S Method Syntax Description
.
N
O
.

1 read() <filehandle>.re Reads at most n bytes;If n is not


ad( [n] ) specified, then reads the entire
file.

Returns the read bytes in the


form of a string.

2 readline( <filehandle>.re Reads a line of input;if n is


) adline([n]) specified reads at most n bytes.
Returns the read bytes in the
form string ending with
in(line)character or returns a
blank string if no more bytes are
left for reading in the file.

3 readlines( <filehandle>.re Read all the lines and returns


) adlines() them in the form ofa list

Methods to write data into files

S. Name Syntax Description


NO

1 write() <filehandle>.write(str1) Write string str1


to file
referenced
by<filehandle>

2 writelines() <filehandle>.writelines Writes all


(L) strings in list L
as lines to file
referenced by
<filehandle>

Random Access methods in a Text file:

S. Name Syntax Description


NO

1 tell() <filehandle>.tell() This method tells


the current
position within the
file, measured in
bytes from the
beginning of file.

2 seek() <filehandle>.seek(offset, This method can


[mode]) be used to
change the current
Offset- this argument
position in a file.
indicates the no of
This method does
bytes to be moved
not return any
Mode- this is no value.
signifying 0 (beginning
of file),

1 (current postion of
cursor)

2 (end of file)

RELATIVE AND ABSOLUTE PATH :


1. A relative path is the path that is relative to the working directory
location on your computer. It does not start with a leading forward
slash (\).
For example, “abc.txt”
2. An absolute path is the path that contains the entire path to the file or
directory that you need to access.
For example, “C:\Users\Python\abc.txt”

To get the paths we need to import a module viz os module


To know the paths, we will write program like
Import os
cwd=os.getcwd()
Print(cwd)

QUESTION : (1 mark)
1. What is the difference between 'w' and 'a' modes?
Ans: ‘w’ mode opens a file in writing only mode. It overwrites a file if file already
exist but 'a’
mode appends the data to the existing file from end. It does not
overwrites the file.

2. Write a statement to open a text file name “sample.txt” in read mode and the
file sample.txt is placed in a folder ( name school) existing in c drive.

Ans: f1=open(“c:\school\sample.txt’,’r’)

3. Which of the following function returns a list datatype?


a. d=f.read()
b. d=f.read(10)
c. d=f.readline()
d. d=f.readlines()
Ans: (d) d=f.readlines()
4. When do you prefer text files over binary files?

Ans: Text file should be preferred when we have to save data in text format
and security of file is not
important.
5. Why binary files are processed faster than text files ?

Ans: No translation is required in case of binary files, so they are faster to


process.

6. In text files, each line of text is terminated with a special character, known
as ___________.
Ans: EOL (End of Line) (\n)

7. Which of the following options can be used to read the first line of a text
file data.txt?
a. f = open(‘data.txt’); f.read()
b. f = open(‘data.txt’,’r’); f.read(n)
c. myfile = open(‘data.txt’); f.readline()
d. f = open(‘data.txt’); f.readlines()
Ans: c. myfile = open(‘data.txt’); f.readline()

8.Let the file pointer is at the end of 3rd line in a text file named “data.txt”.
Which of the following option can be used to read all the remaining lines?
a. f.read( )
b. f.read(all)
c. f.readline( )
d. f.readlines( )
Ans. d. f.readlines( )

9. readlines( ) function returns all the words of the file in the form of List.
(T/F)
a. True
b. False
Ans. b. False

10. The syntax of seek() is:file_object.seek(offset [, reference_point] What is


the default value of reference_point
a. 0
b. 1
c. 2
d. 3
Ans. a. 0

QUESTION (2 marks ):

1. Write a single loop to display all the contens of a text file file1.txt after
removing leading and trailing WHITESPACES.
Ans: for line in open(“file1.txt”):
print(line.strip()
2. What is the output of the following code fragment? Explain.
out=open('abc.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close()
f=open('abc.txt')
r=f.read()
print(r)
Ans: The output will be:
hello,world!
how are you?
The first line of code is opening the file in write mode,the next two lines write
data in text t file. The next line opens the file and from that reference reads
the file contents. In the last line, the read data from the file is displayed.

3. Read the code given below and ANS the Qs:


f1=open('main.txt','w')
f1.write('BYE!!')
f1.close()
If the file contains 'HELLO' before execution, what will be the content of the file
after execution of the code ?
Ans: The file would now contains “BYE!!”only because when an existing file is
opened in write mode, it truncates the existing data in file .

4. Observe the following code and ANS the following:


f1=open("mydata","a")
______#blank1
f1.close()
(i) What type of file is mydata ?
(ii) Fill in the blank1 with statement to write "abc" in the file "mydata".
Ans: i) Text file
ii) f1.write(“abc”)
5. A given text file data.txt contains :
Line1\n
\n
line3
Line 4
\n
line6
What would be the output of following code?
f1=open('data.txt')
L=f1.readlines()
print(L[0])
print(L[2])
print(L[5])
print(L[1])
print(L[4])
print(L[3])
Ans: Line1
Line3
Line 6

Line 4

6. Differentiate between the following:


i) F1= open(“abc.txt”, “a”)
ii) F1= open(“abc.txt”, “r”)
Ans: 1. This statement opens a file “abc.txt” for appending data only.
2. This statement opens a file for reading purpose only.

7. What would be the data types of variables data in following


statements?
i) Data=f.read( )
ii) Data=f.read(10)
iii) Data=f.readline()
iv) Data=f.readlines()
Ans: i ) string ii) string iii) string iv) list

8. Differentiate between text file and CSV file.


Ans:
TEXT FILE CSV FILE

1. It is a file that stores It is a file that stores data in


information in ASCII characters. tabular form.

2. The file extension is .txt The file extension is .csv

9. Consider the following code:


f= open(“mytext.txt”, “w+”)
f.write(“0123456789abcdef”)
f.seek(-3, 2) #statement 1
print(f.read(2)) #statement 2

Explain statement1 and give output.

Ans: Statement1 uses seek() method that can be used to position the file
object at a particular place in the file. This statement positions the file object
at 3 bytes from the end of file.

Output: de

10. What is the difference between a text file and a binary file?
TEXT FILE BINARY FILE

1. In text file, data are stored In binary file, data are stored
as line of characters with each on the disk in the same way
line terminated by a new line as they are presented in the
character (‘\n’) computer memory.

2. Text files are in human Binary files are in binary format


readable form and therefore, and therefore, need no
need translation before translation and process faster
processing. than text files.

QUESTION (3 marks)

Q 1Write a user defined function in python that displays the number of lines
starting with 'H'in the file para.txt.
Ans: 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)

Q2 Write a function countmy() in python to read the text file "DATA.TXT" and
count the number of times "my" occurs in the file. For example if the file
DATA.TXT contains-"This is my website.I have diaplayed my preference in the
CHOICE section ".-the countmy() function should display the output as:"my
occurs 2 times".
Ans: def countmy ():
f=open (“DATA.txt” ,”r”)
count=0
x= f.read()
word =x.split ()
for i in word:
if (i == “my”):
count =count + 1
print (“my occurs” ,count, “times”)
Q3 Write a method in python to read lines from a text file DIARY.TXT and
display those lines which start with the alphabets P.
Ans: def display ():
file=open(‘DIARY.txt ‘ , ‘r’)
lines= file.readline()
while line:
if line[0]== ‘p’ :
print(line)
line=file.readline ()
file.close()

Q4 Write a method in python to read lines from a text file MYNOTES.TXT and
display those lines which start with alphabets 'K'
Ans: def display ():
file=open(MYNOTES.TXT’ , ‘r’)
lines=file.readlines()
while line:
if line[0]==’K’ :
print(line)
line=file.readline()
file.close()

Q5 Write a program to display all the records in a file along with line/record
number.
Ans: f=open(“result.dat” , “r”)
count=0
rec=””
while True:
rec=f.readline (0)
if rec == “ “ :
break
count=count+1
print (count,rec)
f.close()
Q6 Write a program that copies a text file "source.txt" onto "target.txt" barring
the lines starting with ‘@’ sign.
Ans: def filter (oldfile, newfile):
fin =open (oldfile, “r”)
fout= open (newfile, “w”)
while True:
text =fin.readline ()
if len(text)==0:
break
if text[0]== “@”:
continue
fout.write(text)
fin.close()
fout.close()
filter(“source.txt” , “target.txt”)

CASE-STUDY BASED QUESTION :

1. Suppose content of 'Myfile1' is:


Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
ANS the following Qs based on the following code ?
myfile = open("Myfile1")
data = myfile.readlines()
print(len(data))
myfile.close()

1. What will be the output of the above code?


a. 3
b. 4
c. 5
d. 6
Ans: b. 4

2. What is the data type of data in the above code ?


a. String
b. Integer
c. List
d. Tuple
Ans: c.List

3. What type of file is being shown above ?


a. Text file
b. Binary file

4. What is the mode in which above file is opened ?


a. r
b. w
c. wb
d. a
Ans: r

5. Name the function that will return the position of cursor in the file ?
Ans: tell()

2. Suppose content of 'Myfile.txt' is


Humpty Dumpty sat on a wall
Humpty Dumpty had a great fall
All the king's horses and all the king's men
Couldn't put Humpty together again
What will be the output of the following code?
myfile = open("Myfile.txt")
record = myfile.read().split()
print(len(record))
myfile.close()
1. What will be the output of the following code?
a. 24
b. 25
c. 26
d. 27
Ans: 26

2. In which mode the file is opened ?


Ans: ‘r’
3. Identify the stream object in the above code.
Ans: myfile

4. Which function is used to close the file?


Ans: close()
5. What is the datatype of record variable in above code?
Ans: list

BINARY FILE

INTRODUCTION: It is a file which stores the information in the same format


as stored in the memory (RAM of a computer) i.e., data is stored according to
it’s data type so no translation occurs which happens in case of a text file
(conversion of ‘\n’ to new line etc.).

Most of the files we see in our computer system are binary files. For e.g.,
Document files (.pdf,.doc,.xls), Image files (.png , .jpg, .gif , .bmp), Video Files
(.mp4,.3gp,.mkv), Audio Files , Database files , executables etc.

There is no delimiter for a new line. So data is stored in a continuous stream of


bytes. It is comparatively faster than text files and what makes it nice to have in
our program is the convenience and fast speed with which any program reads
from or writes into a binary file. So whenever the file has to be read or written
by program only, it makes perfect sense to use binary files.

Though it brings us to next point, i.e., data in binary file is in such a form that
it can only be read through python program with the help of ‘pickle module’ which
will be explained later.

BASIC OPERATIONS ON A BINARY FILE: Just like text files, the first thing we
need to do while working with binary files is to open it with the help of
open()function. The basic syntax to use open function is given below:

file_handle = open(‘Absolute/Relative address of the file with


extension’,’file_mode’)

The open function returns a file object which is stored in the variable defined on
the left hand side of the assignment operator. This file handle or file object can
then be used to perform various operations on the file.

The various operations that can be performed on a binary file with the help of
this file handle after opening the file are:

(a) Reading from the file


(b) Writing into the file
(c) Appending data into file
(d) Updating the data in a binary file
(e) Searching for a data in binary file

The file_mode argument of open( ) function is optional which takes ‘r’ or read
mode as it’s default value. The detailed explanation of the file modes will be
discussed in coming topics.

But the file handling is not just about opening or closing the files, we usually
perform reading, writing , appending or combinations of the said operations. In
order to do that we must open the file in appropriate file mode which must be
mentioned in the open function.
FILE MODES:

Various file modes available in python to work with binary files are given in the
following table:

File Description Notes


Mode

‘rb’ Read only File must exist, otherwise Python


raises I/O error

‘wb’ Write only If file not exists, file is created. If file


exists, python will truncate existing
data and overwrite the file.

‘ab’ Append only File is in write mode only, new data


will be added to the end of existing
data i.e., no overwriting. If file not
exists it is created.

‘r+b’ or Read and File must exist otherwise error is


‘rb+’ write raised. Both reading and writing can
take place

‘w+b’ Write and File is created if not exists, if data is


or read present in the file it will be truncated,
‘wb+’ both read and write operations
allowed.

‘a+b’ or Append and Same as above but previous content


‘ab+’ read will be retained and both read and
write operations are allowed.

CLOSING A BINARY FILE:


After performing all the required operations on the file , we should close the file
using the close( ) method just like we closed the text files we worked with. The
basic syntax of closing a file is given by

file_handle.close( )

PICKLE MODULE:

If we want to write a data structure such as list or dictionary to a binary file and
read it subsequently, we need to use the pickle module for it.

This module is used for serializing or de-serializing any python object.

Serialization: It is the process of transforming data or any object in memory


(RAM) to a stream of bytes called bytes streams. This is also known as pickling.

While reading the contents of the file, a reverse process called Unpickling is
used to convert the byte stream back to the original structure.

We know that the methods provided in Python for writing/ reading a file work
with string parameters. So, when we wish to work upon binary files, conversion
of data at the time of reading as well writing is required. Pickle module can be
used to store any kind of data object in binary file as it allows us to store Python
objects with their structure.

But first of all, we need to import it like other modules:

import pickle

or

from pickle import dump, load

READING DATA FROM A BINARY FILE (Un-pickling):

The load function inside the pickle module is used to read the contents of a
binary file.

The basic syntax of a load function is:


data_object =pickle.load(file_handle)

here the data_object can be any variable that takes the result of load function
and then subsequently can be traversed and the data may be fetched from this
data_object.

For example, if a dictionary was written in the binary file that was read using
load function then the data_object will contain that dictionary and then it can be
traversed.

Example 1: Program to read dictionary items from the binary file:

WRITING DATA INTO A BINARY FILE (Pickling):

The dump function inside the pickle module is used to write the object (which
can be string/list/tuple/dictionary etc.) into the binary file.

The basic syntax of a dump function is :

pickle. dump(object,file_handle)

here the object is being written in the binary file that is being pointed by the file
handle.

Example 2: Program to write structure, list in the binary file


Example 3: Program to write structure, dictionary to the binary file
APPENDING A RECORD IN BINARY FILE:

In order to append a record in a binary file we just need to follow the steps we
took while writing the data but the only change we need to make is in the file
mode which we change to ‘ab’ which denotes append mode in binary files.

Example 4: Program to append a record in the binary file ‘student.dat’.

SEARCHING A RECORD IN A BINARY FILE:

We can search any record in a binary file by deciding a criteria on the basis of
which the search will be performed. The file can be read and then the complete
file can be read using load() function and then the object may be traversed in
order to check the presence of any record.
Example 5: Program to search a record from the binary file ‘student.dat’ on the
basis of roll number.

UPDATING A RECORD IN BINARY FILE:

In order to update a binary file following steps to be executed:

1. Import the pickle module


2. Open the binary file in read and write mode
3. Load the content of files into any variable.
4. Traverse the data structure and find the record to be updated.
5. Once found make appropriate changes.
6. Then move the file pointer to the beginning of the file with the help of seek(0)
7. Then write the data structure into the file which will overwrite all the existing
data.
8. Close the file

Example 6: Program to search the roll number of a student input by user and
update the name.
RAMDOM ACCESS IN FILES USING SEEK() AND TELL()

Files in python can be accessed from random positions which is different from
sequential access and adds another dimension in the file handling where you can
go to any specified location in a file.

There are 2 built-in methods for the same:

1. seek() – It is used to change the position of the file handle (file pointer) to a
given specific position. File pointer is like a cursor, which defines from where
data has to be read or written in the file.
Python file method seek( ) sets the file’s current position at the offset. It can
have 3 possible positioning values which is given to from_what argument as
explained next:

(a) 0 – default value – sets the reference point at the beginning of the file. IN this
case seek(5) will move the file pointer 5 places right with reference to the
beginning of the file.

(b) 1 –sets the reference point at the current file location. In this case seek(5) will
move the file pointer 5 places right with reference to the current location of file
pointer.
(c) 2 – (only in binary files)sets the reference point at the end of the file.In this case
seek(-5) will move the file pointer 5 places left with reference to the end of the
file.

The basic syntax of a seek( ) method is given by:

filehandle.seek(offset,from_what)

Note: Python 3.x only supports text file seeks from the beginning of the file.
seek() with negative offset values only works when the file is opened in binary
mode.

2. tell() –This method tells the current position of the file pointer of the file read/write
pointer within the file. It’s basic syntax is

filehandle.tell()

Some important points to remember in respect of tell( ) function is:

 When you open a file in reading/ writing mode, the file pointer rests at 0 th position.
 When you open a file in append mode, the file pointer rests at the last byte.
COMMA SEPARATED VALUES (CSV) FILE

INTRODUCTION: CSV is a simple flat file in a human readable format which


is extensively used to store tabular data in a spreadsheet or database. A CSV
file stores tabular data (numbers and text) in plain text.

Files in the CSV format can be imported to and exported from programs that
store data in tables, such as Microsoft Excel or OpenOffice Calc.

As the name suggests in a CSV file all the values are separated with comma.

Each line in a file is known as data/record. Each record consists of one or


more fields, separated with comma (also known as delimiters). This tabular
data is stored as text in a CSV file.

ADVANTAGES OF A CSV FILE:

 CSV is faster to handle


 CSV is smaller in size
 CSV is easier to generate and import onto a spreadsheet or database.
 CSV is human readable and easy to edit manually.
 CSV is simple to implement and parse
 CSV is processed by almost all existing applications

CSV FILE HANDLING IN PYTHON

There is an inbuilt module called csv which needs to be imported first. It is


used to read and write tabular data in CSV format.

In order to work with csv files, the file must be opened using the built-in open(
) function. The modes are same as used in text-files.

Like other files (text and binary) in Python, there are two basic operations that
can be carried out on a CSV file:

1. Reading from a CSV file


2. Writing to a CSV file
READING FROM A CSV FILE

It is done with the help of a reader object. The CSV file is first opened as a
text file with Python’s built-in function open () which returns a file object. This
creates a special type of object to access the CSV file (reader object) using
the reader object.

Reader Object: It is an iterable that gives us access to each line of CSV file
as a list of fields. You can also use next() directly on it to read the next line
of the CSV file or you can treat it like a list in a for loop to read all the lines
of the file.

In order to read from a CSV file, you should either have a pre created CSV
file or you can create it with the help of any spreadsheet software (such as
Microsoft Excel) and then save the file as CSV (comma delimited). When this
file is opened in notepad you will see all the column values separated by
comma.

Detailed steps to create a csv file manually:

1. Open the Microsoft excel by going to Start->type excel-> Click Excel

2. Enter the data as shown


3. Save the file by going to save as then enter the name of file and select
the types as csv(comma delimited) as shown:

4. Open the file in notepad and you will see the following

The first line of the notepad is the header and remaining lines are the
data/records. The values are separated by comma which is also known as
delimiter. There are many limiters that can be used such as tab (\t),colon(:)
and semi-colon(;) characters.

Example 7: Write a program to read the contents of ‘student.csv’ file


WRITING INTO A CSV FILE

To write into a CSV file in python we can use the csv. writer () function. This
function returns a writer object that converts the user’s data into a delimited
string. This string can then be written into CSV file with the help of writerow
() function.

Writer Object: In order to write to a CSV file, we create a special type of


object called as writer object. This is created using the writer () function
defined in the csv module.

Writerow () : This method allows us to write a list of fields into the file. The
fields can be strings or numbers or both. It is used to write one row at a
time.

Writerows() : This function can be used to write multiple rows at a time. This
can be done by storing all the rows as different lists and then writing it in
one go.

Note: While using writerow(), we do not need to add a newline character (or
other EOL indicator) to indicate the end of line. This is done implicitly by the
writerow( ) function. This is why while using the open function we will pass
additional argument as newline=’’. This is to overwrite the default value of
‘\r\n’ to ‘ ‘. So that the additional empty rows won’t appear in the csv file
while writing.

Example 8: Program to write data onto ‘student’ csv file using writerow()
method.

Example 9: Program to write data onto ‘student.csv’ file using writerows()


method.
QUESTIONS

Solved QUESTIONS

Q1: What is the role of the newline argument in the CSV open()?

Ans: The newline argument is used to specify the EOL character at the
specific operating system. Additional optional argument as newline=’’ (null string;
no space in between) with the file open( ) will ensure that no translation of
end of file (EOL) character takes place.

Q2: Write a Python program to read specific columns from a ‘department.csv’


file and print the content of the columns, department id and department name.

Ans: import csv

with open(‘department.csv’,newline=’’) as csvfile:

data = csv.reader(csvfile)

print(‘ID Departmentalize’)

print(‘-----------------------------------‘)

for row in data:

print(row[0],row[1])

Q3: What briefly the CSV format of storing files.

Ans: The acronym CSV is short for comma separated values, which refers
to tabular data saved as plain text where data values are separated by commas.
In CSV format:

 Each row of the table is stored in one row, i.e., the number of rows in a CSV
file are equal to the number of rows in the table (or sheet or database table,
etc.)
 The field values of a row are stored together with commas after every field
value; but after the last field’s value, no comma is given, just the end of line.

Q4: Write a menu-driven program implementing user-defined functions to perform


different functions on a csv file ‘student’ such as :
Ans: (a) import csv

def CreateCSV1():

#Open CSV file

Csvfile = open(‘student.csv’,’w’,newline=’’)

#CSV object for writing

Csvobj = csv.writer(Csvfile)

while True:

Rno = int(input(‘Rno:’))

Name = input(‘Name:’)

Marks = float(input(‘Marks:’))

Line = [Rno,Name,Marks]

#Writing a line in CSV file

Csvobj.writerow(Line)

Ch = input(‘More (Y/N)’?)

ifCh == ‘N’:

break

Csvfile.close()

Q5: In the above Q, create a function to write all the records in one single go
onto the csv.

Ans: #To create a CSV File by writing all lines in one go

def CreateCSV2():

#Open CSV File

Csvfile = open(‘student.csv’,’w’,newline=’’)

#CSV object for writing


Csvobject = csv.writer(Csvfile)

Lines = []

while True:

Rno = int(input(‘Rno’))

Name = input(‘Name’)

Marks = float(input(‘Marks:’)

Lines.append([Rno,Name,Marks])

Ch = input(‘More (Y/N)?’)

ifCh==’N’:

break

#Writing all lines in CSV file

Csvobj.writerows(Lines)

Csvfile.close()

Q6: In the above Q, create a function to Display the contents of the csv file.

Ans: #To read and show the content of a CSV File

defShowAll():

#Opening CSV file for reading

Csvfile = open(‘student.csv’,’r’,newline=’’)

#Reading the CSV content in object

Csvobj = csv.reader(Csvfile)

for Line in Csvobj: #Extracting line by line content

print(Line)

Csvfile.close()

print(“CSV File Handling”)


while True:

Option = input(‘1:CreateCSV 2:CreateSCVAll 3:ShowCSV 4:Quit’)

if Option ==’1’:

CreateCSV1()

elif Option ==’2’:

CreateCSV2()

elif Option ==’3’:

ShowAll()

else:

break

Q7: Create a binary file ‘emp’ that stores that records of employees and display
them one by one.

Ans: import pickle

f1 = open(‘emp.dat’,’rb’)

e = pickle.load(f)

for x in e:

print(x)

f1.close()

Q8: Write a program to display the records of all those employees who are
getting salaries between 25000 to 30000.

Ans: import pickle

f1 = open(‘emp.dat’,’rb’)

e = pickle.load(f1)
for x in e:

if(e[x]>=250000 and e[x] <=30000):

print(x)

f1.close()

Q9: What is the difference between writerow() and writerows() functions in csv
module?

Ans: Writerow() : This method allows us to write a list of fields into the
file. The fields can be strings or numbers or both. It is used to write one
row at a time.

Writerows() : This function can be used to write multiple rows at a time. This
can be done by storing all the rows as different lists and then writing it in
one go.

Q10: Anant has been asked to display all the students who have scored
less than 40 for Remedial classes. Write a user-defined function to display all
those students who have scored less than 40 from the binary file ‘Student.dat’

Ans: Considering the format of binary file to be [‘Rno’,’Name’,’Marks’]

import pickle

f1 = open(‘student.dat’,’rb’)

e = pickle.load(f1)

for x in e:

if(e[2]< 40):

print(x)

f1.close()

UNSOLVED QS

1 MARK QS
MCQ

Q1: Which of the following module is used to work with binary files in python?

(a) csv (b) binary

(c) pickle (d) numpy

Q2: If a file is opened for writing, which of the following statements are true?

(a) The file must exist on the disk on the specified path.
(b) If the file exist at the specified path, the file is successfully opened
(c) The file even if at a different locations on disk other than the specified path,
will get opened
(d) Python gives error if the file does not exist at the specified path
(e) Python will create a new empty file at the specified path if the file doesn’t
exist at the specified path
(f) The existing contents of the file get erased as soon as you open the file.

Q3: Which of the following represents mode of both writing and reading in binary
format in file?

(a) wb+ (b) w (c) wb (d) w+

Q4: Which of the following commands is used to open a file “c:\myfile.dat” for
writing as well as reading in binary format only?

(a) fout = open(‘c:\pat.dat’,’w’) (b) fout = open(‘c:\\pat.dat’,’wb’)

(c) fout = open(‘c:\pat.dat’,’w+’) (d) fout = open(‘c:\\pat.dat’,’wb+’)

Q5: Which of the following functions do you use to write data in the binary
format?

(a) write() (b) load () (c) dump() (d) send()

Q6: Which object gives us access to every record of a file in the form of a list
for reading the file?

(a) File object (b) writer object (c) read object (d) reader object
Q7: A CSV file uses which of the following delimiter for separating values

(a) Semi-colon (b) tab (c) comma (d) full stop

Q8: Which of the following function is used to write multiple rows at once in a
csv file?

(a) writelines() (b) writer() (c) writerow () (d) writerows()

Q9: Which of the following module is used to deal with csv file in a python
program?

(a) pickle (b) CSV (c) csv (d) numpy

Q10: Which of the following object is used to write in a csv file?

(a) reader (b) file object (c) writer (d) seek

TRUE OR FALSE

Q1: When you open a binary file for reading, if the file doesn’t exist, an error
occurs.

Q2: The load ( ) function of the pickle module performs pickling.

Q3: The csv files are text files.

Q4: The csv files can only take comma as a delimiter.

Q5: Conversion of an object hierarchy in byte stream is called Serialization.

ONE WORD ANS

Q1: Which file mode opens a binary file for read and write purpose.

Q2: The _________ method of pickle module writes data into binary file.

Q3: The _________ method of pickle module reads data from a binary file.

Q4: To write a list in a file, _______ method may be used.

Q5: To specify a different delimiter while writing into a csv file, _____ argument
is used with csv.writer().
Q6: To close an open file, ________ method is used.

Q7: The default delimiter for the csv files is _______.

Q8: The character that separates the values in csv files is called the _______.

Q9: To read and write into binary files, _____ module is used.

Q10: The file mode to open a csv file for appending as well reading is
_______.

ASSERTION AND REASONING

Directions: In the following Qs, A statement of Assertion (A) is followed by a


statement of Reason (R). Mark the correct choice as:

(A) Both A and R are true and R is the correct explanation for A.
(B) Both A and R are true and R is not correct explanation for A.
(C) A is true but R is false.
(D) A is false but R is true.
(E) Both A and R are false

Q1: Assertion (A) :If we wish to add data to already created file, be it csv or
binary file, it must be opened in append mode.

Reason (R) : Append mode helps in writing into file at arbitrary locations.

Q2: Assertion (A): A CSV which contains any other delimiter than comma is
not a valid csv file.

Reason (R): A CSV file is a comma separated valued file in which we can
only use comma as delimiter.

Q3: Assertion (A) : With statement can be used to open any file, be it csv
file or binary file and while using with statement to open any file there is no
need to close the file.
Reason (R) : With statement groups all the statements related to file handling
and makes sure to close the file implicitly. It closes the file even when any
error occurs during the execution of statements in a with statement.

Q4: Assertion (A): writerow( ) function helps us to write multiple rows in a


csv file at a time.

Reason (R) : Writing one row at a time in a csv file is not possible, we must
write multiple rows at a time.

Q5: Assertion (A): filehandle.seek(20,1) will move the file pointer 20 places
right in reference to the current position of the file pointer.

Reason (R) : The second argument of seek function deals with the location or
reference of movement.

VERY SHORT ANS TYPE QS

2 MARKS EACH

Q1: What is the full forms of:

(i) CSV
(ii) TSV

Q2: What is the role of CSV reader object?

Q3: What is the role of CSV writer object?

Q4: What is the difference between seek( ) and tell( ) function?

Q5: What is the difference between the dump( ) and load( ) functions of Pickle
module?

Q6: What is the following code doing?

import csv

file = open(‘contacts.csv’,’a’)

name = input(‘Enter your name’)

pno = input(‘Enter your mobile number’)


file.write(name+’,’+pno+’\n’)

file.close()

Q7: What is the role of delimiter character in a csv file?

Q8: What is pickling?

Q9: What is un-pickling?

Q10: How are CSV files different from regular files?

HOTS (HIGHER ORDER THINKING SKILLS)

Q1: Write a function that reads a csv file containing several columns containing
data of a students. The structure of csv file is

‘RNo.’,’Name’,’Subject’,’Marks’

1,’Soma’,’CS’,58

2,’Mona’,’Physics’,88

3,’Kajal’,’Chemistry’,95

And so on.

You have to read the marks of students and write the lists of prime number
and perfect number in a binary file.

Q2: Write a program that reads a csv file and creates another csv file which is
the transpose of the input csv file.

Q3: Write a program that reads a csv file and replaces all the delimiter(comma)
with tab delimiter.

Q4: Write a program that creates 500 copies of a csv file (random.csv). All the
copies should be named as random1.csv , random2.csv …. random500.csv in
a folder called spam.

Q5: Write a program that reads a text file containing an article and then store
the frequency of every character in form of a dictionary in a binary file named
as freq.dat
Q6: Write a program that asks user to input the name of any python program
file and then prints the code written in that file.

Q7: Write a program that reads a csv file and writes it’s data in a binary file.

Q8: Write a program that finds a prime number and writes it into a csv file
simultaneously. The program should run infinitely and should only open the
file when it has found a number.

SHORT ANS TYPE QS

3 MARKS EACH

Q1: What are the advantages of saving data in :

(i) Binary form


(ii) Text form

Q2: What will be stored in the file school.csv after the following code is executed?

data = [ [‘DRS Delhi’, ‘Esha’, ‘Badminton’],

[‘BTS Patna’, ‘Abhi’,’Tennis’] ]

import csv

with open(‘school.csv’,’w’,newline=’’) as csvfile:

writer = csv.writer(csvfile,delimiter=’,’)

writer.writerow([‘School’,’Nickname’,’Sport’])

writer.writerows(data)

Q3: Following code is written to update a record in a file opened with following
code:

import csv

fin = open(‘stu.dat’,’rb+’)

try:
while True:

_______ = fin.tell( ) #storing file pointer position

stu = pickle.load(fin)

ifstu[‘Marks’] in [92,93,94]:

fin.________(_______) #Place the file pointer at exact position

pickle.dump(stu,fin)

except:

__________ # To close the file

Fill in the blanks in Line 1 , Line 2 and Line 3 to complete the code.

Q4: Identify the error in the following code:

1. import csv
2. data = [‘one’,2,[3,4,5]]
3. with open(‘data2.dat’,’rb’) as f:
4. pickle .dump(data,f)

Q5: Identify the error in the following code:

1. import csv
2. line = [ [1,2,3] , [4,5,6] ]
3. with open(path,’w’,newline=’’) as csv_file:
4. writer = csv.writer(csv_file,delimiter=’|’)
5. for line in data:
6. writer.writerrow(line)

Q6: Write the file mode that will be used for opening the following files. Also
write the python statements to open the following files:

(a) A binary file ‘bfile.dat’ in write mode


(b) A csv file named ‘contacts.csv’ in append and read mode
(c) A binary file named ‘studentdata.dat’ in write and read mode

Q7: Differentiate between a text file and a binary file.


Q8: Write a statement to open a binary file C:\Myfiles\Text1.txt in read and write
mode by specifying for the path in two different formats.

Q9: What will be displayed by the following code:

import pickle

Names = [‘First’,’Second’,’third’,’fourth’,’fifth’]

lst = [ ]

fori in range(-1,-5,-1):

lst.append(Names[i])

with open(‘test.dat’,’wb’) as fout:

pickle.dump(lst,fout)

with open(‘test.dat’,’rb’) as fin:

nlist = pickle.load(fin)

print(nlist)

Q10: Give the output of the following code snippet:

import pickle

list1,list2 = [2,3,4,5,6,7,8,9,10],[]

fori in list1:

if (i%2==0 and i%4==0):

list2.append(i)

f = open(‘bin.dat’,’wb’)

pickle.dump(list2,f)

f.close()

f = open(’bin.dat’,’rb’)

data = pickle.load(f)
f.close()

fori in data:

print(i)

PROGRAMMING BASED QS

5 MARKS QS

Q1: Considering the following definitions of dictionary MULTIPLEX ,write a


function in python to search and display all content in a pickled file CINEMA.dat,
where MTYPE key of the dictionary is matching with the value ‘Comedy’.

MULTIPLEX = {‘MNO’:____,’MNAME’:_______,’MTYPE’:_______}

Q2: Write a program to enter the following records in a binary file:

Item no. integer

Item_Name string

Qty integer

Price float

Amount: (to be calculated as Price*Qty)

Q3: Create a CSV file ‘Groceries’ to store information of different items existing
in a shop. The information is to be stored w.r.t. each item code, name, price,
qty. Write a program o accept the data from user and store it permanently in
CSV file.

Q4: Write a program to increase the salary by Rs. 2000/- of the employees
having empno as 1251 in the file empl.dat

Q5: Write a program to read following details of sports’ performance


(sport,competitions,proze-won) of your school and store into a csv file delimited
with tab character.

CASE STUDY BASED QS


5 MARKS QS

Q1: Sonu Bhartiya has joined as an intern at Real soft company. The company
has departments spread across India and the details of all the departments
are stored in a file, Dept.csv, as shown

Dept_ID Dept_Name Location

D010 Admin Delhi

D020 Production Hyderabad

D030 Marketing Bangalore

D040 Agri-Research Mohali

D050 Agri-Marketing Mohali

D060 Human Hyderabad


Resources

D070 Finance Delhi

D080 Public Bangalore


Relations

… … …

Sonu has been asked to write a program to list the departments at a specific
location. He has written the following code, with some words / syntax missing:

______ _______ #Line1

with open(_________,newline=_____) as csvfile: #Line2

data = csv.reader(_______,delimiter=’’) #Line3

for row in data: #Line4

if _______ in row: #Line5

print(______) #Line6
(a) Which library must be added to the program for it to work? Fill Line 1 for

this.

(b) Complete Line 2 so that the file storing the department details gets opened

with suppressed newline processing.

(c) The records are to be read row by row , not field by field. For this fill in

the blank in Line 3.

(d) Sonu wants to print only the departments in locations ‘Mohali’. Complete

Line 5 and Line 6 for the same.

(e) Convert the above given incomplete code so that location name is passed

to a function Deplocation( ) and the function prints the rows of the department

details from that location.

Q2: DikshaBehl is a student of non-IT stream. However, she wants to learn


Python also as it will be helpful to her in her field. While learning Python, her
teacher has assigned her an assignment to complete an incomplete program
given below:

The Program intends to print from a csv file (people.csv) that stores tab
separated fields as:

EmpId Fname Lname Phone

201 VIbhu Jain 43454345345

202 Nooh Kirk 43345453453

203 Haris Jamil 39605940595

204 Kutwani Singh 30909589458

The incomplete code given to Diksha is as follows:


import csv #Line1

with open(_______,_____) as myfile: #Line2

fin = csv._________(myfile,delimiter=_____) #Line3

for row in _______: #Line4

print(_______) #Line5

(a) Complete the Line2 of the given code so that the given csv file is opened

in read mode for processing.

(b) Complete Line3 so that the tab separated csv file is read into fin object.

(c) Compete the code of Line4 and Line5 so that the records from the open

csv file are printed line by line.

(d) Modify the code of Line4 and Line5 so that only the fourth field (Phone)

from each record gets printed.

(e) Write the output obtained by running the code of Line4 and Line5.

Q3: Ranjan Kumar of Class 12 is writing a program to create a CSV file


“user.csv” which will contain user name and password for some entries. He
has written the following code. As a programmer help him out to successfully
execute thegiven task.

import ________ #Line 1

defaddCsvFile(UserName,Password):

f = open(‘user.csv’,’_______’) #line 2

newFileWriter =csv.writer(f)

newFileWriter.writerow([UserName,PassWord])

f.close()
#csv file reading code

defreadCsvFile():

with open(‘user.csv’,’r’) as newFile:

newFileReader = csv._______(newFile) #Line 3

for row in newFileReader:

print(row[0],row[1])

newFile.__________ #Line 4

addCsvFile(‘Arjun’,’123@456’)

addCsvFile(‘Sandhya’,’arjk#rjkjhk’)

addCsvFile(‘sandeepsn72’,’sadsdasd’)

readCsvFile() #Line 5

(a) Name the module he should import in Line1.

(b) In which mode, Ranjan should open the file to ass data into the file.

(c) Fill in the blank in Line3 to read data from the csv file.

(d) Fill in the blank in Line4 to close the file.

(e) Write the output he will obtain while executing Line5.

Q4: Ami Surani has been chosen to participate in a Python workshop. While
learning csv files, she has been assigned the following incomplete code. Help
her complete the code.

import csv

#records of 5 students as lists

S1 = [‘Anju’,’Sharma’,93,’A’]

S2 = [‘Tom’,’Saun’,90,’A’]
S3 = [‘Manu’,’Tiwari’,88,’B’]

S4 = [‘Chunu’,’Kumari’,99,’C’]

S5 = [‘Roberto’,’Carlos’,100,’A’]

#2-D list – list containing lists

studata = [[‘First Name’,’SecondName’,’Marks’,’Grade’], #Fill_1A

___________________________________] #Fill_1B

sfile = open(_______,_____________) #Fill_2

with _______________: #Fill_3A

writer = csv._________(sfile) #Fill_3B

writer. _______(_______) #write 2D list in one go #Fill_4

print(‘Student Records successfully written’)

(a) The given statement records are individually available in the form of lists

S1,S2,S3,S4 and S5. Complete Fill_1A and Fill_1B so that all the students

details along with column headings are available in the form of 2-D list – a list

of lists.

(b) Complete Fill_2 to open a file student.csv to store the student records written

to it.

(c) Complete Fill_3A and Fill_3B in the code so that the open csv file is ready

for writing.

(d) Complete Fill_4 code line so that the 2D list studata is written on the open

csv file in one go.

(e) The given code has opened file using with statement, but not closed it. Is

it an error? Why?
Q5: Rudy Johnson is an enthusiastic student who is chosen for a student
internship with a Government office. As the first day assignment, he has been
asked to store some state-names along with their capitals in a file, namely
capitals.csv. He has been asked to store the following details:

“SNo.”,”State”,”Capital”

1,”Delhi”,”New Delhi”

2,”Assam”,”Dispur”

3,”Bihar”,”Patna”

4,”M.P.”,”Bhopal”

5,”U.P.”,”Lucknow”

He has been given an incomplete Python code for the same, as shown below.

import csv

with open(_______,_____) as sfile:

fileWriter = ________(______,_______) #Fill_Line1

_____._______([“SNo.,”State”,”Capital”]) #Fill_Line2

___________________________________ #Fill_Line3

___________________________________ #Fill_Line4

___________________________________ #Fill_Line5

___________________________________ #Fill_Line6

___________________________________ #Fill_Line7

___________________________________ #Fill_Line8

Help him complete the code as per the following instructions.

(a) Complete Fill_Line1 in the given code so that the mentioned file is opened
for writing the given data.
(b) Complete Fill_Line2 in the given code so that the mentioned file is ready
for csv style writing with delimited as tab.
(c) Complete Fill_Line3 to write the column headings in the csv file as the first
line.
(d) Complete lines Fill_Line4 to Fill_Line8 to write the given states and capitals
in the open file.
(e) Although with the ‘with’ statement, you do not need to close the file, but
assuming that the file is opened in a file object, namely sfile, how would you
close it? Write a statement for this.
ANS KEY

Unsolved Qs

1 MARK QS

MCQ

Q1: (c) pickle

Q2: (b),(e) & (f)

Q3: (a) wb+

Q4: (d)

Q5: (c)

Q6: (d)

Q7: (c)

Q8: (d)

Q9: (b)

Q10: (c)

TRUE OR FALSE

Q1: True

Q2: False

Q3: True

Q4: False

Q5: True

ONE WORD ANSWERS

Q1: rb+

Q2: dump()

Q3: load()
Q4: dump()

Q5: delimiter

Q6: close()

Q7: comma

Q8: delimiter

Q9: pickle

Q10: a+

ASSERTION AND REASONING

Q1: (c) A is true but R is false.

Q2: (e) Both A and R are false

Q3: (a) Both A and R are true and R is the correct explanation for A

Q4: (e) Both A and R are false

Q5: (a) Both A and R are true and R is the correct explanation for A

VERY SHORT ANS TYPE QUESTIONS

2 MARKS EACH

Q1: (a) Comma Separated Values

(b) Tab Separated Values

Q2: The csv.reader object does the opposite of csv.writer object. The csv.reader
object loads data from the csv file, parses it, i.e., removes the delimiters and
returns the data in the form of a Python iterable wherefrom we can fetch one
row of data at a time.

Q3: Before writing onto CSV files, the data must be in csv-writeable-delimited-
form. This task is performed by the CSV writer-object, which does this task by
converting the received user data into the form appropriate for the CSV files.
Q4: The seek function places the file pointer on the loaded file in the file-object
at a random position while the tell() function tells the position of the file pointer
(the offset) in the file object.

Q5: The dump( ) function carries out the pickling effect on a Python object while
the load() carries out the opposite – the unpickling effect.

Q6: The given code is asking user to enter any name and their mobile number
and then writing this row in a csv file called as contacts.csv which has been
opened in append mode.

Q7: A delimiter character (such as comma or a tab etc.) separates the data
items storedin CSV files. It appears between every two successive data items
e.g., 17, “Ria”,77.5.

Q8: Pickling is a process of converting a Python object hierarchy into a byte


stream using the functions of Pickle library of Python, so that it can be written
into a file.

Q9: Unpickling is the inverse of Pickling where a byte stream is converted into
an object hierarchy using the functions of Python’s Pickle library. Unpickling
produces the exact replica of the original object.

Q10: Regular text files store data in ASCII or Unicode format without any
delimiter character and EOL character at the end of every line.

The CSV files are delimited text files that store a delimiter character (Comma
or any other delimiter) between the data items stored.

HOTS (HIGHER ORDER THINKING SKILLS)

Q1:

def isPrime(num):

flag = False

for i in range(2,num//2):

if(num%i==0):
return False

else:

flag = True

if(flag):

return True

def isPerfect(num):

sum=0

for i in range(1,num):

if num%i == 0:

sum+=i

if(sum==num):

return True

else:

return False

defmainFunction(binFile,csvFile):

listofPrime=[]

listofPerfect=[]

import csv

import pickle

fin = open(csvFile,’r’)

csvReader = csv.reader(fin)

for row in csvReader:

if(isPrime(csvReader[3]):

listofPrime.append(csvReader[3])
if(isPerfect(csvReader[3]):

listofPerfect.append(csvReader[3])

fin.close()

fin = open(binFile,’wb’)

pickle.dump(listofPrime,listofPerfect)

fin.close()

Q2:The following code uses zip and map function to perform the transpose,
students may also use matrix transpose for the same

import csv

fin = open('contacts.csv','r')

fr = csv.reader(fin)

fr = list(fr)

transpose = list(map(list, zip(*fr)))

fin.close()

fin = open('contacts.csv','w',newline='')

fw=csv.writer(fin)

fw.writerows(transpose)

fin.close()

Q3:

newcontent=''

fin = open('contacts.csv','r+')

fr =fin.read()

for ch in fr:

ifch==',':
newcontent+='\t'

else:

newcontent+=ch

fin.seek(0)

fin.write(newcontent)

fin.close()

Q4:

import csv

filename = input('Enter Filename without extension')

fin = open(filename+'.csv','r+')

fr =csv.reader(fin)

fori in range(1,501):

f = open('spam\\'+filename+str(i)+'.csv','w+')

fw = csv.writer(f)

for row in fr:

fw.writerow(row)

f.close()

forch in fr:

ifch==',':

newcontent+='\t'

else:

newcontent+=ch
fin.close()

Q5:

import pickle

fin = open(‘inputfile.txt’,’r’)

frequency = {}

content = fin.read()

forch in content:

c = content.count(ch)

ifch not in frequency:

frequency[ch]=c

fin.close()

bin = open(‘freq.dat’,’w’)

pickle.dump(frequency,bin)

bin.close()

Q6:

filename = input(‘Enter the filename’)+’.py’

fin = open(filename,’r’)

program = fin.read()

print(program)

Q7:
import csv

import pickle

cin = open(‘inputcsvfile.csv’,’r’)

cr = csv.reader(cin)

for row in cr:

bin = open(‘outputbin.dat’,’w’)

pickle.dump(row,bin)

bin.close()

cin.close()

Q8:

defisPrime(num):

flag = False

fori in range(2,num//2):

if(num%i==0):

return False

else:

flag = True

if(flag):

return True

import csv

num = 2

while(True):

if(isPrime(num)):

cin = open(‘prime.csv’,’a’)
cr = csv.reader(cin)

cr.writerow(num)

cin.close()

num+=1

SHORT ANS TYPE QUESTIONS

3 MARKS EACH

Q1: (i) binary form:

 Binary files are faster and easier for a program to read and write than are
text files.
 As long as the file doesn’t need to be read by people or need to be ported
to a different type of system, binary files are the best way to store program
information.

(ii) text form:

 It can be read by people.


 It can be ported to a different type of system.

Q2:

'School', 'Nickname', 'Sport'


'DRS Delhi', 'Esha', 'Badminton'
'BTS Patna', 'Abhi', 'Tennis'

Q3: import csv

fin = open(‘stu.dat’,’rb+’)

try:
while True:

pos =fin.tell( ) #storing file pointer position

stu = pickle.load(fin)

ifstu[‘Marks’] in [92,93,94]:

fin._seek(pos,0) #Place the file pointer at exact position

pickle.dump(stu,fin)

except:

fin.close() # To close the file

Q4:

5. import pickle
6. data = [‘one’,2,[3,4,5]]
7. with open(‘data2.dat’,’wb’) as f:
8. pickle .dump(data,f)

Q5:

7. import csv
8. data = [ [1,2,3] , [4,5,6] ]
9. with open(path,’w’,newline=’’) as csv_file:
10. writer = csv.writer(csv_file,delimiter=’|’)
11. for line in data:
12. writer.writerow(line)

Q6: (a) f = open(‘bfile.dat’,’wb’)

(b) f = open(‘contacts.csv’,’a+’)

(c) f = open(‘studentdata.dat’,’w+’)
Q7: Text file and binary files are extensively used in programming. In this article
we are going to point out the major difference between text file and binary file.

In text file, text, character, numbers are stored one character per byte i.e. 32667
occupies 5 bytes even though it occupies 2 bytes in memory.

In binary file data is stored in binary format and each data would occupy the
same number of bytes on disks as it occupies in memory.

In the text file, the newline character is converted to carriage-return/linefeed


before being written to the disk.

In binary file, conversion of newline to carriage-return and linefeed does not take
place.

Text files are used to store data more user friendly.

Binary files are used to store data more compactly.

In the text file, a special character whose ASCII value is 26 inserted after the
last character to mark the end of file.

In the binary file no such character is present. Files keep track of the end of
the file from the number of characters present.

Content written in text files is human readable.

Content written in binary files is not human readable and looks like encrypted
content.

Q8: Format 1:

Myfile = open(r’C:\Myfiles\Text1.txt’,’wb’)

Format 2:
Myfile = open(’C:\\Myfiles\\Text1.txt’,’wb’)

Q9: Output:

[‘fifth’,’fourth’,’third’,’Second’]

Q10: Output:

PROGRAMMING BASED QUESTIONS

4/5 MARKS QUESTIONS

Q1:

def Search():

file = open(‘CINEMA.dat’,’rb’)

try:

while True:

MULTIPLEX = pickle.load(file)

if MULTIPLEX[‘MTYPE’]==’Comedy’:

print(MULTIPLEX)

exceptEOFError:

file.close()

Q2:

import pickle

file = open("myfile.dat","wb")

while True :
dic = { }
Item_No = int(input("Enter Item no."))
Item_Name = input("Enter Item name :-")
Qty = int(input("Enter Quantity :- "))
Price = float(input("Enter price :-"))

dic[ "Item_No" ] = [ Item_No]


dic[ "Item_Name" ] = [ Item_Name ]
dic[ "Qty" ] = [ Qty ]
dic[ "Price" ] = [ Price ]
pickle.dump(dic , file )
ans = input("Do you want to quit Enter [ Y/N ] :-")
ifans == "y" or ans == "Y" :
break

file.close()

file = open("myfile.dat","rb")

while True :
try :
dic = pickle.load(file)
print( "Item No. :","\t", dic[ "Item_No" ] )
print( "Item Name :","\t", dic[ "Item_Name" ] )
print( "Quantity :","\t", dic[ "Qty" ] )
print( "Price per item :","\t",dic[ "Price" ] )
print( "Amount :", "\t" , dic[ "Qty" ] * dic[ "Price" ] )

except :
file.close()

Q3:

import csv

data = []

while True :
item_code = input("Enter item code :-")

name = input("Enter name :-")

price = input("Enter price :-")

qty = input("Enter Quantity :-")

data += [[ item_code, name, price, qty ]]

user = input("Do you want to enter more data (yes/no)")

if user == "No" or user == "no" :

break

with open("Groceries.csv","w",newline="") as f :

csv_w = csv.writer(f,delimiter=',')

csv_w.writerows(data)

Q4:

import pickle

emp = {}

found = False

fin = open('empl.dat', 'rb+')

fin.seek (0)

try:

while True :

rpos = fin.tell()

emp = pickle.load(fin)

ifemp['Empno'] == 1251 :

emp[ 'Salary'] = emp['Salary'] + 2000


fin.seek (rpos)

pickle.dump(emp, fin)

print (emp)

found = True

exceptEOFError:

if found == False:

print("Sorry, no matching record found.")]

else:

print("Record(s) successfully updated.")

fin.close()

Q5:

import csv

fh = open("Sport.csv", "w")

swriter = csv.writer (fh, delimiter = '\t')

swriter.writerow( ["Sport", "Competitions", 'Prizes won'])

ans = 'y'

i = 1

whileans == "y":

print("Record", i)

sport = input ("Sport name: ")

comp = int(input("No. of competitions participated: "))

prizes = int(input("Prizes won: "))

srec = [ sport, comp, prizes ]

swriter.writerow(srec)
i = i + 1

ans = input("Want to enter more records? (y/n).. ")

fh.close()

CASE STUDY BASED QUESTIONS

5/6 MARKS QUESTIONS

Q1:

(a) import csv


(b) with open(‘dept.csv’,newline=’’) as csvfile:
(c) data = csv.reader(csvfile,delimiter=’’)
(d) if “Mohali” in row:

print(row)

(e) import csv

defDepLocation(loacation):

with open(‘dept.csv’,newline=’’) as csvfile:

data = csv.reader(csvfile,delimiter=’’)

for row in data:

if location in row:

print(row)

loc = “Mohali”

DepLocation(loc)

Q2:

(a) with open(‘peple.csv’,’r’) as myfile:


(b) fin = csv.reader(myfile,delimiter=’\t’)
(c) for row in fin:

print(row)
(d) for row in fin:
print(row[3])
(e) 295000
610011
92055
69700

Q3:

(a) Line1: csv


(b) Line2: a
(c) Line3: reader
(d) Line4: close()
(e) Line5: Arjun 123@456
Sandhyaarjk#rjkjhk
sandeepsn72sadsdasd

Q4:

(a) #2D list – list containing lists

Studata = [[“First_name”,”Second_name”,”Marks”,”Grade”],

s1,s2,s3,s4,s5]

(b) sfile = open(‘student.csv’,’w’)


(c) with sfile:

writer = csv.writer(sfile)

(d) writer.writerows(studata)
(e) Misingfile.close() with a ‘with’ statement is not an error. This is because, the
‘with’ statement automatically closes a file when the ‘with’ statement block ends.

Q5:

(a) with open(‘Capitals.csv’,’w’) as sfile:


(b) fileWriter = csv.writer(sfile,delimiter=’\t’)
(c) fileWriter.writerow([“SNo.”,”State”,”Capital”])
(d) fileWriter.writerow([1,”Delhi”,”New Delhi”])
fileWriter.writerow([2,”Assam”,”Dispur”])
fileWriter.writerow([3,”Bihar”,”Patna”])
fileWriter.writerow([4,”M.P.”,”Bhopal”])
fileWriter.writerow([5,”U.P.”,”Lucknow”])
(e) sfile.close()

Python: Data Structure

Data Structure: Data Structure is collection values of different datatypes and


stored in a single unit. A data structure has well defined operations, behaviors
and properties. It is used to store, access and manipulate data in different
ways. (Python inbuilt structures: list, tuple, dictionary, set)

Various Data Structure


Data Structure combines various data values in single unit, but allow various
processing on group as single unit. Data structure is classified in two ways:

1. Simple Data Structure: These types of data structure stored the primitive
data type values like integer, float, character and Boolean.
Example: Linear List
(i). Numpy Array (ii). Linear Lists

2. Compound Data Structure: Compound data structure is formed by collection


of simple data structure in various ways. There are two categories of compound
data structure.
(A) Linear Data Structure: It is a single level data structure that store the
elements in a sequence.
Example:
(i) Stack (ii) Queue (iii) Linked List
(B) Non-Linear Data Structure: These are Multi level data structure and data
stored in multiple levels and linked together. Example: Tree

Operations on Data Structure


Following are the basic operations, which can perform on data structures.
1. Insertion: Addition of new data element in data structure.
2. Deletion: Remove of data element from data structure.
3. Searching: Searching of specific element from structure.
4. Traversal: Processing all data element one by one.
5. Sorting: Arranging data element of structure in either ascending or
descending order.
6. Merging: Combining data elements of two similar type of sorted structures
and form the new data structure.
Linear List / Array
Linear list or array is a collection of homogeneous data elements. Elements of
array are assemble in array in form of index. Insertion and deletion can take
place at any location in the array.
Array can be implemented using numpy array in python.

Ex. L=[2,4,6,7] Elements : 2,4,6,7 Index: 0,1,2,3


0

3
2 4 6 7
Array can be 1-D, 2-D or Multi- dimensional

Stack
Stack structure stores the list elements in such a way that LIFO (Last In First
Out) technique followed. In stack the Insertion and Deletion operation take
place at one end that is called top.

Queue
Queue data structure is works on FIFO (First In First Out) technique.
In Queue the Insertion of element take place at “rear” end where Deletion at
“front” end.
Linked List
Linked list is special type of data structure in which elements linked to one
another. Logically the first element pointing to second element and so on.
Each element is called node that has two parts.
(A) Data / Info : it store the data / element value.
(B) Pointer / Next: it makes a reference that store reference of next node.

The first node is called the head, and it’s used as the starting point for any
iteration through the list. The last node must have its next reference pointing
to None to determine the end of the list. Here’s how it looks:

Tree Structure
Tree is Multi Level data structure. It has hierarchical relationship among the
nodes (elements). Each of node has its reference pointer that points to the
node below it.

Stack Data Structure


Stack is linear structure implemented in LIFO (Last in First Out) manner where
insertions and deletions are take place at one end- TOP. It follow the following
operations..
1. POP Operation: Data can only be removed from top. That mean element
at top will remove and this is called POP operation.
2. PUSH Operation: A new data element can only be added at the top of the
stack and this is called PUSH operation.
3. Peek / Inspection: To inspect the element at the top of stack without
removing it is referred as Peek.
4. Overflow: In the static Stack, when it is already full then we can’t increase
the size of stack. When user tries to PUSH new element in already full stack
then an error occurred and this situation known as stack overflow.
5. Underflow: It is situation when one tries to POP element from an empty
stack.
Stack Application
create (), push (), pop () and display ()

def create():
global stack
stack=list()
n=int(input("How Many nodes: "))
while n>=1:
i=0
el=int(input("Enter Integer Element: "))
stack.append(el)
i+=1
n-=1
print("Stack Created")

def pop():
if(len(stack)==0):
print("stack empty")
else:
stack.pop()
print("Element deleted")

def push():
el=int(input("Enter element for new node: "))
stack.append(el)
print("Element push successfully")

def display():
print("Elements of Stack")
print("*****************")
if(len(stack)==0):
print("Stack is Empty")
else:
for el in stack:
print(el,end=" -> ")

def menu():
msg='''
**********Stack Application**************
Enter 1 for remove stack and create new stack
Enter 2 for pop element from stack
Enter 3 for push element in stack
Enter 4 for display element of stack
Enter 5 for Quit Stack Application
*****************************************'''
print(msg)
option=int(input("Your Option: "))
if(option==1):
create()
input()
menu()
elif(option==2):
pop()
input()
menu()
elif(option==3):
push()
input()
menu()
elif(option==4):
display()
input()
menu()
elif(option==5):
quit()
else:
print("Enter correct option")
menu()

menu()
SHORT ANSWER QUESTIONS

1. ___________________ is a way to represent data in memory.


a. Data Handling b. Data Structure
c. Data Dumping d. Data Collection
2. Python built-in data structures are
a. integer,float,string b. list,tuple,dictionary,sets c. math,pyplot
3. Data structure can be of two type’s namely___________
a. SImple and Compound b. SImple and Nested
c. Sequential and random d. All of the above
4. Array or linear list comes under the category of______
a. SImple Data Structure b. Compund Data Structure
c. random d. None of these
5. Compound Data structure can be ______ & _______
a. Sequential and random b. Simple & Nested c. Linear & Non
Linear
6. The examples of Linear Data Structures are
a. Stacks,Queues,Linked list b. int,float,complex c.
Operators,tokens,punctuators
7. Stacks follows____________ order
a. FIFO (First In First Out ) b. LIFO (Last In First Out) c. Random
8. Queue follows____________ order
a. FIFO (First In First Out ) b. LIFO (Last In First Out) c. Random
9. Main Operations in Stacks are called
a. Insertion and deletion b. append and insertion c. Push and Pop
10. Main Operations in Queue are called
a. Insertion and deletion b. append and insertion c. Push and Pop
11. In Stack Insertion and deletion of an element is done at single end called
________
a. Start b. Last
c. Top d. Bottom
12 In stack we cannot insert an element in between the elements that are
already inserted.
a. True b. False
13. The process of visiting each element in any Data structure is termed as
____________
a. Visiting b. Searching
c. Traversing d. Movement
14. While implementing Stack using list when we want to delete element we
must use pop function as__________
a. list.pop(pos) b. list.pop(0) c. list.pop()
15. Arranging elements of a data structure in increasing or decreasing order is
known as_________
a. Searching b. Arrangement
c. Sorting d. Indexing
16. Searching of any element in a data structure can be done in 2 ways
_________ and ________
a. Sequential and random b. linear and non linear c. linear and binary
17. _________ is an example of nonlinear data structure
a. Stack b. Queue
c. Sorting d. Tree
18. In a stack, if a user tries to remove an element from empty stack it is called
_________
a. Underflow b. Empty
c. Overflow d. Garbage Collection
19. What is the value of the postfix expression 6 3 2 4 + – *
a. 1 b. 40 c. 74 d. -18
20. Which of the following data structure is linear type?
a. Stack b. Array c. Queue d. All of the above
UNIT – II COMPUTER NETWORKS
Introduction

Computer Network is a collection of interconnected autonomous computers for


sharing of services and resources. A computer network is a system that
connects independent computers in order to share information and resources

Brief History of Network

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

Advantage of Computer Network:

 Central Storage of Data


 Sharing of Information
 Sharing of Hardware Resources
 Sharing of Software Resources
 Reliability
 Communication
 Reduced Cost

Disadvantage of Computer Network:

 Computer networks require a specific setup


 Lack of Security
 Cost of network hardware and software
 Maintenance cost of Network

Components of Data Communication:

 Message – it is the information that 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
to receiver
 Protocol – It is set of rules that governs data communication. Actually, it is
agreement between the sender and receiver regarding various communication
parameter.

Data Communication Modes:

 Simplex Mode– In this mode of communication where data transmitted in one


direction only.
It is unidirectional channel between sender and receiver.
e.g. Keyboard to CPU and CPU to Monitor.

 Half Duplex Mode – Communication is bi-directional but not same time.


 i.e. WalkieTalkie. Reading data from CD and Writing Data to CD
 It uses entire capacity of channel is utilized for each direction.
 Full Duplex Mode– Communications is bi-directional simultaneously i.e. both
sender and receiver can be send data at same time.
Ex. Read and Write data with Hard Disk.

Network Terminology

 Node- The device connected to a network.


 Client – The device that request for a service
 Server – The Device that render the services
 Client-Server - In this model, the data are stored on powerful computers called
Server that can be accessed by a much simpler computer called Client that
are connected by a network.

 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
 IP Address: Every device on network has unique identifier called IP address.
It consists of 4 bytes (IPv4) decimal number (between 0 to 255) separated
by ‘.’ (Period).
 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.
 Data – Information stored within the computer system in form of ‘0’ and ‘1’
 Signal- It is electric or electromagnetic encoding of data to be transmitted. It
can be categorized into :
 Analog Signal – that has infinitely many level of intensity over a period of
time.
 Digital Signal – that can have only a limited number of defined values.
 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.

IP Address vs MAC Address

IP Address MAC Address

It is of 4 bytes It is of 6 bytes

Represented by decimal number Represented by hexadecimal


number

It is logical address It is physical address

It is variable address It is fixed address


Switching Technique

A switched network consists of a series of interlinked nodes called switches


capable of creating temporary connections between two or more liked
devices.
There are two switching technique
(1) Circuit Switching: In circuit, switching a dedicated path is established
before sending data from sender to receiver and entire communication is
carried out the same path.
(2) Packet Switching – In packet switching in a message is broken into a
number of parts called packet which are sent independently from sender to
receiver and reassembled at the destination. Circuit Switching vs Packet
Switching

Network Devices

Modem
 It stands for modulator and demodulator
 It a computer hardware device that converts data from a digital format into a
format suitable for an analog.
 A modem transmits data by modulating one or more carrier wave signals to
encode digital information, while the receiver demodulates the signal to
recreate the original digital information
Repeater
 Repeaters are network devices that amplify or regenerate an incoming signal
before retransmitting it.
 It operate at physical layer of the OSI model.
 The repeater allows to transfer the data through large area distance

Hub

 It is a multiport device that allows multiple computers to communicate with


each other over a network.
 It is a non-intelligent network device that sends message to all ports( i.e.
Broadcast)

 Types of Hub
1. Active Hub –
o It strengthen the signal may boost noise too.
o It need electricity.
2. Passive Hub –
o It repeat/copy signals.
o It does not need electricity

Switch

 Network Switch or switch is also a network multiport device that allow


multiple computer to connect together.
 Network switch inspects the packet, determine source and destination address
and route the packet accordingly.
 It operates at Data Link Layer (layer 2) of OSI model.

Bridge
 It connects multiple network segments having same protocol
 It works at Data Link Layer (Layer 2).
 Bridge does not simply broadcast traffic from one network.
 Bridges use bridge table to send frames across network segments.
 It also improves the overall network performance.

Router

 A router is a device that connects two or more packet-switched networks or sub


networks.
 It serves two primary functions: o Managing traffic between these networks by
forwarding data packets to their intended IP addresses, and o Allowing multiple
devices to use the same Internet connection.
 It connects LANs (local area networks) and WANs (wide area networks).
 It operates on layer 3 or 4 in OSI model

Gateway

 It is simply a device or hardware that acts as a "gate" between the networks.


 It connects two networks with different transmission protocols together.
 It converts information, data or other communications from one protocol or format
to another.
 It operates on layer 5 of OSI model
RJ45

 It stands for Registered Jack.


 It is common interface to connect Twisted Pair Cable.
 It is used for Ethernet and Token Ring Network.

Ethernet Card

 It also known as NIC card.


 It enables a computer to access an Ethernet network (LAN)
 It has MAC id which gives it unique identity in the network.

Type of Network

1. PAN
 It stands for Personal Area Network.
 It is a computer network formed around a person.
 It generally consists of a computer, mobile, or personal digital assistant.
 Appliances use for PAN: cordless mice, keyboards, and Bluetooth systems.
 PAN includes mobile devices, tablet, and laptop.
2. LAN
 It is a group of computer and peripheral devices which are connected in a
limited area such as room, building & campus.
 Higher Data Speed. Lower Error Rate.
 LANs are in a narrower geographic scope (upto 1 Km).
 It is a private network.
.

3. MAN
 A Metropolitan Area Network or MAN is consisting of a computer network that
span across a city.
 It mostly covers towns and cities in a maximum 50 km range.
 The dual bus in MAN network provides support to transmit data in both
directions concurrently.
 Moderate Data Rate. Moderate Error Rate.
4. WAN
 It connect device across globe.
 It uses public network
 Internet
 BSNL
 VSNL

Network Media

1. Guided or Wired
A. Telephone (T1) cable
B. Twisted pair cable
o STP (Shielded Twisted Pair)
o UTP (Unshielded Twisted Pair)
C. Co-axial cable
D. Optical Fiber/Fibre
2. Unguided or Wireless
A. Infrared
B. Radio Wave
C. Microwave
D. Bluetooth
E. Satellite

Twisted Pair Cable


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

Twisted Pair Cable – Advantages

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

Twisted Pair Cable – 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 Advantages

 Coaxial cabling has a single copper conductor at its center, and a plastic layer
that provides insulation between the center conductor and a braided metal shield.
 Connector: BNC (Bayonet Neill-Concelman)
 Highly resistant to physical damage.
 Highly resistant to EMI.
 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.

Co-axial Cable disadvantages

 It is expensive to install.
 Cost maintenance is also high.
 Inflexible construction.
 Unsupported by newer networking standards.
 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 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.

Optical Fibre- Advantages

 Higher bandwidth
 Less signal attenuation Immune to cross-talk
 Optical fiber have long life more than 100 or above years
 Grater immune to tapping
 Resistance to corrosive material
 Long distance transmission is possible
 Immunity to electromagnetic interference

Optical Fibre-Disadvantage

 Unidirectional propagation
 High initial cost
 Optical fiber more tensile stress than copper cables
 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


 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

Topology

Physical and Logical arrangement of nodes in the network is called Network


Topology. The Key Elements to be considered to choose correct topology for your
network

 Length of the Cable Needed – longer the cable, more work is required for setup
 Cable Type- Depending on requirement of bandwidth
 Cost- Installation Cost and Complexity
 Scalability – Ease of expansion
 Robustness – Ability to recover from error

Types of Topology
Bus Ring Star Tree Mess Hybrid

Bus Topology

 In Bus Topology all the nodes are connected to single cable or backbone
 Both the end have terminators.

Advantage – Bus Topology

 It is easy to connect a device to the network.


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

Ring Topology

 In Ring Topology all the nodes are connected to each-other to form a loop.
 Each workstation is connected to two other components on either side
 It communicates with these two adjacent neighbors.
 Data is sent and received using Token.

Advantage – Ring Topology

 It is easy to connect a device to the network.


 It require less cable length
 Low setup cost
 There is no need of Hub/Switch
 Minimum collision
 Suitable for Optical Fibre Network

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

Star Topology

 In Star Topology, all the nodes are connected to a central device called
Hub/Switch.
 All communication is controlled by the central Device( Hub/Switch)
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

Tree Topology

 In Tree Topology, the devices are arranged in a tree fashion similar to the
branches of a tree.
 It multilayer architecture.

Advantages- Tree Topology

 It is a combination of bus and star topology


 It provides high scalability, as leaf nodes can add more nodes in the hierarchical
chain.
 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.

Types of Protocol

 TCP/IP
 FTP
 HTTP/HTTPS
 IMAP
 OP3
 SMTP
 PPP
 TELNET
 VoIP

TCP/IP – Transmission Control Protocol/ Internet Protocol

 It is a protocol suite consist of two protocols Transmission Control Protocol and


Internet Protocol.
 TCP ensures reliable transmission or delivery of packets on the network.
 TCP is state full protocol.
 IP is responsible for addressing of node on the network

HTTP (Hyper Text Transfer Protocol)

 It is is an application-layer protocol for transmitting hypermedia documents, such


as HTML.
 It is designed for communication between Client (Web Browser) and Web Server.
 It uses port number 80
 It is stateless protocol.

HTTPS (Secure Hyper Text Transfer Protocol)

 It is is an extension of HTTP protocol for transmitting hypermedia documents,


such as HTML securely over a network.
 It encrypts data to be sent using TLS (Transport Layer Security)/SSL (Secure
Sockets Layer).
 The default port is 443.

FTP (File Transmission Protocol)

 It is used for the transfer of computer files among hosts over TCP/IP (internet
 It allows access to directories or folders on remote computers.
 It uses client-server architecture.
 It is statefull protocol The default port is 21

Telnet (TerminalNetwork)

 It is an application protocol that allows a user to communicate with a remote


device.
 It uses port no 23

SMTP (Simple Main Transfer Protocol)

 It is used to send mail from mail client to mail server over internet
 It can send a single message to one or more recipients.
 Sending message can include text, voice, video or graphics.
 It is connection Oriented Protocol.

POP3 (Post Office Protocol)

 It provides mechanism for retrieving emails from a remote server for a mail
recipient
 POP3 downloads the email from a server to a single computer, then deletes the
email from the server.
 Default port for POP3 110 and secure port 995

IMAP (Internet Message Access Protocol)


 It is also used to retrieve mail from mail server to client over internet (TCP/IP).
 It allows access to mail from different device.
 E-mail client establishes a connection with the server every time you log in and
maintained for the whole session.
 Email will not automatically gets deleted.
 Default Port is – 143 and Secure port is 993.

VoIP (Voice over IP)

 It is also known as Internet Telephony or Internet calling.


 It allows to make voice calls using a broadband Internet connection instead of a
regular (or analog) phone line.

Advantage of VoIP

 Save a lot of money


 More than two people can communicate or speak
 Supports great audio transfer Provide conferencing facility
 More than voice (can transfer text, image, video along with voice).

Disadvantages of VoIP

 Reliable Internet connection required


 No location tracking for emergency calls

Introduction to web services

WWW:

 The World Wide Web, commonly known as the Web, is an information system
where documents and other web resources are identified by Uniform Resource
Locators, which may be interlinked by hyperlinks, and are accessible over the
Internet.
 The Web is not the same as the Internet: the Web is one of many applications
built on top of the Internet.
 Tim Berners-Lee proposed the architecture World Wide Web in 1989.
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:

 Makes web more interactive through online social media web- based forums,
communities, social networking sites.
 It is a website design and development world which aim to encourage sharing of
information and views, creativity and user interactivity between the users
 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.

Hyper Text Markup Language (HTML):

 HTML stands for Hyper Text Markup Language


 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements label pieces of content such as "this is a heading", "this is a
paragraph", "this is a link", etc.

Extensible Markup Language (XML)

 XML stands for eXtensible Markup Language.


 XML was designed to store and transport data.
 XML was designed to be both human- and machine-readable.
 XML is a markup language much like HTML
 XML was designed to be self-descriptive
 XML is a W3C Recommendation
 It simplifies data sharing It simplifies data transport
 It simplifies platform changes It simplifies data availability
 It is a little hard to understand, but XML does not DO anything.

The Difference between XML and HTML

HTML XML

It designed to display the data It is designed to carry data

Its tags are predefined Its tags user defined

It is not case sensitive It is case sensitive

It is static It is dynamic

It is Markup Language It is framework to define Markup language

Closing tags are not necessary in Closing tags are necessary in XML
HTML

Website

 Website is a group of web pages, containing text, images and all types of multi-
media files.

Web browser

 A web browser, or simply "browser," is an application used to access and view


websites. Common web browsers include Microsoft Internet Explorer, Google
Chrome, Mozilla Firefox, and Apple Safari.

Web servers:

 A web server is a computer that stores web server software and a website's
component files (e.g. HTML documents, images, CSS style sheets, and
JavaScript files).

Web hosting:
 Web hosting is an online service that enables you to publish your website or
web application on the internet. When you sign up for a hosting service, you
rent some space on a server on which you can store all the files and data
necessary for your website to work properly.

Types of Web Hosting:

1. Shared Hosting - Web server shared among customers o Reseller Hosting –


Become yourself as web host to sell others
2. Virtual Private Server – One server as multiple server for multiple websites
3. Dedicated Server- Entire web server is dedicated to same website

Domain names

 A domain name is a website's address on the Internet.


 Domain names are used in URLs to identify to which server belong a specific
webpage.
 The domain name consists of a hierarchical sequence of names (labels)
separated by periods (dots) and ending with an extension.

URL

 Uniform Resource Locator (URL) is a text string that specifies where a resource
(such as a web page, image, or video) can find on the Internet.
SHORT ANSWER QUESTIONS :

1 What is a Computer Network?

ANS A computer network is a set of interconnected computers sharing resources


located on or provided by network nodes.

2 Who is considered as the creator(s) of the Internet?

ANS Vinton Cerf and Bob Kahn

3 In which year ARPANET was formed

ANS 1969

4 Which project is considered as the foundation of the Internet?

ANS ARPANET (Advanced Research Projects Agency NETwork)

5 Write the name of the first web browser.

ANS World Wide Web created by Tim Berners Lee in


1990 NOTE: He also created HTTP and HTML

6 Which protocol became the foundation of the Internet?

ANS Transmission Control Protocol/Internet Protocol (TCP/IP)

7 List any 4 services provided by the Internet.

ANS Email, Instant-Messaging, Sharing of Devices and Directory Sharing etc.

8 What is the difference between the Internet and the World Wide Web?

ANS The Internet is a means of connecting a computer to any other computer


anywhere in the world whereas the World Wide Web is a collection of
information which is accessed via the Internet.

9 What is interspace and how is it different from the Internet?

ANS InterSpace is a client-server software program, allows multiple users to


communicate online with real-time audio, video or text chat in dynamic 3D
environments. It provides the most advanced form of communication
available on the Internet today.
InterSpace is a vision of what the Internet will become in the future.

10 Write the full form of ARPANET.

ANS Advanced Research Projects Agency NETwork.

11 Write the name of the funding agency of NSFNET.

ANS National Science Foundation, a federal agency of the USA funded NSFNET.

12 Give an example of WAN (Wide Area Network)

ANS Internet

13 Write the full form of WWW.

ANS World Wide Web

14 When was the original ARPANET (Advanced Research Projects Agency


NETwork) shut down?

ANS 1990

15 Name the types of networks based on the component roles.

ANS Client-Server Networks and Peer-to-Peer Networks

16 While transferring data on the internet, the message is divided into small
units called as____________________________

ANS Packets

17 Give one example of PAN (Personal Area Network)

ANS Computer network formed by connecting a laptop with a mobile phone’s


hotspot internet. Basically, the network formed by connecting personal
devices is called a Personal Area Network.

18 Give one example of LAN (Local Area Network)

ANS Computer network established in a school building.


19 Give one example of MAN (Metropolitan Area Network)

ANS Cable TV network in a city.

20 Name the device responsible for converting the digital signal to continuous
(analog) signal for transmission over telephone lines.

ANS Modem

21 Name the device responsible for forwarding the data packets in a computer
network.

ANS Router

22 Name the device which is required to connect a computer to any network.

ANS NIC(Network Interface Card) also known as the NIU (Network Interface
Unit), LAN Card, Ethernet Card, TAP (Terminal Access Point).

23 What is the name given to the unique address assigned to each NIC?

ANS MAC (Media Access Control) Address also called as the physical address
of a device.

24 Name the types of networks based on their geographical spread.

ANS PAN (Personal Area Network), LAN (Local Area Network), MAN
(Metropolitan Area Network) and WAN(Wide Area Network)

25 Differentiate between WWW (World Wide Web) and the Internet.

ANS WWW, also called as W3 is the collection of interlinked hypertext


documents commonly known as web pages accessed via the internet. The
internet is a global computer network formed by connecting different small
networks.

26 List different components of a computer network.

ANS Following are the components of a computer network - Workstations/Nodes,


Network Hardware such as NIC(network interface card), router, switch, hub
etc., communication channel(either wired or wireless) and softwares such as
network operating system, browsers and protocols.

27 List any four advantages of computer networks.

ANS Resource Sharing.

Cost efficient way of communication.

Collaborative user interaction.

Time Saving.

Provides better and reliable storage solutions.

28 List any four disadvantages of computer networks.

ANS Security issues may arise if proper security measures are not in place.

Productivity may decline due to ill-management of resources shared on the


network.

In case of centralised data servers, failure of the central server will serve
as the single point of failure for bringing down all the services.

In large networks, you might need to hire a specialist team to manage the
network, increasing the cost of network management.

Despite regular updates of antivirus softwares, transmission and spread of


malicious softwares and files is quite rampant in those systems which are
frequently connected to networks.

29 What is baud rate?

ANS It is a measure of the speed at which the data is being transferred in a


communication channel. The rate indicates the number of electrical
oscillations per second that occurs within a data transmission. The higher
the baud rate, the more bits per second that are transferred.

30 What are the components used in communication?

ANS Sender, receiver, message, protocol and transmission media


31 What is a Communication Channel?

ANS It is a medium through which we can send a message to its intended


audience

32 What do you mean by a Protocol?

ANS It is a set of rules or procedures for transmitting data between electronic


devices.

33 What is the full form of IP?

ANS Internet Protocol

34 How many bits are used in an IPv4 address?

ANS 32 bits

35 How many bits are used in an IPv6 address?

ANS 128 bits

36 Which Protocol of TCP/IP uses IP Address?

ANS Internet Protocol (IP)

37 What is the Bandwidth of a channel?

ANS It is the difference between upper and lower frequency limits of the analog
signal or the maximum amount of information that the channel can carry.

38 In which type of switching technique the resources are reserved for the
duration of the data transfer process?

ANS Circuit Switching

39 In which type of switching technique the data is divided into smaller units
before transmission?

ANS Packet Switching

40 List the types of communication media with examples of each.


ANS 1. Wired Communication Media - Twisted Pair Cable, Coaxial Cable, Optical
Fibre Cable

2.Wireless Communication Media - Microwave, Radio Waves, Infrared,


Satellite Communication

41 Which of the following wireless communication media is/are


omnidirectional: Microwaves, Radio waves, Infrared waves?

ANS Radio waves

42 What is an IP (logical) address?

ANS An IP address is a unique address assigned to each device connected to a


computer network.

43 Give an example of an IPv4 address.

ANS An IPv4 address is a 32-bit address expressed in decimal notation as


x.x.x.x where each x is an integer between 0 and 255. Example:
192.0.2.188

44 Which of the following communication media require(s) line-of-sight for


communication? Microwave, Radio waves, Infrared

ANS Microwaves, Infrared

45 Which of the following communication media can penetrate solid


objects? Microwave, Radio waves, Infrared

ANS Radio waves

46 What is transmission media?

ANS Transmission media is a communication channel that carries the information


from the sender to the receiver and vice versa.

47 Write name of guided and unguided media.


ANS Guided Media : Twisted pair, coaxial cable , Fiber
Optic Cable Unguided Media : Radio waves, Micro
waves, Infrared waves

48 Which guided/wired transmission media is fastest and expensive?

ANS Fiber optics

49 Why fiber optic transmission media is faster as compared to other wired


transmission media?

ANS Fiber optic transmits data as light, while other wired media transfer data as
electricity. Light travels exponentially faster than electricity so fiber optic
transmission media is faster.

50 Out of the following, which is the fastest wired medium of Transmission


medium

Telephone Cable , Twisted Pair Cable , Optical Fibre Cable

ANS Optical Fibre Cable

51 Out of the following, identified the unguided communication


media ? Infrared, Coaxial Cable, Optical Fibre, Microwave,
Radio waves

ANS Infrared, Microwave, Radio waves

52 Write the two characteristics of Wi-fi

ANS Convenient and anywhere technology.

Support Secure wireless communication

53 For difficult terrain , which unguided media would you suggest ?

ANS Microwave and Radio Wave

54 Arrange the following communication media in the ascending order of their


transmission speed. Twisted Pair Cable ,Telephone Cable , Optical Fibre
Cable
ANS Telephone Cable , Twisted Pair Cable , Optical Fibre Cable

55 Write the one advantage and one disadvantage of Optical fibre cable

ANS Advantage- Its high speed guided media .

Disadvantage- It is an expensive communication media

56 Rearrange the following terms in increasing order of data


transfer rates Gbps ,Mbps, Tbps, Kbps,Bps

ANS Bps, Kbps, Mbps, Gbps, Tbps

57 What is a network device? Give some examples of network devices.

ANS Hardware devices that are used to connect computers, printers, fax
machines and other electronic devices to a network are called network
devices.
E.g. Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway,
WIFI card.

58 Define repeaters with its two types.

ANS Repeaters are used to amplify the signals, when they are transported over
a long distance.

Repeaters are of two types

(i) Amplifier It amplifies or boosts the incoming signals. So, it amplifies


both the signal and any concurrent noise.
(ii) Signal repeater It only amplifies the signal and filters out the noise
signals. So, we get only the clear signal at the receiver end.
Repeaters may be included after every 100mtrs (approx) distance.

59 Expand the following i. MODEM ii. RJ45

ANS i. MODEM -
MOdulatorDEModulator ii. RJ45
- Registered Jack-45

60 Mention the appropriate networking device for following conditions.


(i) It is a hardware device which is used to amplify the signals when
they are transported over a long distance.
(ii) It is a device that converts digital signal to analog signal and vice
versa

ANS i. Repeater ii. MODEM

61 Write full form of WiFi.

ANS WiFi - Wireless Fidelity

62 Explain Voice over Internet Protocol (VoIP)

ANS It is a technology that allows us to make voice calls using an Internet


connection instead of a regular (or analog) phone line by converting voice
into a digital signal that travels over the Internet.

63 What is the use of TCP/IP Protocol?

ANS It is a suite of communication protocols used to interconnect network


devices on the internet. The entire TCP and IP suite is commonly referred
to as TCP/IP in which TCP and IP are the two main protocols, though
others are included.

64 Write the full form of HTTP, FTP.

ANS HTTP - HyperText Transfer Protocol FTP - File Transfer


Protocol

65 Write the full form of PPP, SMTP.

ANS PPP - Point to Point Protocol SMTP -


Simple Mail Transfer Protocol

66 Write the full form of TCP/IP, POP3.

ANS TCP/IP - Transmission Control Protocol/Internet Protocol POP3 -


Post Office Protocol Version 3

67 Write the full form of HTTPS, VoIP.


ANS HTTPS - HyperText Transfer Protocol Secure VoIP -
Voice Over Internet Protocol

68 Write the full form of XML and HTML.

ANS XML - Extensible Markup Language HTML -


HyperText Markup Language

69 Write the full form of WLL and IMAP.

ANS WLL - Wireless local loop


IMAP - Internet Message Access Protocol

70 Write the full form of CDMA and GSM.

ANS CDMA - Code Division Multiple Access GSM - Global


System for Mobile Communication

71 Write the full form of LTE and GPRS.

ANS LTE - Long Term Evolution GPRS -


General Packet Radio Service

72 Name the softwares that uses the TELNET protocol?

ANS TELNET, AnyDesk, Team Viewer

73 What type of content can be transferred using the HTTP protocol?

ANS Text, images, audio, video and other multimedia files can be transferred
over the web using the HTTP protocol

74 Explain the working of the HTTP protocol in brief.

ANS HyperText Transfer Protocol is a stateless protocol which works on the


request-response model i.e. it gives the users a way to interact with the
resources such as HTML files by transmitting hypertext messages between
clients and servers. HTTP clients generally use TCP (Transmission Control
Protocol) connections to communicate with the servers.

75 Explain the 3-way handshake process of TCP protocol.


ANS TCP protocol uses three-way handshake in which the sender first sends the
RTS (Request to send) frame
After receipt of RTS, the receiver sends the CTS (Clear to send) frame

On receipt of CTS, the sender again sends the ACK (Acknowledgement)


which signifies the successful receipt of the CTS frame.

76 Which out of the following is/are connection-oriented


protocol(s)? TCP, IP, HTTP

ANS TCP (Transmission Control Protocol)

77 Which out of the following is/are connectionless (or


stateless) protocol(s)? TCP, IP, HTTP

ANS IP(Internet Protocol), HTTP (HyperText Transfer Control Protocol)

78 Write the port numbers used by the following


protocols: HTTP, FTP, SMTP, POP3, HTTPS,
TELNET, VoIP

ANS HTTP - Port No. 80 FTP - Port No. 20 for


commands and Port no. 21 for data

SMTP - Port No. 25 POP3 - Port No. 110

HTTPS - Port No. 443


TELNET - Port No. 23 VoIP -Port No.
5060

79 Ram wants to have a meeting with his team-mates where they can see
each other and discuss the new project they have been assigned by the
management. Which protocol would be used in this communication?

ANS H.323 and session initiation protocol (SIP)

80 Tejas wants to download all his emails on his ipad and read them
whenever he is free. Which protocol would be used?

ANS POP3
81 Rani needs to download all the study material regarding her favourite
subject from a remote server. Which protocol would she use?

ANS FTP (File Transfer Protocol)

82 Aman works for an IT company which provides custom-application


softwares. One of his clients does not know how to install one such
software on his computer. Which protocol would Aman use to assist the
client for remote installation of a particular application software?

ANS TELNET (for remote access)

83 Write the name of the protocol used when-

You send an email to another user


You read your email

ANS SMTP (Simple Mail transfer protocol) POP3


(Post Office Protocol Version 3)

84 Dev wants to search for information about esteemed engineering colleges in


India. He opens his web browser and types the phrase “Best engineering
colleges in India” into the Google Search box.

He gets a list of search results in his web browser. Which protocol was
used in this task?

ANS HTTPS (HyperText Transfer Protocol Secure)

85 What is a web service?

ANS A web service is a set of open protocols and standards that allow data to
be exchanged between different applications or systems. A client invokes a
web service by submitting an XML request, which the service responds with
an XML response.

86 What is the World Wide Web?

ANS The World Wide Web, commonly known as the Web, is an information
system where documents and other web resources are identified by Uniform
Resource Locators, which may be interlinked by hyperlinks, and are
accessible over the Internet.

87 What is a Cookie?

ANS Cookies are text files with small pieces of data like a username and
password that are used to identify your computer as you use a computer
network.

88 What is HTML? Explain its tags.

ANS The HyperText Markup Language, or HTML is the standard markup


language that is used to structure a web page and its content.
HTML tags are like keywords which define how a web browser will format
and display the content. These contain three main parts; opening tag,
content and closing tag but some HTML tags are unclosed tags. Example,
<html>, <p>, <h1> etc.

89 What is the Domain Name Server (DNS)?

ANS Domain Name Server, translates human readable domain names (for
example, www.amazon.com) to its corresponding machine readable IP
addresses (for example, 192.0.2.44).
90 What is a website?

ANS It is a set of related web pages located under a single domain name,
typically produced by a single person or an organisation.

91 What is a Web Page and also explain the concept of Index web-page?

ANS A web-page is a hypertext document provided by a website and displayed


to a user in a web browser.
Index page is the first page of a website that contains links to other parts
of the website

92 What is Web Hosting? List any two Web Hosts Service providers.

ANS Web hosting is an online service that allows customers to publish their
website onto the internet. Web host is responsible for making sure that the
website is up and running 24x7. It is also a host's job to prevent any
security breaches and store all website related files, assets and databases
onto the server.

Example, IBM, Amazon Web Services (AWS), Bluehost, HostGator and


Hostinger etc.

93 What is the difference between WWW and W3C?

ANS The World Wide Web Consortium (W3C) is the main international standards
organisation which develops standards and protocols/guidelines to ensure
long-term growth for the World Wide Web; Led by Web inventor and
Director Tim Berners-Lee and CEO Jeffrey Jaffe.

The World Wide Web, also called the Web, is an information space where
documents and other web resources are identified by Uniform Resource
Locator, interlinked by hypertext links, and accessible via the Internet.

94 Write the full form of URL

ANS Uniform Resource Locator

95 Identify the following from the URL :


https://www.sample.com/cs_books.html Type of protocol being
used

Name of the server on the Internet

Domain Indicator

Name of the resource being accessed

ANS HTTPS

Server Name -www.sample.com

Domain Indicator - com

Name of resource being accessed - cs_books.html

96 Give examples of Web browsers. (any two)

ANS Google Chrome, Mozilla Firefox, Safari, Microsoft Internet Explorer, Microsoft
Edge, Opera etc.
97 What is a web server?

ANS It is a computer that serves web pages as and when they are requested
by clients.

98 Give examples of web servers. (Any two)

ANS Apache HTTP Server, Microsoft IIS (Internet Information Services) Server,
Apache Tomcat, NGINX

99 Give examples of DNS servers. (Any two)

ANS Google, Quad9, OpenDNS, Cloudflare, Alternate DNS

100 Give examples of search engines.

ANS Google, Bing, Yahoo. DuckDuckGo

CASE BASED STUDY QUESTIONS : 4/5 MARKS

Q1.PVS Computers decided to open a new office at Ernakulum, the office


consist of Five Buildingsandeach contains number of computers. The details
are shown below.
Computers in each building are networked but buildings are not
networked so far. The Company hasnow decided to connect building
also.
(i) Suggest a cable layout for connecting the buildings
(ii) Do you think anywhere Repeaters required in the campus? Why
(iii) The company wants to link this office to their head office at Delhi
(a) Which type of transmission medium is appropriate for such a
link?
(b) What type of network would this connection result into?
(iv) Where server is to be installed? Why?
(v) Suggest the wired Transmission Media used to connect all
buildings efficiently.
Ans:-
(i) Any efficient layout with shortest Wire length
(ii) Between 3 and 4 due to larger distance
(iii) (a) Wireless (b) WAN
(iv) Building-3 due to maximum no of Computers
(v) Co- axial cable or fiber optics

Q2. Riana Medicos Centre has set up its new centre in Dubai. It has four
buildings as shown in the diagram given below:
As a network expert, provide the best possible answer to the following
queries:
(i) Suggest the type of network established between the buildings.
(ii) Suggest the most suitable place (i.e., building) to house the server
of this organization.
(iii) Suggest the placement of the following devices with justification:
Repeater, Switch
(iv) Suggest a system (hardware/software) to prevent unauthorized
access to or from the network.

Ans.
(i) LAN (Local Area Network)
(ii) Research Lab as it has the maximum number of computers.
(iii) (a) Repeater: It should be placed between Accounts and
Packaging Unit, Accounts to Research Lab, Store to Research Lab
and Accounts to Packaging Unit.
(b) Switch should be placed in each of the buildings for better
traffic management.
(iv) Firewall.

Q.3 Knowledge Supplement Organization has set up its new center at


Mangalore for its office and web based activities. It has 4 blocks of
buildings as shown in the diagram below:
(A) Suggest a cable layout of connections between the blocks.
(B) Suggest the most suitable block to house the server of this
organisation with a suitable reason
(C) Suggest the placement of the following devices with justification
(i) Repeater (ii) Hub/Switch
(D) The organization is planning to link its front office situated in the city
in a hilly region where cable connection is not feasible, suggest an
economic way to connect it with reasonably high speed?

Answer: (A) Any of the following option


(B). The most suitable place / block to house the server of this organization
would be Block C, as this block contains the maximum number of
computers, thus decreasing the cabling cost for most of the computers
as well as increasing the efficiency of the maximum computers in the
network.
(C) For Layout 1, since the cabling distance between Blocks A and C, and
that between B and C are quite large, so a repeater each, would
ideally be needed along their path to avoid loss of signals during the
course of data flow in these routes For layout 2, since the distance
between Blocks A and C is large so a repeater would ideally be placed
in between this path
(D) The most economical way to connect it with a reasonable high speed
would be to use radio wave transmission, as they are easy to install,
can travel long distances, and penetrate buildings easily, so they are
widely used for communication, both indoors and outdoors.

Q.4 Ravya Industries has set up its new center at Kaka Nagar for its office
and web based activities. The company compound has 4 buildings as
shown in the diagram below:
(A) Suggest a cable layout of connections between the buildings.
(B) Suggest the most suitable place (i.e. building) to house the server of
this organization with a suitable reason.
(C) Suggest the placement of the following devices with justification:
(i) Internet Connecting Device/Modem (ii) Switch
(D) The organization is planning to link its sale counter situated in
various parts of the same city, which type of network out of LAN,
MAN or WAN will be formed? Justify your answer.

Answer: (A)
(B). The most suitable place (i.e. building) to house the server is Raj
Building, as this block contains the maximum number of computers, thus
decreasing the cabling cost for most of the computers as well as
increasing the efficiency of the maximum computers in the network.
(C) (i) Raj Building
(ii)In both the layouts, a hub/switch each would be needed in all the
buildings, to interconnect the group of cables from the different
computers in each block
(D) The type of network that shall be formed to link the sale counters
situated in various parts of the same city would be a MAN, because
MAN (Metropolitan Area Networks) are the networks that link computer
facilities within a city.
TOPIC: Unit-3 (Database Management Database Concepts)

Introduction
Database: A database is defined as an organized collection of data about an object
or entity. It also allows us to manage records easily by facilitating entering, accessing
and analysing the data easily. It consists of various tables of different but related/
unrelated entities.

Relation/Tables: A collection of logically related records for storing the data/


information pertaining to an entity is called a table/ relation. For example: A database
named “School” may contain tables like “Students”, “Teachers” etc.

Records: Each table consists of certain records which describe that particular entity.
For example: A “student” table may contain record like “Admission_number”,
“Student_name”, “Father_name” etc.

Fields: A field is a set of characters which are used to represent a particular record
of a particular table. For example, in the students record defined above,
“Admission_number” is a particular field.

Data/Character: Smallest unit of database system


Database

Tables

Records

Fields

Data

Need for DBMS


1. Reduces data redundancy

Reduces data inconsistencyIncreases competency


2. Saves time
3. Ensures security of the data
4. Easy to input, access or update data

Relational Database Model


A relational database model is the one which stores/ manages the data which are
logically related to each other in the form of tables containing rows and columns.
Each row in the table represents a certain record whereas a particular column in
the table represents an attribute of the entity.

Important terminologies in RDBMS:


Attribute: In a relational database model, each table has certain columns which
define a particular characteristic of each record/tuple in the table. For example: a
table/relation “Students” may contain a column for storing “father_name” of the
students. Here, “father_name” is an attribute defining that particular column for all
the students whose data is stored in the table.

Tuple: In a relational database model, each row of the table defines a particular
tuple. Therefore, a tuple defines the complete information of a particular record or
instance of the entity.

Domain: In a relational database model, domain is defined as the set of all


possible values that may be contained in an attribute. For example: a column like
“Age” may contain only Integer values.

Cardinality: The total number of records/tuples/rows in the table.

Degree: The total number of attributes/columns in the table.

Keys: In a table, there is at least one such column/attribute (or combination of


several attributes) which uniquely identify each and every record/ tuple in the table.
For example: In a “Students” table, “Admission_number” may serve as a key.

There are different types of keys in RDBMS:


1. Primary Key: A primary key is an attribute or a group of attributes which can
uniquely identify each record/ tuple in the table
2. Candidate Key: All sets of possible attributes/ group of attributes capable of
becoming a primary key
3. Alternate Key: A candidate key which is not used as a primary key
4. Foreign key: It is a non-key attribute referencing the primary key of another table

Structures Query Language (SQL)


SQL is a standard language which creates an interface between the user and the
database and thus facilitates easy and robust access and manipulation of the
databases. MySQL is an open-source and freely available RDBMS which allows
us to create tables, alter tables, delete tables and manage our records in these
tables.

Advantages of SQL:
1. Portable
2. No coding required
3. Easy to use
4. Compatible
5. Case insensitive

Data Definition Language (DDL)


The types of SQL commands which are used to define/ alter the structure of the
database constitute DDL commands. For example: CREATE, USE, ALTER, DROP,
etc.
CREATE: to create a table
USE: to select and opening the database for using it
ALTER: to modify the structure of table
DROP: to delete a table altogether

Data Manipulation Language (DML)


The types of SQL commands which are used to access/ manipulate the data of
the database constitute DML commands. For example: INSERT, DELETE, UPDATE
etc.
INSERT: For inserting a row in the existing table
DELETE: For deleting particular rows from the existing table, but the table still
exists
UPDATE: For updating or changing data in the existing table

Data Types
CHAR(n): This data type is used to store characters of fixed length ‘n’. A maximum
of 254 characters can be stored in a CHAR(n) data type. The values for this data
type have to be enclosed in single or double inverted quotation marks.

VARCHAR(n): This data type is used to store alphanumeric values of variable


lengths. The value “n” determines the maximum length a value can take. The
values for this data type have to be enclosed in single or double inverted quotation
marks.

INT: For storing positive or negative integer values. The values can range from -
2147483648 to 2147483647.

FLOAT: Used to storing numbers with decimal points. Each float occupies 4 bytes.

DATE: Used for storing dates in the table. For storing a date, the format has to
be ‘yyyy/mm/dd’. The DATE values can be compared with each other and have
to be enclosed in single quotation mark only.

Constraints
These are certain set of rules used to apply data validations. They ensure reliability,
correctness and accuracy in the data being stored in the table. These are not
mandatory to define in a table.
Some commonly used Constraints are:
NOT NULL: When this constraint is applied to a column, that particular column
can never have a NULL value
UNIQUE: When this constraint is applied to a column, the each value in that
particular column shall have unique/ distinct value
PRIMARY KEY: A primary key is an attribute which can uniquely identify each
record/ tuple in the table
SQL Commands

1. DDL Commands:
a. CREATE: Used to create a database in RDBMS or tables in a database
Examples:
CREATE DATABASE restaurant;

CREATE TABLE student(


admno INTEGER PRIMARY KEY,
sname VARCHAR(25),
fname VARCHAR(25),
mname VARCHAR(25)
);
b. USE: Opens a database for using it
Example:USE school;
c. SHOW: Used to show all the available databases in RDBMS or available
tables in the database
Examples:
SHOW databases;
SHOW tables;
d. DROP: For removing a database/ table
Example: DROP DATABASE school; or DROP TABLE student;
e. DESC: For viewing a table structure along with names of columns, data
types and constraints.
Example: DESCRIBE <tablename>; or DESC <tablename>;
f. ALTER: Used to modify the structure of a table by modifying its columns
by performing following functions:
- adding a column -->Syntax: ALTER TABLE <table-name> ADD (<column-
name><data-type><default-data>);
- rename a column
- change data type or size of column
- remove a column --> Syntax: ALTER TABLE <table-name>

2. DML commands:
a. INSERT: Used to insert a new record/row/tuple in a table
Syntax: INSERT INTO <table-name> VALUES (value1, value2, value3 ...);
Examples:
 INSERT INTO student VALUES(1,”Mohit”,”Mahesh”,”M”);
 INSERT INTO student(admno, name, fname, gender)
VALUES(1,”Mohit”, “Mahesh”, “M”); --> This is the query for inserting
values in specified columns
b. DELETE: Used to delete rows from the table
Syntax: DELETE FROM <table-name> WHERE <condition>;
Example: DELETE FROM student WHERE sname LIKE “%f”;
c. SELECT:Used to select a subset of rows or columns from one or more
tables stored in the database.It can perform selection as well as projection.
Syntax:
For Projection: SELECT <column-name-1>, <column-name-2>, <column-
name-3>,... FROM <table-name>;
For Selection:SELECT <column-name-1>, <column-name-2>, <column-name-
3>,... FROM <table-name> WHERE <condition>;
Example: SELECT * FROM student WHERE Gender = “F”;
d. UPDATE: Used to update/modify the existing records in the table.
Syntax: UPDATE tablename SET column1 = value1WHERE condition;
Example: UPDATE student SET sname = “Mohan” WHERE admno = ‘9822’;

SQL Operators
In a SQL query, while using SELECT command along with WHERE condition, the
condition in the query may contain any of the following 4 operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators

Arithmetic Operators: Used in arithmetic and mathematical calculations and


expressions. Examples of operator are: +, -, /, *, %, **
Example: SELECT admno, sname, age+10 FROM student;

Relational Operators:Used in conditionalexpressions, which is usually a


mathematical symbol used to compare two values. They are generally used with
a WHERE clause. Examples of operator are: =, <, <=, >, >=, <>, !=
Example: SELECT * FROM student WHERE subject <> “Hindi”;

Logical Operators: These are the operators used to combine multiple conditions.
Examples of operator are: AND, OR, NOT
Example: SELECT * FROM student WHERE marks < 70 AND Gender = “F”;

Aliases
These are used to give a temporary/ alternative name to a database table or a
column. These are generally used when there are more than two tables involved
in a query or column names/table names are big or not very readable.
Syntax: SELECT <column-1>, <column-2>, ... FROM <table-name> as <alias-
name> WHERE <condition>;
Example: SELECT 22/7 AS Pi;
Output:
Pi

3.1429

Distinct clause
This clause is used with a SELECT clause to return only distinct values of
column(s) from the table.
Syntax:SELECT DISTINCT <column-1>, <column-2>, ... FROM student;
Example:SELECT DISTINCT Country FROM Customers;

WHERE clause
This clause is used to filter the records and extract only those rows/records/tuples
which fulfill a specified condition/predicate.
Syntax: SELECT column1, column2, ... FROM table1,table2,... WHERE condition;
Example: SELECT * FROM student WHERE Gender = “M”;

IN operator
The IN operator is a membership operator that allows us to specify multiple values
in a WHERE clause. It is a shorthand for multiple OR conditions.
Syntax: SELECT column1, column2,... FROM table1, table2, ... WHERE
column_name IN (value1, value2,..);
Example: SELECT * FROM student WHERE State IN (“Delhi”, “Mumbai”, “Kolkata”);

BETWEEN operator
The BETWEEN operator is used when we want to select values within a range
from a table. The values can be text, numbers or dates.
Note: Beginning and Ending values are also included in the returned rows
Syntax: SELECT column_name(s) FROM table(s) WHERE column_name
BETWEEN value1 AND value2;
Example: SELECT * FROM employees WHERE Salary BETWEEN 50000 AND
150000;

ORDER BY
This keyword is used to sort the result in ascending or descending order. By
default, the keyword arranges the returned values in the ascending order. For
arranging in descending order, specifically DESC keyword has to be used.
Syntax: SELECT column_name(s) FROM table(s) ORDER BY column1, column2,
... ASC/DESC;
Example: SELECT * FROM customers ORDER BY firstname;
NULL
Null value is used when a field does not have any value. If in a field which is
NULLABLE, while inserting a row, no value is inserted, then in such a case the
value in the field becomes NULL. It is different from 0 (Zero).
We cannot check a value for NULL using relational operators. For checking a field
for a NULL value, we use IS NULL and IS NOT NULL operartors.
Syntax:
 SELECT column_names FROM table_name WHERE column_name IS NULL;
 SELECT column_names FROM table_name WHERE column_name IS NOT NULL;

LIKE operator
The LIKE operator is used in a WHERE clause to search for a specified pattern
in a column. There are 2 wildcards often used with LIKE operaor:
 % --> Represents zero, one or multiple characters
 _ --> The underscore sign represents exactly a single character
Syntax: SELECT column(s) FROM table(s) WHERE column_name LIKE pattern;
Example: SELECT * FROM student WHERE sname LIKE “a_”;
This query returns all the rows from the table student whose second last character
in column sname is ‘a’

Aggregate Functions
Aggregate functions allow us to apply SELECT query on a group of records rather
than the entire table. These are multi-row functions which work on multiple values.
Aggregate functions in SQL:
 MIN(): Used to find the minimum value among the given set of values of any
column in a table
Example: SELECT MIN(Salary) FROM employee;
 MAX(): Used to find the maximum value among the given set of values of any
column in a table
Example: SELECT MAX(Salary) FROM employee;
 SUM(): Used to find the total sum of a numeric column in a table
Example: SELECT SUM(Salary) FROM employee;
 AVG(): Used to find the average of a numeric column in a table
Example: SELECT AVG(Salary) FROM employee;
 COUNT(): Returns the count or number of rows which match or satisfy a particular
criterion
Example: SELECT COUNT(*) FROM employee;

GROUP BY
This clause is used in a SELECT statement to collect data across multiple records
and group them by one or more columns of the table. This clause is generally
used with aggregate functions like MIN(), MAX(), SUM() etc.
Syntax:SELECT column_name(s) FROM table(s) WHERE condition GROUP BY
column(s) ORDER BY column(s);
Example: SELECT COUNT (*), subject FROM student GROUP BY subject;

HAVING clause
This clause is used along with the GROUP BY clause in SQL. Whereas WHERE
clause cannot be used with aggregate functions, HAVING clause can be used. It
is used to filter a record by specifying a condition which a GROUP BY returns.
Syntax: SELECT column(s) FROM table(s) WHERE condition GROUP BY
column(s) HAVING condition ORDER BY column(s);
Example: SELECT COUNT (*), subject FROM student GROUP BY subject HAVING
AVG(marks)>70;

JOINS
These are used to combine rows from two or more tables of the database, based
upon a related common column between them.
The types of SQL joins are:
1. Cartesian product
2. Equi join
3. Natural join

Cartesian product:
This is also known as cross-join or cross-product. It is denoted by (x). If the
cardinality of table1 is m and table2 is n, then the cardinality of the Cartesian
product of table1 x table2 will be (mxn).
Syntax: SELECT * FROM table1, table2;
Example: SELECT Name, Bookname FROM students, library;

Equi Join:
The equi join uses the equal (=) sign as comparison operator for establishing a
relationship between two or more tables based upon a common field i.e. a primary
key or foreign key.
Syntax: SELECT column(s) FROM table(s) WHERE table1.primarycolumn =
table2.foreigncolumn;
Example: SELECT sname, class FROM student, library WHERE student.admno =
library.admno;

Natural join:
When only one column exists as a common column between the joining tables,
such a join is termed as Natural Join. It is similar to an Equi join except that there
are no duplicate columns in Natural join which may appear in Equi join.
Syntax: SELECT * FROM table1 NATURAL JOIN table2;
Example: SELECT * FROM student NATURAL JOIN fees;

Interface of Python with an SQL database

For accessing a SQL database in Python, we need to import “mysql.connector”


module in our python module. The command for importing is:
import mysql.connector
Then, we need to establish a connection between our Python program and the
database that we wish to use. For this, we use connect () function inside the
mysql.connector module which returns a connection object.
The program for establishing connection is:
import mysql. connector

connectionobj = mysql. connector. connect (host= “localhost”, user= “root”, passwd


= “root”, database = “school”)

The next step is to create a cursor object for the connection that has been
established till now. This cursor object allows us to execute SQL queries on the
database from Python program. After the query is executed, the results record(s)
are returned from SQL over the connection in one go. Cursor object stores all the
data as a temporary container of the returned data and allows us to traverse it
for further processing in our program. We can use functions like fetchone () and
fetchall () here.
import mysql. connector

connectionobj = mysql. connector. connect (host= “localhost”, user= “root”, passwd


= “root”, database = “school”)

cursorobj = connectionobj. cursor ()

Now that we have created the cursor object, for executing any query we need to
create a variable named say “query” in which we write the query as we write in
SQL Command Line. And then cursor object has a function execute() which
executes the query that we wish to execute on the database.

For performing INSERT operation on database using Python:


import mysql.connector

connectionobj = mysql.connector.connect (host= “localhost”, user= “root”, passwd


= “root”, database = “school”)
cursorobj = connectionobj.cursor()

query = “INSERT INTO student VALUES(1,’Mohit’,’Mahesh’,’M’);”

cursorobj.execute(query)

connectionobj.commit()

For performing UPDATE operation on database using Python:


import mysql.connector

connectionobj = mysql.connector.connect (host= “localhost”, user= “root”, passwd


= “root”, database = “school”)

cursorobj = connectionobj.cursor()

query = “UPDATE student SET sname = ‘Mohan’ WHERE admno = ‘9822’;”

cursorobj.execute(query)

connectionobj.commit()

For performing DELETE operation on database using Python:


import mysql.connector

connectionobj = mysql.connector.connect (host= “localhost”, user= “root”, passwd


= “root”, database = “school”)

cursorobj = connectionobj.cursor()

query = “DELETE FROM student WHERE sname LIKE ‘%f”;”

cursorobj.execute(query)
connectionobj.commit()

For displaying the records fetched from SQL using queries, we have two functions:
1. fetchall(): It fetches all the rows of the query result. It returns all the rows as a
list of tuples.
2. fetchone(): It fetches a single record or None if no more rows are available

To display all the records of a table using Python:


import mysql.connector

connectionobj = mysql.connector.connect (host= “localhost”, user= “root”, passwd


= “root”, database = “school”)

cursorobj = connectionobj.cursor()

query = “SELECT * FROM student WHERE Gender = ‘F’;”

cursorobj.execute(query)

records = cursorobj.fetchall()

for x in records:

print(x)

To display one record of a table using Python:


import mysql.connector

connectionobj = mysql.connector.connect (host= “localhost”, user= “root”, passwd


= “root”, database = “school”)

cursorobj = connectionobj.cursor()

query = “SELECT * FROM student WHERE Gender = ‘F’;”

cursorobj.execute(query)

records = cursorobj.fetchone()
for x in records:

print(x)

Rowcount: It returns the number of rows returned by SELECT or number of rows


affected by DML commands.
Syntax: count = cursorobj.rowcount

SOLVED QUESTIONS
Q1. Sahil wants to delete the column coachname from a table SPORTS.Which
command will he use from the following?
A. DELETE Coachname FROM SPORTS;
B. ALTER Coachname FROM SPORTS;
C. ALTER TABLE SPORTS DROP Coachname;
D. DELETE Coachname FROM SPORTS;

ANS: C

Q2. A row of relation generally referred to as …………………….. and column of a relation


is …….…………
A. Domain & Attribute
B. Attribute & Domain
C. Tuple & Attribute
D. Attribute & Tuple

ANS: C

Q3. A relation has 45 tuples & 5 attributes, what will be the Degree & Cardinality
of that relation?
A. Degree 5, Cardinality 45
B. Degree 45, Cardinality 5
C. Degree 50, Cardinality 45
D. Degree 50, Cardinality 225

ANS: A

Q4. In existing table, ALTER TABLE statement is used to


A. Add columns
B. Add constraints
C. Delete columns
D. All of the above

ANS: D

Q5. Assertion (A) : The CREATE TABLE command is used is to create a new
SQL database.
Reason (R) : DESCRIBE command to show the structure of our table, such as
column names, constraints on column names etc.
A. Both A and R are true and R is the correct explanation of A.
B. Both A and R are true but R is not the correct explanation of A.
C. A is true but R is false.
D. A is false but R is true.

ANS: D
Q6. A Stationary Store is considering to maintain their inventory using SQL to
store the data. As a database administer, Rajan has decided that:
• Name of the database – STATIONARY_STORE
• Name of the table - INVENTORY
• The attributes of INVENTORY are as follows:
ItemNo - numeric
ItemName - character of size 20
Scode - numeric
Quantity – numeric
Table: INVENTORY
Table : INVENTORY

Ite ItemName S Q

mN c ua

o o nti

d ty

20 Notebook 2 60

05 Classic 3

20 Ball Pen 0.25 2 50

03 2

20 Get Pen 2 15

02 Premium 1 0

20 Get Pen 2 25

06 Classic 1 0

20 Eraser Small 2 22

01 2 0
20 Eraser Big 2 11

04 2 0

20 Ball Pen 0.5 2 18

09 1 0

1. Identify the attribute best suitable to be declared as a primary key.


ANS: ItemNo

2. Write the degree and cardinality of the table INVENTORY.


Ans. Degree: 4 Cardinality: 7

3. What will be the correct SQL query to insert the following data into the attributes
ItemNo, ItemNameand SCode respectively in the given table INVENTORY (ItemNo
= 2010, ItemName = "Sharpener" and Scode = 25)
Ans. INSERT INTO inventory (ItemNo,ltemName.Scode) VALUES(2010,
“Sharpener”,25);

4. Rajan want to remove the table INVENTORY from the database


STATIONARY_STORE, Which command should he use?
Ans. DROP TABLE inventory;

Q7. Differentiate between WHERE and HAVING clauses?


Ans. WHERE clause is used to select particular rows that satisfy a condition
whereas HAVING clause is used to place condition on an individual group formed
with GROUP BY clause.

Q8. Differentiate between DELETE and DROP commands?


Ans. DROP command is used to delete a table structure along with all the records
stored in it whereas DELETE command is used to delete all the records or some
records of the tablewhile not modifying the structure of table. DROP is a DDL
while DELETE is a DML command.
Q9. What do you mean by Primary Key? Give suitable example to explain.
Ans. A primary key is an attribute or a group of attributes which can uniquely
identify each record/ tuple in the table.
Consider the following table Orders:

O_Id OrderDate OrderPrice Customer

1 2009/12/12 1000 Harry

2 2008/03/23 1600 Nancy

3 2008/09/02 700 Harry

4 2008/09/03 300 Harry

5 2008/08/30 2000 Jensen

6 2008/03/04 100 Nancy

Here O_Id will be the primary key as it will contain unique data for each tuple in
the table.

Q10. Differentiate between ALTER and UPDATE commads.


Ans. ALTER command is used to change the columns of an existing table such
as adding new column, deleting a column etc. whereas UPDATE command is used
to change the records of the table of an existing table. ALTER is a DDL while
UPDATE is a DML command.

MCQ QUESTIONS (1 mark each)


Q1. Which keyword is used to rename the resulting attribute after the application
of the aggregation function?
a) rename
b) as
c) replace
d) to
ANS: b
Explanation: The “as” keyword is used to rename the resulting attribute after the
aggregation function has been applied. Just like any other renaming operation, the
as keyword simplifies the name of the relation

Q2. The _____ aggregation operation adds up all the values of the attribute
a) add
b) avg
c) max
d) sum

ANS: d
Explanation: The sum aggregation operation adds up all the values of the specified
attribute. There does not exist any aggregation such as add.

Q3. Choose the correct option regarding the query:


SELECT branch_name, COUNT (DISTINCT customer_name)
FROM depositor, account
WHERE depositor.account_number = account.account_number
GROUP BY branch_id
HAVING avg(balance) = 10000;

a) The having clause checks whether the query result is true or not
b) The having clause does not check for any condition
c) The having clause allows only those tuples that have average balance 10000
d) None of the mentioned

ANS: c
Explanation: The having clause is used to check for conditions that need to be
set on aggregate functions.
Q4. We apply the aggregate function to a group of sets of tuples using the
_______ clause.
a) group by
b) group
c) group set
d) group attribute

ANS: a
Explanation: We apply the aggregate function to a group of sets of tuples using
the group by clause. The group by clause must always be used whenever we are
willing to apply the aggregate function to a group of sets of tuples.

Q5. Observe the given SQL query and choose the correct option.
SELECT branch_name, COUNT (DISTINCT customer_name)
FROM depositor, account
WHERE depositor.account_number = account.account_number
GROUP BY branch_id

a) The query is syntactically correct but gives the wrong ANS


b) The query is syntactically wrong
c) The query is syntactically correct and gives the correct ANS
d) The query contains one or more wrongly named clauses.

ANS: b
Explanation: The query is syntactically wrong. The attribute in the group by clause
must be one of the attributes specified in the select clause.

Q6. Which of the following is not a built in aggregate function in SQL?


a) avg
b) max
c) total
d) count
ANS: c
Explanation: SQL does not include total as a built in aggregate function. The avg
is used to find average, max is used to find the maximum and the count is used
to count the number of values.

Q7. What does the abbreviation DBMS stand for?


A. Data Borrowing and Movement Software.
B. Database Management System.
C. Digital Base Mapping System.
D. Database Manipulation Software.

ANS: B

Q8. Which of the following statement removes database including its related
components?
A. DROP DATABASE
B. DELETE DATABASE
C. REMOVE DATABASE
D. None of the mentioned

ANS: A

Q9. Which operator defines a range of values that the column values must fall in?
A. In
B. Like
C. Between
D. Is

ANS: C

Q10. We use …………… operator with select for condition based on pattern matching.
A. In
B. Like
C. Between
D. Is

ANS: B

TRUE/FALSE Questions (1 mark each)


Q1. DDL handles operations such as entering rows into a table, changing data,
deleting rows, and extracting data from rows and tables. (True/False)
ANS: False

Q2. A field without any value is a NULL Value. (True/False)


ANS: True

Q3. If two entries about same data do not agree ,then such data can be called
as consistent data. (True/False)
ANS: False

Q4. The LIKE operator is used in a WHERE clause to search for a given operator
in a column. (True/False)
ANS: False

Q5. ‘As’ Clause is used in SQL for projection operation. (true/False)


ANS: False

One word Answers (1 mark each)


Q1. Which command in SQL allows us to group the rows based upon a certain
attribute?
Ans. GROUP BY clause
Q2. Which keyword eliminates duplicate rows from the results of a SELECT
statement?
Ans. DISTINCT

Q3. Which operator is used in SQL to specify a range of values?


Ans. BETWEEN

Q4. Which clause is used in query to place the condition on groups in MYSQL?
Ans. HAVING

Q5. Which commands allow us to perform tasks related to data definition?


Ans. Data Definition Language (DDL)

Q6. Which commands allow us to perform tasks related to data definition?


Ans. Data Definition Language (DDL)

Q7. Which commands allow us to perform tasks related to data manipulation?


Ans. Data Manipulation Language (DDL)

Q8. Which command helps to open databse for using it?


Ans. USE

Q9. Which command helps to see the structure of a table/ relation?


Ans. DESCRIBE

Q10. Which clause helps to sort query results by one or more columns?
Ans. ORDER BY

Assertion and Reasoning (1 mark each)

Q1. Assertion (A): The syntax to drop a primary key in SQL is:
ALTER TABLE table_name DROP PRIMARY KEY;
Reason (R) : Primary keys cannot contain UNIQUE values, and must contain
NULL values.
A. Both A and R are true and R is the correct explanation of A.
B. Both A and R are true but R is not the correct explanation of A.
C. A is true but R is false.
D. A is false but R is true.

ANS: C

Q2. Assertion (A): VARCHAR holds only the characters you assign to it.
Reason (R): CHAR is fixed length whereas VARCHAR is of variable length data
type in MySQL.
A. Both A and R are true and R is the correct explanation of A.
B. Both A and R are true but R is not the correct explanation of A.
C. A is true but R is false.
D. A is false but R is true.

ANS: A

Q3. Assertion (A) :BETWEENoperator results in TRUE if the operand is within the
range of comparisons.
Reason (R) : NOT operator results in displaying a record if the condition(s) is
TRUE
A. Both A and R are true and R is the correct explanation of A.
B. Both A and R are true but R is not the correct explanation of A.
C. A is true but R is false.
D. A is false but R is true.

ANS: C
Q4. Assertion (A) : DDL stands for Data Definition Language, which deals with
database schemas and how the data should reside in the database.
Reason (R): Statements such as SELECT, INSERT, UPDATE, DELETE, etc are
the examples of DML commands.
A. Both A and R are true and R is the correct explanation of A.
B. Both A and R are true but R is not the correct explanation of A.
C. A is true but R is false.
D. A is false but R is true.

ANS: B

Q5. Assertion: Integration of MySQl with Python Interface is very popular now days
Reason: MySQL cannot be integrate with any other language
Choose the correct option:
a. Both Assertion and Reason are true, and Reason is the correct explanation for
Assertion
b. Both Assertion and Reason are true, and Reason is NOT correct explanation
for Assertion
c. Assertion is true, but Reason is false
d. Assertion is false, Reason is true

ANS: C

Very short Answer Questions (2 marks each)


Q1. What are DDL and DML statements?
Ans. DDL statement are used for creating or deleting tables. DML tables are used
for manipulating values of records in a table.

Q2. What do you mean by NULL value?


Ans. Null value is used when a field does not have any value. If in a field which
is NULLABLE, while inserting a row, no value is inserted, then in such a case the
value in the field becomes NULL
Q3. What is the purpose of GROUP BY clause?
Ans. This clause is used in a SELECT statement to collect data across multiple
records and group them by one or more columns of the table. This clause is
generally used with aggregate functions like MIN(), MAX(), SUM() etc.

Q4. What do you mean by HAVING clause?


Ans. This clause is used along with the GROUP BY clause in SQL. Whereas
WHERE clause cannot be used with aggregate functions, HAVING clause can be
used. It is used to filter a record by specifying a condition which a GROUP BY
returns.

Q5. What is the use of ORDER BY clause in SQL?


Ans. This keyword is used to sort the result in ascending or descending order. By
default, the keyword arranges the returned values in the ascending order. For
arranging in descending order, specifically DESC keyword has to be used.

Q6. What is the purpose of LIKE clause in SQL?


Ans. The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column. There are 2 wildcards often used with LIKE operaor:
 % --> Represents zero, one or multiple characters
 _ --> The underscore sign represents exactly a single character

Q7. What is the significance of connect() function in Python?


Ans. connect() function is used to connect or establish a connection with a SQL
database using Python program.

Q8. What si the role of execute() function in python?


Ans. The role of execute() function in Mysql queries is that it allows us to execute
SQL queries from Python script using cursor object.

Q9. What is the significance of cursor object?


Ans. Cursor object allows us to execute SQL queries on the database from Python
program. After the query is executed, the results record(s) are returned from SQL
over the connection in one go. Cursor object stores all the data as a temporary
container of the returned data and allows us to traverse it for further processing
in our program.

Q10. What is the command to establish a connection between Python script and
a database in MySQL?
Ans.
import mysql.connector
connectionobj = mysql.connector.connect (host= “localhost”, user= “root”, passwd =
“root”, database = “school”)

High Order Thinking (HOT) Questions (2 marks each)

Q1. Consider the following code and Answer the Questions that follows:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor. _____________
print(myresult)

What should be written in the fill in the blanks for fetching a single row? Specify
the reason.
Ans. fetchone() function should be used in the blank because we want to directly
print the single row as asked in the question.
Q2. Consider the following code and Answer the questions that follows:
import mysql.connect
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)

Ans. The program will generate an error while connecting to the database due to
wrong calling function connect()

Q3. Consider the following code and Answer the questions that follows:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")

What will be the output of above coding after execution?


Ans. The given program will create the table customers in the database.

Short Answer Questions (3 marks each)

Q1. Define the various constraints in SQL.


Ans. Constraints are certain set of rules used to apply data validations. They
ensure reliability, correctness and accuracy in the data being stored in the table.
These are not mandatory to define in a table.
Some commonly used Constraints are:
NOT NULL: When this constraint is applied to a column, that particular column
can never have a NULL value
UNIQUE: When this constraint is applied to a column, the each value in that
particular column shall have unique/ distinct value
PRIMARY KEY: A primary key is an attribute which can uniquely identify each
record/ tuple in the table

Q2. What is an ORDER BY and GROUP BY clause?


Ans.
ORDER BY keyword is used to sort the result in ascending or descending order.
By default, the keyword arranges the returned values in the ascending order. For
arranging in descending order, specifically DESC keyword has to be used.
Syntax: SELECT column_name(s) FROM table(s) ORDER BY column1, column2,
... ASC/DESC;
Example: SELECT * FROM customers ORDER BY firstname;

GROUP BY clause is used in a SELECT statement to collect data across multiple


records and group them by one or more columns of the table. This clause is
generally used with aggregate functions like MIN(), MAX(), SUM() etc.
Syntax:SELECT column_name(s) FROM table(s) WHERE condition GROUP BY
column(s) ORDER BY column(s);
Example: SELECT COUNT (*), subject FROM student GROUP BY subject;
Q3. Define a Foreign Key. Give an example.
Ans. A foreign key is a key which is used to link two tables together. It is also
known as a referncing key. It is a column or a combination whose values match
a primary key in a different table.

Example: Consider the following table Person


PID PName Age

1 Sandeep 18

2 Akash 22

3 Gautam 21

Consider the table Order


OID Orderno PID

1 44154 2

2 69871 3

3 17452 2

Here PID is the foreign key in the Order table.

Q4. Consider a database LOANS with the following table:


AccNo Cust_Name Loan_Amount Instalments Int_Rate Start_Date Inerest

1 R.K. Gupta 300000 36 12.00 19-07-2009 1200

2 S.P. Sharma 500000 48 10.00 22-03 -2008 1800

3 K.P. Jain 300000 36 NULL 08-03-2007 1600

4 M.P. Yadav 800000 60 10.00 06-12-2008 2250

5 S.P. Sinha 200000 36 12.50 03-01-2010 4500


6 P. Sharma 700000 60 12.50 05-06-2008 3500

7 K.S. Dhall 500000 48 NULL 05-03-2008 3800

Write the queries for following operations:


a. Display the sum of all Loan Amounts whose Interest rate is greater than 10.
b. Display the Maximum Interest from Loans table.
c. Display the count of all loan holders whose name ends with 'Sharma'.

Ans.
a. Mysql> select sum(Loan_Amount) from LOANS where Interest >10;
b. Mysql> select max(lnterest) from LOANS;
c. Mysql> select count( * ) from LOANS where Cust_Name like '%Sharma';

Q5. Define the following terms: Field, Record and Table.


Ans.
Field: A field is the smallest unit of a table which is also known as a column.
Columns are called attributes in a table. For example, Employee Name, Employee
ID, etc.
Record: A record is a collection of values/fields of a specific entity. For example,
record of an employee
that consists of Employee name, Salary, etc.
Table: A table is called a relation. It is a collection of records of a specific type
of data. For example,
employee table, salary table, etc., that can consist of the records of employees
and records of salary
respectively.
Q6. What are the basic steps to connect with MySQL using table Members?
Ans. import MySQLdb
conn = MySQLdb . connect (host= ' host ', user= ' user ', passwd= ' passwd ',
db= ' db ')
cursor = conn. cursor ()
cursor. execute (' SELECT COUNT (MemberID) as count FROM Members WHERE
id= 1')
row = cursor . fetchone ()
conn . close ()
print (row)

Q7. What do you understand by Data Redundancy and Data Consistency?


Ans.
Data Redundancy: Data redundancy is a condition created within a database or
data storage technology in which the same piece of data is held in two separate
places.A DBMS eliminates data redundancy (duplication of data) by integrating the
files so that multiple copies of the same data are not stored.
Data Consistency: A DBMS provides data consistency to a larger extent as the
changes made at one place are reflected at all other places or to all the users.

Q8. Write the full forms of DDL and DML. Write any two commands of DDL in
SQL.
Ans.
DDL – Data Definition Language
DML – Data Manipulation Language
DDL examples: CREATE, DROP, ALTER etc.
DML examples: INSERT, UPDATE, DELETE etc.

Q9. Explain IN, BETWEEN and LIKE operators in SQL.


Ans.
The IN operator is a membership operator that allows us to specify multiple values
in a WHERE clause. It is a shorthand for multiple OR conditions.
The BETWEEN operator is used when we want to select values within a range
from a table. The values can be text, numbers or dates.
The LIKE operator is used in a WHERE clause to search for a specified pattern
in a column.
Q10. Differentiate between candidate key, primary key and alternate key.
Ans.
Candidate Key: All sets of possible attributes/ group of attributes capable of
becoming a primary key
Primary Key: A primary key is an attribute or a group of attributes which can
uniquely identify each record/ tuple in the table
Alternate Key: A candidate key which is not used as a primary key

Essay/ Long Answer Type Questions


Q1. Write the SQL queries (i) to (iv) based on the relations VEHICLE and TRAVEL
given below:
Table VEHICLE
VCOD VEHICLETYP PERK

E E M

V01 VOLVO BUS 150

V02 AC DELUX 125

BUS

V03 ORDINARY 80

BUS

V04 CAR 18

V05 SUV 30

NOTE: PERKM is fright charges per kilometer

Table: TRAVEL
CNO CNAME TRAVELDAT KM VCOD NOP

E E
101 K. Niwal 2015-12-13 200 V01 32

103 Fredrick Sym 2016-03-21 120 V03 45

105 Hitesh Jain 2016-04-23 450 V02 42

102 Ravi Anish 2016-01-13 80 V02 40

107 John Malina 2015-02-10 65 V04 2

104 Sahanubhuti 2016-01-28 90 V05 4

106 Ramesh Jaya 2016-04-06 100 V01 25

NOTE: KM is Kilometres travelled and NOP is number of passengers travelled in


vehicle

i) To display CNO, CNAME, TRAVELDATE from the table TRAVEL in descending


order of CNO.
ii) To display the CNAME of all customers from the table TRAVEL who are
travelling by vechicle with code Vo1 or Vo2
iii) To display the CNO and CNAME of those customers from the table TRAVEL
who travelled between ‘2015-12-¬31’ and ‘2015-05-01’.
iv) To display total number of passengers travel with different types of vehicles.
v) To display all the details from table TRAVEL for the customers, who have travel
distacne more than 120 KM in ascending order of NOE

Ans.
i) Select CNO, CName, TravelDate from Travel Order By CNO DESC;
ii) Select CName From Travel Where VCode=”V01” or VCode=”V02”;
iii) Select CNo, CName from Travel Where TravelDate>=‘2015-05-01’ and
TravelDate<=
‘2015-12-¬31’;
iv) Select Sum(NOP) from Travel;
v) Select * from Travel Where KM>120 Order By NOP;

Q2. Write the SQL commands for the following queries (a) to (e) on the
basis of the following tables
SHOP and ACCESSORIES.

Table: SHOP
ID Sname Area
S01 ABC Computronics CP
S02 All Infotech GK II
S03 Tech Shop CP
S04 Geeks Techno Soft Nehru Place
S05 Hitech Tech Store Nehru Place

Table: ACCESSORIES
No Name Price ID
A01 Mother Board 12000 S01
A02 Hard Disk 5000 S01
A03 Keyboard 500 S02
A04 Mouse 300 S01
A05 Mother Board 13000 S02
A06 Keyboard 400 S03
A07 LCD 6000 S04
T08 LCD 5500 S05
T09 Mouse 350 S05
T10 Hard Disk 4500 S03

a. To display Name and Price of all the Accessories in ascending order of


their Price.
b. To display Id and SName of all Shop located in Nehru Place.
c. To display Minimum and Maximum Price of each Name of Accessories
d. To display Name, Price of All Accessories and their respective Sname
where they are
available.
e. To display all the items Name and Price having price range between 5000
to 12000 (both
inclusiv)

Ans.
a. SELECT Name, Price FROM ACCESSORIES ORDER BY Price Asc;
b. SELECT ID SName FROM SHOP WHERE Area=”Nehru Place”;
c. SELECT Name, max (Price); min(Price) FROM ACCESSORIES, Group By
Name;
d. SELECT Name,Price, Sname
FROM ACCESSORIES, SHOP WHERE SHOP.ID=ACCESSORIES.ID;
e. SELECT Name, Price FROM ACCESSORIES WHERE Price BETWEEN
5000 and 12000;

Q3. Consider the following tables Sender and Recipient. Write SQL
commands for the statements (a)
to (c) and give the outputs for SQL queries (d) to (e).
Sender
SenderID SenderName SenderAddress Sendercity

ND01 R Jain 2, ABC Appls New Delhi

MU02 H Sinha 12 Newtown Mumbai

MU15 S Jha 27/A, Park Street Mumbai

ND50 T Prasad 122-K,SDA New Delhi

Recipients
RecI SenderI RecName RecAddress recCity

D D
KO05 ND01 R 5, Central Avenue Kolkata

Bajpayee

ND08 MU02 S 116, A-Vihar New Delhi

Mahajan

MU1 ND01 H Singh 2A, Andheri East Mumbai

MU3 MU15 P K B5, C S Terminals Mumbai

2 Swamy

ND48 ND50 S Tripathi 13, BI D Mayur New delhi

Vihar

a. To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for

every Recipient

b. To display Recipient details in ascending order of RecName

c. To display number of Recipients from each city

d. SELECT A.SenderName, B.RecName From Sender A, Recipient B Where

A.SenderID = B.SenderID AND B.RecCity =’Mumbai’;

e. SELECT RecName, RecAddress From Recipient Where RecCity NOT IN

(‘Mumbai’, ‘Kolkata’) ;

ANS.
a. Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress

from Sender S, Recepient R where S.SenderID=R.SenderID ;

b. SELECT * from Recipent ORDER By RecName;


c. SELECT COUNT( *) from Recipient Group By RecCity;

d.

A.SenderName B.RecName

R Jain H Singh

S Jha P K Swamy

e.

RecName RecAddress

S Mahajan 116, A Vihar

S Tripathi 13, BID, Mayur Vihar

Q4. Suppose you are data base administrator and for a sport club you are
creating data base clubhouse
and the table ‘Club’ given below:

CLUB
Member_ID Member_name Address Age Fee

M001 SUMIT NEW DELHI 20 2000

M002 NISHA GURGAON 19 3500

M003 NIHARIKA NEW DELHI 21 2100

M004 SACHIN FARIDABAD 18 3500

Attributes of table is given as below


Member_id :unique value
Member_Name:string
Address: String
Age :number
Fees :number

1. What is the cardinality and degree of the given table?


2. In the above table, as a data base administrator can you have member_id
as primary key.
3. Write command to delete table
4. Insert a new row in table
5. Write query to display structure of table

Ans.
1. Degree =4, Cardinality = 5
2. Yes
3. Drop club
4. Insert into store values(“M005”,”rohit”,”jaipur”,16,2000)
5. Desc store

Q.5. A medical store Rajshree is considering to maintain their inventory using


SQL to store the data.
As a database administer, Sahil has decided that :
• Name of the database - rajshree
• Name of the table - medicalstore
• The attributes of medicalstore are as:
MedicineNo - numeric
MedicineName – character of size 25
MedCode – numeric
Quantity – numeric
Table : medicalstore
MedicineN MedicineName MedCod Quantit
o e y
5647 Saridon 141 75
5741 Paracetamol 142 44
3546 Nicip Plus 141 60
9541 Disprin 140 53
2025 Diclofenac 143 73
2783 Corex Syrup 141 97
8614 Psorid 142 48

(a) Identify the attribute best suitable to be declared as a primary key,


(b) Write the degree and cardinality of the table medicalstore.
(c) Insert the following data into the attributes respectively in the given table
medicalstore.
MedicineNo = 6647, MedicineName = “Dapsone”, MedCode = 141 and
Quantity = 55
(d) Sahil want to remove the table medical store from the database rajshree.
Which command
will he use from the following:
i. DELETE FROM rajshree;
ii. DROP TABLE medicalstore;
iii. DROP DATABASE medicalstore;
iv. DELETE medicalstore FROM rajshree;
(e) Now Sahil wants to know the Primary key of the table along with data
types of all the
columns. Which query should he write?

ANS.
(a) MedicineNo
(b) Degree =4, Cardinality = 7
(c) INSERT INTO medicalstore (MedicineNo, MedicineName, MedCode,Quantity)
VALUES(6647, “Dapsone”, 141,55);
(d) DROP TABLE medicalstore;
(e) DESCRIBE medicalstore;
Q6. An educational institution EducationPoint is considering to maintain their
inventory using SQL to
store the data. As a database administer, Ajay has decided that :
• Name of the database - edupoint
• Name of the table - STUDENT
• The attributes of student are as follows: studentID – numeric
studName – character of size 30
sCode – character of size 10
marks – numeric
Table: STUDENT
studentID studName sCode marks
1002 Rama ABC 90
1004 Anurag XYZ 70
1009 Raj PQR 85
1008 Aruna PQR 80
1020 Anish ABC 79
1024 Diksha XYZ 84
1031 Sahil ABC 88

(a) Identify the attribute best suitable to be declared as a primary key


(b) Write the degree and cardinality of the table STUDENT
(c) Insert the following data into the attributes studentID, studName and SCode
respectively in the given table SUDENT.
studentID = 1033, studName = “Aryan” and Scode = ABC
(d) Ajay want to remove the database edupoint .Which command will he use
from the following:
i. DELETE FROM student;
ii. DROP TABLE student;
iii. DROP DATABASE edupoint;
iv. DELETE DATABASE edupoint;
(e) Now Ajay wants to display the structure of the table STUDENT, i.e, name of
the attributes and
their respective data types that he has used in the table. Write the query
to display the same.

ANS.
(a) studentID
(b) Degree = 4 Cardinality = 7
(c) INSERT INTO student (studentID, studName,Scode) VALUES(1033,
“Aryan”,”ABC”);
(d) DROP DATABASE edu
(e) Describe Student;

Q7. Given the following table:

Table: CLUB

COACH COACH Age SPORTS DATOFAPP PAY SEX

_ID NAME

1 KRKREJA 35 KARATE 27/03/1996 1000 M

2 RAVINA 34 KARATE 20/01/1998 1200 F

3 KARAN 34 SQUASH 19/02/1998 2000 M

4 TARUN 33 BASKETBALL 01/01/1998 1500 M

5 ZUBIN 36 SWIMMING 12/01/1998 750 M

6 KETAKI 36 SWIMMING 24/02/1998 800 F

7 ANKITA 39 SQUASH 20/02/1998 2200 F

8 ZAREEN 37 KARATE 22/02/1998 1100 F

9 KUSH 41 SWIMMING 13/01/1998 900 M

10 SHAILYA 39 BASKETBALL 19/02/1998 1700 M

Give the output of following statements:


(i) SELECT COUNT (DISTINCT SPORTS) FROM CLUB;

(ii) SELECT MIN(AGE) FROM CLUB WHERE SEX = ‘F’

(iii) SELECT AVG(PAY) FROM CLUB WHERE SPORTS = ‘KARATE’;

(iv) SELECT SUM(PAY) FROM CLUB WHERE DATEOFAPP ‘31/01/1998’;


(v) SELECT PAY+500 FROM CLUB WHERE COACH_ID = 9;

ANS.
i) COUNT(DISTINCT SPORTS)

ii) MIN(AGE)

34

iii) AVG(PAY)

2665

iv) SUM(PAY)

2665

v) PAY+500

1400

Q8. Consider the following Questions.


a. What do you understand by Alternate Key in a table? Give a suitable
example of Alternate Keys from a table containing some meaningful
data.
b. Write the steps to perform an Insert query in database connectivity
application.
ANS.
A
Alternate Key or Secondary Key is the key that has not been selected to be
the primary key, but are candidate keys. However, it is considered a candidate
for the primary key.
A candidate key not selected as a primary key is called alternate or secondary
key. Candidate key is an attribute or set of attributes that you can consider as
a Primary key.

Student_ID Student_Enroll Student_Name Student_Email

096 2717 Manish [email protected]

055 2655 Manan [email protected]

067 2699 Shreyas [email protected]

Above, Student_ID, Student_Enroll and Student_Email are the candidate keys.


They are considered candidate keys since they can uniquely identify the student
record. Select any one of the candidate key as the primary.Rest of the two keys
would be Alternate or Secondary Key.

B
import mysql.connector as mydb
conn= mydb.connect(host=”localhost”,user=”root”, passwd=”1234”)
cur=conn.cursor()
cur.execute(“INSERT INTO student values(1,’AMIT’,22);”)
cur.commit()

Q9. Consider a database LOANS with the following table:

AccNo Cust_Name Loan_Amount Instalments Int_Rate Start_Date Inerest

1 R.K. Gupta 300000 36 12.00 19-07-2009 1200


2 S.P. Sharma 500000 48 10.00 22-03 -2008 1800

3 K.P. Jain 300000 36 NULL 08-03-2007 1600

4 M.P. Yadav 800000 60 10.00 06-12-2008 2250

5 S.P. Sinha 200000 36 12.50 03-01-2010 4500

6 P. Sharma 700000 60 12.50 05-06-2008 3500

7 K.S. Dhall 500000 48 NULL 05-03-2008 3800

Answer the following Questions:

I. Display the sum of all Loan Amounts whose Interest rate is greater than

10.

II. Display the Maximum Interest from Loans table.

III. Display the count of all loan holders whose name ends with 'Sharma'.

IV. Disp lay the count of all loan holders whose Interest is Null.

V. Display the Interest-wise details of Loan Account Holders.

Ans.

I. Mysql> select sum(Loan_Amount) from LOANS where Interest >10;

II. Mysql> select max(lnterest) from LOANS;

III. Mysql> select count( * ) from LOANS where Cu st_Name like '%Sharma';

IV. Mysql> select count(*) from LOANS where Interest is NULL;

V. Mysql> select * from LOANS group by Interest;

Q10. ANS the following QUESTIONS.


a. Differentiate between fetchmany( ) and fetchone( ) method wit suitable
example of each.
b. Differentiate between WHERE and HAVING clause.

ANS.
A
The fetchmany(<n>) method will return only the <n> number of rows from the
result set in the form of a tuple containing the records.
Example:
Data = cursor.fetchmany(4)
Count = cursor.rowcount
print(“Total number of rows retrieved from resultset :”,count)
for row in data:
print (row)
Total number of rows retrieved from the resultset : 4
The fetchone( ) method will return only one row from the result setn the form of
a tuple containing a record.
Example:
Data = cursor.fetchone( )
Count = cursor.rowcount
print(“Total number of rows retrieved from resultset :”,count)
for row in data:
print (row)
Total number of rows retrieved from the resultset : 1

B
WHERE clause is used to select particular rows that satisfy a condition whereas
HAVING clause is used to place condition on an individual group formed with
GROUP BY clause.

Case-Study Based QUESTIONS (5 marks each)


Q1. Rashmi wants to write a program for connecting python with mysql. Consider
the following code for selecting all the records according to the name. Help Rashmi
to complete the given incomplete code.
import mysql._____ # Line-1
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.___() # Line-2
sql = "_______________________" # Line-3
_____.execute(sql) # Line-4
myresult = mycursor._________() # Line-5
for x in myresult:
print(x)
a. What should come in place of Line-1?
b. What should come in place of Line-2?
c. What should come in place of Line-3?
d. What should come in place of Line-4?
e. What should come in place of Line-5?

Ans.
a. connector
b. cursor
c. SELECT * FROM customers ORDER BY name;
d. mycursor
e. fetchall

Q2. A mobile seller has maintained his database in the form of following
2 tables. You have to help
him execute some queries as per his requirements as given for
the statements (i) to (v).

Table: MobileMaster

M_Id M_Company M_Name M_Price M_Mf_Date

MB001 Samsung Galaxy 4500 23-Jan-2004

MB003 Nokia N1100 2250 12-Dec-2003

MB004 Micromax Unite3 4500 14-Feb-2004

MB005 Sony XperiaM 7500 01-Jan-2004

MB006 Oppo SelfieEx 8500 19-Mar-2004

Table: MobileStock

S_Id M_Id M_Qty M_Supplier

S001 MB004 450 New Vision

S002 MB003 250 Praveen Gallery

S003 MB001 300 Classic Mobile Store

S004 MB006 150 A-one-Mobiles

S005 MB003 150 The Mobile

S006 MB006 50 Mobile Centre


(i) Display the Mobile company, Mobile Name & Price in descending order of
their
manufacturing date.
(ii) List the details of mobile whose name starts with s
(iii) Display the mobile supplier and quantity of all mobiles except MB003.
(iv) Display the name of mobile company having price between 3000 and 5000
(v) Display the name of company, supplier and Price by joining the two tables
where price is
more than 5000.

ANS.
(i) SELECT M_Company, M_Name, M_Price FROM MobileMaster ORDER BY
M_Mf_Date
DESC;
(ii) SELECT * FROM MobileMaster WHERE M_Name LIKE “S%”;
(iii) SELECT M_Supplier,M_Qty FROM MobileStock WHERE M_Id <>”MB003”;
(iv) SELECT M_Company FROM MobileMaster WHERE M_Price BETWEEN
3000 AND
5000;
(v) SELECT M_Company,M_Supplier,M_Price FROM MobileMaster,MobileStock
WHERE
MobileMaster.M_Id = MobileStock.Mid AND M_Price>5000;

Q3. Your friend is a student of Class XII and studying Computer Science. Help
him to write SQL commands for the following queries (i) to (v) based on
therelations Product and Client given below.
Product
P_ID ProductName Manufacturer Price Discount

TP01 Talcum Powder LAK 40

FW05 Face Wash ABC 45 5


BS01 Bath Soap ABC 55

SH06 Shampoo XYZ 120 10

FW12 Face Wash XYZ 95

Client
C_ID ClientName City P_ID

01 Cosmetic Delhi TP01

Shop

02 Total Health Mumbai FW05

03 Live Life Delhi BS01

04 Pretty Delhi SH06

Woman

05 Dreams Delhi TP01

(i) Write SQL query to display ProductName and Price for all products whose Price
is in the range of 50 to 150.
(ii) Write SQL query to display details of product whose manufacturer is either
XYZ or ABC
(iii)Write SQL query to display ProductName, Manufacturer and Price for all
products that are not given any discount.
(iv) Write SQL query to display ClientName, City, and P_ID for all clients whose
city is Delhi
(v) Write SQL query to display product details where ProductName is starting with
letter ‘F’.

Ans.
i) SELECT ProductName, Price FROM PRODUCT WHERE Price BETWEEN
50 AND 100;
OR
SELECT ProductName, Price FROM PRODUCT WHERE Price>=50 AND
Price<=100;

ii) SELECT * FROM PRODUCT WHERE Manufacturer IN(‘XYZ’,‘ABC’);


OR
SELECT * FROM PRODUCT WHERE Manufacturer=’XYZ’ OR
Manufacturer=’ABC’;

iii) SELECT ProductName, Manufacturer, Price FROM PRODUCT WHERE


Discount IS NULL;

(iv) SELECT ClientName, City, CLIENT.P_ID, FROM CLIENT WHERE


city=‘Delhi’;

(v) SELECT * FROM PRODUCT WHERE ProductName like ‘F%’;

Q4. Your friend is a student of Class XII and studying Computer Science.
Help him to write SQL
commands on the following tables RESORT and OWNEDBYand write
the queries for the
given operations to be performed.
1. To display the RCODE and PLACE of all ‘5 STAR’ resorts in the alphabetical
order of the place from table RESORT.
2. To display the maximum and minimum rent for each type of resort from
table RESORT.
3. To display the details of all resorts which are started after 31-DEC-05 from
table RESORT.
4. To display the OWNER of all ‘5 STAR’ resorts from tables RESORT and
OWNEDBY.
5. To display the maximum rent

ANS.
1. SELECT MIN(RENT) FROM RESORT Where PLACE = ‘KERALA’;
2. SELECT TYPE, START DATE FROM RESORT Where TYPE ‘2
STAR’ORDERBY STARTDATE,
3. SELECT PLACE, OWNER FROM OWNED BY Where PLACE LIKE
“%A”;
4. SELECT RCODE, RENT FROM RESORT, OWNEDBY WHERE
(RESORT PLACE= OWNEDBY. PLACE AND TYPE = ‘3 STAR’);
5. SELECT MAX(RENT) FROM RESORT

Q5. Your friend is a student of Class XII and studying Computer Science. Help him to
write SQL commands for the following queries (i) to (v) based on the relations Teacher
and Posting given below:
Table : Teacher

T_ID Name Ag Departme Date_ofJo Salar Gend

e nt in y er
1 Jatin 34 Computer 10/01/201 12000 M

Sc 7

2 Sita 31 History 24/03/200 20000 F

3 Sandy 32 Mathemati 12/12/201 30000 M

cs 6

4 Smriti 35 History 01/07/201 40000 F

5 Ravi 42 Mathemati 05/09/200 25000 M

cs 7

6 Sunny 50 History 27/06/200 30000 M

7 Suresh 44 Computer 25/02/201 21000 M

Sc 7

8 Sunain 33 Mathemati 31/07/201 20000 F

a cs 8

Table :Posting

P_ID Department Place

1 History Agra

2 Mathematics Raipur

3 Computer Science Gurgao

n
i. To show all information about the teacher of History department.
ii. To list the names of female teachers who are in Mathematics department.
iii. To list the names of all teachers with their date of joining in ascending
order.
iv. To display teacher's name, salary, age for male teachers only.
v. To display name, bonus for each teacher where bonus is 10% of salary.

ANS.
i. SELECT* FROM teacher WHERE department= “History”;
ii. SELECT name FROM teacher WHERE
department=“Mathematics”ANDgender=“F”;
iii. SELECT name FROM teacher ORDER BY date_of_Join;
iv. SELECT name, salary, age FROM teacher WHERE gender=“M”;
v. SELECT name, salary*0.1 AS Bonus FROM teacher;

HOT Qs (5 marks)

Q1. A music store MySports is considering to maintain their inventory using SQL
to store the data. The detail is as follow:
• Name of the database – MySports
• Name of the table – Sports
• The attributes of SPORTS are as follows:
• SCode – character
• SportName – character of size 20
• Noofplayers – numeric
• coachname – character of size 20

Table: Sports
SCode SportName Noofplayers Coachname

S001 Cricket 21 Rahul Dravid


S002 Football 25 Roshan Lal

S003 Hockey 40 Sardar Singh

S004 Cricket 19 Chetan Sharma

S005 Archery 12 Limbaram

S006 Shooting 17 Deepika Kumari

a) Identify the attribute best suitable to be declared as a primary key


b) Write the degree and cardinality of the SPORTS table
c) Insert the following data into the attributes SCode, SportName and
Coachname respectively
in the given table SPORTS. SCode = S007, SportName = “Kabbadi”
and Noofplayers = 15
d) Someone wants to delete the column coachname.
Which command will he use from the following:
i. DELETE Coachname FROM SPORTS;
ii. ALTER Coachname FROM SPORTS
iii. ALTER TABLE SPORTS DROP Coachname
iv. DELETE Coachname FROM SPORTS
e) Write the command to delete the structure of the table

ANS.
a. Scode can be a primary key
b. Degree = 4, Cardinality = 6
c. INSERT INTO Sports(Scode, SportName, Noofplayers) VALUES (“S007”,
“Kabaddi”, 15);
d. ALTER TABLE SPORTS DROP Coachname;
e. DROP TABLE Sports;

Q2. Suppose you are data base administrator and for a travel agency you are
creating data base clubhouse and the table ‘Transport’ given below:
Attributes of table is given as below
TCODE :unique value
TTYPE:string
PERKM: NUMERIC

1. What is the cardinality and degree of the given table?


2. In the above table, as a data base administrator can you have TCODE as
primary key.
3. Write command to delete table
4. Insert a new row in table
5. Write query to display structure of table

ANS.
1. Cardinality: 6 and Degree: 3
2. No
3. DROP TABLE Transport;
4. INSERT INTO Transport(TCODE, TType, PERKM) VALUES(22,”Deluxe”,103);
5. DESC Transport;

Q3. ABC School is managing students’ data in “Student” table in “School”


database. Write a Python program that connects to database school and retrieves
all records and displays total number of students.

ANS.
import mysql.connector
connectionobj = mysql.connector.connect (host= “localhost”, user= “root”, passwd
= “root”, database = “school”)
cursorobj = connectionobj.cursor()
query = “SELECT * FROM Student;”
cursorobj.execute(query)
records = cursor.fetchall()
count = 0
for i in records:
count += 1
print(x)
print( “Total number of records:”, x)
connectionobj.close()

Q4. Consider a database with the following tables and write queries for the
given problems:
Table: Worker
ECODE NAME DESIG PLEVEL DOJ DOB
11 Sachin Patel Supervisor P001 13- Sep- 23-Aug-1985
12 Chander Operator P003 22-Feb-2010 12-Jul-1987
2004
13 Fizza Operator P003 14-Jun-2009 14-0ct-1983
Nath
15 AmeenAhme Mechanic P002 21-Aug-2006 13-Mar-1984
18 Sanya Clerk P002 19-Dec-2005 09-Jun-1983
d

Table: Paylevel
PLEVEL PAY ALLOWANCE
P001 26000 12000
P002 22000 10000
P003 12000 6000

a. To display the details of all WORKERs in descending order of DOB.


b. To display the PLEVEL and worker name whose allowance is more than
9000.
c. To display the PLEVEL and DESIG whose pay is greater than 15000
d. To display NAME and DESIG of those WORKERs, whose PLEVEL is either
P001 or P002.
e. To delete all rows from table Paylevel

ANS.
a. SELECT * FROM Worker ORDER BY DOB DESC;
b. SELECT PLEVEL, NAME FROM Worker, Paylevel WHERE
ALLOWANCE >
9000;
c. SELECT PLEVEL, DESIG FROM Worker, Paylevel WHERE PAY >
15000;
d. SELECT NAME, DESIG FROM Worker WHERE Plevel IN (“P001”,
“P002”);
e. DELETE * FROM Paylevel;

Q5. A tech organization ZS Solutions is considering to maintain their inventory


using SQL to store the data of their employees. As a database administer, sahil
has decided that :
• Name of the database - zsRecords
• Name of the table – EMPLOYEE
• The attributes of student are as follows: empID - numeric
empName – character of size 30
empDept – character of size 10
salary – numeric

Table: Employee
empID empName empDept Salary

1021 Radhika sales 5000

1022 Anu dev 12000

1023 Rajesh support 8000


1024 Arunag dev 20000

1026 Manisha sales 7000

1027 Disha support 4000

1035 Sanjay dev 34000

(a) Identify the attribute best suitable to be declared as a primary key


(b) Write the degree and cardinality of the table Employee
(c) Insert the following data into the attributes empID, empName and empDept
respectively in the
given table SUDENT empID = 1042, empName = “Abhinav” and empDept
= support
(d) Ajay want to remove the table Employee. Which command will he use?
(e) Now Ajay wants to display the structure of the table Employee, i.e, name of
the attributes and
their respective data types that he has used in the table. Write the query
to display the same.

ANS.
a. empID can become the primary key
b. Degree: 4, Cardinality: 7
c. INSERT INTO Employee(empID, empName, empDept) VALUES(1042,
“Abhinav”,
“support”);
d. DROP TABLE Employee;
e. DESC Employee;
SAMPLE PAPER-I

Computer Science (083)

Maximum Marks: 70 Time Allowed: 3 hours

General Instructions:

1. This question paper contains two parts A and B. Each part is compulsory.

2. Both Part A and Part B have choices.

3. Part-A has 2 sections:

a. Section – I is short answer questions, to be answered in one word or


one line.

b. Section – II has two case studies questions. Each case study has 4

case-based sub- parts. An examinee is to attempt any 4 out of the

5 subparts.

4. Part - B is Descriptive Paper.

5. Part- B has three sections

a. Section-I is short answer questions of 2 marks each in which

two question have internal options.

b. Section-II is long answer questions of 3 marks each in which two

questions have internal options.

c. Section-III is very long answer questions of 5 marks each in which

one question has internal option.

6. All programming questions are to be answered using Python Language only


Question Part-A Marks

No. allocated
Section-I

Select the most appropriate option out of the options


given for each question. Attempt any 15 Questions from
Question no 1 to 21.
1 Find the invalid identifier from the following 1

a) my%name b) myage c) _name_ d)


students1
2 Given the lists L=[“H”, “T”, “W”, “P”, “N”] , write the output of 1
print(L[1:4])
3 Which module is required to work with CSV files in Python? 1

4 Identify the invalid relational operator in Python from the 1


following.

a) == b) < c) =< d) <=


5 Suppose a tuple T is declared as T = (10, 12, 43, 39), which of 1

the following is incorrect?

a) print(T[-2])
b) T[0] = 45

c) print(min(T))

d) print(max(T))
6 Write a statement in Python to declare a dictionary whose 1

keys are a,b,c and values are January, February and March

respectively.

7 A List is declared 1
as

L = [2,5,6,9,8]

What will be the value of len(L)?


8 Name the built-in mathematical function / method that is 1

used to return the smallest integer greater than or equal to

x.

9 Name the protocol that is used to send files over a Network. 1

10 Your friend Sridhar complains that somebody has created is 1

continuously sending him mails claiming that Sridhar has won

Rs. 1 crore and has to submit his account details. Identify the

type of cybercrime for these situations.

11 In SQL, name the clause that is used to display the tuples in 1

descending order of an attribute.

12 In SQL, what is the use of NOT NULL operator? 1

13 Write any one aggregate function used in SQL. 1

14 Which of the following is a DML command? 1

a) SELECT b) ALTER c) CREATE d) DROP


15 Name the transmission media best suitable for connecting to 1
islands like Andaman & Nicobar from Chennai.
16 Identify the data type of T: 1

T = [‘A’, ‘23’, ‘92’, ‘(10,20)’]

a. dictionary b. string c.tuple d. list


17 If the following code is executed, what will be the output 1

of the following code?

name="Kendriya Vidyalaya Sangathan"

print(name[2:13:2])

18 In SQL, write the query to display the structure of tables stored 1


in a database.
19 Write the expanded form of POP3 protocol. 1

20 Which of the following types of table constraints will prevent 1

the printing of duplicate values after the Select statement

fetches data from table?

a) Unique
b) Distinct

c) Primary Key

d) NULL
21 Rearrange the following terms in decreasing order of data 1
transfer rates.

Gbps, Mbps, Pbps, bps


Section-II

Both the Case study based questions are compulsory.


Attempt any 4 sub parts from each question. Each
question carries 1 mark
22 A medical store Rajshree is considering to maintain their inventory

using SQL to store the data. As a database administer, Sahil

has decided that :

 Name of the database - rajshree

 Name of the table - medicalstore

 The attributes of medicalstore

are as:

MedicineNo - numeric

MedicineName – character of size 25

MedCode – numeric
Quantity – numeric
Table : medicalstore
MedicineN MedicineName MedCod Quantit
o e y
5647 Saridon 141 75
5741 Paracetamol 142 44
3546 Nicip Plus 141 60
9541 Disprin 140 53
2025 Diclofenac 143 73
2783 Corex Syrup 141 97
8614 Psorid 142 48
(a) Identify the attribute best suitable to be declared as a 1
primary key,
(b) Write the degree and cardinality of the table medicalstore. 1

(c) Insert the following data into the attributes respectively in 1

the given table medicalstore.

MedicineNo = 6647, MedicineName = “Dapsone”, MedCode = 141


and Quantity = 55
(d) Sahil want to remove the table medicalstore from the 1

database rajshree. Which command will he use from the

following:

a) DELETE FROM rajshree;

b) DROP TABLE medicalstore;

c) DROP DATABASE medicalstore;

d) DELETE medicalstore FROM rajshree;


(e) Now Sahil wants to know the Primary key of the table 1

along with data types of all the columns. Which query

should he write?
23 Rajat Kumar of Class 12 is writing a program to create a CSV

file “employees.csv” which will contain employee name and

employee ID for some entries. He has written the following

code. As a programmer, help him to successfully execute the

given task.

import # Line 1

def addEmployee(empName,empId): # to write / add data

into the CSV

f=open(' employees.csv','___’') # Line 2


writerObj = csv.writer(f)

writerObj.writerow([empName,empId])

f.close()

#csv file reading code

def readEmployees(): # to read data from

CSV with open(' employees.csv','r') as fobj:

readerObj = csv. (fobj) # Line

3 for row in readerObj:

print (row[0],row[1])
fobj.close()
# Line 4

addEmployee (“Ram”, “2541”)

addEmployee(“Jagat”,”5471”)

addEmployee(“Fido”,”5418”)

readEmployees () #Line 5
(a) What should be written in Line 1. 1
(b)Which mode should Rajat write in Line-2 1
(c) Fill in the blank in Line 3 to read the data from a csv file. 1
(d) Which of the above mentioned lines is a redundant line? 1
(e) Write the output he will obtain while executing Line 5. 1
Part – B
Section-I
24 Evaluate the following 2

expressions: a) 8/2 +

2**5 – 5/2 + 7

b) 17 >= 6 and 3 > 11 or not 24 < 3


25 Differentiate between Viruses and Trojan Horse in context of 2

networking and data communication threats.

OR
Differentiate between Client Software and Web Browsers. Write
any two popular web browsers.
26 Expand the following terms: 2

a. FTP b. XML c. MAN d. WAN


27 Differentiate between default parameter(s) and keyword 2

parameter(s) with a suitable example for each.

OR

Explain the concept of Scope in functions with suitable

Example.

28 Rewrite the following code in Python after removing all 2

syntax error(s). Underline each correction done in the

code.

Def myfun():

r = raw-input(‘enter any radius : ’)

a = pi * Math.pow(r,2)

Print (“Area = ”, a)
29 What possible outputs(s) are expected to be displayed on 2

screen at the time of execution of the program from the

following code?

import random
x = 3
N = random, randint (1, x)
for i in range (N):
print(i, ‘#’, i + i)

a. What is the minimum and maximum number of times the loop


will execute?
b. Find out, which line of output(s) out of (i) to (iv) will not be
expected from the program?
i. 0#1
ii. 1#2
iii. 2#3
iv. 3#4
30 What do you understand by Foreign Keys in a table? Give a 2

suitable example of Foreign Keys from a table containing some

meaningful data.

31 2
Differentiate between DELETE and DROP commands in SQL?

32 Write the full forms of DDL and DML. Write any two commands 2
of DDL in

SQL.
33 Find and write the output of the following Python code: 2

def myfun():

n =

50

i = 5

s =

while

i<n:

s+ = i

i+ = 10

print(“sum”, s)

myfun()
Section- II

34 Rewrite the following while loop into for loop and also tell its 3

output:

i = 10

while i<250:

print(i)

i = i+50
35 Write a function in Python that counts the number of “the” or 3
“this” words present in a text file “myfile.txt”.
Example: If the “myfile.txt” contents are as follows:
This is my first class on Computer Science. File handling is the
easiest topic for me and Computer Networking is the most
interesting one.
The output of the function should be: Count of the/this in file: 3

OR
Write a function countVowels() in Python, which should read each
character of a text file “myfile.txt”, count the number of vowels
and display the count.
Example: If the “myfile.txt” contents are as follows:
This is my first class on Computer Science.
The output of the function should be: Count of vowels in file: 10
36 Write the outputs of the SQL queries (i) to (iii) based on the 3

given tables:

Watches

Watchid Watch_nam Price Type Qty_store

W001 High Time 10000 Ladies 100

W002 Life Time 15000 Gents 150

W003 Wave 12500 Ladies 200

W004 High 13500 Ladies 135

Fashion

W005 Golden 14000 Unisex 150

Time

Sale

Watchid Qty_sold Quarter

W001 10 1

W002 8 2

W003 15 1

W001 12 3

W003 11 2

W004 9 1

W002 15 1

i. SELECT MAX (PRICE), MIN(QTY_STORE) FROM WATCHES;


ii. SELECT QUARTER, SUM(QTY SOLD) FROM SALE GROUP

BY QUARTER;

iii. SELECT WATCH_NAME, QTY_STORE, SUM (QTY_SOLD)

FROM WATCHES W, SALE S WHERE W. WATCHID =

S.WATCHID GROUP BY S.WATCHID;

37 Write a function in Python Push(Arr, value), where Arr is a list of 3


Strings. From this list push all the Strings starting with “a” or “g
into a stack implemented by using a list. Display the stack if it has
at least one element, otherwise display appropriate error message.

OR

Write a function in Python, Pop(Arr), where Arr is a stack


implemented by a list of numbers. The function should return the
value deleted from the Stack only if it is a multiple of 6.

Section-III
38 Freshminds University of India is starting its first campus Anna 5
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 in the 5 km area campus.
As a network expert, you need to suggest the network plan as per
(a) to (e) to the authorities keeping in mind the distance and other
given parameters.

Expected wire distances between various locations:


Office block to Science block 90m
Office block to Commerce 80m
block
Science block to Commerce 15m
block
Kolkata Admission Office to 2450m
Anna Nagar Campus

Expected number of computers to installed at various locations in


the university are as follows:
Office block 10
Science Block 140
Commerce Block 30
Kolkata Admission Office 8

a. Suggest the authorities, the cable layout amongst various


blocks inside university campus for connecting the blocks
b. Suggest the most suitable place (i.e. block) to house the
server of this university with a suitable reason
c. Suggest an efficient device from the following to be installed
in each of the blocks to connect all the computers
d. Suggest the placement of a Repeater (if any) in the network
with justification.
e. Suggest the most suitable (very high speed) service to
provide data connectivity between Admission Office located in
Anna Nagar and Kolkata Admission Office

39 Write the SQL commands for the following queries (a) to (e) on the 5
basis of the following tables SHOP and ACCESSORIES.

Table: SHOP
ID Sname Area
S01 ABC Computronics CP
S02 All Infotech GK II
S03 Tech Shop CP
S04 Geeks Techno Soft Nehru Place
S05 Hitech Tech Store Nehru Place

Table: ACCESSORIES
No Name Price ID
A01 Mother Board 12000 S01
A02 Hard Disk 5000 S01
A03 Keyboard 500 S02
A04 Mouse 300 S01
A05 Mother Board 13000 S02
A06 Keyboard 400 S03
A07 LCD 6000 S04
T08 LCD 5500 S05
T09 Mouse 350 S05
T10 Hard Disk 4500 S03

f. To display Name and Price of all the Accessories in


ascending order of their Price.
g. To display Id and SName of all Shop located in Nehru Place.
h. To display Minimum and Maximum Price of each Name of
Accessories
i. To display Name, Price of All Accessories and their
respective Sname where they are available.
j. To display all the items Name and Price having price range
between 5000 to 12000 (both inclusive)

40 A binary file “employees.dat” has structure [empid, empname, age, 5


department].
a. Write a user defined function CreateEmployee() to input the
data to a record and add to employee.dat
b. Write a function CountRec(department) in Python which
accepts the Department of the employee as the parameter
and count and return the number of employees in that
department.

OR

A binary file “students.dat” has structure (admission_number, Name,


Percentage, subject). Write a function countrec() in Python that
would read contents of the file and display the details of those
students whose subject is “Biology” and percentage is below 45%.
Also display the number of such students.

SAMPLE PAPER -1
Computer Science – 083

MARKING SCHEME

Maximum Marks: 70 Time Allowed: 3 hours


Part – A

Section - I
1 a) my%name 1
2 [“T”, “W”, “P”] 1
3 Module “csv” 1
4 c) =< 1
5 b) T[0] = 45 (as tuple is immutable) 1
6 {“a” : “January” , “b” : “February” , “c”: “March”} 1
7 5
8 ceil() from math module 1
9 FTP (File Transfer Protocol) 1
10 Phishing 1
11 ORDER BY DESC 1
12 To check if the column does not have any Null/undefined value 1
13 SUM / AVG / COUNT / MAX / MIN (anyone of them) 1
14 a) SELECT 1
15 Microwave / Radio wave 1
16 d. List 1
17 “ediaVd” 1
18 DESC <tableName> 1
19 Post Office Protocol-3 1
20 (b) DISTINCT 1
21 Pbps, Gbps, Mbps , Bps 1
Part – A

Section - II
22 (a) MedicineNo 1

(b) Degree = 4 Cardinality = 7 1

(c) INSERT INTO medicalstore (MedicineNo, MedicineName, 1


MedCode,Quantity) VALUES(6647, “Dapsone”, 141,55);
1
(d) DROP TABLE medicalstore;
1
(e) DESCRIBE medicalstore;

23 (a) Line 1 : import csv 1

(b) Line 2 : f=open(' user.csv','a') 1

(c) Line 3 : readerObj = csv.reader(fobj) 1

(d) Line 4 : as we have opened the file in “with” operator, it closes itself 1

(e) Line 5 Output: 1

Ram 2541

Jagat 5471

Fido 5418
Part – B
24 a) 40.5 1
1
b) True
25 Virus is a computer program or software that connect itself to another software 2

or computer program to harm computer system. When the computer program

runs attached with virus it perform some action such as deleting a file from the

computer system. Virus can’t be controlled by remote.

Trojan Horse does not replicate itself like virus and worms. It is a hidden piece

of code which steal the important information of user. For example, Trojan

horse software observe the e-mail ID and password while entering in web

browser for logging.

OR
Web Browser : A web browser is a software application for accessing

information on the World Wide Web. When a user requests a web page from a

particular website, the web browser retrieves the necessary content from a web

server and then displays the page on the user's device.


Client software is a specific application that’s installed on our computer, that

can be used to communicate to some other piece of software over a network

(such as the internet’s world wide web). However, a client software doesn't

necessarily need a network connection to run on your computer.

Popular web browsers : Google Chrome, Mozilla Firefox, Internet Explorer etc

26 a. FTP - File Transfer Protocol 2


b. XML - eXtensible Markup Language

c. MAN – Metropolitan Area Network

d. WAN – Wide Area Network


27 Default arguments are the arguments where we provide a Default value to any 2

parameter while defining the function. Even if the value of that parameter is not

passed while calling the function, Python will take the default value for further

processing otherwise it will take the passed value.

Ex:

def greet(name, msg="Good morning!"):

#body of function

In keyword arguments, we call a function with some values and these values

get assigned to the arguments according to their position, irrespecive of their

positions in the function definition.

Ex:

def greet(name, msg="Good morning!"):

#body of function
greet(msg = “Hello”, name= “Sandeep”) #function called here

OR

A variable is only available from inside the region it is created. This is


called scope. A variable created inside a function belongs to the local scope of
that function, and can only be used inside that function. A variable created in the
main body of the Python code is a global variable and belongs to the global
scope. Global variables are available from within any scope, global and local.
28 CORRECTED CODE: 2
Def myfun():

r = raw_input(‘enter any radius : ’)

a = pi * math.pow(r,2)

print (“Area = ”, a)

29 OUTPUT: (ii) 2
a. Minimum Number = 1
Maximum number = 3
b. Option (iv)
30 When we create two tables that are related to each other, they are often 2

related by a column in one table referencing the primary key of the other
table - that column is called the "foreign key". Ex: consider following table
Track, where artistid is a foreign key.

trackid Title artistid

1 Great Big Words 1

1 This Pretty Planet 1

2 Cat's in the Cradle 2


31 DELETE command is used to remove information from a particular row or rows. 2
If used without condition, it will delete all row information but not the structure
of the table. It is a DML command.
DROP table command is used to remove the entire structure of the table and
information. It is a DDL command.

32 DDL – Data Definition Language 2

DML – Data Manipulation

Language

Any two out of CREATE, DROP, ALTER


33 OUTPUT : sum= 125 2

34 for i in range(10, 250, 50): 3

print(i)

Output:
10
60
110
160
210

35 def displayTheThis(): 3
num=0
f=open("myfile.txt","r")
N=f.read()
M=N.split()
for x in M:
if x=="the" or x== "this":
print(x)
num=num+1
f.close()
print("Count of the/this in file:",num)
OR
def countVowels():
fobj = open(“myfile.txt”)
data = fobj.read()
count = 0
for ch in data:
if ch == “a” or ch == “e” or ch == “i” or ch == “o” or ch == “u”:
count +=1
print(“Count of vowels in file:”, count)
Note : Using of any correct code giving the same result is also accepted.
36 3
i.Max(Price) = 15000, Min(Price) = 10000
ii.
QUARTER SUM(QTY_SOLD)
1 49
2 19
3 12

iii.
WATCH_NAME QTY_STORE QTY_SOLD
High Time 100 22

Life Time 150 23

Wave 200 26

High Fashion 135 9

Golden Time 150 NULL

37 Answer: (Using of any correct code giving the same result is accepted.)

3
def Push(Arr, value):
s =[]
for x in range(0,len(Arr)):
if Arr[x]== “a” or Arr[x] == “g”:
s.append(Arr[x])
if len(s) == 0:
print(“Stack is empty!!”)
else:
print(s)

OR

def Pop(Arr):
if len(s) == 0:
print(“Stack underflow”)
return
else:
L = len(Arr)
Val = Arr[-1]
if Val%6 ==0:
print(Val+5)
x = Arr.pop(Val)
return x

38 a. Using Star Topology: 5

b. The most suitable place (i.e. block) to house the server of this university
is Science Block, because in this block there are maximum number of
computer.
c. The efficient device to be installed in each of the blocks to connect all
the computers is switch.
d. No Repeater is required as distance is less than 100m at which the
signal starts to weaken in an Ethernet Cable/ Twisted Pair Cable.
e. For very high-speed connectivity between Admission office located in
Kolkata and the campus office in Anna Nagar is Satellite connection
39 a. SELECT Name, Price FROM ACCESSORIES ORDER BY Price Asc; 5

b. SELECT ID SName FROM SHOP WHERE Area=”Nehru Place”;


c. SELECT Name, max (Price); min(Price) FROM ACCESSORIES, Group
By Name;
d. SELECT Name,Price, Sname
FROM ACCESSORIES, SHOP
WHERE SHOP.ID=ACCESSORIES.ID;
e. SELECT Name, Price
FROM ACCESSORIES
WHERE Price BETWEEN 5000 and 12000;
40 import pickle 5

def CreateEmployee():
fobj = open(“employees.dat”, “ab”)
empid = input(“Enter employee ID: “)
empname = input(“Enter employee name: “)
age = int(input(“Enter employee age: “))
department = int(input(“Enter employee department: “))
record = [empid, empname, age, department]
pickle.dump(record, fobj)
fobj.close()

def CountRec(department):
fobj = open(“employees.dat”, “rb”)
count = 0
try:
while True:
record = pickle.load(fobj)
if department == record[3]:
count = count + 1
except:
fobj.close()
return count

OR
import pickle
def countrec():
fobj = open(“students.dat”, “rb”)
count = 0
try:
while True:
record = pickle.load(fobj)
if record[2] < 45 and record[3] == “Biology”:
print(record[0], record[1], record[2], sep=”\t”)
count +=1
except:
fobj.close()
return count
Sample Paper -2
(Theory)

Class: XII

Session: 2020-21

Computer

Science (083)

Maximum Marks: 70 Time Allowed:


3

General Instructions:

1. This question paper contains two parts A and B. Each part


compulsory.

2. Both Part A and Part B have choices.

3. Part-A has 2 sections:

a. Section–Iis short answer questions, to be answered in one


word or one line.

b. Section–II has two case studies questions. Each case study

has 4 case-based sub- parts .An examinee is to attempt

any4 out of the 5subparts.

4. Part –B is Descriptive Paper.

5. Part- B has three sections


a. Section-I is short answer questions of 2 marks each in

which two question have internal options.

b. Section-II is long answer questions of 3 marks each in which

two questions have internal options.

c. Section-III is very long answer r questions of 5markseachin

which one question has internal option.

6. All programming questions are to be answered using Python


Language only

Questi Marks Part-A


on
allocat
No.
ed
Section-I

1 Select of
Which thethe most appropriate
following can be option
used as valid variable 1
out of the in
identifier(s) options given for each
Python?
question. Attempt any 15 questions
Ans i) Data
Data from question
(ii) to (ii)
_Total no 1(each21.½ _Total
mark)
(iii) 4thSum (iv) Number#
2 S = “Hello” what will output of print S[:-3] 1
Ans He
3 What is use of ‘r’ mode 1
ans To read mode open
4 Identify and write the name of the module to which the 1
following functions belong:Randomint()
Ans Random
5 What is the difference between a string and a list? 1
Ans A tuple is immutable whereas a list is a mutable.

6 Write the type of tokens from the following: (i) if (ii) 1


Ans Keyword, identifier
roll_no
7 A tuple is declaredas 1

T= (1,2,3)
Ans 3

8 Name the be
What will built-in mathematical
the value function / method that
of max(T)? 1
Ans Split()
9 is usedthe
Name to protocol
return words
which for
usedgiven stringemails
to send 1
Ans Smtp
10 What is the difference between Packet switching and 1

Ans In circuit switching, a dedicated path exists from source to


circuit switching techniques?

destination while in packet switching, there is no fixed


11 In SQL, atrribiute /es which uniquely identify the row 1
called___________
Ans path.
Primary key
12 In SQL, what is the use of order by? 1
Ans To sorting the result of query
13 What is candidate key 1
Ans Key which are candidate to become primary key
14 What is join ? 1
Ans A JOIN clause is used to combine rows from two or more
15 What is DNS 1
tables
Ans Domain name system
16 Identify the valid data type for declaration of L: 1

a. dictionary b. string‘hello’,’60.5’]
L= [‘Mon’,‘23’, c.tupled. list
Ans List
17 If the following code is executed, what will be the output 1
of the following code?

name="hello world"
ans Hello

18 In SQL,print(name[:5])
write the query to count the rows present a 1
database school.
Ans Select count(*) from school;
19 Write the expanded form of html 1
Ans Hypertext markup language
20 What do you understand by constraint? 1
Ans Constraints are the condition to provide integrity to data
21 base
What is bandwidth ? 1
Ans Bandwidth is the amount of data that can be transferred
from one point to another within a network

S
e
ct
io
n-
22 II
Suppose you are data base administrator and for a sports
club you are creating data base clubhouse and the table
Both the Case study based questions are compulsory
‘Club’ given below:
.Attemptany 4 sub parts from each question .Each
question carries 1 mark

Attributes of table is given as below

Member_id :unique value

Member_Name:string

Address: String

Ans 1. Age :number


Degree =4
Cardinality = 5

Fees :number
2. Yes

1.
3. What is the cardinality and degree of the given
Drop club
table?

4. Insert into store values(“M005”,”rohit”,”jaipur”,16,2000)


2. In the above table, as a data base administrator can
you have member_id as primary key.
1. Desc store
23 Roshni as programmer writing a program in which
she is creating a csv file “peak.csv” as following
data

She created following code help her to complete


following lines

import _____ #line 1

data = [{‘MOUNTAIN’ : ‘Everest’, ‘HEIGHT’: ‘8848’},

{‘MOUNTAIN’ : ‘Anamudi ‘, ‘HEIGHT’: ‘2695’},

{‘MOUNTAIN’ : ‘Kanchenjunga’, ‘HEIGHT’: ‘8586’}]

1
(a)Name the module she should import in Line1.
(b)what would be the mode for file open in line 2 1
CF= open(‘c:\\pyprg\\ch13\\peak.csv’, ‘____’) #line 2
(c)Fill in the blank in Line3 to write header the data into 1
a csv file.
(d)name the function in line 4 doing in this program 1
writing row in file
(e)Write the function name which can close the file in 1
line =
fields 5 [‘MOUNTAIN’, ‘HEIGHT’]
import csv #line 1

data = [{‘MOUNTAIN’ : ‘Everest’, ‘HEIGHT’: ‘8848’},


w = csv.DictWriter(CF, fieldnames=fields)
{‘MOUNTAIN’ : ‘Anamudi ‘, ‘HEIGHT’: ‘2695’},

{‘MOUNTAIN’ : ‘Kanchenjunga’, ‘HEIGHT’: ‘8586’}]


w.___________ () #line 3
CF= open(‘c:\\pyprg\\ch13\\peak.csv’, ‘w’) # line 2

fields = [‘MOUNTAIN’, ‘HEIGHT’]


P
w.___________(data) # line 4
Sa
w = csv.DictWriter(CF, fieldnames=fields)
e
cr
w.writeheader() #line 3 ti
print(“writing completed”) ot
w.writerows(data) # line 4 n
-I–
CF.______()# line 5
print(“writing completed”) B

CF.close() # line 5
24 Evaluate thefollowingexpressions: 2

a) 2 + 3**4*5
Ans a. 407
b. True
b) 5<5 or 10
25 If someone hacks your website , who would you complaint 2
do ?

O
R

Ans Police
Name the primary law deal with cyber crime in india
Or
IT Act 2000
26 Expand the following abbreviations : 2

1. FTP

2. TCP

3. SMTP
Ans 1.
4. FTP:
VOIP File Transfer Protocol
2. TCP: Transmission Control Protocol.
3. SMTP: Simple Mail Transfer Protocol.
27 4. VOIP:between
Difference Voice Over Internet
global Protocol
and local variables? OR 2

What are default argument, what is use of default


Ans I Local Variable: A variable defined
arguments ?
within a function has local scope. Global
Variable: A variable defined in the main
28 Rewrite 2
program the
hasfollowing code in Python after removing all
global scope.

syntax errors(s). Underline each STRING=""WELCOME

NOTE=""

for S in range[0,8]:

print STRING(S)

print S+STRING
Ans STRING= "WELCOME"

NOTE=""

for S in range (0,8) :

29 print STRING [S] 2


Import random

X=3
print S.STRING
N=random.randint(1,X)

For I in range(N):

Print(I,”#”,i+1)

Ans a. a. What is theNumber


Minimum minimum = 1and maximum number of
times the loop will execute?
Maximum Number = 3
30 b.
Define Find
domainout, with
which line of
respect to output(s)
database. out of an
Give (i) example.
to (iv) 2
b. will
Line notiv beis not expected to be a part of the output.
Ans A domain is a pool of values from which the actual values
expected from the
appearing in a given column are drawn.
program?
For example: The values appearing in the Supp# column
i. 0#1 ii. 1#2 iii. 2#3 iv. 3#4
31 of
Nameboththe themodule
suppliersusetable and the connection
to establish Shipment table are
between 2
drawn from
python the same
and mysql domain.
database ? name the function which
Ans Mysql.connection
check connection established or not

Is_connect()
32 Differentiate between DDL and DML Commands 2
Ans Data definition language Commands :that allow you to
perform task related to data definition.Data Manipulation
Language:Commands that allow you to perform data
manipulation
33 Find and write the output of the following Python code: 2

def fun(s):

k=len(s)

m=" "

for i in range(0,k):

if(s[i].isupper()):

Ans The new string is:


SCHOOLbbbbCOM m=m+s[i].lower()
Se
elif s[i].isalpha(): cti
34 on
Write a function listchange(Arr,n)in Python,which accepts 3
-
m=m+s[i].upper()
II
a list Arr of numbers and n is an umeric value by which
else:
all even numbers doubled and odd number multiply by
m=m+'bb'
Ans 3 . Sample
Def Input Data of the list
listchange(arr,n):
print(m)

Arr=For
[ 10,20,30,40,12,11],n=6
fun('school2@com')
a in range(n):

OutputIf(arr[a]%2==0):

35 Arr[a]=arr[a]*2
Write 3
Arr =a [20,40,60,80,24,33]
Python program to find the number of words in a
text file. Or
Else
Write a Python program to count all the line having 'a' as
Arr[a]=arr[a]*3
last character
count =0
f=open("abc.t
xt","r")
data=f.readlin
es()
print(data)

for line in data:

if line[-
2] ==
What is the'a':
output for (i) to (iii) based on a table 3

COMPANY and CUSTOMER.


count=count+1

print("Number of lines having 'a' as last character


is/are : " ,count)

f.close()

1. SELECT COUNT(*) , CITY FROM


COMPANY GROUP BY CITY;

2. SELECT MIN(PRICE), MAX(PRICE) FROM


CUSTOMER WHERE QTY>10;
3. SELECT PRODUCTNAME,CITY, PRICE
FROM COMPANY, CUSTOMER WHERE
COMPANY. CID=CUSTOMER.CID AND
PRODUCTNAME=”MOBILE”;
Ans

1.
2. 50000,70000

37 3. 11 3
Write a function in python, PushEl(element) and
MakeEl(element) to add a new element and delete a element
from a List of element Description, considering them to act as
push and pop operations of the Stack data structure . OR

Write InsertQ(Customer) and DeleteQ(Customer)

methods/functions in Python to add a new Customer and

delete a Customer from a list of Customer names,

considering them to act as insert and delete operations of the

Queue
def PushEl(element):
a=int(input("enter package title : "))
element.append(a)
def PopEl(element):
if (element==[]):
print( "Stack empty")
else:
print ("Deleted element:", element.pop())

or

def InsertQ(queue):
a=input(“Enter customer name :”)
queue.append(a)
def DeleteQ(queue):
if (queue==[]):
print (“Queue is empty…..”)
else:
print(“Deleted element is”, queue[0])
del queue[0]

Secti

on-
III
38 Vidya Senior Secondary Public School in Nainital is setting 5
up the network between its different wings. There are 4
wings named as SENIOR(S), JUNIOR(J), ADMIN(A) and
HOSTEL(H).
Distance between various wings are given below:

1. Suggest a suitable Topology for networking the


computers of all wings.

2. Name the most suitable wing where the Server


should be installed. Justify your answer.

3. Suggest where all should Hub(s)/Switch(es) be


placed in the network.

4. Which communication medium would you suggest to


connect this school with its main branch in Delhi ?

5. What is router ?
1.
2. Server should be in Wing S as it has the maxi-mum
number of computers. 1
3. All Wings need hub/switch as it has more than
one computer.

4. Since the distance is more, wireless transmission


would be better. Radiowaves are reliable and can
39 travel
Consider thethrough obstacles.
following tables RESORT and OWNEDBY and 5
answer (a) and
5. Directs the(b)packets
parts of
to this
the question:
destination

(a)Write SQL commands for the following statements:

1. To display the RCODE and PLACE of all ‘5 STAR’


resorts in the alphabetical order of the place from
table RESORT.

2. To display the maximum and minimum rent for each


type of resort from table RESORT.

3. To display the details of all resorts which are started


after 31-DEC-05 from table RESORT.

4. Display the OWNER of all ‘5 STAR’ resorts from


tables RESORT and OWNEDBY.

5. Display the maximum rent


Ans 1. SELECT MIN(RENT) FROM RESORT Where PLACE =
‘KERALA’;

2. SELECT TYPE, START DATE FROM RESORT Where


TYPE ‘2 STAR’

ORDERBY STARTDATE,

3. SELECT PLACE, OWNER FROM OWNED BY Where


PLACE LIKE “%A”;
In a school class there are students [roll_no,marks,data] whos
40 information are stored
4. SELECT RCODE, in RENT
afile student.dat
FROM RESORT,write OWNEDBY
a user define 5
function to update the records of students whos roll is given .
OR WHERE (RESORT PLACE= OWNEDBY. PLACE AND TYPE =
‘3 STAR’);
xyz.pvt company storing their employees data in file empl.dat
which have [employee_number,salary] as data write a function
5. SELECT MAX(RENT) FROM RESORT
to increase the salary by Rs. 2000/- of the employee having
empno 1251 in the file empl.dat.
Ans import pickle

f=open("student.dat","rb+")

stre=pickle.load(f)

found=0

roll=int(input("enter the roll number "))

for r in stre:

rno=r[0]

if rno==roll:

print(" name of the student",r[1])

r[1]=input("enter the name")

r[2]=int(input("enter the mark"))

found=1

break

if found==1:

f.seek(0)

pickle.dump(stre,f)

print ("name and marks updated")

f.close()

or

import pickle

import os

emp={}

found=False

f=open("emp1.dat","rb")

t=open("temp","wb")

try:

You might also like