Class 12 Exam Revision Material

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 178

Python is a case sensitive language- it means python considers lowercase and uppercase differently. e.g.

Num=3 , num=24
python will consider both the variables differently though their pronunciation is same.

Q What are the different types of Tokens?


Ans
1. Keyword(system defined names)
2. Identifier(user defined names)
3. Literals
4. Operators
5. Punctuators

Q Explain Keyword .
Ans Keywords are the reserve words/pre-defined words/special words of python

False True None def if

lambda class yield continue else


assert or while break elif
del from is not pass
For global finally import as
in nonlocal return with and

int except raise print csv

pickle reader writer dump load

sys connector cursor execute fetch

Q What are identifiers?


Ans
Identifiers are the name given to the different programming elements like variables, functions, lists, dictionaries etc.

Q What are the naming rules of Identifiers?


Ans
1. Spaces are not allowed
2. Special symbols like $%^&#@! Not allowed
3. Must made up of only letters,numbers and underscore(_)
4. Can’t begin with a number
5. Keywords are not allowed
6. Can start with underscore(_)

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.

Q Explain the concept of variable in


Python. Ans
Variable is a name given to a memory location.
A variable can consider as a container which holds value.
Python is a type infer language that means you don't need to specify the datatype of variable.
Variable name= Identifier name
VARIOUS WAY TO DECLARE A VARIABLE:

1. Assigning single Value 2. ASSIGNING DIFFERENT VALUES TO MULTIPLE


to Variable VARIABLES
variable_name= value variable_name1, variable_name2= value_of_variable1, value_of_variable2

name = ‘python' >>>a,b=3,4


num =
2
roll_no
=1
3. ASSIGNING SAME VALUES TO MULTIPLE VARIABLES
variable_name1, variable_name2= value_of_variable1,
value_of_variable2 e.g.
a,b=0,0
or
a=b
=0

Q Explain the different types of Literals in Detail.


Ans
1. Numeric Literals- are numeric values like integer floating point number or a complex number
(a) Integer literals- whole numbers. (e.g. 123,-1234)
(b) Floating literal – integer with decimal (e.g.-13.0,3.5)
(c) Complex (e.g. 2+3j here 2 and 3 are real and j are imaginary )
2. String literal
3. Special literal –none (empty legal value)- is to indicate absence of value
4. Boolean literal- to represent one of the two Boolean Values i.e. True or False

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

Q What are operators?


Ans
Operators are the symbols or words that perform some kind of operation on given values (operands) in an expression and
returns the result.

Types of operators are:

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

Difference between Assignment and Arithmetic Assignment Operator


Arithmetic Assignment Operator Assignment
Used to assign values to the variables after Used to assign values to the variables.
performing arithmetic operations.
respresented by (+=,-=,*=,/=,%=,//=) Represented by (=)

Practice questions on concepts keywords,identifiers


and operators

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.

Python Operator Precedence – Python follows PEMDAS

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

Evaluate the following expressions:


a) 8/4+4**2//5%2-8 Ans -5.0
b) 10 >= 5 and 7 < 12 or not 13 == 3 Ans True
c) 6 * 3 + 4**2 // 5 – 8 Ans 13
d) 10 > 5 and 7 > 12 or not 18 > 3 Ans False
e) 18 % 4 ** 3 // 7 + 9 Ans 11
f) 2 > 5 or 5 == 5 and not 12 <= 9 Ans True
g) 6 * 3 + 4**2 // 5 – 8 Ans 13
h) 10 > 5 and 7 > 12 or not 18 > 3 Ans False
i) 51+4-3**3//19-3 Ans 51
j) 1718 and not 19==0 Ans True
k) 8 * 3 + 2**3 // 9 – 4 Ans 25
l) 12 > 15 and 8 > 12 or not 19 > 4 Ans False
m) not(20>6) or (19>7)and(20==20) Ans True
n) 17%20 Ans 17
o) 2 ** 3 ** 2 Ans 512
p) 7 // 5 + 8 * 2 / 4 – 3 Ans 2.0
If given A=2,B=1,C=3, What will be the output of following expressions:
(i) print((A>B) and (B>C) or(C>A)) Ans True
(ii) print(A**B**C) Ans 2
Write the output of the following python expression:
(a) print((4>5 and (2!=1) or (4<9)) Ans True
(b) print(2 + 3*4//2 - 4) Ans 4
(c) print(10%3 – 10//3) Ans -2

Question : How many types of strings are supported in Python ?


Answer:
Single line strings : Multiple strings :
Strings that are terminated in single line. Strings storing multiple lines of text.

For example : str = ‘Oswal Books’ For


example :
str =
‘Owal \
Books’
or str = ” ” ”
Oswal Books
””“

Question : What is “None” literal in Python ?


Answer:
Python has one special literal called ‘None’. The ‘None’ literal is used to indicate something that has not yet been created. It is also used
to indicate the end of lists in Python.

Q What are Escape Sequences or Backslash Character Constants?


Ans1. These are some non-printable or non-graphic characters which are mainly for formatting(display purpose) and used only with
print().
2. All escape sequences occupies one byte in computer memory .

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:

Escape Sequence Description


\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n New line or ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh

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

Question 7: What is used to represent Strings in Python ?


Answer:
Using Single Quotes (‘) Using Double Quotes (”) Using Triple Quotes o(”’ or ” ”
You can specify strings using Strings in double quotes work “) You can specify multi-line
single quotes such as ‘Quote me on exactly the same way as strings in strings using triple
this’. All white space i.e. spaces single quotes. An example is quotes. You can use single quotes
and tabs are preserved as it is. “What’s your name?” and double
quotes freely within the triple quotes.
An
example
is
“‘This is a multi-line string. This is
the first line. This is the second line.
“What’s your name?,” I asked.
He said “syed saif naqvi.”’

Q What are comments in Python ?


Ans A comment is text that doesn't affect the outcome of a code. It is readable for programmer(a person who is writing
the code) but ignored by python interpreter.
TYPES of comments :
Single line comment Multi line comment
Which begins with # (hash)sign. either write multiple line beginning with # sign
or
use triple quoted multiple line.
‘’’this is to check the concept of
python multiline comment ‘’’
DOCSTRING AND COMMENT
Docstring Comment
Docstrings are similar to commenting, but Comments are mainly used to explain non-
they are enhanced, more logical, and useful obvious portions of the code and can be useful
version of commenting. for comments on Fixing bugs and tasks that are
Docstrings act as documentation for the needed to be done.
class, module, and packages.
Docstrings are represented with opening and comments can start with a # at the beginning.
closing quotes
docstring can be accessed with the help function. The comments cannot be accessed with the help
function

DATA TYPES
Data types are used to identify the type of data and set of valid operations which can be performed on it.

Q How many types of data types in Python?


Ans
1. Numbers( integer(whole no), floating(number with decimal)
2. String
3. List
4. Tuple
5. Dictionary

Mutable Data types Immutable Data types


Object can be changed after it is created, Object can’t change its value in position
after it is created.

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.

Q How we can find the address of any identifier or variable ?


Ans By using id() we can find the address or memory location of any variable.

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

e.g. >>>y=12.3 >>>type(“hello”) >>>a=[1,23,36,48,5]


>>>x=10 >>>type(y) <class ‘str’> >>>type(a)
>>>type(x) <class ‘float’> <class ‘list’>
<class ‘int’>
>>>a=(1,23,36,48,5) >>>b=‘teena’, 101, 90.5 >>>a={1:’teena’,2:’heena’,3:’sheena’}
>>>type(a) >>>type(b) >>>type(a)
<class ‘tuple’> <class ‘tuple’> <class ‘dict’>
CONDITIONAL STATEMENTS
( DECISION MAKING)
If statement If….else statement
It is used to control the The if…else statement is If …..elif…..else statement-
flow of execution of called alternative execution , elif- is a keyword used in Python in replacement of else
the statements and also in which there are two if to place another condition in the program.
used to test logically possibilities and the This is called chained conditional.
whether the condition condition determines which Chained conditions allows than two possibilities and
is true or one gets executed need more than two branches
false. Syntax:
Syntax: if test_expression :
if test_expression : Statement of if Syntax:
Statement else: if test_expression :
Statement of else Statement of if elif expression:
Statement of elif
else:
Statement of else
Nested if…else statement
We can write an entire if..else statement in
another if ….else statement called nesting,
and the statement is called nested if.

In a nested if construct, you can have an if…


elif…else construct inside an if…elif…else
construct

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)

CONTROL STATEMENT (LOOPING STATEMENT) OR ITERATION


• Program statement are executed sequentially one after another.
• These are repetitive program codes, the computers have to perform to complete tasks.
• Three types of loops provided by Python are:

while loop for ….loop Nested loop


while loop

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

break continue pass


It is used to terminate the loop It is used to skip all the • This statement does
remaining statements in the nothing.
loop and move controls back • It can be used when a
to the top of the loop. statement is required
syntactically but the
program requires no
action.
for val in "string": for val in "string": for val in "string":
if val == "i": if val == "i": if val == "i":
bre contin p
ak ue print(val) ass
print(val) print("The end") print(val)
print("The end") print("The end")
Outp Out Out
ut: s put s put s
t t t

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”

Elements in a string can be individually accessed using its index (positive or


negative)
Positive index value 0 1 2 3 4
String H E L L O
Negative index value -5 - - - -
4 3 2 1

Functions supported by string data type are:


isupper() islower() isalnum() isaplha() isnumeric() isdigit()
isspace() capitalize() title() split() endswith() startswith()
index() len() find() lower() upper() replace()
strip() lstrip() rstrip() count() swapcase() splitlines()

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

Functions supported by LIST data type are:


append() extend() pop() del remove() index()
find() len() reverse() sort() clear() max()
min() insert() list() sum()

LIST and STRING


LIST STRING
Lists are mutable strings are immutable.
In consecutive locations, strings store the individual
In consecutive locations, list stores
characters
the references of its elements.

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

Identify the valid declaration of Find the output –


P: P= [‘Jan’, 31, ‘Feb’, 28] >>>A = [17, 24, 15, 30]
a) dictionary b) string c)tuple d) list >>>A.insert( 2, 33)
>>>print ( A [-4])
Ans (d) list Ans 24
Find the output of the following: Given the lists
>>>Name = “Python Examination” Lst=[‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R
>>>print (Name [ : 8 : -1]) ’] ,
Ans write the output of:
noitanima print(Lst[3:6])
Ans PUT
What will be the output of following Give Output:
program: a='hello' colors=["violet", "indigo", "blue", "green",
b='virat' "yellow", "orange", "red"]
for i in del colors[4]
range(len(a)): colors.remove("blue"
print(a[i],b[i]) ) colors.pop(3)
A print(colors)
n
Ans ['violet', 'indigo', 'green', 'red']
s

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’

d).'helloworl' Ans (a)


