Xii Cs Study Material (2022-23)
Xii Cs Study Material (2022-23)
अध्ययन सामग्री
STUDY MATERIAL
कक्षा बारहिी ं
CLASS: XII
SUBJECT: COMPUTER SCIENCE (083)
सत्र 2022-23
SESSION 2022-23
Our Inspiration
Dr. D. Manjunath
Deputy Commissioner, KVS RO Jammu
SUBJECT CONVENOR
MODERATION BY:
2. Learning Outcomes
Student should be able to
a) apply the concept of function.
b) explain and use the concept of file handling.
e) use Database concepts, SQL along with connectivity between Python and SQL.
3. Distribution of Marks:
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.
S.No Marks
Unit (Total=30)
Name
1 Lab Test:
● 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.
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.
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.
1. Expressions,
2. Statements,
3. Comments,
4. Functions,
5. Block and Indentation.
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
DATA TYPES
b=999999999999999999
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
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 −
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
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.
Method Description
if statement.
if-else statement.
if-elif statement.
Loop Types
Syntax:
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
break.
continue.
pass.
FUNCTION IN PYTHON
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.
Example
Calling a Function
my_function()
Types of Function:
BUILT-IN :
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.
import random
Examples :
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.
def my_func():
my_func()
x=20
def my_func():
my_func()
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)
x=20
def my_func():
global x
x=x+10
print(‘value inside function’, x)
my_func()
MUTABLE ARGUMENTS :
In Python, Mutable arguments are always passed by reference. The
following snippet will confirm this:
myFun(lst);
def myFun(x):
myFun(lst);
IMMUTABLE ARGUMENTS:
print(‘value of n is’,n)
value of n: 20
n 20
n 20
SOLVED QUESTIONS:-
Q1
What are tokens in Python? How many types of tokens are allowed in
Python? Exemplify your ANS.
ANS:
Q 2
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:
Q5
ANS.
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.
1. Lists
2. Dictionaries
3. Sets
Q 7
ANS.
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
count = 0
while count < 10:
print ("Hello")
count += 1
ANS.
OUTPUT:-
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Q 9
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
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
Q 11
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
for x in 'lamp':
print(str.upper(x))
ANS.
OUTPUT:-
L
A
M
P
Q 13
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.
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:-
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:-
Q 17
Sample run :
ANS.
OUTPUT:-
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
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:-
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
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
ANS
Q 25
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
(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
ANS
ANS
Q 29
What is the difference between interactive mode and script mode in Python?
ANS
Q 30
ANS
print(newdic)
Q 31
ANS
OUTPUT
Q 32
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
Q 33
ANS
if (n%2==0):
else:
OUTPUT
enter a number 45
number is odd
Q 34
PROGRAM TO FIND THE DAY OF THE WEEK
ANS
if n==1:
elif n==2:
print("day is monday")
elif n==3:
elif n==4:
print("day is wednesday")
elif n==5:
elif n==6:
elif n==7:
print("day is saturday")
else:
OUTPUT
>>>enter day of 2
day is Monday
>>>enter day of 5
day is thursday
>>> enter day of 8
Q 35
ANS
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("result is ",res)
OUTPUT
enter a number 4
enter a another number34
enter a character*
result is 136
Q 36
ANS
dis=450km
average=20
time =dis/average
OUTPUT
Q 37
ANS
avg = n1+n2+n3+n4+n5/5
Q 38
ANS
p=2000
r=5
t=6.5
s = p*r*t/100
Output
Q 39
ANS
OUTPUT
Q 40
ANS
print("name is")
s2=s+s1
print(s2)
l=len(s2)
print("slice",s2[-2:-9:-2])
OUTPUT
name is
HARSIMRANSINGH
slice GINR
Q 41
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
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
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
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
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
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
OUTPUT
Q 51.
z=x+y
#main
sum(12,56)#function calling
OUTPUT
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.
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.
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
265
Q 55.
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
Q 56.
#program to calculate factorial using function
result=1
while num>=1:
result=result*num
num=num-1
print(result)
#main
fact(8)#function calling
OUTPUT
40320
Q 57.
def simpleint(p,r,t):
si=p*r*t/100
#main
simpleint(1000,5,6)
OUTPUT
Q 58.
z=x-y
print("sub is",z)
#main
sub(70)#calling of funtion
OUTPUT
sub is 60
Q 58.
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:
else:
OUTPUT
enter a number 9
tne sum is 45
Q 59.
def greet_msg(name,msg):
print("hello",name,msg)
#main
greet_msg(name="vivek",msg="good afternoon")
OUTPUT
Q 60.
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)
for i in result:
print(i)
OUTPUT
the result obtained are:
112
-22
3015
0.6716417910447762
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.
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
1 (current postion of
cursor)
2 (end of file)
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’)
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 ?
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
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.
Line 4
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.
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”)
5. Name the function that will return the position of cursor in the file ?
Ans: tell()
BINARY FILE
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.
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:
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:
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_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.
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.
import pickle
or
The load function inside the pickle module is used to read the contents of a
binary file.
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.
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.
pickle. dump(object,file_handle)
here the object is being written in the binary file that is being pointed by the file
handle.
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.
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.
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.
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.
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()
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
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.
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:
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.
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.
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.
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.
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.
data = csv.reader(csvfile)
print(‘ID Departmentalize’)
print(‘-----------------------------------‘)
print(row[0],row[1])
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.
def CreateCSV1():
Csvfile = open(‘student.csv’,’w’,newline=’’)
Csvobj = csv.writer(Csvfile)
while True:
Rno = int(input(‘Rno:’))
Name = input(‘Name:’)
Marks = float(input(‘Marks:’))
Line = [Rno,Name,Marks]
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.
def CreateCSV2():
Csvfile = open(‘student.csv’,’w’,newline=’’)
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
Csvobj.writerows(Lines)
Csvfile.close()
Q6: In the above Q, create a function to Display the contents of the csv file.
defShowAll():
Csvfile = open(‘student.csv’,’r’,newline=’’)
Csvobj = csv.reader(Csvfile)
print(Line)
Csvfile.close()
if Option ==’1’:
CreateCSV1()
CreateCSV2()
ShowAll()
else:
break
Q7: Create a binary file ‘emp’ that stores that records of employees and display
them one by one.
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.
f1 = open(‘emp.dat’,’rb’)
e = pickle.load(f1)
for x in e:
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’
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?
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?
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?
Q5: Which of the following functions do you use to write data in the binary
format?
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
Q8: Which of the following function is used to write multiple rows at once in a
csv file?
Q9: Which of the following module is used to deal with csv file in a python
program?
TRUE OR FALSE
Q1: When you open a binary file for reading, if the file doesn’t exist, an error
occurs.
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.
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.
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
_______.
(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.
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.
2 MARKS EACH
(i) CSV
(ii) TSV
Q5: What is the difference between the dump( ) and load( ) functions of Pickle
module?
import csv
file = open(‘contacts.csv’,’a’)
file.close()
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.
3 MARKS EACH
Q2: What will be stored in the file school.csv after the following code is executed?
import csv
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:
stu = pickle.load(fin)
ifstu[‘Marks’] in [92,93,94]:
pickle.dump(stu,fin)
except:
Fill in the blanks in Line 1 , Line 2 and Line 3 to complete the code.
1. import csv
2. data = [‘one’,2,[3,4,5]]
3. with open(‘data2.dat’,’rb’) as f:
4. pickle .dump(data,f)
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:
import pickle
Names = [‘First’,’Second’,’third’,’fourth’,’fifth’]
lst = [ ]
fori in range(-1,-5,-1):
lst.append(Names[i])
pickle.dump(lst,fout)
nlist = pickle.load(fin)
print(nlist)
import pickle
list1,list2 = [2,3,4,5,6,7,8,9,10],[]
fori in list1:
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
MULTIPLEX = {‘MNO’:____,’MNAME’:_______,’MTYPE’:_______}
Item_Name string
Qty integer
Price float
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
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
… … …
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:
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
(c) The records are to be read row by row , not field by field. For this fill in
(d) Sonu wants to print only the departments in locations ‘Mohali’. Complete
(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
The Program intends to print from a csv file (people.csv) that stores tab
separated fields as:
print(_______) #Line5
(a) Complete the Line2 of the given code so that the given csv file is opened
(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
(d) Modify the code of Line4 and Line5 so that only the fourth field (Phone)
(e) Write the output obtained by running the code of Line4 and Line5.
defaddCsvFile(UserName,Password):
f = open(‘user.csv’,’_______’) #line 2
newFileWriter =csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
defreadCsvFile():
print(row[0],row[1])
newFile.__________ #Line 4
addCsvFile(‘Arjun’,’123@456’)
addCsvFile(‘Sandhya’,’arjk#rjkjhk’)
addCsvFile(‘sandeepsn72’,’sadsdasd’)
readCsvFile() #Line 5
(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.
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
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’]
___________________________________] #Fill_1B
(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
(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
_____._______([“SNo.,”State”,”Capital”]) #Fill_Line2
___________________________________ #Fill_Line3
___________________________________ #Fill_Line4
___________________________________ #Fill_Line5
___________________________________ #Fill_Line6
___________________________________ #Fill_Line7
___________________________________ #Fill_Line8
(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
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
Q1: rb+
Q2: dump()
Q3: load()
Q4: dump()
Q5: delimiter
Q6: close()
Q7: comma
Q8: delimiter
Q9: pickle
Q10: a+
Q3: (a) Both A and R are true and R is the correct explanation for A
Q5: (a) Both A and R are true and R is the correct explanation for A
2 MARKS EACH
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.
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.
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)
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)
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
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)
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)
frequency[ch]=c
fin.close()
bin = open(‘freq.dat’,’w’)
pickle.dump(frequency,bin)
bin.close()
Q6:
fin = open(filename,’r’)
program = fin.read()
print(program)
Q7:
import csv
import pickle
cin = open(‘inputcsvfile.csv’,’r’)
cr = csv.reader(cin)
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
3 MARKS EACH
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.
Q2:
fin = open(‘stu.dat’,’rb+’)
try:
while True:
stu = pickle.load(fin)
ifstu[‘Marks’] in [92,93,94]:
pickle.dump(stu,fin)
except:
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)
(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 binary file, conversion of newline to carriage-return and linefeed does not take
place.
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 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:
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 :-"))
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 :-")
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.seek (0)
try:
while True :
rpos = fin.tell()
emp = pickle.load(fin)
ifemp['Empno'] == 1251 :
pickle.dump(emp, fin)
print (emp)
found = True
exceptEOFError:
if found == False:
else:
fin.close()
Q5:
import csv
fh = open("Sport.csv", "w")
ans = 'y'
i = 1
whileans == "y":
print("Record", i)
swriter.writerow(srec)
i = i + 1
fh.close()
Q1:
print(row)
defDepLocation(loacation):
data = csv.reader(csvfile,delimiter=’’)
if location in row:
print(row)
loc = “Mohali”
DepLocation(loc)
Q2:
print(row)
(d) for row in fin:
print(row[3])
(e) 295000
610011
92055
69700
Q3:
Q4:
Studata = [[“First_name”,”Second_name”,”Marks”,”Grade”],
s1,s2,s3,s4,s5]
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:
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
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.
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
Network Terminology
It is of 4 bytes It is of 6 bytes
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
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
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
Gateway
Ethernet Card
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
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.
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
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
Radio Wave
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
Bluetooth
Topology
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.
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.
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.
Tree Topology
In Tree Topology, the devices are arranged in a tree fashion similar to the
branches of a tree.
It multilayer architecture.
Types of Protocol
TCP/IP
FTP
HTTP/HTTPS
IMAP
OP3
SMTP
PPP
TELNET
VoIP
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 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.
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
Advantage of VoIP
Disadvantages of VoIP
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
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.
HTML XML
It is static It is dynamic
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
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.
Domain names
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 :
ANS 1969
8 What is the difference between the Internet and the World Wide Web?
ANS National Science Foundation, a federal agency of the USA funded NSFNET.
ANS Internet
ANS 1990
16 While transferring data on the internet, the message is divided into small
units called as____________________________
ANS Packets
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
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.
ANS PAN (Personal Area Network), LAN (Local Area Network), MAN
(Metropolitan Area Network) and WAN(Wide Area Network)
Time Saving.
ANS Security issues may arise if proper security measures are not in place.
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.
ANS 32 bits
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?
39 In which type of switching technique the data is divided into smaller units
before transmission?
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.
55 Write the one advantage and one disadvantage of Optical fibre cable
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.
ANS Repeaters are used to amplify the signals, when they are transported over
a long distance.
ANS i. MODEM -
MOdulatorDEModulator ii. RJ45
- Registered Jack-45
ANS Text, images, audio, video and other multimedia files can be transferred
over the web using the HTTP protocol
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?
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?
He gets a list of search results in his web browser. Which protocol was
used in this task?
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.
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.
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?
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.
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.
Domain Indicator
ANS HTTPS
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.
ANS Apache HTTP Server, Microsoft IIS (Internet Information Services) Server,
Apache Tomcat, NGINX
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.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.
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.
Tables
Records
Fields
Data
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.
Advantages of SQL:
1. Portable
2. No coding required
3. Easy to use
4. Compatible
5. Case insensitive
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.
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;
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
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;
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
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.
cursorobj.execute(query)
connectionobj.commit()
cursorobj = connectionobj.cursor()
cursorobj.execute(query)
connectionobj.commit()
cursorobj = connectionobj.cursor()
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
cursorobj = connectionobj.cursor()
cursorobj.execute(query)
records = cursorobj.fetchall()
for x in records:
print(x)
cursorobj = connectionobj.cursor()
cursorobj.execute(query)
records = cursorobj.fetchone()
for x in records:
print(x)
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
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
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
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
09 1 0
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);
Here O_Id will be the primary key as it will contain unique data for each tuple in
the table.
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.
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
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.
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
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
Q4. Which clause is used in query to place the condition on groups in MYSQL?
Ans. HAVING
Q10. Which clause helps to sort query results by one or more columns?
Ans. ORDER BY
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
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”)
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))")
1 Sandeep 18
2 Akash 22
3 Gautam 21
1 44154 2
2 69871 3
3 17452 2
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';
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.
E E M
BUS
V03 ORDINARY 80
BUS
V04 CAR 18
V05 SUV 30
Table: TRAVEL
CNO CNAME TRAVELDAT KM VCOD NOP
E E
101 K. Niwal 2015-12-13 200 V01 32
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
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
Recipients
RecI SenderI RecName RecAddress recCity
D D
KO05 ND01 R 5, Central Avenue Kolkata
Bajpayee
Mahajan
2 Swamy
Vihar
every Recipient
(‘Mumbai’, ‘Kolkata’) ;
ANS.
a. Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress
d.
A.SenderName B.RecName
R Jain H Singh
S Jha P K Swamy
e.
RecName RecAddress
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
Ans.
1. Degree =4, Cardinality = 5
2. Yes
3. Drop club
4. Insert into store values(“M005”,”rohit”,”jaipur”,16,2000)
5. Desc store
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
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;
Table: CLUB
_ID NAME
ANS.
i) COUNT(DISTINCT SPORTS)
ii) MIN(AGE)
34
iii) AVG(PAY)
2665
iv) SUM(PAY)
2665
v) PAY+500
1400
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()
I. Display the sum of all Loan Amounts whose Interest rate is greater than
10.
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.
Ans.
III. Mysql> select count( * ) from LOANS where Cu st_Name like '%Sharma';
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.
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
Table: MobileStock
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
Client
C_ID ClientName City P_ID
Shop
Woman
(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;
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
e nt in y er
1 Jatin 34 Computer 10/01/201 12000 M
Sc 7
cs 6
cs 7
Sc 7
a cs 8
Table :Posting
1 History Agra
2 Mathematics Raipur
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
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
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;
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
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;
Table: Employee
empID empName empDept Salary
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
General Instructions:
1. This question paper contains two parts A and B. Each part is compulsory.
b. Section – II has two case studies questions. Each case study has 4
5 subparts.
No. allocated
Section-I
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]
x.
Rs. 1 crore and has to submit his account details. Identify the
print(name[2:13:2])
a) Unique
b) Distinct
c) Primary Key
d) NULL
21 Rearrange the following terms in decreasing order of data 1
transfer rates.
are as:
MedicineNo - numeric
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
following:
should he write?
23 Rajat Kumar of Class 12 is writing a program to create a CSV
given task.
import # Line 1
writerObj.writerow([empName,empId])
f.close()
print (row[0],row[1])
fobj.close()
# Line 4
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
OR
Differentiate between Client Software and Web Browsers. Write
any two popular web browsers.
26 Expand the following terms: 2
OR
Example.
code.
Def myfun():
a = pi * Math.pow(r,2)
Print (“Area = ”, a)
29 What possible outputs(s) are expected to be displayed on 2
following code?
import random
x = 3
N = random, randint (1, x)
for i in range (N):
print(i, ‘#’, i + i)
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
Fashion
Time
Sale
W001 10 1
W002 8 2
W003 15 1
W001 12 3
W003 11 2
W004 9 1
W002 15 1
BY QUARTER;
OR
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.
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
OR
SAMPLE PAPER -1
Computer Science – 083
MARKING SCHEME
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
(d) Line 4 : as we have opened the file in “with” operator, it closes itself 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
runs attached with virus it perform some action such as deleting a file from the
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
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
(such as the internet’s world wide web). However, a client software doesn't
Popular web browsers : Google Chrome, Mozilla Firefox, Internet Explorer etc
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
Ex:
#body of function
In keyword arguments, we call a function with some values and these values
Ex:
#body of function
greet(msg = “Hello”, name= “Sandeep”) #function called here
OR
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.
Language
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
Wave 200 26
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
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
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)
General Instructions:
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.
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
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
Member_Name:string
Address: String
Fees :number
2. Yes
1.
3. What is the cardinality and degree of the given
Drop club
table?
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
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
NOTE=""
for S in range[0,8]:
print STRING(S)
print S+STRING
Ans STRING= "WELCOME"
NOTE=""
X=3
print S.STRING
N=random.randint(1,X)
For I in range(N):
Print(I,”#”,i+1)
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()):
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)
if line[-
2] ==
What is the'a':
output for (i) to (iii) based on a table 3
f.close()
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
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:
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.
ORDERBY STARTDATE,
f=open("student.dat","rb+")
stre=pickle.load(f)
found=0
for r in stre:
rno=r[0]
if rno==roll:
found=1
break
if found==1:
f.seek(0)
pickle.dump(stre,f)
f.close()
or
import pickle
import os
emp={}
found=False
f=open("emp1.dat","rb")
t=open("temp","wb")
try: