Class 12 Exam Revision Material
Class 12 Exam Revision Material
Class 12 Exam Revision Material
Num=3 , num=24
python will consider both the variables differently though their pronunciation is same.
Q Explain Keyword .
Ans Keywords are the reserve words/pre-defined words/special words of python
Keyword Identifier
These are system defined words These are user defined words
These can have only letters these can have letters, digits and a symbols underscore.
These are reserved These are not reserved
For example : if, else, elif etc. For example : chess, _ch, etc.
Question: What are literals in Python ? How many types of literals are allowed in Python ?
Answer:
Literals mean constants i.e. the data items that never change value during a program run. Python allow five types of literals :
String literals Numeric literals, Boolean literals, Special literal Literal collections like tuples, lists
(None),
Question : How many ways are there in Python to represent an integer literal ?
Answer: 3 types of integer literals :
Decimal (base 10) integer literals Octal (base 8) integer literals Hexadecimal (base 16) integer literals
Numbers between 0-9 Begin with 0o Begin with Ox
arithmetic +,-,/,*,%,**,//
bitwise &, ^, |
Identity is, is not
(these are used to compare the memory locations of two objects). These can be used in place of
== (is) and != (is not)
Relational >,<,>=,<=,==,!=
(comparison ) (these operators are used to compare the values)
logical and, or, not
(these are used to perform logical operations on the given two variables or values.)
shift <<, >>
Assignment =
(these are used to assign values)
Membership in, not in
(these operators used to validate whether a value is found within a sequence such as such as
strings, lists, or tuples.)
arithmetic- +=, -=, //=, **=, *=, /=
assignment
Write the full form of IDLE Which of the following is not an assignment operator?
Ans integrated development learning environment
i.) **= ii.) /= iii.) == iv.)
%= Ans (iii) ==
Write the type of tokens from the following. Find the correct identifiers out of the following, which can
be used for naming Variable, Constants or Functions in a
i. _Var ii. In python program :
Ans (i) identifier (ii) For, while, INT, NeW, del, 1stName, Add+Subtract,
operator- membership operator name1 Ans For, INT, NeW, name1
Find the correct identifiers out of the Which of the following is valid logical operator
following, which can be used for naming (i) && (ii) > (iii) and (iv)
variable, constants or functions in a python == Ans (iii) and
program :
While, for, Float, int, 2ndName, A%B, Amount2,
_Counter
Ans While, Float, _Counter, Amount2
Write the data type of following literals: Which of the following is not a valid identifier name in
(i) 123 (ii) True Python? Justify reason for it not being a valid name.
Ans (i) number-integer (ii) Boolean a) 5Total b) _Radius c) pi d)While
Ans (a) 5total-it starts with number (c) pi-is a keyword
Which of the following are valid operator in Which of the following are Keywords in Python ?
Python: (i) break (ii) check (iii) range
(i) */ (ii) is (iii) ^ (iv) like (iv) while Ans (i) break (iii)
Ans (ii) is-identity operator range (iv) while
Find the invalid identifier from the following Which of the following is valid arithmetic operator in Python:
a) def b) For c)_bonus d)First_Name (i) // (ii)? (iii) < (iv)
and Ans (i) //
Ans (a) def
Find the invalid identifier from the following Which operator is used for replication?
a) Subtotal b) assert c) temp_calc d) Name2 a) + b) % c) *
d) // Ans (c) *
Ans (b) assert- it is a keyword
What is the value of the Identify the invalid keyword in Python from the following:
expression 4+4.00, 2**4.0 (a) True (b) None (c) Import (d)
Ans (8.0, 16.0) return Ans (c) Import
Find the operator which cannot be used Name the mutable data types in Python.
with a string in Python from the following: Ans : list,dictionary
(a) + (b) in (c) *
(d) // Ans
(d) //
Find the valid identifier from the following Identify the valid logical operator in Python from the
a) My-Name b) True c) 2ndName d) following.
S_name a) ? b) < c) ** d)
and Ans (d) and
Ans (d) S_name
Which one is valid relational operator in Python Which of the following can be used as valid variable
identifiers in Python?
a). / b). = c). = = d). a) 4th Sum b) Total c) Number# d)
and Ans (c) == _Data Ans (b) Total (d) _Data
Identify the mutable data types? Which of the following are valid operators in Python:
(a) List (b) Tuple (c) Dictionary (d) String (a) ** (b) between (c) like (d) ||
Ans (a) **
Ans (a) List (c) Dictionary
Find the invalid identifier from the following Which of the following is a valid assignment operator
a) yourName b) _false c) 2My_Name d) in Python ?
My_Name a) ? b) < c) *= d) and e) //
Ans (c) *=
Ans (c) 2My_Name
Which of the following is not a valid Which of the following is valid relational operator in
identifier in Python? Python: (a)// (b)? (c) <
a) KV2 b) _main c) Hello_Dear1 d) 7 (d) and
Sisters Ans (d) 7 Sisters
Ans (c) <
Find the valid identifier from the following Identify the invalid logical operator in Python from the
a) False b) Ist&2nd c) 2ndName d) My_Name following.
a) and b) or c) not d)
Ans (d) My_Name Boolean Ans (d) Boolean
Which of the following variable names are
invalid ? Justify.
(a) try
(b) 123 Hello
(c) sum
(d) abc@123
Answer:
(a) try : is a keyword can’t be used as an identifier.
(b) 123 Hello : Variable names can’t start with a
digit.
(c) abc@123 : Special characters aren’t allowed
in variable names.
Parentheses|Exponentiation|Multiplication|Division|Addition|Subtraction
Operators Meaning
() Parentheses
** Exponent
*,/, //, % Multiplication, Division, Floor, Division,
Modulus
+,- Addition, Subtraction
==,!=,>,>=,<,<=, is, is not, in, not in Relational,Identity,Membership Operators
Not Logical NOT
And Logical AND
Or Logical OR
Operator evaluations - questions
3. An escape sequence always starts with backslash followed by one or more special characters.
4. Escape Sequences must be enclosed in single quotes or in double
quotes. few Escape sequences are:
Question : What will be the size of the following constants : “\a”. “\a”, “Manoj\’s”, ‘\”, “XY\ YZ”
Answer:
‘\a’. “\a” “Manoj\’s” “\” “XY\
YZ
size is 1 as size is 1 as there size is 7 size is 1. It is a size is 4. It
there is one is one character because \’ is an character is a
character enclosed in escape sequence constant multiline
double quotes string
DATA TYPES
Data types are used to identify the type of data and set of valid operations which can be performed on it.
Mutable is behaving like pass by reference Immutable is behaving like pass by value
Mutable objects: list, dictionary Immutable objects: int, float, complex,
string, tuple
Everything in Python is an object ,and every objects in Python can be either mutable or
immutable.
>>>x=10
>>>id(x)
Q Which function is used to find the data type of an variable
Ans type() function is used to find the data type of any variable,object or function.
Syntax: e.g.
if n=int(input(“enter
test_expressio number”)) if n<=15:
n: if n==10:
Statement(s) print(“o
if k”)
test_expressio else:
n: print(“use another
Statement(s) option”)
elif else:
expressio print(“more than 15”)
n:
Statement
(s)
else:
Statement(s)
A while loop statement in python programming language repeatedly executes a target statement as
long
as a given condition is true.
Syntax: e.g.
while n=int(input(“enter
expression no”)) s=0
: while(n>0):
statement( s=s+n
s)
n=n-1
print(“the sum is”,s)
while loop- infinite loop
while 1: while
print(“ True:
*”) OR print(“
while 1: print(“*”) *”)
OR
while True: print(“*”)
else statement with while loops
• Python supports have an else e
statement associated with a loop .
statement g
• If the else statement is used with a .
while loop, the else statement is c
executed when the condition false. =
0
while c<3:
print(“inside
loop”) c=c+1
else:
print(“outside loop”)
Note: else statement execution is optional in conditional statement( if statement) ,but in loops it will definitely execute
For loop
• The for loop is another repetitive control structure, and is used to execute a set of
instructions repeatedly, until the condition becomes false.
• The for loop in python is used to iterate over a sequence (list,tuple,string) or other
iterable objects. Iterating( means use loop concept) over a sequence is called traversal.
Syntax:
for val in expression: e.g.
Body of the for loop for i in [1,2,3]: #list
usage print(i)
expression -> tuple|string|list|dictionary|range() for i in (1,2,3): #tuple
usage print(i)
for i in “hello”: #string
usage print(i)
for i in {1:’a’,2:’b’}: #dictionary
usage print(i)
range( start, end-1, e.g.
step_value) note: for i in range(5): #take values
if only one value is specified then it takes 0,1,2,3,4 print(i)
only end-1 and will take 0 as starting value for i in range(1,5): #take values
1,2,3,4 print(i)
for i in range(1,5,2): #take values 1,3
print(i)
JUMP STATEMENTS
• Jump statements are used to transfer the program's control from one location to another.
• Means these are use d to alter the flow of a loop like - to skip a part of a loop or terminate a loop.
3 types of jump statements used in python. 1) break 2) continue 3) pass
r r r
The end
n i
g n
The end
g
The end
String data type- is an ordered and immutable data type that can hold any known character like letters, numbers, special
characters etc . e.g. "abcd", "$@&%", '???', "1234", "apy”
List data type- is an ordered and mutable group of comma-separated values of any datatype enclosed in square brackets []
Elements in a List can be individually accessed using its index (positive or negative)
Positive index value 0 1 2 3 4
List 1 2 3 4 5
3 6 8
Negative index value -5 - - - -
4 3 2 1
lists can store elements belonging to Strings store single type of elements-all characters
different types.
It is represented by [] It is represented by “ “ or ‘ ‘
e.g. e.g.
L=[1,2,3,4] s=”hel
lo”
s1=’world’
String and List – practice questions
h
v
i
lr
la
ot
If the following code is executed, what will Given the list
be the output of the following code? Lst = [ 12, 34, 4, 56, 78, 22, 78, 89],
name="Computer Science with Python" find the output
print(name[2:10]) of
Ans mputer print(Lst[1:6:2
S ])
Ans [34,56,22]
Give the output of the following Write the output of the following
code: L = [ 1,2,3,4,5,6,7] python statements:
B=L Array=[8,5,3,2,1,1]
B[3:5] = 90,34 print(Array[-1:-6:-1])
print(L) Ans 11235
Ans [1, 2, 3, 90, 34, 6, 7]
Given the lists L=[1,3,6,82,5,7,11,92] Given the lists L=[“H”, “T”, “W”, “P”,
, “N”] , write the output of
What will be the output of print(L[3:4]) Ans [“P”]
print(L[2:5]) Ans [6,82,5]
Write the output of following Given the lists
code t1 = [10, 12, 43, 39] L=[1,3,6,82,5,7,11,9
print(t1*3) 2] ,
Ans write the output
[10, 12, 43, 39, 10, 12, 43, 39, 10, 12, 43, 39] of print(L[1:6])
Ans [3,6,82,5,7]
Identify the valid declaration of L: L If the following code is executed, what will be the
= [‘Mon’, ‘23’, ‘hello’, ’60.5’] output of the following code?
a). dictionary b). string c).tuple d). name="ComputerSciencewithPython"
list print(name[3:10])
Ans puterSc
Ans (d) list
Which statement is not correct What will be the output of following code
a) The statement x = x + 10 is a snippet: msg = “Hello Friends”
valid statement msg [ : : -1]
b) List slice is a list itself. a) Hello b) Hello Friend
c) Lists are immutable while strings c) 'sdneirF olleH' d) Friend
are mutable. Ans (c)
d) Lists and strings in pythons support
two way indexing.
e) Ans (c)
Identify the valid declaration A list is
of L: L = [1, 23, ‘hi’, 6] declared as
(i)list L=[(2,5,6,9,8)]
What will be the value
(ii)dictionary of print(L[0])?
(iii)array (iv)tuple Ans (2,5,6,9,8)
Ans (i) list
What will be the output when the If the following code is executed, what will be the
following code is executed output of the following code?
>>> str1 = “helloworld” name="Kendriya Vidyalaya Class
>>> str1[ : -1] 12" print(name[9:15])
a). 'dlrowolleh' b).‘hello’ Ans Vidyal
c).‘world’
● If the length of the string is 10 then what would be the positive index value of last element?
● Ans. 9
● If the length of string is 9, what would be the index value of middle element? 9 Ans. 4
● What type of error is returned by following statement, if the length of string 'str1' is
10. print(str1[13]) Ans. Index error
(iv)Diction
ary Ans (ii)
Tuple
A tuple is declared Consider the tuple in python
as T = (1,2), (1,2,4), named
(5,3) DAYS=(”SUN”,”MON”,”TUES
What will be the value of min(T) ? ”)
Identify the invalid statement(s) from
Ans (1,2) the given below statements:
a). S=DAYS[1] b). print(DAYS[2])
c). DAYS[0]=”WED” d).
LIST=list(DAYS) Ans (c)
DAYS[0]=”WED”
Suppose a tuple Tup is declared What is the output of the following
as Tup = (12, 15, 63, 80), code: for i in range(-3,4,2):
which of the following is incorrect? print(i, end =
a) print(Tup[1]) b) Tup[2] = 90
c) print(min(Tup)) d) print(len(Tup)) '$') Ans -3$-1$ 1$
Ans (b) Tup[2]=90
3$
If a is (1, 2, 3), what is the difference (if any) If a is (1, 2, 3), is a *3 equivalent to a +
between a*3 and [a, a, a]? a+ a?
Ans: a*3 is different from [a,a,a] because, a*3 Ans yes
will produce a tuple (1,2,3,1,2,3,1,2,3) and [a, a,
a] will
produce a list of tuples [(1,2,3),(1,2,3),(1,2,3)].
Does a slice operator always produce a new How is an empty Tuple
Tuple? Ans: Yes created? Ans: T=() or
T=tuple()
How is a tuple containing just one element What is the difference between (30)
created? Ans: T=3, or T=(4,) and (30,)?
Ans: (30) is an integer while (30,) is a
tuple
Predict the Predict the
output output
G=’a’,’b’ T=(1,)*3
H=(‘a’,’b’) T[0]=2
print(G== print(T)
H) Ans Ans typeError. Tuple is immutable so
True can’t do changes
Find output Find output
(a,b,c)=(1,2 a,b,c,d=(1,2
,3) ,3)
Ans this will assign 1 to a , 2 to b and 3 to c Ans Error becoz not enough values to
pack(expected 4, got 3)
Find output How can you add an extra element
a, b, c, d, e = (p, q, r, s, t) = t1 to a tuple?
Ans If tuple t1 has 5 values then this will assign Ans T=T+(9,)
first value of t1 in to a and p , next value to b and q
and so on.
Which of the following will create a What is the output of following line of
tuple x? (a) x = (1)(b). x = (1,) code ? x= (2, 1, 4)
(c) . x = {1} (d) None of the print(len(
above Ans (b) x)) Ans 3
What is the output of following line of What is the output of following line of
code? x,y, z = (3.3, 4.1, 2.2) code? x,_, z = (3.3, 4.1, 2.2)
print(x) print(_)
Ans 3.3 Ans 4.1
What is the output of following line of code ? What is the output of following line of
_,_ = (3.3, 4.1, 2.2) code ? x = (3.3, 4.1, 2.2) *2
print(_) print(x)
Ans Ans (3.3, 4.1, 2.2, 3.3, 4.1,2.2)
Error
What is the output of following line of What is the output of following line of
code? x = (3.3, 3.3, 4.1, 4.1, 2.2, 2.2) code? x = (3.3, 3.3, 4.1, 4.1, 2.2, 2.2)
print(x.index(3. print(x[0::2] ==
3)) Ans 0 x[1::2]) Ans True
Which of the following method will not work
with Python tuple object?
a). sort() b). count()
c). index() d). None of the
above Ans (a)
+ (concatenation (combine)),
* (replicate),
s=”hello” t=[1,2,3] t=[1,2,3]
print(s+”worl print(t+[4,5, print(t+[4,5,
d”) 6]) 6])
print(s*2) print(t*2) print(t*2)
len(),
in (check for availability,
not in
count(element/
string)---
index(value)
s=”hello” t=[1,2,3,4,2] t=(1,2,3,4,2)
print(s.count(‘l print(t.count( print(t.count(
’)) print(len(s)) 2)) 2))
print(s.index(‘l print(len(t)) print(len(t))
’)) if ‘l’ in s: print(s.index( print(s.index(
print(“ok”) 2)) if 3 in t: 2)) if 3 in t:
print(“ok”) print(“ok”)
here, 'a', 'b', 'c', 'd', 'e' are the keys & 1,2,3,4,5 are the values
Module Package
A module is a single file (or files) that are A package is a collection of modules in
imported under one import and used. directories that give a package hierarchy.
No _init_.py is required in module In a package _init_.py file should be
included
Which module is used for working with CSV files in Python? Ans csv
Name the built-in function / method that is used to return the lengthof the object. Ans len()
Name the function/method required for
(a) Finding second occurrence of m in madam. Ans (a) index or find()
(b) Get the position of an item in the list Ans (b) find() or index ()
Observe the following Python code and write the name(s) of the header file(s), which will be
essentially required to run in a Python compiler.
X=randint(1
,3)
Y=pow(X,3
)
print(“hello”.upper()) Ans random,math,string
Name the built-in mathematical function / method that is used to return square root of a number
Ans sqrt()
Name the Python library module(s) which needs to be imported to run the following program:
print(sqrt(random.randint(1,16)))
Ans math,random
Which of the following function is used to write data in binary mode?
a) write ( ) b) output ( ) c) dump ( ) d) send ( ) Ans (c) dump
Function
A function is a subprogram that acts on data and often returns a
value ADVANTAGES
Types of Functions
Built –in functions Functions defined in the modules User defined functions
(Pre-defined functions) (function using (defined by the
Libraries/modul programmer)
es)
int(),type(),float(),str(), sin(),floor(),ceil(),dump(),load() PARTS OF USER
print(),input(),ord(),he ,random(),writer() etc DEFINED FUNCTIONS
x • Function definition(def keyword)
(),oct() , len() etc • Arguments( function calling)
• Parameters( function definition)
• Function Calling
Note: parameters/ arguments are the variables/values what are provided in the function definition/calling.
Categories of user defined functions
void functions Non void functions
those functions which are not returning values those functions which are returning values to
to the
the calling function calling function
return value can be literal, variable , expression
#expressions
here x,y , 5,6, x+3, y+3 are arguments
x,y=4,5
r=sum(x,y) #x, y are actual
arguments print(r)
1. e.g.
Received values as tuple def fun(a,b):
return a+b,a-b
x
=
2
y
=
4
z=fun(x
,y)
print(z)
2. e.g.
Unpack received values as tuple def fun(a,b):
return a+b,a-b
x
=
2
y
=
4
d,z=fun(x
,y)
print(d,z)
1. Variable in global scope not in local 2. Variable neither in in local scope nor
scope in global scope
e.g e.g.
def fun1(x,y): def fun():
s=x+y print(“hello”,n)
print(nu fu
m1) n(
return s )#
num1=1 Output:
00 Name error: name ‘n’ is not defined
num2=2
00
sm=fun1(num1,nu
m2) print(sm)
3. Variable name in local scope as well as 4. Using global variable inside local
in global scope scope (this case is discouraged in
e.g. programming) e.g.
def fun(): def fun():
a=10 global a
# output
a=10 #
print(a) 5 print(a) outpu
a=5 a=5
10 t5
print(a) print
10 10
fun() (a)
10
print(a) fun()
print(a)
Function Questions
Write a function that receives two Write a function that takes a positive integer and
numbers and generates a random returns the ones position digit
number from that range and prints it. of the integer. E.g. if the integer is 432, then the
import random function should return 2.
def fun(a):
def fun(a,b): r=a
print(random.randint(a,b)) %10
print(
r)
Write a program having a function Write a small python function that receive two
that takes a number as argument and numbers and return their sum, product, difference
calculates cube for it. The function does and multiplication.
not return a value. If there is no return def ADD(X,Y):
value passed to the function in function return
(X+Y) def
call, the function should calculate cube
PRODUCT(X,Y):
of 2. return(X*Y)
def DIFFERENCE(X,Y):
def fun(n=2): return(X-Y)
print(n**3)
Write a function CHANGEO ,which accepts Write function which accepts an integer array and size
an list of integer and its size as parameters as arguments and replaces elements having odd values
and divide all those list elements by 7 which with thrice its value and elements having even values
are divisible by 7 and multiply list elements with twice its value.
by 3. Example : if an array of five elements
initially contains elements as 3, 4, 5,
sol: 16, 9
def CHANGEO(A,S): The function should rearrange the content of the array
for i in as 9, 8, 15, 32,27
range(S): sol
if(A[i] def fun(d,s):
%7==0): for i in
A[i]=A[i]/7 range(s):
else: if(d[i]%2!
A[i]=A[i]*3 =0):
print("after d[i]*
change",A) =3
else:
d[i]*=2
print("after
change",d)
Write a function which accepts an integer Write a function which accepts an integer array and
array and its size as parameters and its size as arguments and swap the elements of every
rearranges the array in reverse. even location with its following odd location.
Example: Example :
If an array of nine elements initially If an array of nine elements
contains the elements as 4, 2, 5, 1,6, 7, 8, 12, initially contains the elements as
10 Then the function should rearrange the 2,4,1,6,5,7,9,23,10
array as 10, 12, 8, 7, 6, 1, 5, 2, 4 then the function should rearrange
the array as 4,2,6,1,7,5,23,9,10
sol
def fun(a,size): sol:
for i in range(size-1,-1,-1): def fun(d,s):
print(a[i],end=" ") for i in range(0,s-
1,2): if(i%2==0):
d[i],d[i+1]=d[i+1],d[i]
print("after swapping",d)
iv) calculate(x=10,b=12)
Ans#name x is not mentioned in the function
parameter . corrected code:
calculate(c=10, b=12, a=15)
find and write the output of the following python code:
(a) (b)
def change(p,q=20): def callme(n1=1,n2=2):
p=p+q n1=n1*n2
q=p-q n2+=2
print(p,'#',q) print(n1,n2)
return(p)
r=150 callme()
s=100 callme(2,1)
r=40 callme(3)
r=change(r,s)
print(r,'#',s)
s=change(s)
Ans Ans
140 # 40 24
140 # 100 23
120 # 100 64
(c) (d)
def show(x,y=2): def upgrade(a,b=2):
print(ord(x)+y) a=a+b
show('A') print(a+b)
show('B',3) i,j=10,20
upgrade(i,5)
Ans upgrade(i)
67
69 Ans
20
14
(e) (f (g)
def func(a,b=5,c=10): ) def wish(message, num=1):
print(“a:”,a,” b:”,b, “ x print(message *
c:”,c) func(3,7) = num)
func(25,c=24) 1 wish(‘Good’,2)
func(c=50, def cg(): wish(“Mornin
a=100) globa g”)
lx
Ans x=x+ Ans
a: 3 b: 7 c: 10 1 GoodGo
a: 25 b: 5 c: 24 cg() od
a: 100 b: 5 c: 50 print Morning
(x)
A
n
s
2
File Handling
Q what is the usage of file?
Ans File is created for permanent storage of data or that stores data in an application.
Q How many types of files supported by Python?
Ans 3 types of files 1)text file 2)binary file 3) CSV file)
Q Why is it necessary to close a file?
Ans
1. close() breaks the link of file object 2. In case we forgot to close the file ,
Files are automatically closed at the
end of the program,
3. After using this method, an opened 4. if our program is large and we are
file will be closed and a closed file reading or writing multiple files that
cannot be read or written any more. can take significant amount of
resource on the system. If we keep
opening new files
carelessly, we could run out
of resources.
syntax:
with open(<file_name>, <access_mode>)
as file_object/file_handler
Q Name two important functions of CSV module which are used for reading and writing.
csv.reader() returns a reader object which iterates over lines of a CSV file
csv.writer() returns a writer object that converts the user's data into a delimited string. This string can later be used to write
into CSV files using the writerow() or the writerows() function.
r+ and w+
r+ w+
Opens a file for reading and writing, placing Opens a file for writing and reading,
the pointer at the beginning of the file. overwrites the existing file if the file exists. If
the
file does not exist, creates a new file for
writing and reading
r and a
r a
Reading only for appending
Sets file pointer at beginning of the file Move file pointer at end of the file
This is the default mode. Creates new file for writing,if not exist
e.g. e.g.
f=open(“abc.dat”,’r’) f=open(“abc.dat”,’a’)
TEXT FILE AND BINARY FILE
A text file is simply a sequence of ASCII or Best way to store program information.
Unicode characters.
EOL (new line character i.e. enter) or internal No EOL or internal translation occurs( not converted
translation occurs into other form becoz it is converted into computer
understandable form i.e. in binary format)
e.g. Python programs, contents written in text editors e.g. exe files,mp3 file, image files, word documents
seek() tell()
takes the file pointer to the specified byte it gives current position within file
position
Syntax: Syntax
seek(“no_of_bytes_to_move”, fileobjectname.tell()
Example:
“from_where”) “from_where”- has 3 values f.tell()
‘w’ ‘a’
'w' Open a file for writing 'a' Open for appending at the end of the file
without truncating it.
Creates a new file if it does not exist or Creates a new file if it does not exist.
truncates
the file if it exists.
write() writelines()
write() function write a single string at a time writelines() methods can be used to write a
sequence of strings
PICKLING UNPICKLING
Pickling is the process whereby a Python object Unpickling is the process by which a byte
is converted into a byte stream. stream is converted back into the desired
object.
readline() and readlines()
readline() readlinelines()
The readline() method reads one line(i.e. till The readlines()method reads the entire content
newline) at a time from a file and returns of the file in one go and returns a list of lines
that line of the entire file.
It reads the file till newline including the
newline character.
The readline() method returns an empty string This method returns an empty value when an
when the end of file is reached. end
of file (EOF) is reached.
read() readline()
The read() method reads the entire file content The readline() method reads one line(i.e. till
of the file in one go newline) at a time from a file
it reads info character by character It reads the info line by line
The readline() method returns an empty string
when the end of file is reached.
or
f=open(“firewall.tx
t") for i in
range(3):
print(f.readline())
f=open(“firewall.txt") Write a program that reads character from
print(f.read(20)) #0 to 20 the keyboard one by one. All lower case
bytes characters get store inside
print(f.read(30)) #next 30 bytes i.e. 21 to the file LOWER, all upper case characters
30 get stored inside the file UPPER and all
(upto 50 bytes) other characters get stored
inside OTHERS.
Write a program in python to read entire
content of file ("data.txt") f=open("hello.txt")
f=open(“data.txt”,”r f1=open("lower.txt","a")
”) d=f.read() f2=open("upper.txt","a")
print(d) f3=open("others.txt","a")
r=f.read()
for i in r:
if(i>='a' and
i<='z'):
Write a program in python to read
f1.write(i)
first 5 characters from the
elif(i>='A' and
file("data.txt")
i<='Z'):
f2.write(i)
f=open(“data.txt”,”
else:
r”) d=f.read(5) f3.write
print(d) (i) f.close()
f1.close()
f2.close()
f3.close()
Write a program in python to display number Write a program in python to display first
of lines in a file("data.txt"). line from the file("data.txt") using
readlines().
f=open(“data.txt”,”
r”) d=f.readlines() f=open(“data.txt”,”
print(d) r”) d=f.readlines()
print(d[0])
Write a program in python to display first Write a program in python to display all the
character of all the lines from the lines from the file("data.txt") with first
file("data.txt"). f=open(“data.txt”,”r”) character in uppercase.
d=f.readline f=open(“data.txt”,”
s() for i in d: r”) d=f.readlines()
print(i[0]) for i in d:
print(i[0].upper+i[1:-1]))
Write a program in python to find the number Write a program in python to display last
of characters in first line of file ("data.txt") two characters of all the lines from the
f=open(“data.txt”,’r’) file("data.txt").
t=f.readline()
print(len(t)) f=open(“data.txt”,’r’)
t=f.readlines()
for i in t:
print(i[-3:])
Write a program to read all the characters Write a program to count all the upper
from the file("data.txt") and display in case characters from the file ("data.txt").
uppercase.
f=open(“data.txt”,’r’)
f=open(“data.txt”,’r’) t=f.read()
t=f.read() c=0
print(t.upper()) for i in t:
if(i.isupper()):
c=c+1
print(“total uppercase characters”,c)
Write a program to count number of spaces Write a program to count number of vowels
from the file ("data.txt"). in a file ("data.txt").
f
=open(“data.txt”,’r f
’) t=f.read() =open(“data.txt”,’r
c=0 ’) t=f.read()
for i in t: c=0
if(i.isspace() and i!=’\ for i in t:
n’): c=c+1 if(i==’a’ or i==’e’ or i==’o’ or i==’i’ or
print(“total spaces”,c) i==’u’): c=c+1
print(“total spaces”,c)
Write a function in python to count the Write a user defined function countwords() to
number lines in a text file ‘Country.txt’ which display the total number of words present in
is starting with an alphabet ‘W’ or ‘H’. the file from a text file “Quotes.Txt”.
def count_W_H():
f = open (“Country.txt”, “r”) def countwords():
W,H = 0,0 s=
r= open("Quotes.txt","r")
f.read() f = s.read()
for x in z=
r: f.split ()
if x[0] == “W” or x[0] == “w”: count =
W=W+1 0 for i in
elif x[0] == “H” or x[0] == “h”: z:
H=H+1 count = count + 1
f.clos print ("Total number of words:", count)
e() print
(W, H)
Write a user defined function countwords() to Write a function COUNT_AND( ) in Python to
display the total number of words present in read the text file “STORY.TXT” and count the
the file from a text file “Quotes.Txt”. number of times “AND” occurs in the file.
def countwords(): (include AND/and/And in the counting)
s= def COUNT_AND( ):
open("Quotes.txt","r") count=0
f = s.read() file=open(‘STORY.TXT','r
z= ') line = file.read()
f.split () word =
count = line.split() for
0 for i in w in word:
z: if w ==’AND’:
count = count + 1 count=count
print ("Total number of words:", count) +1 print(count)
file.close()
Write a function DISPLAYWORDS( ) in python to Write a function that counts and display the
display the count of words starting with “t” or number of 5 letter words in a text file
“T” in a text file ‘STORY.TXT’. “Sample.txt def count_words( ):
def COUNT_AND( ): c=0
count=0 f=
file=open(‘STORY.TXT','r open("Sample.txt")
') line = file.read() line = f.read()
word = word =
line.split() for line.split() for
w in word: w in word:
if w[0] ==’t’ or if len(w) ==
w[0]==’T’: 5: c +=
count=count+1 1
print(cou print(c)
nt)
file.close()
Write a function that counts and display the Write a function that counts and display the
number of 5 letter words in a text file number of 5 letter words in a text file
“Sample.txt def count_words( ): “Sample.txt def count_words( ):
c=0 c=0
f= f=
open("Sample.txt") open("Sample.txt")
line = f.read() line = f.read()
word = word =
line.split() for line.split() for
w in word: w in word:
if len(w) == if len(w) ==
5: c += 5: c +=
1 1
print(c) print(c)
Write a function that counts and display the Write a function to display those lines which
number of 5 letter words in a text file start with the letter “G” from the text file
“Sample.txt def count_words( ): “MyNotes.txt”
c=0 def
f= count_lines( ):
open("Sample.txt") c=0
line = f.read() f=
word = open("MyNotes.txt")
line.split() for line = f.readlines()
w in word: for w in line:
if len(w) == if w[0] == 'G':
5: c += print(
1 w) f.close()
print(
c)
f.clos
e()
Write a function in python to read lines from Write a function COUNT() in Python to read
file “POEM.txt” and display all those words, contents from file “REPEATED.TXT”, to count
which has two characters in it. and display the occurrence of the word
def TwoCharWord(): “Catholic” or “mother”.
f= def COUNT():
open('poem.txt') f=
count = 0 open('REPEATED.txt')
for line in f: count = 0
words = for line in f:
line.split() for w words =
in words: line.split() for w
if len(w)==2: in words:
if w.lower()=='catholic' or w.lower()=='mother':
print(w,end=' ')
f.close() count+=1
print('Count of Catholic,mother
is',count)
Write a method/function COUNTLINES_ET() in Write a method/function SHOW_TODO() in
python to read lines from a text file python to read contents from a text file
REPORT.TXT, and COUNT those lines which are ABC.TXT and display those lines which have
starting either with ‘E’ and starting with ‘T’ occurrence of the word ‘‘TO’’ or ‘‘DO’’.
respectively. And display the Total count def SHOW_TODO():
separately. f=open(“ABC.TX
def COUNTLINES_ET(): T”)
f=open(“REPORT.TX d=f.readline
T”) s() for i in d:
d=f.readline if “TO” in i or “DO”
s() le=0 in i: print(i)
lt=0 f.close()
for i in d:
if i[0]==’E:
le=le+1
elif
i[0]==’T
’:
lt=lt+1
print(“no of line start
with”,le) print(“no of line
start with”,lt)
Write a function in Python that counts the Write a function AMCount() in Python,
number of “Me” or “My” words present in a which should read each character of a text
text file “STORY.TXT”. file STORY.TXT, should count and display
def the occurrences of alphabets A and M
displayMe (including small cases a and m too).
My(): def AMCount():
num=0 f=open("story.txt","r")
f=open("story.txt","rt A,M=0,0
") N=f.read() r=f.read()
M=N.spli for x in r:
t() for x if x[0]=="A" or x[0]=="a" :
in M: A=A+1
if x=="Me" or x== elif x[0]=="M" or x[0]=="m":
"My": print(x) M=M+1
num=num+1 print("A or a:
print("Count of Me/My in ",A) f.close()
file:",num) f.close()
Write a function in python that displays Write a function countmy() in Python to read
the number of lines starting with ‘H’ in file Data.txt and count the number of times
the file “para.txt”. “my” occur in file.
def countH(): def countmy():
f=open("para.txt","r") f=open(“Data.txt”,”r”)
lines=0 count=0
l=f.readline x=f.read()
s() for i in l: word=x.spli
if i[0]='H': t() for i in
lines+=1 word:
print("NO of lines if i ==”my” :
are:",lines) f.close() count=count
+1
print(“my occurs “, count, “times”)
Write a Python program to find the number Write a Python program to count the word “if “
of lines in a text file ‘abc.txt’. in a text file abc.txt’.
f=open("abc.txt","r") file=open("abc.txt","
d=f.readline r") c=0
s() line =
count=len(d file.read()
) word =
print(count) line.split() for
f.close() w in word:
if w=='if':
print(
w)
c=c+1
print(c)
file.clos
e()
Write a method in python to read lines from a Write a method/function ISTOUPCOUNT() in
text file DIARY.TXT and display those lines python to read contents from a text file
which start with the alphabets P. WRITER.TXT, to count and display the
def countp(): occurrence of the word ‘‘IS’’ or ‘‘TO’’ or ‘‘UP’’
f=open("diary.txt","r
") lines=0 def ISTOUPCOUNT():
l=f.readline c=0
s() for i in l: file=open('sample.txt','r
if i[0]='P': ') line = file.read()
lines+=1 word =
print("No of lines are:",lines) line.split()
cnt=0
for w in word:
if w=='TO' or w=='UP' or
w=='IS': cnt+=1
print(c
nt)
file.clos
e()
Write a code in Python that counts the number Write a function VowelCount() in Python, which
of “The” or “This” words present in a text file should read each character of a text file
“MY_TEXT_FILE.TXT”. MY_TEXT_FILE.TXT, should count and display
c=0 the occurrence of alphabets vowels.
f=open('MY_TEXT_FILE.TXT',
'r') : def VowelCount():
d=f.rea count_a=count_e=count_i=count_o=count_u
d() =0 f= open('MY_TEXT_FILE.TXT', 'r')
w=d.spli d=f.rea
t() for i d() for i
in w: in d:
if i.upper()== 'THE' or i.upper()== if i.upper()=='A':
'THIS' : c+=1 count_a+=1
print(c) elif
letter.upper()=='
E': count_e+=1
elif
letter.upper()=='
I': count_i+=1
elif
letter.upper()=='
O': count_o+=1
elif
letter.upper()=='U
': count_u+=1
print("A or a:",
count_a) print("E or
e:", count_e) print("I
or i:", count_i)
print("O or o:",
count_o)
print("U or u:", count_u)
Write a function filter(oldfile, newfile) that
copies all the lines of a text file “source.txt”
onto
“target.txt” except those lines which starts with
“@” sign.
A binary file “student.dat” has structure [rollno, A binary file “emp.dat” has structure
name, marks]. [EID, Ename, designation, salary].
i. Write a user defined function insertRec() i. Write a user defined function CreateEmp()
to input data for a student and add to to input data for a record and create a file
student.dat. emp.dat.
ii. Write a function searchRollNo( r ) in ii. Write a function display() in Python to
Python which accepts the student’s rollno as display the detail of all employees whose
parameter and searches the record in the file salary is more than 50000.
“student.dat” (i)
and shows the details of student i.e. rollno, import pickle
name and marks (if found) otherwise shows the def CreateEmp():
message as ‘No record found’. f1=open("emp.dat",'wb')
eid=input("Enter E. Id")
(i) ename=input("Enter Name")
import designation=input("Enter
pickle def Designation") salary=int(input("Enter
insertRec(): Salary"))
f=open("student.dat","ab") l=[eid,ename,designation,salary]
rollno = int (input("Enter Roll Number : ")) pickle.dump(l,f1)
name=input("Enter Name :") f1.close()
marks = int(input("Enter Marks : (ii)
")) rec = [rollno, name, marks ] import
pickle.dump( rec, f ) pickle def
f.close() display():
(ii) f2=open("emp.dat","rb
def searchRollNo( r ): ") try:
f=open("student.dat","rb" while True:
) flag = False rec=pickle.load(
while True: f2) if
try: rec[3]>5000:
rec=pickle.load print(rec[0],rec[1],rec[2],rec[3])
(f) if rec[0] == r except:
: f2.close()
print(rec[‘Rollno’
])
print(rec[‘Name’]
)
print(rec[‘Marks]
) flag == True
except
EOFError:
break
if flag == False:
print(“No record
Found”) f.close()
Write a python program to append a new Write a python program to search and display
records in a binary file –“student.dat”. The the record of the student from a binary file
record can have Rollno, Name and Marks. “Student.dat” containing students records
import (Rollno, Name and Marks). Roll number of
pickle the student to be searched will be entered
while by the user.
True:
rollno = int(input("Enter your rollno: ")) import pickle
name = input("Enter your name: ") f1 = open("Student.dat", "rb")
marks = int(input("enter marks obtained: rno = int(input(“Enter the roll no to search: ”))
")) d = [rollno, name, marks] flag = 0
f1 = open("Student.dat", try:
"wb") pickle.dump(d, f1) while True:
choice = input("enter more records: r=
y/n") if choice== "N": pickle.load(f1)
bre if rno == r[0]:
ak print (rollno, name,
f1.close marks) flag = 1
() except:
if flag == 0:
print(“Record not
found…”) f1.close()
i. A binary file “emp.DAT” has structure (EID, A binary file named “EMP.dat” has some
Ename, designation,salary). Write a function records of the structure [EmpNo, EName,
to add more records of employes in existing Post, Salary]
file emp.dat. (a) Create a binary file “EMP.dat” that stores
ii. Write a function Show() in Python that the records of employees and display them
would read detail of employee from file one by one.
“emp.dat” and display the details of those (b) Display the records of all those
employee whose employees who are getting salaries
designation is between 25000 to 30000.
“Salesman”. (i) (a)
import import pickle
pickle def f1 =
createemp: open('emp.dat','rb')
f1=open("emp.dat",'ab') try:
eid=input("Enter E. Id") while True:
ename=input("Enter Name") e=
designation=input("Enter pickle.load(f1)
Designation") salary=int(input("Enter print(e)
Salary")) except:
l=[eid,ename,designation,salary] f1.close()
pickle.dump(l,f1)
f1.close() (b)
(ii) import pickle
def display(): f1 =
f2=open("emp.dat","r open('emp.dat','rb')
b") try: try:
while True: while True:
rec=pickle.load(f2) e = pickle.load(f1)
if (rec[2]=='Manager'): if(e[3]>=25000 and e[3]<=30000):
print(rec[0],rec[1], print(e)
rec[2],rec[3]) except:
except: f1.close()
bre
ak
f2.close()
A binary file “Book.dat” has structure [BookNo,
Book_Name, Author, Price].
i. Write a user defined function CreateFile()
to input data for a record and add to
“Book.dat” .
ii. Write a function CountRec(Author) in
Python which accepts the Author name as
parameter and count and return number of
books by the given Author are stored in the
binary file
“Book.d
at” (i)
import pickle
def
createFile():
f=open("Book.dat","ab")
BookNo=int(input("Book Number :
")) Book_name=input("Name :")
Author =
input("Author:" ) Price =
int(input("Price : "))
rec=[BookNo,Book_Name,Author,Pri
ce] pickle.dump(rec,f)
f.close()
(ii)
def CountRec(Author):
f=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load
(f) if
Author==rec[2]
:
num = num + 1
except:
f.clos
e() return
num
A binary file student.dat has structure A binary file “STUDENT.DAT” has structure
(rollno,name,class,percentage). Write a (admission_number, Name, Percentage). Write
program to updating a record in the file a function countrec() in Python that would
requires roll number to be fetched from the read contents of the file “STUDENT.DAT” and
user whose name is to be updated display the details of those students whose
import percentage is above 75. Also display number of
pickle students scoring above 75%
import os
f1 = import pickle
open(‘student.dat','rb') def
f2=open(“temp.dat”,”wb CountRec():
”) f=open("STUDENT.DAT","rb")
r=int(input(“enter rollno which you want num
to search”)) =0
try: try:
while True: while True:
e= rec=pickle.load
pickle.load(f1) (f) if rec[2] >
if e[0]==r: 75:
e[1]=input(“enter print(rec[0],rec[1],rec[
name”) 2]) num = num + 1
pickle.dump(e,f2) except:
else: f.clos
pickle.dump(e,f2) e() return
except: num
f1.close()
f2.close()
os.remove(“student.dat”)
os.rename(“temp.dat”,”student,dat”)
A binary file named “EMP.dat” has some A binary file “Items.dat” has structure as
records of the structure [EmpNo, EName, [ Code, Description, Price ].
Post, Salary] i. Write a user defined function MakeFile( )
(a) Write a user-defined function named to input multiple items from the user and
NewEmp() to input the details of a new add to Items.dat
employee from the user and store it in ii. Write a function SearchRec(Code) in
EMP.dat. Python which will accept the code as
(b) Write a user-defined function named parameter and search and display the
SumSalary(Post) that will accept an argument details of the corresponding code on screen
the post of employees & read the contents of from Items.dat. (i)
EMP.dat and calculate the SUM of salary of all import pickle
employees of that Post. def
(a) MakeFile( ):
import pickle while True:
def NewEmp code = input(“Enter Item
( ): Code :”) desc = input(“Enter
f = open(“EMP.dat”,”wb”) description :”) price =
EmpNo = int(input(“Enter float(input(“Enter price:”)) d=
employee number: “)) [code,desc,price]
EName = input(“Enter f = open (“Items.dat”,
name:”) Post = input(“Enter “ab”) pickle.dump( d,f )
post:”) ch = input(“Add more record?
Salary = int(input(“Enter (y/n) :”) if ch==’n’:
salary”)) rec = [EmpNo, Ename, bre
Post,Salary] pickle.dump(rec, f) ak
f.close() f.close( )
(b) (ii)
def SumSalary(Post): def SearchRec(code):
f = open("EMP.dat", f = open("Items.dat",
"rb") c=0 "rb") found = False
while while
True True
: try: : try:
g= g=
p.load(f) if p.load(f) if
g[2]==Post g[0]==code
: :
c=c+g[3] print(g[0],g[1],g[2])
except: found=True
f.close() break
print("sum of salary", except:
c) if found == False:
print("No such
record")
f.close()
A binary file named “TEST.dat” has some Consider a binary file emp.dat having records
records of the structure [TestId, Subject, in the form of dictionary. E.g {eno:1,
MaxMarks, ScoredMarks] Write a function in name:”Rahul”, sal: 5000} write a python
Python named DisplayAvgMarks(Sub) that will function to display the records of above file
accept a subject as an argument and read the for those employees who get salary between
contents of TEST.dat. The function will 25000 and 30000
calculate & display the Average of the
ScoredMarks of the passed Subject on screen.
def SumSalary(Sub):
f = open("ABC.dat", import
"rb") c=0 pickle def
search():
f=open(“emp.dat”,”rb”)
s=0 while
while True
True :
: try: try:
g= d=pickle.load(f)
p.load(f) if(d[‘sal’]>=25000 and d[‘sal’]<=30000):
print(g) print
if g[1]==Sub: (d) except
s=s+g EOFError:
[3] bre
c=c+1 ak f.close()
except:
f.close()
print("sum of salary",
s/c)
f.close()
A binary file “Bank.dat” has structure Consider an employee data, Empcode,
as [account_no, cust_name, empname and salary.
balance]. (i) Write python function to create
i. Write a user-defined function addfile( ) and binary file emp.dat and store
add a record to Bank.dat. their records.
ii. Create a user-defined function CountRec( ) (ii) write function to read and display
to count and return the number of all the records
customers whose balance amount is more Ans
than 100000. import pickle
(i) def add_record():
import f = open(“emp.dat”,”ab”)
pickle def empcode =int(input(“employee
addfile( ): code:”)) empname =
f = open(“bank.dat”,”wb”) int(input(“empName:”)) salary =
acc_no = int(input(“Enter int(input(“salary:”))
account d = [empcode, empname,
number: “)) salary] pickle.dump(d,f)
cust_name = input(“Enter f.clos
name:”) bal = int(input(“Enter e() import
balance”)) rec = [acc_no, pickle
cust_name, bal] p.dump(rec, f)
f.close() def search():
(ii) f=open(“emp.dat”,”r
def CountRec( ): b”) while True:
f= try:
open(“bank.dat”,”rb”) d=pickle.load
c=0 (f) print(d)
try: except
while True: EOFError:
rec = p.load(f) break
if rec[2] > f.close()
100000: c
+= 1
except:
f.close()
return c
Write a function SCOUNT( ) to read the Given a binary file “emp.dat” has
content of binary file “NAMES.DAT‟ and structure (Emp_id, Emp_name,
display number of records (each name Emp_Salary). Write a function in Python
occupies 20 bytes in file ) where name begins countsal() in Python that
from “S‟ in it would read contents of the file “emp.dat” and
def display the details of those employee whose
SCOUN salary is greater than 20000
T( ): s=' import
' pickle def
count=0 countsal():
f=open('Names.dat', f = open (“emp.dat”,
'rb'): while True: “rb”) n = 0
s= try:
f.read(20) while True:
if len(s)!
=0:
if s[0].lower()=='s':
count+=1 rec =
print('names beginning from "S" are pickle.load(f) if
',count) rec[2] > 20000:
print(rec[0], rec[1],
rec[2]) n = n + 1
except:
print(
n)
f.clos
e()
Write Python function DISPEMP( ) to read Consider the following CSV file (emp.csv):
the content of file emp.csv and display Sl,name,salary
only those records where salary is 4000 or 1,Peter,3500
above 2,Scott,4000
import csv 3,Harry,5000
def DISPEMP(): 4,Michael,25
csvfile=open('emp.csv'): 00
myreader = 5,Sam,4200
csv.reader(csvfile,delimiter=',') Write Python function DISPEMP( ) to read
print(EMPNO,EMP NAME,SALARY) the content of file emp.csv and display
for row in myreader: only those records where salary is 4000 or
if int(row[2])>4000: above
print(row[0], import csv
row[1],row[2]) def DISPEMP():
csvfile=open('emp.csv'):
myreader =
csv.reader(csvfile,delimiter=',')
print(EMPNO,EMP NAME,SALARY)
for row in myreader:
if int(row[2])>4000:
print(row[0],
row[1],row[2])
A binary file “Stu.dat” has structure (rollno, A binary file “Stu.dat” has structure (rollno,
name, marks). name, marks).
Write a function in Python add_record() to input Write a function in python Search_record() to
data for a record and add to Stu.dat. search a record from binary file “Stu.dat” on the
import pickle basis of roll number.
def add_record(): def Search_record():
fobj = f = open(“Stu.dat”,
open(“Stu.dat”,”ab”) “rb”) stu_rec =
rollno =int(input(“Roll pickle.load(f) found =
no:”)) name = 0
int(input(“Name:”)) rno = int(input(“roll number to
marks = search:”)) try:
int(input(“Marks:”)) data for R in
= [rollno, name, marks] stu_rec: if
pickle.dump(data,fobj) R[0] ==
fobj.close() rno:
print (R[1],
“Found!”) found =
1
break
except:
if found == 0:
print (“Sorry, record not
found:”) f.close()
CSV-
#import csv #csv module
#csv module functions csv.reader() ,csv.writer()
#writerow()-single record,
#writerows()-multiple
records
''' '''
write a python function writecsv () to write write a python function writecsv () to write
the following information into the following information into
product.csv. product.csv.Heading of the product .csv is as
follows
pid,pname,cost,quantity
p1,brush,50,200 pid,pname,cost,quan
p2,toothbrush,120,150 tity '''
p3,comb,40,300 def writecsv(pid,pname,cost,quantity):
p4,sheets,100,500 f=open("marks.csv","w")
p5,pen,10,250 r=csv.writer(f,newline="")
''' r.writerow([pid,pname,cost,quantit
#solution y]) f.close()
def writecsv():
f=open("product.csv","w")
r=csv.writer(f,lineterminator='\n')
r.writerow(['pid','pname','cost','qt
y'])
r.writerow(['p1','brush','50','200'])
r.writerow(['p2','toothbrush','12','150'])
r.writerow(['p3','comb','40','300'])
r.writerow(['p5','pen','10','25
0']) f.close()
write a python function readcsv () to display write a python function readcsv () to display
the following information into the following information into
product.csv. assume that following info is product.csv. assume that following info is
already present in the file. already present in the file.
pid,pname,cost,quantity pid,pname,cost,quantity
p1,brush,50,200 p1,brush,50,200
p2,toothbrush,120,150 p2,toothbrush,120,150
p3,comb,40,300 p3,comb,40,300
p4,sheets,100,500 p4,sheets,100,500
p5,pen,10,250 p5,pen,10,250
Ans Ans
import import
csv csv
def readcsv(): def readcsv():
f=open("product.csv","r" f=open("product.csv","
) r=csv.reader(f) r") r=csv.reader(f)
for i in for i in r:
r: print(i[0],i[1],i[2],i[
prin 3])
t(i) f.close()
f.close()
Ashok Kumar of class 12 is writing a program to create a CSV
file “empdata.csv” with empid, name and mobile no and search
empid and display the record. He has written the following
code. As a programmer, help him to successfully execute the
given task. import #Line1
fields=['empid','name','mobile_no']
rows=[['101','Rohit','8982345659'],
['102','Shaurya','8974564589'],
['103','Deep','8753695421'],['104','Prerna','9889984567'],
['105','Lakshya','7698459876']]
filename="empdata.csv"
with open(filename,'w',newline='') as f:
csv_w=csv.writer(f,delimiter=
',') csv_w. #Line2
csv_w. #Line3
with open(filename,'r') as f:
csv_r= (f,delimiter=',') Ans:
#Line4 ans='y' a) csv
while
ans=='y': b) writerow(fields)
found=Fal
se c) writerows(rows)
emplid=(input("Enter employee id to
search=")) for row in csv_r: d) csv.reader
if len(row)!=0:
if ==emplid: e) row[0]
#Line5 print("Name :
",row[1])
print("Mobile No :
",row[2]) found=True
bre
ak if
not found:
print("Employee id not found")
ans=input("Do you want to search more? (y)")
(a) Name the module he should import in Line 1.
(b) Write a code to write the fields (column heading) once
from fields list in Line2.
(c) Write a code to write the rows all at once from rows list
in Line3.
(d) Fill in the blank in Line4 to read the data from a csv file.
(e) Fill in the blank to match the employee id entered by the
user with the empid of record from a file in Line5.
Priti of class 12 is writing a program to create a CSV file
“emp.csv”. She has written the following code to read the
content of file emp.csv and display the employee record
whose name begins from “S‟ also show no. of employee with
first letter “S‟ out of total record. As a programmer, help her
to successfully execute the given task. Consider the following
CSV file (emp.csv): 1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,25
00 Ans
5,Sam,4200 (a) csv
import #
Line 1 def SNAMES(): (b) read mode
with open( ) as csvfile: # Line 2 (c) 'emp.csv'
myreader = csv. (csvfile, delimiter=',') #
Line 3 count_rec=0
count_s=0
for row in myreader:
if row[1][0].lower()=='s':
print(row[0],',',row[1],',',row[2])
count_s+=1
count_rec+=1 (d) reader
print("Number of 'S' names are ",count_s,"/",count_rec)
(e)2,Scott,
(a) Name the module he should import in Line 1 4000
(b) In which mode, Priti should open the file to print data.
(c) Fill in the blank in Line 2 to open the file. 5,Sam,4200
(d) Fill in the blank in Line3 to read the data from a csv file. Number of “S” names are 2/5
(e) Write the output he will obtain while executing the
above program.
addCsvFile(“Aman”,”123@456”)
addCsvFile(“Anis”,”aru@nima”) (e) Line 5 :
addCsvFile(“Raju”,”myname@FRD”) Aman
readCsvFile() #Line 5 123@456
Anis
(a) Give Name of the module he should import in Line 1. aru@nima
(b) In which mode, Aman should open the file to add data Raju myname@FRD
into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.
Parth Patel of class 12 is writing a program to create a CSV file
“emp.csv” which will contain employee code and name of some
employees. He has written the following code. As a Ans
programmer, help him to successfully execute the given task. (a) LINE 1 : csv
import #Line 1
def addemp(empcode,name):#to write/add data into the CSV
file fo=open('emp.csv','a')
writer=csv. (fo) (b) LINE 2 : writer
#Line 2
writer.writerow([empcode,name])
fo.close() #csv file reading code
def reademp(): (c) LINE 3: r
with open('emp.csv',' ') as fin:
#Line 3 filereader=csv.reader(fin)
for row in
filereader: for
data in row:
print(data,end='\ (d) LINE 4: close()
t') print(end='\n')
fin. #Line 4
addemp('E105','Parth')
addemp("E101",'Arunim
a') (e)
addemp("E102",'Prahala E105 Parth
d') reademp() #Line 5 E101
Arunima
(a) Name the module he should import in Line 1. E102
(b) Fill in the blank in Line 2 to write the data in a CSV file. Prahalad
(c) In which mode, Parth should open the file to read the
data from the file(Line 3).
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.
MOHIT of class 12 is writing a program to search a name in a
CSV file “MYFILE.csv”. He has written the following code. As a
programmer, help him to successfully execute the given task. Ans
import # Statement 1 (a) csv
f = open("MYFILE.csv", )# (b) “r”
Statement 2 data = ( f ) # Statement 3 (c) data = csv.reader(f)
nm = input("Enter name to be
searched: ") for rec in data:
if rec[0] == nm:
print (rec) f. ( ) # Statement 4 (d) f.close()
(a) Name the module he should import in Statement 1. (e) Comma Separated Values
(b) In which mode, MOHIT should open the file to search the
data in the file in statement 2?
(c) Fill in the blank in Statement 3 to read the data from the file.
(d) Fill in the blank in Statement 4 to close the file.
(e) Write the full form of CSV.
DATA STRUCTURE
‘’’ ‘’’
A linear stack called "List" contain the Write push(edetail) and pop(edetail) in python
following information: to add and remove the employee detail in a
a. Roll Number of student stack called "edetail".
b. Name of student "edetail" stack store the following details:
Write add(List) and pop(List) methods in a. Name of employee
python to add and remove from the stack. b. Salary of
A employee Ans.
ns ‘’’
. edetail = []
‘’’ def push(edetail):
List=[] name = input("Enter name")
def add(List): sal = int(input("Enter
rno=int(input("Enter roll Salary")) item = [name, sal]
number")) name=input("Enter edetail.append(item)
name") item=[rno,name]
List.append(item) def pop(edetail):
if len(edetail) >
def pop(List): 0:
if edetail.pop()
len(List)>0 else:
: List.pop() print("Stack is empty")
else:
print("Stack is empty")
''' Write a function Push() which takes "name" as
Write addsal(sal) and removesal(sal) functions argument and add in a stack named "MyStack".
in python to add and remove salary from a list After calling push() three times, a message
of salary in a list "sal", considering these should be displayed "Stack is Full"
methods to act as push and pop operations of A
data structure stack. ns
A .
ns '''
. MyStack=[]
''' StackSize=3
sal = [] def Push(Value):
def addsal(sc): if len(MyStack) <
sal.append( StackSize:
sc) MyStack.append(Value
)
def pop(): else:
if len(sal) > print("Stack is full!")
0:
sal.pop()
else:
print("Stack is empty")
''' '''
Write a function Push that takes "name" as Write a function pop() which remove name
argument and add in a stack named from stack named "MyStack".
"MyStack" '''
def Pop(MyStack):
Mynames=[] if len(MyStack) >
def Push(Value): 0:
Mynames.append(Val MyStack.pop()
ue) else:
print("Stack is empty.")
Write add(bookname) and delete() method in Q1. Organization of data means
python to add bookname and remove Write the full form of the following:
bookname considering a. LIFO
them to act as push() and pop() operations in b. FIFO
stack. Q3. Which data structure is represented as
''' FIFO? Q4. Insertion into stack is called
MyStack=[] (push/pop)
def add(bname): Q5. Giving printing command to printer is
MyStack.append(bna an example of
me) (stack/queue)
Q6. Reversing a number or a word/string is
def
an example of
delete(MyStack):
(stack or queue)
if len(MyStack) >
0: Q7. In stack addition or removal of elements
MyStack.pop() takes place at
(one/both) end of the list.
else:
Q8. In queue, addition of elements take place
print("Stack is empty. There is no book
at one end and
name")
removal of elements takes place at other
Write add(no) and delete() method in python
end. (T/F)
to add no and remove no considering
Q9. If the elements "A", "B", "C" are added in
them to act as enqueue () and
the queue in the
dequeue() operations in queue.
following order,
qe=[] first A then B and in last C.
def Enqueue(no): #inserting into the In what order, it will come out
queue qe.append(no) of queue?
Q10. function is used to add
an element in stack.
def
dequeue( Ans 1. Data
): Structure Ans 2.
if(qe==[] a. Last In First Out
): b. First In First
print("underflow/empty Out Ans 3. Queue
queue") else: Ans 4. Push
qe.pop(0) Ans 5. Queue
Ans 6. Stack
Ans 7. One
Ans 8. True
Ans 9. A, B,
C
Ans 10. Append
DDL DML
Data definition language Data manipulation language
Cre Inser
ate t
Dro Upd
p ate
Alte Dele
r te
Select
Creating a Database-To create a database
in RDBMS, create command is used. INSERT Statement -To insert a new tuple(row
Syntax, or record) into a table is to use the insert
create database database-name; statement
Example (i) To insert records into specific
create database Test; columns
------------------------------------------- Syntax:
CREATE TABLE Command: Create insert into
table command is used to create a table in table_name(column_name1,
SQL. Syntax : column_name2…)values
CREATE TABLE tablename (value1,value2….);
(column_name data_type(size),
column_name2 data_type(size) e.g. INSERT INTO student
…. (rollno,name )VALUES(101,'Roha
); n');
e.g. create table student (rollno integer(2), (ii) insert records in all the columns
name char(20), dob date); insert into table_name
values(value1,value2……);
CONSTRAINTS-
Constraints: Constraints are the conditions i. Not Null constraint : It ensures that the
that can be enforced on the attributes of a column cannot contain a NULL value.
relation. The constraints come in play
whenever we try to insert, delete or update a ii. Unique constraint : A candidate key is a
combination of one or more columns, the value
record in a relation. of which uniquely identifies each row of a
They are used to ensure integrity of a table.
relation, hence named as integrity
constraints.
1. NOT NULL iii. Primary Key : It ensures two things :
2. UNIQUE (i) Unique identification of each row
3. PRIMARY KEY in the table.
4. FOREIGN KEY (ii) No column that is part of the
5. CHECK Primary Key constraint can contain a NULL
6. DEFAULT value.
Example:
Example:
create table Employee v. Check Constraint : Sometimes we may
(EmpNo integer(4) Primary require that values in some of the columns of
Key, Name char(20) Not Null, our table are to be within a certain range or
Salary integer(6,2) check (salary > they must satisfy certain conditions.
0), DeptNo integer(3)
);
WHERE clause
Where clause is used to specify condition while retrieving data from table. Where clause is used mostly with
Select, Update and Delete query. If condition specified by where clause is true then only the result from table is returned.
Syntax
SELECT column-name1, column-name2, column-name3, column-nameN
from table-name
WHERE [condition];
Relational Operator (comparison ) IN- used to show the records from a LIST
>, <, >=, <=, <> (not equal to ) =( equal
to ) Display all records of those employees
whose belong to mumbai,delhi,jaipur
only
HAVING Clause
It is used to give more precise condition for a statement. It is used to mention condition in Group
based SQL functions, just like WHERE clause.
Syntax:
select column_name,
function(column_name) FROM
table_name
WHERE column_name
condition GROUP BY
column_name
HAVING function(column_name)
condition; Consider the following Sale
table.
Oid order_name previous_balance
customer To find the customer whose previous_balance sum is
more than 3000.
SELECT *
from sale
group by customer
having sum(previous_balance) > 3000;
Order By Clause- arrange or sort data Group By Clause- it is used to group the
To sort data in descending order DESC keyword results of a SELECT query based on one or
more columns
Syntax :
SELECT column- SELECT column_name,
list|* from table- aggregate_function(column_name)
name FROM table_name
order by asc / desc; WHERE condition
GROUP BY
To display all records in ascending order of column_name;
the salary.
SELECT * from Emp order by salary; To find name and age of employees grouped
To display all records in descending order by their salaries
of the salary. Example
SELECT * from Emp order by salary DESC; SELECT name,
age from Emp
group by salary;
-----------------------------------------------------------
-
-Group by in a Statement with WHERE
clause
select name, max(salary) from
Emp where age > 25 group by
salary;
where having
Where- Where clause is used to specify having- It is used to mention condition in Group
condition on single row.
Where clause is used mostly with Having clause is used only with group by clause
Select, Update and Delete command/query
Which command is used to change the Which keyword is used to select rows
number of columns in a table? containing
Ans ALTER column that match a wildcard pattern?
Ans LIKE
Differentiate between Degree and All aggregate functions except
Cardinality. ignore null values in their input collection.
Ans Degree – it is the total number of a) Count (attribute) b) Count (*)
columns in the table. c) Avg () d) Sum
Cardinality – it is the total number of () Ans count(*)
tuples/Rows in the table.
Group functions can be applied to any Which command is used to change the
numeric values, some text types and existing information of table?
DATE values. (True/False) Ans update
Ans True
Which clause is used in query to place the Which command is used for counting the
condition on groups in MySql? number of rows in a database?
i) where ii) having i) row ii) count
iii) group by iv) none of the iii) rowcount iv)
above Ans (ii) having row_count Ans rowcount
A Resultset is an object that is returned In SQL, name the clause that is used to place
when a cursor object is used to query a condition on groups
table. True/False Ans Having
Ans True
In SQL, which command is used to change the Which operator performs pattern matching
structure of already created table. in SQL?
Ans Alter table Ans Like
What does the following function result In SQL, what are aggregate functions? Ans
into? count(field_name) These functions work with data of multiple
Ans It returns the number of non-null records rows at a time and return a single value.
from the field.
How many Primary and Foreign keys can a In SQL, write the name of the aggregate
table have? function which is used to calculate & display
Ans Primary Key – 1 Foreign Key – Many the average of numeric values in an attribute of
a relation.
Ans AVG()
Write an SQL query to display all the attributes What is the use of LIKE keyword in SQL?
of a relation named “TEST” along with their Ans LIKE keyword is used to find matching
description. CHAR values with WHERE clause.
Ans DESCRIBE TEST; or DESC TEST;
Which of the following is NOT a DML What is the purpose of following SQL
command? a). SELECT b). command: SHOW DATABASES;
DELETE c). UPDATE d). DROP Ans This command will print name of all
Ans (d) DROP the databases present in RDBMS.
Identify the error in the following SQL query In SQL, name the command/clause that is used
which is expected to delete all rows of a table to display the rows in descending order of a
TEMP without deleting its structure and write column. Ans Order By …… Desc
the correct one:
DELETE
TABLE TEMP;
Ans DELETE FROM TEMP;
In SQL, what is the error in Write any two aggregate functions used in
following query : SELECT NAME, SQL.
SAL, DESIGNATION WHERE
DISCOUNT=NULL; Ans max(),min(),avg(),count()
Ans SELECT
NAME,SAL,DESIGNATION WHERE
DISCOUNT IS NULL;
Which of the following is a DML command? In SQL, write the query to display the list of
a) SELECT b) Update databases.
c) INSERT d) Ans SHOW DATABASES’
All Ans (d) All
Which of the following will suppress the entry A non-key attribute, whose values are
of duplicate value in a column? derived from primary key of some other
a) Unique b) Distinct table.
c) Primary Key d) NOT a). Alternate Key b). Foreign Key c).
NULL Ans (b) Distinct Primary Key d). Candidate Key
Ans (b) foreign Key
Identify the DDL Command. Which clause is used with a SELECT
(i) Insert into command (ii) Create table command in SQL to display the records in
command (iii) Drop table Command (iv) ascending order of an attribute?
Delete command Ans Order by
Ans (ii) Create table command (iii) Drop table
Command
A relation has 45 tuples & 5 attributes, what In SQL, which aggregate function is used to
will be the Degree & Cardinality of that count all records of a table?
relation? Ans count(*)
a). Degree 5, Cardinality 45
b). Degree 45, Cardinality 5
c). Degree 50, Cardinality 45
d). Degree 50, Cardinality 2250
Ans (a) Degree 5, Cardinality 45
Anita is executing sql query but not getting the Sunita executes following two statements but got
appropriate output, help her to do the the variation in result 6 and 5 why?
correction. (i) select count(*) from user ;
Select name from teacher (ii)select count(name) from
where subject=Null; user ;
Ans Select name from teacher where subject is (iii) Ans
Null; Count(*) will count rows where as
count(name) will count name column only
which is having one null value.
What is the difference between where and Write a command to add new column
having in SQL. marks in table ‘student’ data type int. Ans
Ans Where is used apply condition in Alter table student add marks int(3)
query, where as having is used only
with group.
Write query to display the structure of In SQL, what is the use of BETWEEN
table teacher. operator?
Ans describe teacher or desc teacher Ans The BETWEEN operator selects values
within a given range
In SQL, name the clause that is used to display In SQL, what is the use of IS NULL
the tuples in ascending order of an attribute. operator?
Ans Orderby Ans To check if the column has null value
/ no value
Write any one aggregate function used in Which of the following is a DDL command?
SQL. a) SELECT b) ALTER
Ans SUM / AVG / COUNT / MAX / MIN c) INSERT
Ans (b) ALTER
In SQL, write the query to display the list of Which of the following types of table
tables stored in a database constraints will prevent the entry of duplicate
Ans Show tables; rows?
a) check b) Distinct
c) Primary Key d)
NULL Ans (c) Primary Key
Which is known as range operator in MySQL. If column “salary” of table “EMP” contains the
a) IN b) BETWEEN dataset {10000, 15000, 25000, 10000, 25000},
c) IS d) what will be the output of
DISTINCT following SQL statement?
Ans (b) BETWEEN SELECT SUM(DISTINCT SALARY)
FROM EMP; a) 75000 b)
25000
c) 10000 d) 50000
Ans (d) 50000
Which of the following functions is used to Name the clause used in query to place the
find the largest value from the given data in condition on groups in MySQL?
MySQL? Ans having
a) MAX ( ) b) MAXIMUM ( )
c) LARGEST ( ) d) BIG ( )
Ans (a) MAX()
Write SQL statement to find total number of Write command to list the available
records in table EMP? databases in MySQL.
Ans count(*) Ans show databases
In SQL, name of the keyword used to In SQL, what is the use of ORDER BY
display unique values of an attribute. clause ?
Ans DISTINCT Ans To display the values in sorted order
Write the function used in SQL to display Which of the following is a DML command?
current date a) CREATE b)ALTER c) INSERT
Ans curdate() d) DROP
Ans (c) insert
In SQL, write the command / query to display Which of the following type of column
the structure of table ‘emp’ stored in a constraints will allow the entry of unique and not
database. null values in the column?
Ans desc emp a) Unique b) Distinct
c) Primary Key
Ans (c) Primary Key
In SQL, name the clause that is used to display In SQL, what is the use of <>
the unique values of an attribute of a table. operator?
Ans distinct Ans not equal to
Write any two aggregate function used in Which of the following is/ are
SQL DML command(s)?
Ans max/min/avg/sum/count(*) a) SELECT b) ALTER
c) DROP
Ans (a) select (d) update
In SQL, write the query to display the Which of the following types of table
list databases. constraints will not prevent NULL entries in a
Ans show databases table?
a) Unique b) Distinct
c) Primary Key d)
NOT NULL
Ans (c) Primary Key
MySQL -3 and 4 marks Questions
A department is considering to maintain their worker data using SQL to store the data. As a database administer,
Karan has decided that :
The attributes of WORKER are as follows: WORKER_ID - character of size 3 FIRST_NAME – character of size 10
LAST_NAME– character of size 10 SALARY - numeric
JOINING_DATE – Date
DEPARTMENT – character of size 10
WORKER_I D FIRST_NA ME LAST_NAM E SALARY JOINING_D ATE DEPARTM ENT
d) Karan wants to remove all the data from table WORKER from the
database Department. Which command will he use from the following:
i) DELETE FROM WORKER;
ii) DROP TABLE WORKER;
iii) DROP DATABASE Department;
iv) DELETE * FROM WORKER;
e) Write a query to display the Structure of the table WORKER, i.e. name of
the attribute and their respective data types.
Ans
Observe the following table and answer the question (a) to (e) (Any 04)
TABLE:
VISITOR
VisitorI VisitorNam ContactNumbe
D e r
V001 ANAND 9898989898
V002 AMIT 9797979797
V003 SHYAM 9696969696
V004 MOHAN 9595959595
(a) Write the name of most appropriate columns which can be considered as
1
Candidate keys?
(b) Out of selected candidate keys, which one will be the best to choose as Primary
Key?
TABLE: ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD
a)
i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;
ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE DESIGNATION = ‘COORDINATOR’
AND SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
Ans
i) ENGLISH 51 PHYSICS 76 MATHS 24 CHEMISTRY 27
ii) PRIYA RAI FEMALE LISA ANAND FEMALE
iii)4
b)
i) To decrease period by 10% of the teachers of English subject.
ii) To display TEACHERNAME, CODE and DESIGNATION from tables SCHOOL and ADMIN whose gender is male.
iii) To Display number of teachers in each subject.
iv) To display details of all teachers who have joined the school after 01/01/1999 in descending order of experience.
v) Delete all the entries of those teachers whose experience is less than 10 years in SCHOOL table.
Ans
Relation : Employee
id Name Designation Sal
101 Naresh Clerk 32000
102 Ajay Manager 42500
103 Manisha Clerk 31500
104 Komal Advisor 32150
105 Varun Manager 42000
106 NULL Clerk 32500
Ans
i) id
ii) Ans. select avg(sal) from employee;
iii) Ans. select designation, count(*) from employee group by designation;
iv) Ans. select designation, count(*), sum(sal) from employee group by designation having count(*)>1;
v) Degree : 4 Cardinality : 6
Write the outputs of the SQL queries (i) to (iii) based on the relation
COURSE CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C2 DDTP 9000 2019-09-15 104
04
C2 DHN 20000 2019-08-01 101
05
C2 O 18000 2018-07-25 105
06 LEVEL
(i) SELECT DISTINCT TID FROM COURSE;
(ii) SELECT TID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY TID HAVING COUNT(*)>1;
(iii) SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE STARTDATE< ‘2018-09-15’;
Ans
(i) DISTINCT
TID 101
103
102
104
105
(ii)TID COUNT(*) MIN(FEES)
101 2 12000
(iii) COUNT(*)
SUM(FEES) 4
65000
Write SQL commands for the following queries (i) to (v) on the basis of relation Mobile Master and Mobile Stock.
TABLE: MOBILEMASTER
TABLE: MOBILESTOCK
(i) Display the Mobile Company, Name and Price in descending order of their manufacturing date.
(ii) List the details of mobile whose name starts with “S” or ends with “a”.
(iii) Display the Mobile supplier & quantity of all mobiles except “MB003”.
(iv) List showing the name of mobile company having price between 3000 & 5000.
(v) Display M_Id and sum of Moble quantity in each M_Id.
Ans
(i) SELECT M_Company, M_Name, M_Price FROM MobileMasterORDER BY M_Mf_Date DESC;
(ii) SELECT * FROM MobileMaster WHERE M_Name LIKE “S%” or M_Name LIKE “%a”;
(iii) SELECT M_Supplier, M_Qty FROM MobileStock WHERE M_Id <>“MB003”;
(iv) SELECT M_Company FROM MobileMaster WHERE M_PriceBETWEEN 3000AND 5000;
M_ID
(v) SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;
M_Company
M_Name
M_Price
M_Mf_Date
MB001
SAMSUNG
S_ID
M_ID
M_QTY
M_SUPPLIER
S001
MB004
450
NEW VISION
As a database administrator
Name of the table :
SOFTDRINK The attributes
are as follows:
Drinkcode, Calories -
Integer Price - Decimal
Dname - Varchar of size 20
Drinkcode Dname Price Calories
101 Lime and Lemon 20.00 120
102 Apple Drink 18.00 120
103 Nature Nectar 15.00 115
104 Green Mango 15.00 140
105 Aam Panna 20.00 135
106 Mango Juice Bahar 12.00 150
a) Identify the attributes that can be called Candidate keys.
b) What is the cardinality and degree of the table SOFTDRINK.
c) Include the following data in the above table.
Drinkcode = 107, Dname = “Milkshake” and Calories = 125
d) Give the command to remove all the records from the table.
e) Write a query to create the above table with Drinkcode as the Primary Key.
Ans
a) Drinkcode and Dname
b) Cardinality = 6, Degree = 4
c) Insert into softdrink(drinkcode,dname,calories) values (107,”Milkshake”,125);
d) Delete from softdrink;
e) Create table softdrink(drinkcode integer(5) Primary Key, dname varchar(20), Price
decimal(6,2), calories integer(5));
Write the outputs of the SQL queries i) to iii) based on the tables given
below: Table: ITEM ID
Item_Name Manufacturer
Price PC01
Personal Computer ABC
35000
LC05 Laptop ABC 55000
PC03 Personal Computer XYZ 32000
PC06 Personal Computer COMP 37000
LC03 Laptop PQR 57000
Table: CUSTOMER
C_ID CName City ID
01 N Roy Delhi LC03
06 R Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Agarwal Bangalore PC01
i) Select Item_Name, max(Price), count(*) from Item group by Item_Name ;
ii) Select CName, Manufacturer from Item, Customer where Item.ID = Customer.ID;
iii) Select Item_Name, Price * 100 from Item where Manufacturer = “ABC”;
Ans
i) Personal Computer 37000 3
Laptop 57000 2
ii) N Roy PQR
R Singh XYZ
R Pandey COMP
C Sharma
PQR K Agarwal
ABC
iii) Personal Computer 3500000
Laptop 5500000
Write SQL commands for i) to v) based on the relations given below.
Table: Store
ItemNo Item Scode Qty Rate
LastBuy 2005 Sharpner Classic 23 60
8 31-Jun-09
2003 Ball Pen 0.25 22 50 25 01-Feb-10
2002 Gel Pen Premium 21 150 12 24-Feb-10
2006 Gel Pen Classic 21 250 20 11-Mar-09
2001 Eraser Small 22 220 6 19-Jan-09
2004 Eraser Big 22 110 8 02-Dec-09
2009 Ball Pen 0.5 21 180 18 03-Nov-09
Table: Suppliers
Scode Sname
21 Premium Stationary
23 Soft Plastics
22 Tetra Supply
i) To display details of all the items in the Store table in descending order of LastBuy.
ii) To display Itemno and item name of those items from store table whose rate is more than 15 rupees.
iii) To display the details of those items whose supplier code is 22 or Quantity in store is more than 110 from the
table Store.
iv) To display minimum rate of items for each Supplier individually as per Scode from the table Store.
v) To display ItemNo, Item Name and Sname from the tables with their corresponding matching Scode.
Ans
Ans
(a) Degree- 4 , cardinality- 6
(b) CDNO
(c) INSERT INTO LIBRARY VALUES (10009, ”Motivational Songs”, 15, 70);
(d) SELECT MIN(QTY) FROM LIBRARY;
(e) SELECT COUNT(*) FROM LIBRARY WHERE PRICE IS NULL;
Write the Outputs of the SQL queries (i) to (iii) based on the given below tables:
TABLE: TRAINER
TI TNAME CITY HIREDATE SALA
D RY
1 SUNAINA MUMBAI 1998-10- 90000
0 15
1
1 ANAMIKA DELHI 1994-12- 80000
0 24
2
1 DEEPTI CHANDIGAR 2001-12- 82000
0 H 21
3
1 MEENAKSHI DELHI 2002-12- 78000
0 25
4
1 RICHA MUMBAI 1996-01- 95000
0 12
5
1 MANIPRABH CHENNAI 2001-12- 69000
0 A 12
6
(a)
(i) SELECT DISTINCT(CITY) FROM TRAINER WHERE SALARY>80000;
(ii) SELECT TID, COUNT(*), MAX(FEES) FROM COURSE GROUP BY TID HAVING COUNT(*)>1;
(iii) SELECT T.TNAME, C.CNAME FROM TRAINER T, COURSE C WHERE T.TID=C.TID AND T.FEES
Ans (a)
(i)
MUMBAI
DELHI
CHANDIGARH
CHENNAI
(ii)
TID COUNT(*) MAX(FEES)
101 2 20000
(iii)
T.TNAME C.CNAME
MEENAKSHI DDTP
(b)
(i) Display all details of Trainers who are living in city CHENNAI.
(ii) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(iii) Count & Display the number of Trainers in each city.
(iv) Display the Course details which have Fees more than 12000 and name ends with ‘A’.
(v) Display the Trainer Name & Course Name from both tables where Course Fees is less than 10000.
Ans
(i) SELECT * FROM TRAINER WHERE CITY IS “CHENNAI”;
(ii) SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE DESC;
(iii) SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;
(iv) SELECT * FROM COURSE WHERE FEES>12000 AND CNAME LIKE ‘%A’;
(v) SELECT T.TNAME, C.CNAME FROM TRAINER T, COURSE C WHERE T.TID=C.CID AND C.FEES;
Modern Public School is maintaining fees records of students. The database administrator Aman decided that- •
Name of the database -School
• Name of the table – Fees
• The attributes of Fees are as follows:
Rollno - numeric Name – character of size
20 Class - character of size 20
Fees –
Numeric Qtr
– Numeric
(i) Identify the attribute best suitable to be declared as a primary key
(ii) Write the degree of the table.
(iii) Insert the following data into the attributes Rollno, Name, Class, Fees and Qtr in fees table.
(iv) Aman want to remove the table Fees table from the database School. Which command will he use from
the following:
a) DELETE FROM Fees;
b) DROP TABLE Fees;
c) DROP DATABASE Fees;
d) DELETE Fees FROM Fees;
(v) Now Aman wants to display the structure of the table Fees, i.e, name of the attributes and their respective
data types that he has used in the table. Write the query to display the same.
Ans
i)Primary Key –
Rollno ii)Degree of
table= 5
iii)Insert into fees values(101,’Aman’,’XII’,5000);
iv)DELETE FROM Fees
v)Describe Fees
Consider the table TEACHER given below. Write commands in SQL for (i) to (iii)
TABLE: TEACHER
ID Name Department Hiredate Category Gender Salary
1 Taniya SocialStudies 03/17/1994 TGT F 25000
2 Abhishek Art 02/12/1990 PRT M 20000
3 Sanjana English 05/16/1980 PGT F 30000
4 Vishwajeet English 10/16/1989 TGT M 25000
5 Aman Hindi 08/1/1990 PRT F 22000
6 Pritam Math 03/17/1980 PRT F 21000
7 RajKumar Science 09/2/1994 TGT M 27000
8 Sital Math 11/17/1980 TGT F 24500
i. To display all information about teachers of Female PGT Teachers.
ii. To list names, departments and date of hiring of all the teachers in descending order of date of joining.
iii. To count the number of teachers and sum of their salary department
wise Ans
Write SQL commands for the queries (i) to (iii) and output for (iv) & (v) based on a table COMPANY and CUSTOMER .
TABLE:COMPANY
CID NAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE
666 DELL DELHI LAPTOP
TABLE:CUSTOMER
CUSTID NAME PRICE QTY CID
101 Rohan Sharma 70000 20 222
102 Deepak Kumar 50000 10 666
103 Mohan Kumar 30000 5 111
104 SahilBansal 35000 3 333
105 NehaSoni 25000 7 444
106 SonalAggarwal 20000 5 333
107 Arjun Singh 50000 15 666
(i) To display those company name which are having price less than 30000.
(ii) To display the name of the companies in reverse alphabetical order.
(iii) To increase the price by 1000 for those customer whose name starts with ‘S’
(iv) SELECT PRODUCTNAME,CITY, PRICE FROM COMPANY,CUSTOMER WHERE COMPANY.CID=CUSTOMER.CID
AND PRODUCTNAME=”MOBILE”;
(v) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
Ans
i) SELECT COMPANY.NAME FROM COMPANY,CUSTOMER WHERECOMPANY.CID = CUSTOMER.CID
AND CUSTOMER.PRICE<30000;
ii) SELECT NAME FROM COMPANY ORDER BY NAME DESC;
iii) UPADE CUSTOMER SET PRICE = PRICE+1000 WHERE NAME LIKE ‘S%’;
iv) PRODUCTNAME CITY
PRICE MOBILE MUMBAI 70000
MOBILE MUMBAI 25000
v) 12
ABC school is considering to maintain their student’s information using SQL to store the data. As a database
administrator Harendra has decided that:
Name of database :
school Name of table :
student
Attributes of the table are as follow:
AdmissionNo-numeric
FirstName –character of size
30 LastName - character of
size 20 DOB - date
Table student
AdmissionNo FirstName LastName DOB
012355 Rahul Singh 2005-05-
16
012358 Mukesh Kumar 2004-09-15
012360 Pawan Verma 2004-03-03
012366 Mahesh Kumar 2003-06-08
012367 Raman Patel 2007-03-19
Ans
i. Degrre-4 Cardinility-5
ii. AdmissionNo
iii. insert into student values(012368,’Kamlesh’,’Sharma’,’2004-01-01’)
iv. Delete command
v. Drop table student
Table : Employee
EmployeeId Name Sales JobId
E1 Sumit Sinha 110000 102
E2 Vijay Singh Tomar 130000 101
E3 Ajay Rajpal 140000 103
E4 Mohit Kumar 125000 102
E5 Sailja Singh 145000 103
Table: Job
JobId JobTitle Salary
101 President 200000
102 Vice President 125000
103 Administrator Assistant 80000
104 Accounting Manager 70000
105 Accountant 65000
106 Sales Manager 80000
Give the output of following SQL statement:
(i) Select max(salary),min(salary) from job
(ii) Select Name,JobTitle, Sales from Employee,Job where Employee.JobId=Job.JobId and JobId in (101,102)
(iii) Select JobId, count(*) from Employee group by JobId;
Ans
i.200000, 65000
ii.
Vijay Singh Tomar President 130000
Sumit Sinha Vice President 110000
Mohit Kumar Vice President 125000
iii. 101 1
102 2
103 2
Write SQL Commands for the following queries based on the relations PRODUCT and CLIENT given below.
Table: Product
P_ID ProductName Manufacturer Price ExpiryDate
TP01 Talcum Powder LAK 40 2011-06-
26
FW05 Face Wash ABC 45 2010-12-01
BS01 Bath Soap ABC 55 2010-09-10
SH06 Shampoo XYZ 120 2012-04-09
FW12 Face Wash XYZ 95 2010-08-15
Table: Client
C_ID ClientName City P_ID
1 Cosmetic Shop Delhi FW05
6 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty One Delhi FW05
16 Dreams Bengaluru TP01
14 Expressions Delhi NULL
(i) To display the ClientName and City of all Mumbai- and Delhi-based clients in Client table.
(ii) Increase the price of all the products in Product table by 10%.
(iii) To display the ProductName, Manufacturer, ExpiryDate of all the products that expired on or before ‘2010-12-
31’. (iv)To display C_ID, ClientName, City of all the clients (including the ones that have not purchased a product)
and their corresponding ProductName sold.
(v) To display productName, Manufacturer and ClientName of Mumbai City.
Ans
(i) select ClientName, City from Client where City = ‘Mumbai’ or City = ‘Delhi’;
(ii) update Product set Price = Price + 0.10 * Price;
(iii) select ProductName, Manufacturer, ExpiryDate from Product where ExpiryDate < = ‘2010-12-31’;
(iv) select C_ID, ClientName, City, ProductName from Client Left Join Product on Client. P_ID = Product.P_ID;
(v) select ProductName, Manufacturer, ClientName from product,client Where product.P_ID=Client.P_ID
and city=’Mumbai’;
A school KV is considering to maintain their eligible students’ for scholarship’s data using SQL to store the data.
As a database administer, Abhay has decided that :
• Name of the database - star
• Name of the table - student
• The attributes of student table as
follows: No. - numeric
Name – character of size 20
Stipend - numeric
Stream – character of size
20 AvgMark – numeric
Grade – character of
size 1 Class – character
of size 3 Table ‘student’
No. Name Stipend Stream AvgMark Grade Class
1 Karan 400.00 Medical 78.5 B 12B
2 Divakar 450.00 Commerce 89.2 A 11C
3 Divya 300.00 Commerce 68.6 C 12C
4 Arun 350.00 Humanities 73.1 B 12C
5 Sabina 500.00 Nonmedical 90.6 A 11A
6 John 400.00 Medical 75.4 B 12B
7 Robert 250.00 Humanities 64.4 C 11A
8 Rubina 450.00 Nonmedical 88.5 A 12A
9 Vikas 500.00 Nonmedical 92.0 A 12A
10 Mohan 300.00 Commerce 67.5 C 12C
Ans
(i) create table student(no integer,name char(20), stipend integer,stream char(20),avgmark integer, grade
char(1),class char(3));
(ii)No is Best suitable primary key
(iii) Degree = 7, cardinality = 10
(iv) select * from student order by name;
(v) update student set grade=’A’ where name=’Karan’;
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).
Table: Sender
SenderID SenderName SenderAddress Sendercity
ND01 R Jain 2, ABC Appls New
Delhi MU02 H Sinha 12 Newtown
Mumbai MU15 S Jha 27/A,
Park Street Mumbai ND50 T Prasad 122-
K,SDA New Delhi
Table: Recipients
RecID SenderID RecName RecAddress recCity
KO05 ND01 R Bajpayee 5, Central Avenue Kolkata
ND08 MU02 S Mahajan 116, A-Vihar New
Delhi MU19 ND01 H Singh 2A, Andheri East
Mumbai MU32 MU15 PK
Swamy B5, C S Terminals
Mumbai ND48 ND50 S
Tripathi 13, BI D Mayur Vihar New
delhi
a. To display the RecIC, Sendername, SenderAddress, RecName, RecAddress for every Recipient
b. To display Recipient details in ascending order of RecName
c. To display number of Recipients from each city
d. To display the details of senders whose sender city is ‘mumbai’
e. To change the name of recipient whose recid is ’Ko05’ to’ S Rathore’.
Ans
a. Select R.RecIC, S.Sendername, S.SenderAddress, R.RecName, R.RecAddress from Sender S, Recepient R
where S.SenderID=R.SenderID ;
b. SELECT * from Recipent ORDER By RecName;
c. SELECT COUNT( *) from Recipient Group By
RecCity; d.Select * from sender where
Sendercity=’mumbai’;
e. update recipient set RecName=’S Rathore’ where RecID=’ KO05’
A departmental store MyStore is considering to maintain their inventory using SQL to store the data. As a database
administer, Abhay has decided that :
• Name of the database - mystore
• Name of the table - STORE
• The attributes of STORE are as follows:
ItemNo - numeric
ItemName – character of size
20 Scode - numeric
Quantity – numeric
Table : STORE
ItemNo ItemName Scode
Quantity 2005 Sharpener Classic 23
60
2003 Ball Pen 0.25 22 50
2002 Get Pen Premium 21 150
2006 Get Pen Classic 21 250
2001 Eraser Small 22 220
2004 Eraser Big 22 110
2009 Ball Pen 0.5 21 180
Ans
(a) ItemNo 1
(b) Degree = 4 Cardinality = 7
(c) INSERT INTO store (ItemNo,ItemName,Scode) VALUES(2010, “Note Book”,25);
(d) DROP TABLE store; 1
(e) Describe Store;
Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and Posting given below:
Table : Teacher
T_ID Name Age Department Date_of_join Salary
Gender 1 Jugal 34
Computer Sc 10/01/2017 12000 M
2 Sharmila 31 History 24/03/2008 20000 F
3 Sandeep 32 Mathematics 12/12/2016 30000
01/07/2015 40000 F
5 Rakesh 42 Mathematics 05/09/2007 25000
27/06/2008 30000 M7
25/02/2017 21000 M
8 Shalakha 33 Mathematics 31/07/2018 20000 F
Table : Posting
P_ID Department Place
1 History Agra
2 Mathematics Raipur
3 Computer Science Delhi
(a)
i. SELECT Department, count(*) FROM Teacher GROUP BY Department;
ii. SELECT Max(Date_of_Join),Min(Date_of_Join) FROM Teacher;
iii. SELECT Teacher.name,Teacher.Department, Posting.Place FROM Teacher, Posting WHERE
Teacher.Department = Posting.Department AND Posting.Place=”Delhi”;
Ans
i. Department Count(*)
History 3
Computer Sc 2
Mathematics 3
(b)
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”; 5
ii. SELECT name FROM teacher WHERE department= “Mathematics” AND gender= “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;
An organization SoftSolutions is considering to maintain their employees records using SQL to store the data. As a
database administer, Murthy has decided that :
• Name of the database - DATASOFT
• Name of the table - HRDATA
• The attributes of HRDATA are as follows:
ECode – Numeric
EName – character of size
30 Desig – Character of
size 15 Remn – numeric
Table: HRDATA
ECode EName Desig
Remn 80001
Lokesh Programmer
50000
80004 Aradhana Manager 65000
80007 Jeevan Programmer 45000
80008 Arjun Admin 55000
80012 Priya Executive 35000
Ans
a) Ecode
b) Degree: 4, Cardinality: 5
c) Insert into HRDATA (Ecode, Ename, Remn) VALUES (80015, “Allen”, 43000)
d) DELETE FROM HRDATA WHERE ENAME LIKE “Jeevan”;
e) UPDATE HRDATA SET REMN = REMN * 1.10;
Consider the following tables: COMPANY and MODEL. Write the outputs of the SQL queries (a) to (c) based on the
relations COMPANY and MODEL given below:
Table: COMPANY
Table: BOOKS
book_id Book_name author_name Publishers Price Type qty
L01 Let us C Sanjay Mukharjee EPB 450 Comp 15
L02 Genuine J. Mukhi FIRST PUBL. 755 Fiction 24
L04 Mastering C++ Kantkar EPB 165 Comp 60
L03 VC++ advance P. Purohit TDH 250 Comp 45
L05 Programming with Python Sanjeev FIRST PUBL. 350 Fiction 30
Table: ISSUED
Book_ID
Qty_Issued L02
13
L04 5
L05 21
Ans
i) SELECT * FROM BOOKS WHERE PUBLISHER LIKE „FIRST PUBL.‟ AND AUTHOR_NAME LIKE „P. Purohit‟;
ii) Select Price from Books where PUBLISHER LIKE „EPB‟;
iii) UPDATE BOOKS SET PRICE = PRICE * 0.90 WHERE PUBLISHER LIKE „EPB‟;
iv) SELECT BOOK_NAME, PRICE FROM BOOKS B, ISSUED I WHERE B.BOOK_ID = I.BOOK_ID AND QTY_ISSUED > 5;
v) SELECT SUM(PRICE) FROM BOOKS GROUP BY TYPE;
A Medical store “Lifeline” is planning to maintain their inventory using SQL to store the data. A database administer
has decided that:
●Name of the database -medstore
●ino - integer
●mcode - integer
●qty – integer
Ans
(a) ino
(b) Degree= 6 Cardinality =7
(c) UPDATE MEDICINE set iname= ‘Paracetamol Tablet’,mcode=25, qty=100 where ino = 1003 ;
(d) DROP TABLEMEDICINE;
(e) Select distinct mcode from MEDICINE;
Write SQL commands for the following queries (i) to (v) based on the relations Vehicle and Travel given below.
Table :Travel
NO NAME TDATE KM CODE
NOP 101 Janish Kin 2015-11-13
200 101 32
103 Vedika Sahai 2016-04-21 100 103 45
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed Khan 2015-01-10 75 104 2
104 Raveena 2016-05-28 80 105 4
Table : Vehicle
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
i. To display NO, NAME, TDATE from the table Travel in descending order of NO.
ii. To display the NAME of all the travelers from the table Travel who are travelling by vehicle with code 101 or 102.
iii. To display the NO and NAME of those travelers from the table Travel who travelled between ‘2015-12-31’
and ‘2016-04-01’.
iv. To display the CODE,NAME,VTYPE from both the tables with distance travelled (km) less than 90 Km.
v. To display the NAME of those traveler whose name starts with the alphabet ‘R’.
Ans
To fetch some useful information from the database, can use either
fetchone() method to fetch single record
fetchall() method to fetch multiple values from a database table.
fetchmany()- to fetch limited no of records
Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
NETWORKING
Two or more computing devices connected to one another in order to exchange information or
share resources, form a computer network.
Advantages-
Share Share Storage Share Software and Security Back up and Roll back is
resources- hardware easy
Switching Techniques
Follows Store(RAM) and Each message is stored (usually on In circuit switching, data is
forward technique hard drive) before being not stored.
transmitted to the next switch.
bps- bits per second ARPAnet- POP- Post nfc- Near VoIP-voice
Advanced office field over internet
Research Project Protocol Communicati protocol
Agency Network on
Network Devices
Hub-connects multiple Switch- connects multiple Modem-used to access
computers in a single LAN computers in a single LAN the internet , converts
network. It distributes the network but doesn’t analog signal into digital
bandwidth equally to all distribute equal bandwidth and vice versa.
computers to all. It is intelligent hub. It
sends (modulation/demodulation)
information only to
intended computer/node
Router- to receive packets Gateway-connects Repeater-(amplify )
from one connected network dissimilar networks regenerates the signal
and pass them to second and forwards these
connected network.(for signal with more power.
routing)
Connects multiple networks Bridge- connects
with different protocols similar networks
Network Protocols
Layout-draw block diagram to show interconnecting blocks. Prefer the block with maximum devices as
main server to connect other blocks
Cost effective medium for internet- Broadband connection over telephone lines
Communication media for LAN-Ethernet/Co-axial cable for high speed within LAN
TOPOLOGIES
Name the transmission media best suitable Write the expanded form of
for connecting to desert areas. Ans VPN. Ans Virtual Private
microwave Network
State whether the following statements is True Expand the term a). XML b). SMS
or False. When two entities are communicating
and do not want a third party to listen, this Ans
situation is defined as secure communication. (a) XML-Extensible Markup Language
Ans True (b) SMS–Short Messaging Service
Which of the following appears harmless Name the protocol that is used to send emails.
but actually performs malicious functions Ans SMTP
such as deleting or damaging files.
(a) WORM (b)Virus
(c) Trojan Horse
(d)Mal
war e Ans
(c) Trojan Horse
Your friend Ranjana complaints that Name The transmission media best
somebody has created a fake profile on suitable for connecting to hilly areas
Facebook and defaming her character with Ans microwave/radiowave
abusive comments and pictures. Identify the
type of cybercrime for these situations.
Ans Cyber Stalking / Identity theft
Name the protocol that is used for the transfer of In a Multi-National company Mr. A steals Mr.
hypertext content over the web. B’s intellectual work and representing it as A’s
Ans HTTP own work without citing the source of
information, which kind of act this activity be
termed as?
Ans Plagiarism
Give at least two names for Guided and Write the expanded form of Wi-Fi and
Unguided Transmission Media in networking. GSM Ans
Ans Guided Media: Twisted pair Cable, WiFi : Wireless Fidelity
Coaxial Cable , Fiber Optic Cable GSM : Global System for
Unguided Media: Microwave / Radio Mobile Communication
wave , Infrared, Satellite
Rearrange the following terms in increasing Name the protocol that is used to transfer files.
order of data transfer rates. Ans FTP
Gbps, Mbps, Tbps, Kbps, bps Ans
Your friend’s mother receives an e-mail to Name the fastest available transmission
access the additional services of bank at zero media.
cost from some agency asking her to fill her Ans Optical Fibre cable( OFC)
bank details like credit card number and PIN
in the form attached to the mail. Identify the
type of cybercrime in this situation
Ans phishing
Write the expanded form of LAN & MAN. Rearrange the following transmission
media in increasing order of data transfer
Ans rates.
Local Area Network UTP CAT - 5 , UTP CAT – 6, IR, Bluetooth,
Network OFC
Ans IR, Bluetooth, UTP CAT - 5, UTP CAT – 6,
OFC
fee=2 fee=250
50 0=i i=0 # i=0
while fee=<2000: while fee<=2000: #
if fee<=750: <= if fee<=750:
print(f print(fee)
ee) fee=+250 # +=
fee=+2 else:
50 print(fee*i) #
else: ( and “ i=i+1
print(("fee fee=fee+250 # fee
*i) i=i+1
fee=Fee+2
50
10=step step=10 # variable on left
for e in the side for e in range(0,step): # extra
range(0,step): the
If e%2==0: if e%2==0: # if
print(e+1) print(e+1)
else: else:
print(e-1 print(e-1) # missing )
str="Welcome to my str="Welcome to my Blog” # missing “
Blog for s in range[3,9] for s in range (3,9) : # () and colon
Print(str(S))
print(str(s)) # print() and small s
#function calling
makenew("sTUdeN
T")
Display('Fun@Python3.
0')
Ans fUN#pYTHONn#
def mainu(): s=”United Nations”
Moves=[11, 22, 33, 44] for i in
Queen=Move range(len(s)): if i
s %2==0:
Moves[2]+=2 print(s[i],end= ‘ ‘)
2 elif s[i]>=’a’ and s[i]<=’z’:
L=len(Moves) print(‘*’, end= ‘ ‘)
for i in range elif s[i]>=’A’ and s[i] <=’Z’:
(L): print(s[i:],end= ‘ ‘)
print(Queen[L-i-1], "#", Moves [i])
#function Ans
calling
mainu()
Ans U * i * e * Nations a * i * n *
44 # 11
55 # 22
22 # 55
11 # 44
tup=(10,30,15,9) L
s =["X",20,"Y",10,"Z",30
= ] CNT = 0
1 ST = ""
t INC = 0
= for C in range(1,6,2):
0 CNT= CNT + C
for i in range(s,4): ST= ST + L[C-1] +
t=t+tup[i] "@" INC = INC +
print(i,":",t) L[C] print(CNT,
t=t+tup[0]* INC, ST)
10 print(t)
An Ans
s1 1 20 X@
: 4 30 X@Y@
30 9 60 X@Y@Z@
130
2 : 145
245
3 : 254
354
def def
increment(n) display(x=2,y=3)
: : x=x+y
n.append([4] y += 2
) return n print(x,
y)
L=[1,2,3] display()
M=increment display(5
(L) print(L, M) ,1)
display(9
Ans [1, 2, 3, [4]] [1, 2, 3, [4]] )
A
n
s
5
5
63
12 5
mystr=”cs2study data=[‘d’,’o’,’ ‘,’k’,’t’,’ ‘,’@’,’ ‘,’1’,’2’,’3’,’ ‘,’!’]
@” newstr = " " for i in range(len(data)-
count = 0 1):
for i in mystr: if(data[i].isupper()):
if count%2 !=0: data[i]=data[i].lower()
newstr = elif(data[i].isspace(
newstr+str(count) else: )):
if islower(i): data[i]=data[i+1]
newstr = newstr+upper(i) print (data)
else:
newstr =
newstr+i count
+=1 Ans
newstr = newstr+mystr[:1] ['d', 'o', 'k', 'k', 't', '@', '@', '1', '1', '2', '3', '!', '!']
print ("The new string is :",newstr)
Ans
The new string is : CcSc2c1c1c1c1c1c1c
RANDOM MODULE
randint() – function takes starting and ending values both
randrange()-function takes only starting value and ending-1 value
random()-generates decimal values between 0 and 1 but not include 1
What possible output(s) are expected to be What possible outputs(s) are expected to be
displayed on screen at the time of execution displayed on screen at the time of execution of
of the program from the following code? Also the program from the following code? Also
specify the minimum values that can be specify the maximum values that can be
assigned to each of the variables BEGIN and assigned to each of the variables FROM and
LAST. TO.
import random import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80] AR=[20,30,40,50,60,70]
BEGIN = random.randint (1, FROM=random.randint(1,3)
3) LAST = TO=random.randint(2,4)
random.randint(2, 4) for I in for K in range(FROM,TO):
range (BEGIN, LAST+1): print (AR[K],end=”#“)
print (VALUES[I], end = "-") (i)10#40#70#
(i) 30-40-50- (ii) 10-20-30-40-
(iii) 30-40-50-60- (iv) 30-40-50-60-70- (ii)30#40#50# (iii)50#60#70#
Ans
OUTPUT – (i) 30-40-50- (iv)40#50#70#
Minimum value of
BEGIN: 1 Minimum value Ans
of LAST: 2 Maximum value of FROM
= 3 Maximum value of TO
=4
(ii) 30#40#50#
Consider the following code: import math Consider the following code and find out the
import random possible output(s) from the options given
print(str(int(math.pow(random.randint(2,4),2)))) below. Also write the least and highest value
print(str(int(math.pow(random.randint(2,4),2)))) that can be generated. import random as r
print(str(int(math.pow(random.randint(2,4),2)))) print(10 + r.randint(10,15) , end =
What could be the possible outputs out of the ‘ ‘) print(10 + r.randint(10,15) ,
given four choices? end = ‘ ‘) print(10 +
i) 2 3 4 ii) 9 4 4 r.randint(10,15) , end = ‘ ‘)
iii)16 16 16 iv)2 4 9 print(10 + r.randint(10,15))
i) 25 25 25 21 iii) 23 22 25 20
Ans ii) 23 27 22 20 iv) 21 25 20 24
Possible outputs : ii) , iii)
randint will generate an integer between 2 Ans
to 4 which is then raised to power 2, so Possible
possible outcomes can be 4,9 or 16 outputs : i), iii)
and iv) Least
value : 10
Highest value : 15
What possible outputs(s) are expected to be What possible outputs(s) are expected to be
displayed on screen at the time of execution of displayed on screen at the time of execution of
the program from the following code? Also the program from the following code? Also
specify the maximum values that can be specify the maximum values that can be
assigned to each of the variables BEG and assigned to each of the variables Lower and
END. Upper. import random
AR=[20,30,40,50,60,70]
import random Lower
heights=[10,20,30,40, =random.randint(1,4)
50] Upper
beg=random.randint(0 =random.randint(2,5)
,2) for K in range(Lower, Upper
end=random.randint(2 +1): print
,4) for x in (AR[K],end=”#“)
range(beg,end):
print(heights[x],end=’@’) (i) 10#40#70# (ii) 30#40#50#
(a) 30 @ (b) (iii) 50#60#70# (iv) 40#50#70#
10@20@30@40@50@
(c) 20@30 (d) 40@30@
Ans Ans (i) ,(ii) and (iii)
(a) & (b)
Maximum value of
BEG: 2 Maximum value
of END: 4
What possible output(s) are expected to be What possible outputs(s) are expected to be
displayed on screen at the time of execution displayed on screen at the time of execution
of the program from the following code? of the program from the following code. Select
Import random which option/s is/are correct
Ar=[20,30,40,50,60,70] import random
From print(random.randint(15,25) ,
=random.randint(1,3) end=' ')
To=random.randint(2,4) print((100) + random.randint(15,25) , end = ' ' )
for k in print((100) -random.randint(15,25) , end = ' ' )
range(From,To+1): print((100) *random.randint(15,25) )
print(ar[k],end=”#”)
(i) 10#40#70# (iii) 50#60#70# (i) 15 122 84 2500 (ii) 21 120 76 1500
(ii) 30#40#50# (iv) 40#50#70# (iii) 105 107 105 1800 (iv) 110 105 105 1900
Ans Ans
(ii) 30#40#50# (i) (ii) are correct answers.
What possible outputs(s) are expected to be What possible outputs(s) are expected to be
displayed on screen at the time of execution displayed on screen at the time of execution
of the program from the following code? of the program from the following code?
Also specify the minimum and maximum
values that can be assigned to the variable import random
End . X= random.random()
import random Y=
Colours = ["VIOLET","INDIGO","BLUE","GREEN", random.randint(0,4)
"YELLOW","ORANGE","RED"] print(int(),":",Y+int(X
End = randrange(2)+3 ))
Begin = randrange(End)
+1 for i in (i) 0:5 (ii) 0:3
range(Begin,End):
print(Colours[i],end="&") (iii) 0:0 (iv) 2:5
(i) INDIGO&BLUE&GREEN&
(ii) VIOLET&INDIGO&BLUE& Ans
(iii) BLUE&GREEN&YELLOW& (ii) and (iii)
(iv) GREEN&YELLOW&ORANGE&
Ans
(i)
INDIGO&BLUE&GREEN&
Minimum Value of End =
3
Maximum Value of End = 4
import random (e) Observe the following Python code and
x=random.random() find out which of the given options (i) to (iv)
y=random.randint(0 are the expected correct output(s). Also,
,4) assign maximum and minimum values that can
print(int(x),":",y+int( be assigned to the variable ‘Go’.
x))
Choose the possible output(s) from the import random
given options. Also write the least and X=[100,75,10,1
highest value that may be generated. 25]
(i) 0:0 ii.) 1:6 Go
iii.) 2:4 iv.) 0:3 =random.randint(0,3)
Ans min value of x 0.01 and max value will for i in range(Go):
be 0.99899 print(X[i],"$$")
Min value of y 0 and max value will
be 4 Corrected options will be (i) and (i) 100$$ (ii) 100$$
(iv) 75$$ 99$$
10$$
(ii) 150$$ (iv) 125$$
100$$ 10$$
Ans
(i) 100
$$
75$
$
10$
$
import random import
pick=random.randint(0,3 random
) p='my
city=["delhi","mumbai","chennai","kolkata program' i=0
"] for i in city: while p[i]!='y':
for j in t=random.randint(0,3)
range(1,pick): +5 print(p[t],'-')
print(i,end=" ") i=i+1
Ans Ans
delhi mumbai chennai Kolkata g –O- r- a-
order can vary but print only
delhi delhi mumbai mumbai these 4 characters
chennai chennai kolkata kolkata
import random import random
sel=random.randint(0,3) picker=random.randint(0,3)
animal=["deer","monkey","cow","kangaro color=["blue","pink","green","red
o"] for a in animal: "] for i in color:
for aa in for j in
range(1,sel): range(1,picker):
print(a, end="") print(i, end="")
print() print()
Ans Ans
deer blu
monk e
ey pin
cow k
kangar gre
en
oo or red
deer or
deer
monk blu
ey e
monk blu
ey e
cow pin
cow k
kangar pin
oo k
kangar gre
oo en
gre
en
r
e
d
r
e
d
What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables first, second and third.
Ans 35#40#60#
Maximum Values: First: 40, Second: 45, Third: 60