Given the lists A list is declared
L=[1,30,67,86,23,15,37,131,9232] , as Lst =
write the output [1,2,3,4,5,6,8]
of print(L[3:7]) What will be the value of
Ans [86, 23, 15, 37] sum(Lst)? Ans 29
Identify the valid declaration If the following code is executed, what will be
of L: L = (‘Mon’, ‘23’, the output of the following code?
‘hello’, ’60.5’) name="Computer_Science_with_Python"
a). dictionary b). string c). tuple d). print(name[-25:10])
list Ans puter_S
Ans (c)
How many times is the word ‘hello’ printed Given the list
in the following statement? L=[1,3,6,82,5,7,11,9
S=’python 2],
rocks’ for ch write the output
in s[3:8]: of
print(‘hello’) print(L[1:4:2]
(i) 5 (ii) 6 Ans [3,82]
(iii) 7

(iv) 4 Ans (i)


Given the string Identify the correct option to print the value 80
x="hello from the list
world", write L=[10,20,40,80,20,5,55]
the output of (i) L[80] (ii) L[4] (iii) L[L] (iv) L[3]
print(x[:2],x[:- Ans (iv) L[3]
2]) Ans he
hello wor
if a=[5,4,3,2,2,2,1], Give the output of the
evaluate the following following: x="Marvellous"
expression: print( x[2:7], "and" , x[-4:-1] )
print( a[a[a[a[2]+1]]]) Ans rvell and lou
Ans 2
What is the output produce by Is there any difference in ‘a’ or “a” in python?
the following code?
Ans. No
alst=[1,2,3,4,5,6,7,8,9] A string with zero character is called
print(alst[: :3]) string Ans empty string
Ans [1, 4, 7]
Is there any difference between 1 or ‘1’ Python does not support a character type.
in python? (T/F) Ans True. (Python supports string
Ans. Yes type)
● Write a code to create empty string 'str1' Ans. str1 = ' '

● What do you mean by traversing a string?


Ans. Traversing a string means accessing all the elements of the string one by one by using
index value.
● What is the index value of first element of a string? Ans. 0

● What is the index value of last element of a string? Ans. -1

● 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

● Index value of a string can be in float. (T/F) Ans. False

● What type of error is returned by following statement, if the length of string 'str1' is
10. print(str1[13]) Ans. Index error

Tuple Data Type


is an ordered and immutable group of comma-separated values of any datatype enclosed within parentheses ().
e.g. (1,23,36,48,5), ‘teena’, 101, 90.5, ('a', 'e', 'i', 'o', 'u')

Elements in a tuples can be individually accessed using its index (positive or


negative)
Positive index value 0 1 2 3 4
Tuple 1 2 3 4 5
3 6 8
Negative index value -5 - - - -
4 3 2 1

Functions supported by tuple data type are:


find() len() index() sorted() max()
min() count() tuple() sum()

LIST and TUPLES


LIST TUPLES
lists are mutable. Tuples are immutable

List can grow or shrink tuples cannot grow or shrink


For list []symbol is used For tuples () symbol is used
e.g. e.g.
L=[1,2,3,4] T=(1,2,3
,4)
Tuple: 1 mark Questions

A tuple is declared as Find the output from the


t1=(1,2,3,3,5,6,5,6,7,3 following code:
t=tuple()
,8,9) t=t+
what will be the value (‘Python’,)
of print(t1.count(3)) print(t)
print(len(t))
Ans 3 ans
(‘Python
’,) 1
Suppose a tuple T is declared as Choose the correct way to
T = "Yellow", 20, access value 20 from the
"Red" a, b, c = T following tuple
print(a)
which of the following is correct? aTuple = ("Orange", [10, 20, 30], (5, 15, 25))
(a) (‘Yellow’, 20, ‘Red’) a) aTuple[1:2][1]
(b) TypeError b) aTuple[1:2](1)
(c) Yellow c) aTuple[1][1]
Ans (c)“Yellow” Ans (c) aTuple[1]
[1]
Suppose a tuple T is declared Suppose a tuple T1 is declared
as T = (10, 12, 43, 39), as T1 = (10, 20, 30, 40, 50)
which of the following is Incorrect? which of the following is
a) print(T[1]) b) print(max(T)) incorrect? a) print(T[1]) b) T[2] =
c) print(len(T)) d) None of the -29
above Ans (d) c) print(max(T))d)

print(len(T)) Ans (b)


Suppose a tuple T is declared Identify the data type of X:
as T = (10, 12, 43, 39), X = tuple(list( (1,2,3,4,5) ) )
which of the following is a)Dictionary (b) string (c) tuple (d)
incorrect? a) print(T[1]) b) T[3] list Ans tuple
=9
c) print(max(T)) d) print(len(T))
Ans (b) because tuple is immutable.
A tuple is declared
as T = Suppose a tuple T is declared
(20,5,16,29,83) as T = (10, 20, 30, 40),
What will be the problem with the what will be the output
code T[1]=100. of print(T*2)
Ans It will show error tuple is immutable. Ans 20,40,60,80
t1=(2,3,4,5,6) What is the length of the tuple shown
print(t1.index( below? t=(((('a',1),'b','c'),'d',2),'e',3)
4)) output is Ans 3
a). 4 b). 5 c). 6 d). 2
Ans (d) 2
A tuple is declared as T = (2,5,6,9,8) Which of the following statements will
What will be the value of sum(T)? create a tuple ?
Ans 30 (a) Tp1 = (“a”, “b”) (b) Tp1= (3) * 3
(c) Tp1[2] = (“a”, “b”) (d) None of these
Ans (a)
Find the output of the following: Identify the valid declaration of
>>>S = 1, (2,3,4), 5, (6,7) Rec: Rec=(1,‟Vikrant”,50000)
>>> len(S) (i)List (ii)Tuple
Ans 4 (iii)String

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

SIMILARITIES AMONG STRING, LIST AND TUPLE


STRING (store text type of data) LIST Tuple
1.Slicing- extract limited information or access a range of characters
2. Elements can be individually accessed using its index (positive or negative)
3. Iterating/Traversing - Each character can be accessed sequentially using for loop.
for i in “hello”: #string usage for i in for i in (1,2,3):
similariti print(i) [1,2,3]: print(i)
es print(i)
s=”hell t=[1,2,3,4] t=(1,2,3,4)
o” for i for i in t: for i in t:
in s: print(i) print(i)
print(i)
s=”hello” t=[1,2,3,4] t=[1,2,3,4]
for i in for i in for i in
range(len(s)): range(len(t)): range(len(t
print(i,s[i]) print(i,t[i]) )):
print(i,t[i])
4. Common functions

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

Dictionary Data type


It is an unordered and mutable set of comma-separated key:value pair enclosed within curly braces {}.
e.g. vowels ={'a':1,'b':2,'c':3,'d':4,'e':5}

here, 'a', 'b', 'c', 'd', 'e' are the keys & 1,2,3,4,5 are the values

Functions supported by dictionary data type are:


len()
clear()
get()
• Dictionaries are mutable - (can modify its contents(values) but Key must be unique and immutable)
• In dictionary keys are unique but values can be duplicate.
• Keys are immutable but values are mutable.

LIST and DICTIONARY


LIST DICTIONARY
lists are sequential collections(ordered) dictionaries are non-sequential
collections(unordered).
In LIST the values can be obtained using But in dictionaries the values can be obtained
positions using keys
this thing is not possible in list. By changing the sequence of key we can
shuffle the order of elements of dictionary
e.g. e.g.
d={1:”hello”,2:”worl
L=[1,2,3,4]
d”}

Dictionary: 1 mark Questions

What will be the result of the following code?


>>>d1 = {“abc” : 5, “def” : 6, “ghi” : 7}
>>>print (d1[0])
(a) abc (b) 5 (c) {“abc”:5} (d) Error Ans (d)
Error
Which of the following statement create a dictionary?
a) d = { }
b) d = {“john”:40, “peter”:45}
c) d = (40 : “john”, 45 : “peter”}
d) All of the above Ans (d) all of the above
Which statement is correct for dictionary?
(i) A dictionary is a ordered set of key:value pair
(ii) each of the keys within a dictionary must be unique
(iii) each of the values in the dictionary must be unique
(iv) values in the dictionary are immutable
Ans (ii) each of the keys within a dictionary must be unique
Which is the correct form of declaration of dictionary?
(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]
Ans (i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
Declare a dictionary in python named QUAD having Keys(1,2,3,4)
and Values(“India”,”USA”,”Japan”,”Australia”)
Ans QUAD={1:”India”, 2:”USA”, 3:”Japan”, 4:”Australia”}
Write a statement in Python to declare a dictionary whose keys are 1,2,3 and values are Apple, Mango
and Banana respectively.
Ans Dict={1:’Apple’, 2: ’Mango’,3 : ‘Banana’}
Given
employee={'salary':10000,'age':22,'name':'Mahesh'}
employee.pop('age')
what is output
print(employee) Ans {'salary':10000,'name':'Mahesh'}
Write the ouput of following code:
d={'amit':19,'vishal':20}
print(d.keys()) Ans dict_keys(['amit', 'vishal'])
What will be output of following:
d = {1 : “SUM”, 2 : “DIFF”, 3 : “PROD”}
for i in d:
a) 1 print (i)
b) SUM
c) 1
d) 3
2
DIFF
SUM
Ans (a)
Write a statement in Python to declare a dictionary whose keys are ‘Jan’, ’Feb’, ’Mar’ and values
are 31, 28 and 31 respectively.
Ans Month={‘Jan’:31,’Feb’:28,’Mar’:31}
Write a statement in Python to declare a dictionary whose keys are 5, 8, 10 and values are May,
August and October respectively.
Ans Dict= {5:"May", 8: "August", 10: "October"}
Write a code to add the following key-value to a given dictionary.
A={‘class’:’VI’, ‘Sec’:’B’,’Rollno’:1}
Key Value
Fee Done
Route AB
Ans
A["Fee"]="Do
ne"
A["Route"]="AB"
Which of the following is the correct form of using
dict()? a) dict([('a' , 45), ('b', 78)])
b) dict({'a' : 45, 'b' :78})
c) dict('a'=45, 'b'=78)
d) All of these Ans (d)
a={1:10,2:20,3:30}
(a) Write code to delete the second element using del command. Ans del(a[2])
(b) Write code to delete the third element using pop() function. Ans a.pop(3)
Modules
Q How do we create modules in Python?
Ans Modules in Python are simply Python files with a .py extension. The name of the module will be the name of the file.

Module and Package

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

How we can import library in Python program?


Ans: - We can import a library in python program with the help of import command.
e.g: -
import random
import mysql.connector as ms

Q What are the different ways of importing modules in Python?


1. Importing entire module
2. Importing selected function/object from a module
3. Importing all function/objects of a module
importing importing selected function/object from a importing all
entire module module function/objects of a
module
syntax Syntax: from module_name import function_name syntax
import module_name from module_name import *
e.g. e.g. e.g.
import math from math import from math
print(math.sqrt( sqrt print(sqrt(4)) import *
4)) print(sqrt(4))
from math import print(pow(3,2))
sqrt,pow print(sqrt(4))
print(pow(3,2))
Import Statement and From Import Statement
Import Statement From Import Statement
import all the modules from that package only imports the required module as
specified
math random pickle csv mysql.connector sys os
sin() random() dump() reader() connect() stdi rem
cos() randint() load() writer() isconnecte n ove
tan() randrang writerow d() std rena
log() e() () execute() out me
sqrt writerow cursor() std
() s() fetchall() err
floo fetchaone(
r() )
exp fetchmany
() ()
ceil() rowcount
pow(
)
roun
d()
pi
fmo
d()
factorial()
dir() – is used to display all the functions related to particular module syntax: dir(module
name) help()- is to display the syntax of particular function. syntax:
help(modulename.functionname) MODULE, PACKAGE AND LIBRARY
MODULE PACKAGE LIBRARY
● Module is a file which ● Package is a collection  Library is a collection
contains python of modules. of packages.

functions, global
● Each package in Python is a There is no difference
variables etc.
directory which MUST between package and
● It is nothing but .py contain a special file called python library
file which has init .py. conceptually.

python executable
● This file can be empty, and Some examples of library
code / statement
it indicates that the in Python are: Python
directory it contains is a standard library
Python package, containing math module,
so it can be imported the random module, statistics
same way a module can be module etc.
imported

Q What is the use of _init.py file?


Ans
1. Each package in Python MUST contain a special file called init .py.
2. This file can be empty.
3. it specifies that the directory it contains is a Python package.
4. it can be imported the same way a module can be imported.

Module Identification- I mark questions


Name the Python Library modules which need to be imported to invoke the following functions:
(i) ceil() (ii) randrange() Ans (i) math (ii) random
(i) sin( ) (ii) randint ( ) Ans (i) math (ii) random
(i) sqrt() (ii) randint() Ans (i) math (ii) random
(i) dump() (ii) random() Ans (i) pickle (ii) random
(i) round() (ii) load() Ans (i) math (ii) pickle
(i) writerow() (ii) sqrt() Ans (i) csv (ii) math
(i) replace() (ii) load() Ans (i) string (ii) pickle
(i) cursor() (ii) pi Ans (i) mysql.connector (ii) math
(i) sin() (ii) reader() Ans (i) math (ii) csv
(i) cursor() (ii) reader() Ans (i) mysql.connector (ii) csv
i) stdin() ii) load() Ans (i) sys (ii) pickle
(i) log() (ii) writer() Ans (i) math (ii) csv
Which of the following functions generates an integer?
a) uniform( ) b) randint( ) c) random( ) d) None of the above Ans (b) randint()

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

Q What is Type conversion? Explain Implicit and Explicit type Conversion.


Ans
The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type
conversion.
Python has two types of type conversion.
Implicit type conversion Explicit Type conversion
Python automatically converts one data type to Users(programmer) convert the data type of an object to required data
another data type. This process doesn't need type. We use the predefined functions like int(),float(),str() etc.
any user involvement.
e.g. >>>a=3
>>>a=3 >>>c=3.4
>>>b=3.4 >>>str(a) #str()function converts integer to
>>>d=a+b string. ‘3’
>> >>>str(c) #str() function converts float number to string
>d ‘3.4’
6.4 >>>b=3.4
>>>d=’3’
>>>int(b) # int() function converts floating number to
integer 3
>>>d=input(“enter any number”) #input() takes value in the string
form 4
>>
>d
‘4’
>>>d=int(input(“enter any number”)) #int()function converts string to
integer 4
>>
>d
4
input() function always enter string value in python .
There is need of int(),float() function can be used for data conversion.

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

Program Program Code sharing Code re- Increase


developmen testing becomes usability s
t made easy becomes easy possible increases program
and readabil
fast ity

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

Give the basic structure of user defined


function. def funtionname(parameters name):
statement of the
function

Q What are Arguments and Parameters?


Arguments Parameters
passed values in function call received values in function definition.
Passed values can be in the form of variable, It should be of variable types.
literal or expression
def fun(a,b): def fun(a,b): #parameters
c=a+ c=a+
b b
print print
(c) (c)

x here a and b are the parameters


=
2
y
=
4
fun(x,y) #variables
fun(5,6) #literals
fun(x+3,y+6)

#expressions
here x,y , 5,6, x+3, y+3 are arguments

Q What are actual and formal arguments /parameters?

Formal parameter Actual Parameter


A formal parameter, i.e. a parameter, is in An actual parameter, i.e. an argument, is in
the function definition. a function call.

def sum(x,y): #x, y are formal


arguments z=x+y
return z #return the result

x,y=4,5
r=sum(x,y) #x, y are actual
arguments print(r)

Q What is the use of return statement?


Ans It is used to return either a single value or multiple values from a function.
Q Can Python return Multiple values and in what forms?

Ans Python returns Multiple values in the form of tuples :

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)

Q Explain different types of arguments in


detail Ans

1. 2. Default Arguments- if right 3.


Positiona parameter have default value then left Keyword
l parameters can also have default value. Arguments
paramet this argument can be skipped at the (Named
ers time of function Arguments)-
(Required calling
Arguments) -
these
arguments must We can write arguments in
be provided for any order but we must give
all values
parameters according to their name
e.g. e.g. e.g.
def fun(a,b): def fun(a,b,c=3): def fun(a,b,c):
c=a+ d=a+b print(a,b
b +c
print print(d ,c)
(c) )
x=10 x=10 fun(b=3,c=4,a=2
y=3 y=3
fun(x fun(x,y) #here c parameter value is 3 )
,y) z=5
fun(x,y,z) #here it will be take parameter c
value as 5

Q What do you mean by scope of variables?


Ans Scope means –to which extent a code or data would be known or accessed. 2 types of scope are: Global scope and
Local scope.

Global variable Vs Local Variable


Global variable Local Variable
Global variables are defined outside of all A local variable is declared within the body
the of
functions, generally on top of the program. a function or a block
The global variables will hold their Local variable only use within the function
value throughout the life-time of your or block where it is declare.
program.
a=10 //global
variable def fun():
b=20
print(b) //local
variable print(a)

Naming Resolution- LEGB-(LOCAL, ENCLOSED, GLOBAL and BUILT-IN)

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 the definition of a function Write the definition of a function Alter(A, N) in


Alter(A, N) in python, which should python, which should change all the odd numbers in
change all the multiples of 5 in the list to the list to 1 and even numbers as 0.
5 and rest of the elements as 0. #sol
#sol def Alter ( A, N):
def Alter ( A, N): for i in
for i in range(N):
range(N): if(A[i]%2==0):
if(A[i]%5==0): A[i]=0
A[i]=5 else:
else: A[i]=1
A[i]=0 print("LIst after Alteration", A)
print("LIst after Alteration", A)
Write code for a function void oddEven (s, N) Write a code in python for a function void Convert ( T,
in python, to add 5 in all the odd values and N) , which repositions all the elements of array by
10 in all the even values of the list 5. shifting each of them to next position and shifting last
#sol element to first position.
e.g. if the content of
def oddEven ( s, N): array is 0 1 2
for i in range(N): 3
if(s[i]%2==0): 10 14 11 21
The changed array content will
s[i]=s[i] be: 0 1 2 3
+5 else: 21 10 14 11
s[i]=s[i]+10 sol:
print("LIst after Alteration", s) def Convert ( T, N):
for i in range(N):
t=T[N-1]
T[N-
1]=T[i]
T[i]
=t
print(
T)
Write a code in python for a function Convert Write a function SWAP2BEST ( ARR, Size) in
( python to modify the content of the list in such a
T, N) , which repositions way that the elements, which are multiples of
all the elements of array by shifting each 10 swap with the value present in the very
of them to next position and shifting first next position in the list
element to last position.
e.g. if the content of sol :
array is 0 1 2 def
3 SWAP2BEST(A,size)
10 14 11 21 : i=0
The changed array content will while(i<size):
be: 0 1 2 3 if(A[i]
14 11 21 %10==0):
10 ''' A[i],A[i+1]=A[i+1],A[i]
def Convert ( T, i=i
N): t=T[0] +2
for i in range(N- else:
1): i=i
T[i]=T[i+1] +1
T[N-1]=t return(
print("after conversion",T) A)

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)

Write a user defined function Write definition of a Method MSEARCH(STATES)


findname(name) where name is an to display all the state names from a
argument in Python to
delete phone number from a dictionary list of STATES, which are starting with alphabet M. For
phonebook on the basis of the name, example: If the list STATES
where name is the key. contains["MP","UP","WB","TN","MH","MZ","DL",
" BH","RJ","HR"]
sol The following should get displayed MP MH MZ
def findname(d):
n=input("enter key which u want to def
delete") d.pop(n) MSEARCH(STATES):
print("dictionary after deletion",d) for i in STATES:
if(i[0]=='M'):
print(i)
Write a Get2From1( ) function in to Identify the type one or more types of arguments in
transfer the content from one list ALL[ ] the following codes:
to two list Odd[ ]and Even[]. a)
The Even should contain values from def sum(a=4,b=6):
places (0,2,4,………) of ALL[] and Odd[] return a+b
should contain values from print (sum( )) Ans
places ( 1,3,5, ). #default b)
''' def sum(a=1,b):
return a+b
even print(sum(b=20, a=5 )) Ans
=[] #keyword c)
odd= def sum(*n):
[] for i in n:
def fun(all,s): total+
for i in range(0,s- =I return total
1): if(i print (sum(4,3,2,1,7,8,9)) Ans #positional
%2==0):
even.append(all[ d)
i]) else: def sum(a=1,b):
odd.append(all[i]) return a+b
print(sum(10,20)) Ans #positional
print("even
list",even)
print("odd
list",odd)

Consider the following function calls


with respect to the function definition.
Identify which of these will cause an error
and why?
i) calculate(12,3)
def Ans #no error
calculate(a,b=5,
c=10): return ii) calculate(c=50,35)
a*b-c Ans #we should have to specify the value to all the
parameters .corrected calling is
i) calculate(12,3) calculate(c=50,a=35,b=12)
ii) calculate(c=50,35)
iii) calculate(20, b=7, a=15) iii) calculate(20, b=7, a=15)
iv) calculate(x=10,b=12) Ans #name c is missing . corrected code:
calculate(c=20, b=7, a=15)

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.

Q Write the different ways to open a file


Ans
open() with statement
file_object/file_handler = open(<file_name>, with statement- in this mode , no need to
<access_mode>). call close() function

syntax:
with open(<file_name>, <access_mode>)
as file_object/file_handler

file_name = name of the file ,enclosed in double quotes.


access_mode= It is also called file mode. It determines ,kind of operations can be performed with
file,like read,write etc
If no mode is specified then the file will open in read mode.

File mode or access mode


Text file Binary file CSV file
r rb r
w wb w
a ab a
r+
w+
a+
e.g e.g.
f=open(“abc.txt”,’ with open(“abc.txt”) as f:
r’) f.write(“hello”) f.write(“hello”)
f.close()

Q purpose of read(n) method?


This method reads a string of size (here n) from the specified file and returns it. If size parameter is not given or a negative
value is specified as size, it reads and returns up to the end of the file. At the end of the file, it returns an empty string

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

TEXT FILE BINARY FILE


A file whose contents can be viewed using a text editor is A binary file stores the data in the same way as as
called a text file. (.txt) stored in the memory.

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

Relative and Absolute Path


Relative Path Absolute Path
The relative path is the path to some file with respect to The absolute path is the full path to some place on your
current working directory computer.

e.g. Relative For example: Absolute path: C:\


path: Users\hp\Desktop\cs\function.py
“function.py”
or “..\
function.py
seek() and tell()

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

from=0 -means to move from the beginning of


file. It is default also
from=1 means to move the pointer at the current
position
from=2 means to move pointer at end of file
TEXT FILE, BINARY FILE AND CSV FILE.

TEXT FILE BINARY FILE CSV FILE


A file whose contents can A binary file stores the data Data is stored in the form of
be viewed using a text in the same way as as rows and column i.e in
editor is called a text file. stored in the memory. tabular form. (.csv)
(.txt) (.dat)
A text file is simply a Can store different types They are plain text files
sequence of ASCII or of data (audio, having ASCII/Unicode
Unicode characters. text,image) in a single file. Characters

EOL (new line character No EOL occurs Language which support


i.e. enter) or internal text files will also support
translation occurs csv files.

TEXT FILE AND CSV FILE


TEXT FILE CSV(COMMA SEPARATED VALUES) FILE
Text files contain text which can be opened CSV also contain text data but in a format
by any text editor and there is plain text where each line is considered as row/record
with no which has
format many fields(columns).
EOL (new line character i.e. enter) or fields are the values separated by a
internal translation occurs delimiter like , " ' ,"*","/" ,”\n”etc.

No title is required the first record is the title of each field.


No need to import any module csv module must be imported

‘a’ AND ‘w’ MODE

‘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() and writelines()

write() writelines()
write() function write a single string at a time writelines() methods can be used to write a
sequence of strings

PICKLING AND UNPICKLING

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

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.

Text file questions


#lines starting with #find no of lines
F f=open(“firewall.tx
f=open(“firewall.tx t") t=f.readlines()
t") c=0 print(len(t))
for i in
f.readline():
if(i=='F'):
c=c
+1
print(c)
#count no of digits #count no of
f=open(“firewall.tx alphabets
t") t=f.read() f=open(“firewall.txt
c=0 ") t=f.read()
for i in t: c=0
if(i>='0' and for i in t:
i<='9') : c=c+1 if(i>='a' and i<='z')or(i>='A' and
print(c) i<='Z') : c=c+1
print(c)
#find size of file or how many characters in a #find how many 'f' and 's' present in a
file f=open(“firewall.txt") file f=open(“firewall.txt")
t=f.read() t=f.rea
print(len( d()
t)) c=0
d=0
for i in t:
if(i=='
f'):
c=c+1
elif(i=='
s'):
d=d+1
print(c,
d)
#find how many 'firewall' and 'to' present in a #find how many 'firewall' or 'to' present in a file
file f=open(“firewall.txt") f=open(“firewall.txt")
t=f.rea t=f.rea
d() d()
c=0 c=0
d=0 for i in t.split():
for i in t.split(): if(i=='firewall')or (i=='is'):
if(i=='firewal c=c
l'): c=c+1 +1
elif(i=='t print(c)
o'):
d=d+1
print(c,d)
#print 5 lines from #display first 3
file lines
f=open(“firewall.txt f=open(“firewall.tx
") t")
print(f.readlines(5)) print(f.readline())
print(f.readline())
print(f.readline())

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.

def filter(oldfile, newfile):


f1 = open("oldfile","r")
f2 =
open(“newfile”,”w”)
while True:
text=
f1.readline() if
len(text) ==0:
break
if text[0] == ‘@’:
contin
ue
f2.write(tex
t)
f1.clos
e()
f2.clos
e()

Binary file—pickle module (to write - dump () and to read- load() )


Write a definition for function Itemadd () to Write a definition for function SHOWINFO() to
insert record into the binary file ITEMS.DAT, read each record of a binary file
(items.dat- id,gift,cost). info should stored in ITEMS.DAT,
the form of list. (items.dat- id,gift,cost).Assume that info is
''' stored in the form of list
#Sol : '''
import #Sol:
pickle def import pickle
itemadd (): def SHOWINFO():
f=open("items.dat","wb") f=open("items.dat","r
n=int(input("enter how many b") while True:
records")) for i in range(n): try:
r=int(input('enter id')) g=pickle.load
n=input("enter gift (f) print(g)
name") except:
p=float(input("enter bre
cost")) v=[r,n,p] ak
pickle.dump(v f.close()
,f) f.close()
Write a definition for function COSTLY() to read Write a definition for function COSTLY() to read
each record of a binary file each record of a binary file
ITEMS.DAT, find ,count and display those items, ITEMS.DAT, find and display those items,
which are priced less than 50. which are priced between 50 to 60.
(items.dat- id,gift,cost).Assume that info is (items.dat- id,gift,cost).Assume that info is
stored in the form of list stored in the form of list
''' '''
#sol #sol
def COSTLY(): def COSTLY():
f=open("items.dat","r f=open("items.dat","r
b") c=0 b") while True:
while try:
True: r=pickle.load(f)
try: if(r[2]>=50 and
r=pickle.load r[2]<=60):
(f) print
if(r[2]<50): (r)
c=c+ except:
1 bre
print ak
(r) f.close()
except:
break
print(
c)
f.clos
e()
''' '''
Write a function for function to Write a function in to search and display
SEARCH()for a item from a binary file details of all flights, whose
"items.dat" destination is “Mumbai” from a binary
The user should enter the itemno and function file “FLIGHT.DAT”.
should search and (flight.dat- fno,from (starting point), to
display the detail of items.(items.dat- (destination)).
id,gift,cost). Assume that info is stored in the form of
Assume that info is stored in the form of list '''
list ''' import
import pickle def
pickle def FUN():
SEARCH(): f=open("FLIGHT.DAT","rb")
f=open("items.dat","rb")
n=int(input("enter itemno which u want while
to True:
search")) try:
while r=pickle.load(f)
True: if(r[2]=="Mumbai
try: "):
r=pickle.load print
(f) (r)
if(r[0]==n): except:
print bre
(r) ak
except: f.close()
bre
ak
f.close()
''' '''
Write a definition for function UPDATEINFO() Write a function in that would read the
from binary file contents from the file GAME.DAT and
ITEMS.DAT. The user should enter the item creates a file named BASKET.DAT copying
name and function should search and only those records from GAME.DAT where
update the entered itemno the game name is “BasketBall”.
info (items.dat- id,gift,cost). (game.dat - gamename, participants).
Assume that info is stored in the form of Assume that info is stored in the form of
list ''' list '''
import import
pickle pickle def
import os fun():
def UPDATEINFO(): f=open("GAME.DAT","rb")
f=open("items.dat","rb") f1=open("BASKET.DAT","wb")
f2=open("temp.dat","w while
b") s=[] True:
a=input("enter item name which we want try:
to update") r=pickle.load(f)
while if(r[0]=="BasketBall
True: "):
try: pickle.dump(r,
r=pickle.load(f) f1) except:
break
if(r[1]==a): print(c
r[0]=int(input("enter new item )
id")) r[1]=input("enter item f.close
name") r[2]=int(input("enter cost ()
of item")) s.append(r) f1.clos
except: e()
break
pickle.dump(s,
f2) f.close()
f2.close()
os.remove("items.dat")
os.rename("temp.dat","items.dat")

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.

Anuj Kumar of class 12 is writing a program to create a CSV file


“user.csv” which will contain user name and password for
some entries. He has written the following code. As a
programmer, help him to successfully execute the given task.
import # Line 1 Ans
def addCsvFile(UserName,PassWord): # to write / add data (a) Line 1 : csv
into the CSV file (b) Line 2 : a
f=open(' user.csv',' ') # Line 2 (c) Line 3 : reader
newFileWriter = csv.writer(f) (d) Line 4 : close()
newFileWriter.writerow([UserName,PassWor (e) Line 5 :
d]) f.close() #csv file reading code Arjun 123@456
Arunima
def readCsvFile(): # to read data from CSV aru@nima Frieda
file with open(' user.csv','r') as myname@FRD
newFile:
newFileReader = csv. (newFile) #
Line 3 for row in newFileReader:
print (row[0],row[1])
newFile. #
Line 4 addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD
”) readCsvFile() #Line 5

(a) Name the module he should import in Line 1.


(b) In which mode, Anuj should open the file to add data 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.
Krishna of class 12 is writing a program to read the details
of Sports performance and store in the csv file “Sports.csv”
delimited with a tab character. As a programmer, help him
to achieve the task. Ans
import # a) Line 1 : csv
Line 1 f =
open(“Sports.csv”,”a”) b) Line 2 : writer
wobj = csv. (f, delimiter = ‘\t’) #
Line 2 wobj.writerow( [‘Sport’, ‘Competitions’,
‘Prizes Won’] ) ans = ‘y’
i=1
while ans == ‘y’:
print(“Record :”, i)
sport = input(“Sport Name :”)
comp = int(input(“No. of competitions
participated :”)) prize = int(input(“Prizes won:”)) c) Line 3 : [sport, comp, prize]
record = # Line 3
wobj. (rec) # d) Line 4 : writerow
Line 4 i += 1
ans = input(“Do u want to continue ?
(y/n) :”) f. # Line 5 e) close( )
a) Name the module he should import in Line 1
b) To create an object to enable to write in the csv file in Line 2
c) To create a sequence of user data in Line 3
d) To write a record onto the writer object in Line 4
e) Fill in the blank in Line 5 to close the file.

Abhisar is making a software on “Countries & their Capitals” in


which various records are to be stored/retrieved in
CAPITAL.CSV data file. It consists some records(Country &
Capital). He has written the following code in python. As a Ans
programmer, you have to help him to successfully execute the (a) csv
program.
import # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a new record in
CSV file (b) “a”
f=open(“CAPITAL.CSV”, ) # Statement-2
fwriter=csv.writer(f) (c) close()
fwriter.writerow([Country,Capital]) f. #
Statement-3

def ShowRec(): # Fn. to display all records from CSV (d)reader


file with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv. (NF) #
Statement-4 for rec in NewReader:
print(rec[0],rec[1])
(e)
AddNewRec(“INDIA”,”NEW INDIA NEW
DELHI”) DELHI CHINA
AddNewRec(“CHINA”,”BEIJING”) BEIJING
ShowRec() # Statement-5

(a) Name the module to be imported in Statement-1.


(b)Write the file mode to be passed to add new record
in Statement-2.
(c) Fill in the blank in Statement-3 to close the file.
(d)Fill in the blank in Statement-4 to read the data from a csv
file.
(e) Write the output which will come after executing
Statement- 5.
Anis of class 12 is writing a program to create a CSV file
“mydata.csv” which will contain user name and password
for some entries. 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 addCsvFile(UserName,PassWord): # to write / add (b) Line 2 : a
data f=open(' mydata.csv',' ') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close() #csv file reading code
def readCsvFile(): # to read data from CSV
file with open('mydata.csv','r') as
newFile:
newFileReader = csv. (newFile) # (c) Line 3 : reader
Line 3 for row in newFileReader:
print
(row[0],row[1]) newFile. # (d) Line 4 : close()
Line 4

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

Write a function AddCustomer(Customer) Write a function DeleteCustomer() to delete


in Python to add a new Customer a Customer information from a list of CStack.
information NAME into the List of CStack The function delete the name of customer
and display the information. from the stack.
CStack=[] CStack=[]
def AddCustomer(Customer): def
CStack.append(Custom DeleteCusto
er) if len(CStack)==0: mer(): if
print (“Empty Stack”) (CStack ==[]):
else: print(“There is no Customer!”)
print (CStack) else:
print(“Record deleted:”,CStack.pop())
Write A Function Python, MakePush(Package) Write InsQueue(Passenger) and
and MakePop (Package) to add a new Package DelQueue(Passenger) methods/function in
and delete a Package form a List Package Python to add a new Passenger and delete a
Description, considering them to act as push Passenger from a list ‘names’ , considering
and pop operations of the Stack data them to act as insert and delete operations of
structure. the Queue data structure.
def MakePush(Package): def InsQueue (Passenger):
a=int(input("enter package a=int(input("enter passenger
title:")) Package.append(a) name:")) Passenger.append(a)

def def DelQueue


MakePop(Packag (Passenger):
e): if(Passenger ==[]):
if(Package==[]): print("queue empty")
print("Stack empty") else:
else: print(Passenger.pop(0))
print("Deleted element:",Package.pop())
Write AddCustomer(Customer) method in Write RemoveCustomer(Customer) method in
Python to add a new customer, considering it Python to remove a Customer, considering it
to act as a PUSH operation of the stack to act as a POP operation of the stack
datastructure. Also display the contents of the datastructure. Also return the value deleted
Stack after PUSH operation. Details of the from stack.
Customer are : CID and Name.
def AddCustomer(Customer): def
cid = int(input(“Enter customer id:”)) RemoveCustomer(Custo
Name = input(“Enter customer mer): if Customer == [ ]:
name:”)) Customer.append print(“Underflo
( [cid,Name] ) w”) else:
p=
Customer.pop( )
return p
Write a function in python named Write a function in python named POP(STACK)
PUSH(STACK, SET) where STACK is list of some where STACK is a stack implemented by a list of
numbers forming a stack and SET is a list of numbers. The function will display the popped
some numbers. The function will push all the element after function call.
EVEN elements from the SET into a STACK def
implemented by using a list. Display the stack POP(STAC
after push operation. K): if
def STACK==[]
PUSH(STACK,SET): :
for i in print(“underflo
SET: if i w”) else:
%2==0: print(STACK.pop())
STACK.append(i)
print(STACK)
Write a function in Python PUSH(Arr), where Write a function in Python POP(Arr), where
Arr is a list of numbers. From this list push all Arr is a stack implemented by a list of
numbers divisible by 5 into a stack numbers. The function returns the value
implemented by using a list. Display the stack if deleted from the stack.
it has at least one element, otherwise display
appropriate error message. def popStack(st)
def PUSH(Arr,value): :
if len(st)==0:
s=[] print("Underflo
for x in w") else:
range(0,len(Arr)): print(st.pop())
if Arr[x]%5==0:
s.append(Arr[
x]) if len(s)==0:
print("Empty
Stack") else:
print(s)
Write a function in Python PUSH (Lst), where Write a function in python, PushEl(e) to add
Lst is a list of numbers. From this list push all a new element and PopEl(e) to delete a
numbers not divisible by 6 into a stack element from a List ,considering them to act
implemented by using a list. Display the stack as push and pop operations of the Stack data
if it has at least one element, otherwise display structure .
appropriate error message.
def def PushEl(element):
PUSH(Arr,valu a=int(input("enter package title :
e): s=[] ")) element.append(a)
for x in
range(0,len(Arr)): def PopEl(element):
if Arr[x]%6!=0: if (element==[]):
s.append(Arr[ print( "Stack empty")
x]) if len(s)==0: else:
print("Empty print (element.pop())
Stack") else:
print(s)
Write InsertQ(C) and DeleteQ(C) Write a function DELQ(Customer) in Python
methods/functions in Python to add a new to delete a Customer from a Queue
Customer and delete a Customer from a list implemented using list.
of Customer names, considering them to act
as insert and delete operations of the Queue def DELQ(queue):
def InsertQ(queue): if (queue == []):
a=input(“Enter customer print (“Queue is empty…..”)
name :”) queue.append(a) else:
print(queue.pop(0))
def
DeleteQ(qu
eue): if
(queue==[])
:
print (“Queue is
empty…..”) else:
print(queue.pop(0))
Write a function POP(Book) in Python to Write a function in Python PushBook(Book) to
delete a Book from a list of Book titles, add a new book entry as book_no and
considering it to act as a pop operation of the book_title in the list of Books , considering it
Stack data structure. to act as push operations of the Stack data
structure.
def POP(Book):
if (Book ==[]): def PushBook(Book):
print(“Stack empty”) bno = input("enter book no :
else: ") btitle = input(“enter book
print(Book.pop()) title:”) rec = [bno , btitle]
Book.append(rec)
print(Book)
MySQL
Data types of SQL- Following are the most common data types of SQL.
NUMBER / INTEGER CHAR VARCHAR DATE DECIMAL

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

e.g.INSERT INTO student


Alter command is used for alteration of
(VALUES(101,'Rohan','XI',400,'Jammu'
table structures. Various uses of alter );
command, such as,
Update command –it is used to update a row
● to add a column to existing table
of a table. syntax,
● to rename any existing column UPDATE table-name set column-name = value
where condition;
● to change datatype of any column or e.g.
to modify its size. UPDATE Student set s_name='Abhi',age=17
where s_id=103;
● alter is also used to drop a column.

Example: Delete command


ALTER command- Add Column to
existing Table It is used to delete data(record) from a table.It can
Using alter command we can add a column to also be used with condition to delete a particular
an existing table.
Syntax, row.
alter table table-name (i) syntax:- to Delete all Records from a Table
add(column- name datatype);
e.g. DELETE from table-
alter table Student
add(address char); name; Example
DELETE from Student;
ALTER command-To Modify an
existing Column (ii) syntax: to Delete a particular Record
alter command is used to modify data type of from a Table
an existing column .
DELETE from Student where s_id=103;
Syntax:-
---------------------------------------------------------------
alter table table-name modify(column-
--
name datatype);
e.g. SELECT command
alter table Student modify(address varchar(30)); Select query is used to retrieve data from a tables.
It is the most used SQL query. We can retrieve
ALTER command- To Rename a column complete tables, or partial by mentioning
Using alter command you can rename an conditions using WHERE clause.
existing column. Syntax :
(i) DISPLAY SPECIFIC COLUMNS
Syntax:- SELECT column-name1, column-name2,
alter table table-name change old-column- column- name3, column-name from table-
name new_ column-name; name;
e.g.
alter table Student change address Location; Example
SELECT s_id, s_name, age from Student;
The above command will rename address
column to Location. (ii) DISPLAY ALL COLUMNS from
Table- A special character asterisk *
ALTER command -To Drop a Column is used to address all the
alter command is also used to drop columns data(belonging to all columns) in a
also. Syntax:- query. SELECT statement uses *
alter table table-name drop(column- character to retrieve all records from
a table.
name) e.g.
Example: SELECT * from student;
alter table Student drop column (address);

DDL - Drop command


This command completely removes a table
from database. This will also destroy the table
structure. Syntax,
drop table table-
name Example
drop table
Student; To drop
a database, drop
database Test;

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:

Create table Fee


(RollNo integer(2) Foreign key iv. Foreign Key : The foreign key designates a
(Rollno) references Student (Rollno), column or combination of columns as a foreign
Name char(20) Not key and establishes its relationship with a
null, Amount primary key in different table.
integer(4), Fee_Date
date);

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

example: vi. Default Constraint : The DEFAULT


create table Employee constraint is used to set a default value for a
(EmpNo integer(4) Primary column. The default value will be added to all
Key, Name char(20) Not Null, new records, if no other value is specified.
Salary integer(6,2) check (salary >
0), DeptNo integer(3) default 0
);

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

Logical operator- AND,OR,NOT


AND operator- AND to show true value if Like clause- pattern matches
all the conditions are true
Wildcard operators - used in like clause.
EXAMPLE (i) Percent sign % : represents zero, one
TO return records where salary is less than or more than one character.
10000 and age greater than 25. (ii) Underscore sign _ : represents only
SELECT * from Emp WHERE salary < one character.
10000 AND age > 25; Example of LIKE clause
- To display all records where s_name
starts with character 'A'.
OR operator- SELECT * from Student where s_name like 'A
In this , atleast one condition from the %'; Example
conditions specified must be satisfied by any To display all records from Student table
record to be in the result. where s_name contain 'd' as second
Example character. SELECT * from Student where
To return records where either salary is s_name like '_d%';
greater than 10000 or age greater than 25.
SELECT * from Emp WHERE salary >
10000 OR age > 25;

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

Select * from emp where city


in
(‘mumbai’,’delhi’,’jaipur’);
BETWEEN- show records within range

Display records whose salary between


2000 to 3000

select * from emp where sal between


2000 and 3000;

Aggregrate Functions-These Distinct keyword- it is used


functions return a single value after
with Select statement to retrieve unique values
calculating from a group of values.
from the table. Distinct removes all the
frequently used Aggregrate duplicate records while retrieving from
functions. Avg(), Sum(), max(), min(), database.
count(column_name),count(distinct)
count(column name)- Count returns the Syntax :
number of rows present in the table either
SELECT distinct column-name from table-
based on some condition or without condition.
name; Example
COUNT(distinct)
To display only the unique
SELECT COUNT(distinct salary) from emp;
salary from Emp table
select distinct salary from Emp;

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 and having clause

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

MySQL- 1 mark questions

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

Expand the term: RDBMS Write an Aggregate function that is used in


Ans Relational Database Management MySQL to find No. of Rows in the database
System Table
Ans count(*)
For each attribute of a relation, there is a In SQL, write the query to display the list of
set of permitted values, called the of that databases stored in MySQL.
attribute. Ans show databases
a). Dictionaries b). Domain
c). Directory d). Relation
Ans (b) Domain
Which is not a constraint in SQL? Which command is used to see the structure of
a) Unique b) Distinct the table/relation.
c) Primary key d) a) view b) describe
check Ans (b) Distinct c) show d)
select Ans (b) describe

A virtual table is called a ............. Which clause is used to remove the


Ans view duplicating rows of the table?
i) or ii) distinct iii) any
iv)unique Ans (ii) distinct

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 :

Name of the database - Department Name of the table - WORKER

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

001 Monika Arora 100000 2014-02-20 HR


002 Niharika Diwan 80000 2014-06-11 Admin
003 Vishal Singhal 300000 2014-02-20 HR
004 Amitabh Singh 500000 2014-02-20 Admin
005 Vivek Bhati 500000 2014-06-11 Admin
06 Vipul Diwan 200000 2014-06-11 Account
07 Satish Kumar 75000 2014-02-20 Account
08 Monika Chauhan 80000 2014-04-11 Admin

a) Write a query to create the given table WORKER.


b) Identify the attribute best suitable to be declared as a primary key.
c) Karan wants to increase the size of the FIRST_NAME column from 10
to 20 characters. Write an appropriate query to change the size

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

a) Create table WORKER(WORKER_ID varchar(3), FIRST_NAME


varchar(10), LAST_NAME varchar(10), SALARY integer, JOINING_DATE
Date, DEPARTMENT varchar(10) );
b) WORKER_ID
c) alter table worker modify FIRST_NAME varchar(20);
d) DELETE FROM WORKER;
e) Desc WORKER / Describe WORKER;

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?

(c) What is the degree and cardinality of the table? 1


(d) Insert the following data into the attributes VisitorID, VisitorName and

ContactNumber respectively in the given table VISITOR. 1


VisitorID = “V004”, VisitorName= “VISHESH” and ContactNumber= 9907607474
(e) Remove the table VISITOR from the database HOTEL. Which command will he
used from the following:
a) DELETE FROM VISITOR;

b) DROP TABLE VISITOR;


1

c) DROP DATABASE HOTEL;

d) DELETE VISITOR FROM HOTEL;

(a) VIsitorID and ContactNumber


(b) VisitorID
(c) Degree=
3
Cardinality=
4
(d) insert into VISITOR values (“V004”, “VISHESH”,9907607474)
(b) DROP TABLE VISITOR;
Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and ADMIN given below:
TABLE: SCHOOL
CODE TEACHERNAME SUBJECT DOJ PERIODS EXPERIENCE
1001 RAVI SHANKAR ENGLISH 12/03/2000 24 10
1009 PRIYA RAI PHYSICS 03/09/1998 26 12
1203 LISA ANAND ENGLISH 09/04/2000 27 5
1045 YASHRAJ MATHS 24/08/2000 24 15
1123 GANAN PHYSICS 16/07/1999 28 3
1167 HARISH B CHEMISTRY 19/10/1999 27 5
1215 UMESH PHYSICS 11/05/1998 22 16

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

i) update SCHOOL set PERIODS=0.9*PERIODS;


ii) select SCHOOL.TEACHERNAME, SCHOOL.CODE, ADMIN.DESIGNATION from SCHOOL, ADMIN
where gender=’MALE’.
iii) select SUBJECT, count(*) from SCHOOL group by SUBJECT;
iv) select * from SCHOOL where DOJ>’ 01/01/1999’ order by EXPERIENCE desc;
v) delete from SCHOOL where EXPERIENCE

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

i. Identify the primary key in the table.


Write query for the following
ii. Find average salary in the table.
iii. Display number of records for each individual designation.
iv. Display number of records along with sum of salaries for each individual designation where number of records
are more than.
v. What is the degree and cardinality of the relation Employee?

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

(i) Select * from Store order by Lastbuy;


(ii) Select Itemno, Item from store where rate > 15;
(iii) Select * from store where scode = 22 or qty > 110;
(iv) Select scode, min(rate) from store group by scode;
(v) Select Itemno, Item, Store.scode, Sname from Store, Suppliers where Store.scode = Suppliers.scode;
A CD/DVD Shop named “NEW DIGITAL SHOP” stores various CDs & DVDs of songs/albums/movies and use SQL to
maintain its records. As a Database Administrator, you have decided the following:
Name of Database -
CDSHOP Name of Relation
- LIBRARY Attributes are:-
(a) CDNO - Numeric values
(b)NAME - Character values of size (25)
(c) QTY - Numeric
values (d)PRICE -
Decimal values Table:
LIBRARY
CDNO NAME QTY PRICE
10001 Indian Patriotic 20 150
10004 Hanuman Chalisa 15 80
10005 Instrumental of Kishore 25 95
10003 Songs of Diwali 18 125
10006 Devotional Krishna Songs 14 75
10002 Best Birthday Songs 17 NULL
Answer the following questions based on the above table LIBRARY:-
(a) Write the Degree & Cardinality of the relation LIBRARY.
(b) Identify the best attribute which may be declared as Primary key.
(c) Insert the following record in the above relation: (10009, ”Motivational Songs”, 15, 70)
(d) Write an SQL query to display the minimum quantity.
(e) Database administrator wants to count the no. of CDs which does not have any Price value.
Write the query for the same.

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

CID CNAM FEES STARTDA TI


E TE D
C20 AGDC 1200 2018-07- 10
1 A 0 02 3
C20 ADCA 1500 2018-07- 10
2 0 15 3
C20 DCA 1000 2018-10- 10
3 0 01 2
C20 DDTP 9000 2018-09- 10
4 15 4
C20 DHN 2000 2018-08- 10
5 0 01 1
C20 O 1800 2019-07- 10
6 LEVEL 0 25 5

(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

i) SELECT * FROM TEACHER WHERE CATEGORY= ‘PGT’ AND GENDER= ‘F’;


ii) SELECT NAME, DEPARTMENT, HIREDATE FROM TEACHER ORDER BY HIREDATE DESC;
iii) SELECT DEPARTMENT, COUNT(NAME), SUM(SALARY) FROM TEACHER GROUP BY DEPARTMENT;

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

(i) What is the degree and cardinality of the table student


(ii) Identify the attribute best suitable to be declared as Primary Key
(iii) Insert the following data in table
student AdmissionNo=012368
FirstName =
Kamlesh LastName
= Sharma DOB =01
Jan 2004
(iv) Harendra wants to remove the data of mukesh whose admission no is 012358, suggest him SQL command
to remove the above said data.
(v) To remove the table student which command is used :
i. Delete from student
ii. Drop table student
iii. Drop database school
iv. Delete student from school

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

(a) Write query to create table.


(b) Which column is suitable to be a primary key attribute.
(c) What is the degree and cardinality of table student.
(d) Display the details of student in ascending order of name.
(e) Write query to change the grade of karan from ‘B’ to ‘A’

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

(a) Identify the attribute best suitable to be declared as a primary key,


(b) Write the degree and cardinality of the table STORE.
(c) Insert the following data into the attributes ItemNo, ItemName and SCode respectively in the given table STORE.
ItemNo = 2010, ItemName = “Note Book” and Scode = 25
(d) Abhay want to remove the table STORE from the database MyStore. Which command will he use from
the following:
a) DELETE FROM store;
b) DROP TABLE store;
c) DROP DATABASE mystore;
d) DELETE store FROM mystore;
(e) Now Abhay wants to display the structure of the table STORE, i.e, name of the attributes and their respective
data types that he has used in the table. Write the query to display the same.

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

ii. Max - 31/07/2018 or 2018-07-31 Min- 05/09/2007 or 2007-09-05

iii. name Department Place


Jugal Computer Sc
Delhi Shiv Om
Computer Sc
Delhi

(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

a) Identify the attribute best suitable to be declared as a primary key.


b) Write the degree and cardinality of the table HRDATA,
c) Write command to insert following data in the table:
ECode = 80015, Ename = “Allen” Remn = 43000
d) Write SQL statement to delete the record of Jeevan from the table HRDATA.
e) Write SQL statement to increase the Remn of all the employees by 10 percent.

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

CompID CompName CompHQ Contact Person


1 Titan Okhla C.B. Ajit
2 Ajanta Najafgarh R. Mehta
3 Maxima Shahdara B. Kohli
4 Seiko Okhla R. Chadha
5 Ricoh Shahdara J. Kishore
Table: MODEL

Model_ID Comp_ID Cost


DateOfManufacture T020 1
2000 2010-05-12
M032 4 7000 2009-04-15
M059 2 800 2009-09-23
A167 3 1200 2011-01-12
T024 1 1300 2009-10-14

a) Select COUNT(DISTINCT CompHO) from Company;


b) Select CompName, „Mr.‟, ContactPerson from Company where CompName like „%a‟;
c) select Model_ID, Comp_ID, Cost, CompName, ContactPerson from Model, Company
where Model.Comp_ID = Company.Comp_ID and Comp_ID > 2; 3 37;
Ans
a) 3
b) Ajanta Mr. R. Mehta
Maxima Mr. B. Kohli
c) M032 4 7000 Seiko R.
Chadha A167 3 1200 Maxima
B. Kohli
Write SQL commands for (i) to (v) on the basis of relations given below:

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

(i) To show the books of FIRST PUBL. Publishers written by P. Purohit.


(ii) To display cost of all the books published for EPB.
(iii) Depreciate the price of all books of EPB publishers by 5%.
(iv) To display the BOOK_NAME and price of the books, more than 5 copies of which have been issued.
(v) To show total cost of books of each type.

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

●Name of the table –MEDICINE

●The column of MEDICINE table are as follows:

●ino - integer

●iname – character of size 15

●mcode - integer

●qty – integer

ino iname mcode qty


1001 Surgical Mask 22 60
1002 Sanitizer 22 50
1003 Paracetamol 21 150
1005 Fast Relief gel 23 250
1006 Dettol 22 220
2004 Cough syrup 24 110
2009 Hand gloves 22 1803
(a) Identify the attribute best suitable to be declared as a primary key,
(b) If Administrator adds two more attributes in the table MEDICINE then what will be the degree and cardinality of
the table MEDICINE.
(c) Administrator wants to update the content of the row whose
ino is 1003 as , iname = “Paracetamol Tablet ” mcode = 25 and qty = 100
(d) Administrator wants to remove the table MEDICINE from the database medstore . Which command will he use
from the following:
a) DELETE FROM store;
b) DROP TABLE MEDICINE;
c) DROP DATABASE medstore;
d) DELETE MEDICINE FROM medstore;
(e) Now Administrator wants to display only unique code of the table MEDICINE . Write the query to display the same

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

i. SELECT NO,NAME,TDATE from Travel ORDER BY NO DESC;


ii. SELECT NAME from Travel WHERE CODE = 101 OR CODE= 102;
iii. SELECT NO, NAME from Travel WHERE TDATE BETWEEN ‘2015-12-31’ AND ‘2016-04-01’;
iv. SELECT A.CODE, NAME, VTYPE FROM Travel A, Vehicle B WHEREA.CODE=B.CODE AND KM<90;
v. SELECT NAME from Travel WHERE NAME LIKE ‘R%’ ;
MySQL Connectivity
import mysql.connector as m
# Open database connection
db = m.connect(host="localhost",user="root",passwd="1234")

# prepare a cursor object using cursor() method


cursor = db.cursor()

# execute SQL query using execute() method.


cursor.execute("show databases") # write any sql related command in execute function

# Fetch a first three rows using fetchmany() method.


data = cursor.fetchmany(3)
for i in data:
print (i)

# disconnect from server


db.close()

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

rowcount – it returns the number of rows using execute() method

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

TYPES OF NETWORK-based on geographical spread


PAN (personal area LAN(local area MAN(metropolitan area WAN(wide area network)-
network)- network)- limited area network)- within city (10- within multiple city/state/
communication (within building, block 100 kms) countries
between two- three or campus) 0-10 km (more than 100 kms)
mobile devices or PC
for personal purpose.

Switching Techniques

Packet Switching Message Switching Circuit Switching


data to be transmitted is divided delay in delivering email is A dedicated path has to be
into packets transmitted through allowed unlike real time data established between the source
the network transfer between two and the destination before
computers. transfer of data commences.

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.

There is no need to establish a There is no need to establish a It is a connection oriented


dedicated path from the source dedicated path from the source network switching technique.
to to
the destination. the destination.

e.g. email e.g. Internet call e.g. Voice call

Full Form of networking Terms

SSL- Secure IMAP- FTP- File WiFi- HTTPs- Hyper


Sockets Layer Internet transfer Wireless Text Transfer
Message protocol Fidelity Protocol Secure
Access
Protocol

WAP-Wireless VoIP- Voice SMTP-Simple TDMA- Time CDMA- Code


Application Over Internet Mail Transfer DIvision Multiple Division Multiple
Protocol Protocol Protocol Access Access

TCP/IP- LAN- Local WAN- Wide MAN- PAN-Personal


Transmission Area Area Network Metropolitan Area Network
Control Network Area Network
Protocol/Internet
Protocol

IR-Infrared IRC-Internet GPRS-General GSM- Global e-mail-


Relay Chat Packet Radio System for Electronic
Service Mobile Mail
Communications

ASP-Active JSP-Java XML-eXtensible HTML-Hyper Bps- Bytes


Server Pages Server/Script Markup Text Markup per Second
Pages Language Language

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

FTP-for HTTP-for downloading a file POP3()-for receiving emails Telnet-for


uploading a file remote login

IMAP-for SMTP-for sending mails VoIP-for video calling or TCP/IP-for


receiving mails voice call using internet communicati
connection on

GPRS,GSM,WLL- for wireless /mobile RTP-(Real-time Transport Protocol)- transport


communication protocol protocol for real-time audio and video data

Tips for Case Based Questions

Layout-draw block diagram to show interconnecting blocks. Prefer the block with maximum devices as
main server to connect other blocks

Topology-write name of the topology-star/bus/ring etc

Placement of server-block/unit with maximum number of computers

Cost effective medium for internet- Broadband connection over telephone lines

Communication media for LAN-Ethernet/Co-axial cable for high speed within LAN

Communication media for Hills-Radiowave/Microwave

Communication media for desert-Radio Wave

Very fast communication wired media between two cities-Optical fiber

Very fast communication wireless / media between two cities/countries-Satellite

Device/Software to prevent unauthorized access-Firewall (hardware and Software)

Repeater-distance between server and other block is more than 80

TOPOLOGIES

Bus- Star- Ring


Easy to install
Easy to Easy to install, easy to configure
Easy to
install configure
Minimal Easy to detect a problem
Cable
Difficult to find the If one link fails the network can Break means the whole system
problem Difficult to add still function is dead
new devices Difficult If central computer
reconnection fails ,entire network fails

Networking-1 marks Questions

is a network Give one example of each – Guided media


device that connects dissimilar and Unguided media
networks. Ans Guided – Twisted pair, Coaxial Cable,
Ans Gateway Optical Fiber (any one)
Unguided – Radio waves, Satellite, Micro Waves
(any one)
Ravi received a mail from IRS department is a specific condition in a
on clicking “Click –Here”, he was taken to a network when more data packets are coming
site designed to imitate an official looking to network device than they can handle and
website, such as IRS.gov. He uploaded some process at a time. Ans Network Congestion
important information on it
Ans Phishing
Name the protocol that is used to transfer file Raj is a social worker, one day he noticed
from one computer to another. someone is writing insulting or demeaning
Ans FTP comments on his post. What kind of Cybercrime
Raj is facing?
Ans Identity Theft
Name the Transmission media which Write the expanded form of GPRS?
consists of an inner copper core and a Ans General Packet Radio Service (GPRS)
second conducting outer sheath.
Ans Co-axial cable
Define Bandwidth? --------------describe the maximum data
Ans a band of frequencies used for transfer rate of a network or Internet
sending electronic signals connection.
Ans Bandwidth
Mahesh wants to transfer data within a city at What is a Firewall in Computer
very high speed. Write the wired Network? A). The physical boundary
transmission medium and type of network. of Network
Ans Wired transmission medium – Optical B). An operating System of Computer
fiber cable Network
Type of network – MAN. C). A system designed to
prevent unauthorized access
D). A web
browsing Software
Ans
C). A system designed to
prevent unauthorized access.
Which of the following is not done by cyber Name the wired transmission media which
criminals? has a higher bandwidth. Ans Optical
a) Unauthorized account access Fiber
b) Mass attack using Trojans as botnets
c) Report vulnerability in any system
d) Email spoofing and spamming
Ans (c) Report vulnerability in any
system
Name the network device that connects Arrange the following media in decreasing order
dissimilar networks. of transmission rates.
Ans Gateway Twisted Pair Cables, Optical Fiber, Coaxial
Cables.

Ans Optical Fiber, Coaxial Cables,


Twisted Pair Cables
Name the protocol used for remote login. Website incharge KABIR of a school is
Ans TELNET handling downloading/uploading various files
on school website. Write the name of the
protocol which is being used in the above
activity.
Ans FTP
What is its use of Data encryption in a Give the full form of the following:
network communication? (a) URL (b)
Ans Data encryption is the process of TDMA Ans
converting a message into an unmeaningful (a) URL – Uniform Resource Locator
form. It is used to ensure data security while (b)TDMA – Time Division Multiple
communication. Access
Differentiate between Bps & bps. Identify the Guided and Un-Guided
Ans Bps is Byte per second and Transmission Media out of the following:
bps is bits per second which tells the Satellite, Twisted Pair Cable, Optical Fiber,
variation in data transmission speed. Infra- Red waves
Ans Guided: Twisted Pair Cable, Optical
Fiber Unguided: Satellite, Infra-Red
waves
Protocol is used to send email ………… Your friend Sunita complaints that somebody
Ans SMTP (simple mail transfer protocol) has created a fake profile on Twitter and
defaming her character with abusive comments
and pictures. Identify the type of cybercrime
for these situations.
Ans Identity Theft

Name the transmission media best suitable Write the expanded form of
for connecting to desert areas. Ans VPN. Ans Virtual Private
microwave Network

Rearrange the following terms in increasing What is Telnet?


order of speedy medium of data transfer. Ans Telnet is an internet utility that lets us log
Telephone line, Fiber Optics, Coaxial on to a remote computer system. A user is able
Cable, Twisted Paired Cable to log in the system for sharing of files without
being the actual user of that system
Ans Telephone line, Twisted Pair Cable,
Coaxial Cable, Fiber Optics

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

Name two web scripting languages Which of these is not an example of


Ans VBScript, JavaScript, ASP, PHP, PERL unguided media?
and JSP (i) Optical Fibre Cable(ii) Radio wave
(iii) Bluetooth (iv) Satellite
Ans Optical Fiber( guided media or wired
media)
What is HTML? Name the protocol that is used to upload and
Ans HTML (Hyper Text Markup Language) is download files on internet.
used to create Hypertext documents (web Ans FTP or HTTP
pages) for websites.

Your friend kaushal complaints that somebody Which is not a network


accessed his mobile device remotely and topology? a)BUS b).
deleted the important files. Also he claims that STAR c). LAN d). RING
the password of his social media accounts were Ans (c) LAN
changed. What crime was Manoj a victim of?
Also classify the crime on basis of it’s intent
(malicious
/ non-malicious).
Ans The gaining of unauthorized access to
data in a system or computer is termed as
hacking. It can be classified in two ways: (i)
Ethical Hacking (ii)Cracking

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

Write the expanded form of Wi- TCP/IP stands for-


Fi. Ans Wireless-Fidelity Ans Transmission Control Protocol/Internet
Protocol
An attack that encrypts files in a computer Write the name of topology in which all
and only gets decrypted after paying money the nodes are connected through a single
to the attacker. Coaxial cable?
a) Botnet b) Trojan Ans BUS totplogy
c) Ransomware d) Spam
Ans (c) Ransomware

Write full form of VoIP. Expand the term DHCP.


Ans voice over internet protocol Ans Dynamic Host Configuration Protocol

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

bps, Kbps, Mbps, Gbps, Tbps

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

Error Related Questions


Observe the following Python codes very carefully and rewrite it after removing all syntactical errors
with each correction underlined.

DEF result_even( ): def result_even( ):


x = input(“Enter a
number”) if (x % 2 = 0) : #def x = int(input(“Enter a
print (“even number”) number”)) #int if (x % 2 == 0) : #
==
print (“even number”)
else: else:
print(“Number is odd”) print(“Number is odd”)
even ( )
result_even( ) #function_name()
def checkval: def checkval( ): #()
x = input("Enter a x = int(input(“Enter a number”))
number") if x % 2 =0: #int() if x % 2 =0:
print (x, "is print (x, "is even")
even") elseif x<0: elif x<0: #elif
print (x, "should be print (x, "should be
positive") else; positive") else: #
print (x, "is odd") colon
print (x, "is odd")
30=To To=30 #variable on left
for K in range(0,To) for K in range(0,To): # colon
IF k%4==0: if K%4==0: #K
print capital print(K*4)
(K*4) Else: else: #else ‘e’
print (K+3) small
print(K+3)
for name in [‘Shruthi’,’Priya’,’Pradeep’,’Vaishnav’): for name in [‘Shruthi’,’Priya’,’Pradeep’,’Vaishnav’]:
print name #]
if name[0] = print (name) #
‘P’ () if name[0] == ‘P’ #
break ==
else: break
print(‘Over”) else:
print(“Done”) print(“Over”) #
” “ print(“Done”)
Y=integer(input(“Enter 1 or Y=int(input(“Enter 1 or 10”))
10”)) if Y==10 #int if Y==10:
for Y in
range(1,11): #colon
print(Y) for Y in range(1,11): #indentation
else: print(Y)
for m in range(5,0,- #indentation else:
1): print(thank for m in range(5,0,-1):
you) print(“thank you”) # “ “ missing
p=30 p=30
for c in for c in range(0,p):
range(0,p) if c%4==0: #if
If c%4==0: print (c*4)
print elif c%5==0:
(c*4) Elseif
c%5==0: #elif print (c+3)
print (c+3) else: #colon
else print(c+10)
print(c+10)
x=int(“Enter value for x=int(input((“Enter value for x:”) )
x:”) for y in #input for y in range(0,11): #round
range[0,11]: brackets
if x=y
print(x if x==y : #== and colon
+y) else: print(x
Print x-y +y) else:
print (x-y) #print()
Def func(a): def func(a): #def
for i in s=m=n=0 #local
(0,a): variable for i in (0,a):
if i%2 if i
=0: %2=
s=s+1 =0:
else if i%5= =0
s=s+
1
m=m elif i%5= =0: #elif and colon
+2 else: m=m+2
n=n+i else:
print(s,m n=n+i
,n) print(s,m,n)
func(15)
#indentation func(15)
Value=30 Value=30 #val=30
for val in for val in range(0,Value): #colon
range(0,Value) If If val%4==0:
val%4==0: print (val*4)
print elif val%5==0:
(val*4) Elseif
val%5==0: #elif print (val+3)
print (val+3) Else : #else and colon
Else print(val+10)
print(val+10)
Num = Num = int(input("Number:"))
int(input("Number:") s=0 # ) s=0
for i in for i in range(1,Num,3): #colon
range(1,Num, s+=1
3) s+=1
if i%2==0: # ==
if i%2=0:
print(i*2) print(i*2)
Else else: # else and colon
print(i print(i*3)
*3) print (s) print (s)
DEF execmain(): def execmain(): #def
x = int( input("Enter a x = int( input("Enter a
number:")) if (abs(x) = x): number:")) if (abs(x)== x):# ==
print"You entered a positive print("You entered a positive number")
number" else: #() else:
x=*-1 x*=-1 # *=
print("Number made print("Number made positive :",x)
positive :",x) execmain() execmain()
a = 200 a = 200
b = 33 b = 33
if b > a if b > a: # colon
Print("b is greater than print("b is greater than a") # small p of
a") elseif a == b: print() elif a == b: #elif
print(a and b are print(“a and b are equal”) #
equal) else: “ “ else:
print("a is greater than b") print("a is greater than b")
x=int("enter value of x=int(input("enter value of x:"))
x:") for i in #input() for i in range(0,10): # ()
range[0,10]: if x==y: # == and
if x=y colon
print("they are equal")
else: print("they are equal")
Print("they are unequal") else:
print("they are unequal")
a,b= a=b=0 # = in place
0 of , if(a==b): # == and
if(a colon
=b) c=a+b # c=a+b
a+b= print(c) # c
c
print
(z)
a=int(input("enter any a=int(input("enter any
number")) ar=0 number")) ar=0
for x in range(0,a,2) for x in range(0,a,2): #colon
ar+=x ar+=x
if x%2=0: if x%2==0: # ==
Print(x*10) print(x*10) # print()
Else: else: # else
print(c) print(c)
print(ar) print(ar)

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

For i in Range(10): for i in range(10): #for and


if(i==5) range if(i==5): # colon
break: break # no colon
else: else:
print(i print(i
) )
contin contin
ue ue
a=input("enter any a=int(input("enter any number")) #
number") if a%2=0: int() if a%2==0: #
print("Even number) ==
Else print("Even number)
print("Odd number") else: # else and
colon
print("Odd number")
a=int(Input("enter any a=int(input("enter any number")) #
number")) b=int(input("enter input b=int(input("enter any number"))
any number")) if a=>b: if a>=b: # >=
print("First number is greater)) print("First number is greater")) # “
else: else:
Print("Second number is greater") print("Second number is greater") #print
a=int{input("Enter any a=int(input("Enter any number")) #
number")} for i IN range(1:11): () for i in range(1:11): #
print(a,"*",i,"=",a*i) in
print(a,"*",i,"=",a*i) #indentation
def def sum(c): # colon
sum(c) s=0 #indentation
s=0
for i in for i in range(1,c+1): # range and
Range(1,c+1) colon s=s+i # indentation
s=s+i return s
retur print(sum(5)) # ) and indentation
ns
print(sum(5)
Print("Anuj") print("Anuj") # print
For i in for i in range(2,4): # for
range(2,4): for i for i in range(3,9): #range and
in Range(3,9): indentation def title(): #colon
def title() if i=<5: #colon and indentation
if i=<5
N=int(input("Enter any number:")) N=int(input("Enter any number:"))
S=0 S=0
for i in for i in range(1,N,2): #
range(1, colon s+=1
N,2) if i%2==0: # == and
s+=1 colon print("i"*2)
if i%2=0: else:
print("i"*2) print("i"*3)
else: print(S) # ()
print("i"
*3)
print[S]
L=[1,2,3,4,5,6,7,'a','e' L=[1,2,3,4,5,6,7,'a','e'] # missing ]
for i in L: for i in L:
if i==a if i==a: #
break colon break
el else:
se: print("A") #indentation
print("A")
a={'6': "Amit", '2' : "Sunil" : '3' : a={'6': "Amit", '2' : "Sunil" ,'3' : "Naina"} #
"Naina"} for i in a: comma for i in a:
if(int(i) if(int(i)%3==0: # == and colon
%3=0 print(a(i)) #indentation
print(a(i))
30=max max=30
For N in range(0,max) for N in range(0,max) : # for and
IF n%3==0: colon if N%3==0: # if and capital
print(N N
*3) ELSE: print(N*3)
print(N+3) else: #else
print(N+3)
def checksum: def checksum(): # missing ()
x=input(“enter a x=int(input(“enter a number”))
number”) if(x%2==0): #int() if(x
for i range(2*x): %2==0):
print(i) for i in range(2*x): #missing
loop else: in print(i)
print(“#”) else: #else
print(“#”)
Salary=400 Salary=4000,
0, Bonus=8900 #
Bonus==89
00 single = For I in range(0,6) : #
For I in range(0,6) colon
If Bonus>=5000 If Bonus>=5000: #colon
Print(Salary+4 print(Salary+400) # small p of
00)
print elif Bonus<5000:# elif and colon
Else if
print(Salary+500)
Bonus<5000
print(Salary+5
00)
else: else:
Print(“ no increment”) Print(“ no increment”)

Find and write the output of the following Python codes:


def s="welcome2k
makenew(mys v" n = len(s)
tr): newstr = " m=""
" count = 0 for i in range(0, n):
for i in mystr: if (s[i] >= 'a' and s[i] <=
if count%2 !=0: 'm'): m = m
newstr = newstr+str(count) +s[i].upper()
else: elif (s[i] >= 'n' and s[i] <=
if i.islower(): 'z'): m = m +s[i-1]
newstr = newstr+i.upper() elif (s[i].isupper()):
else: m = m + s[i].lower()
newstr = else:
newstr+i count +=1 m = m +'#'
newstr = newstr+mystr[:1] print(m)
print("The new string is :",
newstr) Ans vELCcME#Kk

#function calling
makenew("sTUdeN
T")

Ans: The new string is : S1U3E5Ts


def display(s): def change(s):
l= d = {"UPPER" : 0, "LOWER" : 0 }
len(s) for c in s:
m="" if c.isupper():
for i in range(0,l): d["UPPER"] += 1
if s[i].isupper(): elif c.islower():
m=m+s[i].lower() d["LOWER"] += 1
elif s[i].isalpha(): else:
m=m+s[i].upper() pass
elif s[i].isdigit(): print("Upper case count :",
m=m+"$" d["UPPER"]) print("Lower case
else: count :", d["LOWER"])
m=m+"*"
print(m) #function calling
change("School Days are Happy")
display("[email protected]
Ans
m") Upper case count :
3 Lower case count
Ans exam$$*CBSE*COM : 15
def def Show(str):
Convert(Ol m=""
d): for i in
l=len(Old) range(0,len(str)
New=”” ):
for i in range(0,1): if(str[i].isupper(
if Old[i].isupper(): )):
New=New+Old[i].lowe m=m+str[i].lowe
r() r() elif str[i].islower():
elif Old[i].islower(): m=m+str[i].uppe
New=New+Old[i].uppe r() else: if i%2==0:
r() m=m+str[i
elif -1] else:
Old[i].isdigit m=m+"#"
():
New=New+”
*”
else:
New=New+” print(m)
%” return New
Show('HappyBirthda
Older =
“InDIa@2020” y')
Newer=Convert(Old
er) Ans
print(“New string is: “,Newer) hAPPYbIRTHD
AY
Ans New string is : iNdiA%****
def replaceV(st): def swap(P ,Q):
newstr = '' “ P,Q=Q,P
for character in st: print( P,"#",
if character in Q) return
'aeiouAEIOU': (P)
newstr += '*'
else: R=1
newstr += 00
character return newstr S=2
00
st = “Hello how are R=swap(R,
you” st1 = S)
replaceV(st) print(R,"#"
print("The original String is:", st) ,S)
print("The modified String is:",
st1) Ans
200 # 100
Ans 200 # 200
The original String is: Hello how are you
The modified String is: H*ll* h*w *r* y**
def Display(str): Text="Welcome
m="" Python" L=len(Text)
for i in ntext=""
range(0,len(str) for i in range (0,L):
): if Text[i].isupper():
if(str[i].isupper( ntext=ntext+Text[i].lowe
)): r()
m=m+str[i].lowe elif Text[i].isalpha():
r() elif str[i].islower(): ntext=ntext+Text[i].uppe
m=m+str[i].upper() r()
else: else:
if i%2==0: ntext=ntext+"!!"
m=m+str[i-1] print (ntext)
else:
m=m+"#" Ans wELCOME!!
print(m) pYTHON

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.

from random import randint


LST=[5,10,15,20,25,30,35,40,45,50,60,70]
first = randint(3,8)
second =
randint(4,9) third =
randint(6,11)
print(LST[first],"#", LST[second],"#", LST[third],"#")
(i) 20#25#25# (ii) 30#40#70# (iii) 15#60#70# (iv) 35#40#60#

Ans 35#40#60#
Maximum Values: First: 40, Second: 45, Third: 60

You might also like