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

CS Unitwise Case Based Questions

Uploaded by

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

CS Unitwise Case Based Questions

Uploaded by

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

Class -XII (Computer Science)

CS Notes and CASE Based study


Questions:
Unit-1
Chapter-1

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 (None), Literal collections like tuples, lists

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 python
i. _Var ii. In program :
Ans (i) identifier (ii) operator- For, while, INT, NeW, del, 1stName, Add+Subtract,
membership operator name1 Ans For, INT, NeW, name1
Find the correct identifiers out of the following, Which of the following is valid logical operator
which can be used for naming variable, (i) && (ii) > (iii) and (iv)
constants or functions in a python program : == Ans (iii) and
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 Python?
(i) 123 (ii) True 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 Python: Which of the following are Keywords in Python ?
(i) */ (ii) is (iii) ^ (iv) like (i) break (ii) check (iii) range (iv)
Ans (ii) is-identity operator while Ans (i) break (iii) 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 expression Identify the invalid keyword in Python from the following:
4+4.00, 2**4.0 (a) True (b) None (c) Import (d) return
Ans (8.0, 16.0) Ans (c) Import
Find the operator which cannot be used with Name the mutable data types in Python.
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 following.
a) My-Name b) True c) 2ndName d) 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). and a) 4th Sum b) Total c) Number# d) _Data
Ans (c) == 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) My_Name in Python ?
a) ? b) < c) *= d) and e) //
Ans (c) 2My_Name Ans (c) *=
Which of the following is not a valid Which of the following is valid relational operator in Python:
identifier in Python? (a)// (b)? (c) < (d) and
a) KV2 b) _main c) Hello_Dear1 d) 7
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) Boolean
Ans (d) My_Name 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 there size is 1 as there is size is 7 because \’ is size is 1. It is a size is 4. It is a
is one character one character an escape sequence character constant multiline string
enclosed in double
quotes

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 single Strings in double quotes work exactly You can specify multi-line strings
quotes such as ‘Quote me on this’. the same way as strings in single using triple
All white space i.e. spaces and tabs quotes. An example is “What’s your quotes. You can use single quotes and
are preserved as it is. name?” 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 they Comments are mainly used to explain non-
are enhanced, more logical, and useful version obvious portions of the code and can be useful
of commenting. for comments on Fixing bugs and tasks that are
Docstrings act as documentation for the class, needed to be done.
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 If …..elif…..else statement-


We can write an entire if..else statement in
It is used to control The if…else statement is elif- is a keyword used in Python in replacement of
another if ….else statement called nesting,
the flow of called alternative else if to place another condition in the program.
and the statement is called nested if.
execution of the execution , in which there This is called chained conditional.
statements and also are two Chained conditions allows than two
In a nested if construct, you can possibilities
have an if…and
used to test logically the condition determines possibilities and need more than two branches
elif…else construct inside an if…elif…else
whether the
construct which one gets executed
condition is true or Syntax:
false. Syntax: if test_expression :
Syntax: e.g.
Syntax: if test_expression : Statement of
if test_expression : n=int(input(“enter number”))
if test_expression : Statement of if if elif expression:
Statement(s) if n<=15:
Statement else: Statement of elif
if test_expression : if n==10:
Statement of else else:
Statement(s) print(“ok”)
Statement of else
elif expression: else:
Nested if…else Statement(s)
statement print(“use another option”)
else: else:
Statement(s) print(“more than 15”)

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 expression: n=int(input(“enter no”))
statement(s) s=0
while(n>0):
s=s+n
n=n-1
print(“the sum is”,s)
while loop- infinite loop
while 1: while True:
print(“*”) print(“*”)
OR OR
while 1: print(“*”) while True: print(“*”)
else statement with while loops
• Python supports have an else e.g.
statement associated with a loop c=0
statement while c<3:
• If the else statement is used with a while print(“inside loop”)
loop, the else statement is executed c=c+1
when the condition false. 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, step_value) e.g.
note: for i in range(5): #take values 0,1,2,3,4
if only one value is specified then it takes 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 nothing.
remaining statements in the • It can be used when a
loop and move controls back to statement is required
the top of the loop. 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":
break continue pass
print(val) print(val) print(val)
print("The end") print("The end") print("The end")
Output: Output Output
s s 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 23 36 48 5
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.
s=”hello”
L=[1,2,3,4]
s1=’world’
String and List – practice questions

Identify the valid declaration of P: Find the output –


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]) write the output of:
Ans 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 range(len(a)): del colors[4]
print(a[i],b[i]) colors.remove("blue")
An colors.pop(3)
sh print(colors)
ve
i Ans ['violet', 'indigo', 'green', 'red']
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 of
print(name[2:10]) print(Lst[1:6:2])
Ans mputer S Ans [34,56,22]
Give the output of the following Write the output of the following python
code: L = [ 1,2,3,4,5,6,7] 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 code Given the lists
t1 = [10, 12, 43, 39] L=[1,3,6,82,5,7,11,92] ,
print(t1*3) write the output of
Ans print(L[1:6])
[10, 12, 43, 39, 10, 12, 43, 39, 10, 12, 43, 39] 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). list name="ComputerSciencewithPython"
print(name[3:10])
Ans (d) list Ans puterSc
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 c) 'sdneirF olleH' d) Friend
strings are mutable. Ans (c)
d)Lists and strings in pythons support
two way indexing.
e)Ans (c)
Identify the valid declaration A list is declared
of L: L = [1, 23, ‘hi’, 6] as L=[(2,5,6,9,8)]
(i)list (ii)dictionary What will be the value of
(iii)array (iv)tuple print(L[0])?
Ans (i) list Ans (2,5,6,9,8)
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 12"
>>> str1[ : -1] print(name[9:15])
a). 'dlrowolleh' b).‘hello’ Ans Vidyal
c).‘world’ d).'helloworl'
Ans (a)
Given the lists A list is declared as
L=[1,30,67,86,23,15,37,131,9232] , Lst = [1,2,3,4,5,6,8]
write the output of What will be the value of
print(L[3:7]) sum(Lst)? Ans 29
Ans [86, 23, 15, 37]
Identify the valid declaration If the following code is executed, what will be
of L: L = (‘Mon’, ‘23’, ‘hello’, the output of the following code?
’60.5’) name="Computer_Science_with_Python"
a). dictionary b). string c). tuple d). list print(name[-25:10])
Ans (c) Ans puter_S
How many times is the word ‘hello’ printed Given the list
in the following statement? L=[1,3,6,82,5,7,11,92],
S=’python rocks’ write the output of
for ch in s[3:8]: print(L[1:4:2]
print(‘hello’) Ans [3,82]
(i) 5 (ii) 6
(iii) 7 (iv) 4
Ans (i)
Given the string Identify the correct option to print the value 80 from
x="hello world", the list
write the output L=[10,20,40,80,20,5,55]
of print(x[:2],x[:- (i) L[80] (ii) L[4] (iii) L[L] (iv) L[3]
2]) Ans he hello Ans (iv) L[3]
wor
if a=[5,4,3,2,2,2,1], Give the output of the
evaluate the following following: x="Marvellous"
expression: print( a[a[a[a[2]+1]]]) print( x[2:7], "and" , x[-4:-1] )
Ans 2 Ans rvell and lou
What is the output produce by the Is there any difference in ‘a’ or “a” in python?
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’ in Python does not support a character type.(T/F)
python? Ans True. (Python supports string type)
Ans. Yes
 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 23 36 48 5
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.
T=(1,2,3,4)
L=[1,2,3,4]
Tuple: 1 mark Questions

A tuple is declared as Find the output from the following


t1=(1,2,3,3,5,6,5,6,7,3,8,9) code:
t=tuple() t=t+
what will be the value of (‘Python’,)
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 access
T = "Yellow", 20, "Red" value 20 from the following tuple
a, b, c = T
print(a) aTuple = ("Orange", [10, 20, 30], (5, 15, 25))
which of the following is correct?
(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 incorrect?
a) print(T[1]) b) print(max(T)) 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 incorrect? a)Dictionary (b) string (c) tuple (d) list
a) print(T[1]) b) T[3] = 9 Ans tuple
c) print(max(T)) d) print(len(T))
Ans (b) because tuple is immutable.
A tuple is declared as
T = (20,5,16,29,83) Suppose a tuple T is declared
What will be the problem with the as T = (10, 20, 30, 40),
code T[1]=100. what will be the output of
Ans It will show error tuple is immutable. print(T*2)
Ans 20,40,60,80
t1=(2,3,4,5,6) What is the length of the tuple shown
print(t1.index(4)) below? t=(((('a',1),'b','c'),'d',2),'e',3)
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 Rec:
>>>S = 1, (2,3,4), 5, (6,7) Rec=(1,‟Vikrant”,50000)
>>> len(S) (i)List (ii)Tuple
Ans 4 (iii)String (iv)Dictionary
Ans (ii) Tuple
A tuple is declared as Consider the tuple in python named
T = (1,2), (1,2,4), (5,3) DAYS=(”SUN”,”MON”,”TUES”)
What will be the value of min(T) ? Identify the invalid statement(s) from the
given below statements:
a). S=DAYS[1] b). print(DAYS[2])
Ans (1,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 code:
as Tup = (12, 15, 63, 80), 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$ 3$
Ans (b) Tup[2]=90
If a is (1, 2, 3), what is the difference (if any) between If a is (1, 2, 3), is a *3 equivalent to a + a+
a*3 and [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) and
created? Ans: T=3, or T=(4,) (30,)?
Ans: (30) is an integer while (30,) is a tuple
Predict the output Predict the output
G=’a’,’b’ T=(1,)*3
H=(‘a’,’b’) T[0]=2
print(G==H) print(T)
Ans True Ans typeError. Tuple is immutable so
can’t do changes
Find output Find output
(a,b,c)=(1,2,3) a,b,c,d=(1,2,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 to
a, b, c, d, e = (p, q, r, s, t) = t1 a tuple?
Ans If tuple t1 has 5 values then this will assign first Ans T=T+(9,)
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 code
tuple x? (a) x = (1) (b). x = (1,) ? x= (2, 1, 4)
(c) . x = {1} (d) None of the above print(len(x))
Ans (b) Ans 3
What is the output of following line of code? What is the output of following line of code?
x,y, z = (3.3, 4.1, 2.2) 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 code
_,_ = (3.3, 4.1, 2.2) ? x = (3.3, 4.1, 2.2) *2
print(_) print(x)
Ans Error Ans (3.3, 4.1, 2.2, 3.3, 4.1,2.2)
What is the output of following line of code? What is the output of following line of code?
x = (3.3, 3.3, 4.1, 4.1, 2.2, 2.2) x = (3.3, 3.3, 4.1, 4.1, 2.2, 2.2)
print(x.index(3.3)) print(x[0::2] ==
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 [1,2,3]: for i in (1,2,3):
similarities print(i) print(i) print(i)
s=”hello” t=[1,2,3,4] t=(1,2,3,4)
for i in s: for i in t: for i in t:
print(i) print(i) print(i)
s=”hello” t=[1,2,3,4] t=[1,2,3,4]
for i in range(len(s)): for i in range(len(t)): for i in
print(i,s[i]) print(i,t[i]) range(len(t)):
print(i,t[i])
4. Common functions

+ (concatenation (combine)),
* (replicate),
s=”hello” t=[1,2,3] t=[1,2,3]
print(s+”world”) print(t+[4,5,6]) print(t+[4,5,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(2)) print(t.count(2))
print(len(s)) print(len(t)) print(len(t))
print(s.index(‘l’)) print(s.index(2)) print(s.index(2))
if ‘l’ in s: if 3 in t: if 3 in t:
print(“ok”) 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() items() values() max() min()
keys() update() pop() del popitem() sorted() setdefault()

• 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:”world”}
L=[1,2,3,4]

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:
print (i)
a) 1 b) SUM c) 1 d) 3
2 DIFF SUM SUM
3 PROD 2 3
DIFF DIFF
3 3
PROD PROD
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"]="Done"
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 entire importing selected function/object from a module importing all
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 sqrt from math import *
print(math.sqrt(4)) print(sqrt(4)) print(sqrt(4))
print(pow(3,2))
from math import 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() stdin remove
cos() randint() load() writer() isconnected() stdout rename
tan() randrange() writerow() execute() stderr
log() writerows() cursor()
sqrt() fetchall()
floor() fetchaone()
exp() fetchmany()
ceil() rowcount
pow()
round()
pi
fmod()
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 python
 It is nothing but .py contain a special file called library conceptually.
file which has python init .py.  Some examples of library
executable code /  This file can be empty, and it in Python are: Python
statement indicates that the directory it standard library containing
contains is a Python package, math module, random
so it can be imported the same module, statistics module
way a module can be imported etc.

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 any type. We use the predefined functions like int(),float(),str() etc.
user involvement.
e.g. >>>a=3
>>>a=3 >>>c=3.4
>>>b=3.4 >>>str(a) #str()function converts integer to string.
>>>d=a+b ‘3’
>>>d >>>str(c) #str() function converts float number to string
6.4 ‘3.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 testing Code sharing Code re-usability Increases


development becomes easy becomes possible increases program
made easy and readability
fast

Types of Functions
Built –in functions Functions defined in the modules User defined functions
(Pre-defined functions) (function using (defined by the programmer)
Libraries/modules)
int(),type(),float(),str(), sin(),floor(),ceil(),dump(),load() PARTS OF USER DEFINED
print(),input(),ord(),hex ,random(),writer() etc FUNCTIONS
(),oct() , len() etc • Function definition(def keyword)
• 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 to those functions which are returning values to the
the calling function calling function
return value can be literal, variable , expression

Give the basic structure of user defined


Q function.
What aredef funtionname(parameters
Arguments name):
and Parameters?
statement of the
Arguments
function 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+b c=a+b
print(c) print(c)

x=2 here a and b are the parameters


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 a
the function definition. 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 parameter 3.
Positional have default value then left parameters Keyword Arguments
parameters can also have default value. this argument (Named Arguments)-
(Required can be skipped at the time of function
Arguments) - these calling
arguments must be We can write arguments in any
provided for all order but we must give 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+b d=a+b+c print(a,b,c)
print(c) print(d)
x=10 x=10 fun(b=3,c=4,a=2)
y=3 y=3
fun(x,y) fun(x,y) #here c parameter value is 3
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 the A local variable is declared within the body of
functions, generally on top of the program. a function or a block
The global variables will hold their value Local variable only use within the function or
throughout the life-time of your program. block where it is declare.

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(num1) fun()
return s #
num1=100 Output:
num2=200 Name error: name ‘n’ is not defined
sm=fun1(num1,num2)
print(sm)
3. Variable name in local scope as well as in 4. Using global variable inside local scope
global scope (this case is discouraged in programming)
e.g. e.g.
def fun(): def fun():
a=10 # output global a
print(a) a=10 # output
5 print(a)
a=5 5
10 a=5
print(a) 10
fun() 10 print(a)
print(a) 10
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 number returns the ones position digit
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%10
print(random.randint(a,b)) print(r)
Write a program having a function that Write a small python function that receive two
takes a number as argument and numbers and return their sum, product, difference
calculates cube for it. The function does not and multiplication.
return a value. If there is no return def ADD(X,Y):
return (X+Y)
value passed to the function in function
def PRODUCT(X,Y):
call, the function should calculate cube return(X*Y)
of 2. def DIFFERENCE(X,Y):
return(X-Y)
def fun(n=2):
print(n**3)

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

Write a function CHANGEO ,which accepts an Write function which accepts an integer array and size
list of integer and its size as parameters and as arguments and replaces elements having odd values
divide all those list elements by 7 which are with thrice its value and elements having even values
divisible by 7 and multiply list elements by 3. with twice its value.
Example : if an array of five elements
sol: initially contains elements as 3, 4, 5, 16, 9
def CHANGEO(A,S): The function should rearrange the content of the array
for i in range(S): as 9, 8, 15, 32,27
if(A[i]%7==0): sol
A[i]=A[i]/7 def fun(d,s):
else: for i in range(s):
A[i]=A[i]*3 if(d[i]%2!=0):
print("after change",A) d[i]*=3
else:
d[i]*=2
print("after change",d)

Write a function which accepts an integer array Write a function which accepts an integer array and
and its size as parameters and rearranges the its size as arguments and swap the elements of every
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 initially
contains the elements as 4, 2, 5, 1,6, 7, 8, 12, 10 contains the elements as
Then the function should rearrange the array 2,4,1,6,5,7,9,23,10
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) to


findname(name) where name is an argument display all the state names from a
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 MSEARCH(STATES):
delete") d.pop(n) for i in STATES:
print("dictionary after deletion",d) if(i[0]=='M'):
print(i)
Write a Get2From1( ) function in to Identify the type one or more types of arguments in the
transfer the content from one list ALL[ ] to following codes:
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 #default
places ( 1,3,5,. ). b)
''' def sum(a=1,b):
return a+b
even=[] print(sum(b=20, a=5 )) Ans #keyword
odd=[] c)
def fun(all,s): def sum(*n):
for i in range(0,s- for i in n:
1): if(i%2==0): total+=I
even.append(all[i]) return total
else: print (sum(4,3,2,1,7,8,9)) Ans #positional
odd.append(all[i])
d)
print("even list",even) def sum(a=1,b):
print("odd list",odd) return a+b
print(sum(10,20)) Ans #positional

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 calculate(a,b=5,c=10): Ans #no error
return a*b-c
ii) calculate(c=50,35)
i) calculate(12,3) Ans #we should have to specify the value to all the
ii) calculate(c=50,35) parameters .corrected calling is
iii) calculate(20, b=7, a=15) calculate(c=50,a=35,b=12)
iv) calculate(x=10,b=12)
iii) calculate(20, b=7, a=15)
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): x=1 def wish(message, num=1):
print(“a:”,a,” b:”,b, “ c:”,c) def cg(): print(message * num)
func(3,7) global x wish(‘Good’,2)
func(25,c=24) x=x+1 wish(“Morning”)
func(c=50, a=100) cg()
print(x) Ans
Ans GoodGood
a: 3 b: 7 c: 10 Ans Morning
a: 25 b: 5 c: 24 2
a: 100 b: 5 c: 50

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 file 4. if our program is large and we are
will be closed and a closed file cannot reading or writing multiple files that can
be read or written any more. 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”,’r’) with open(“abc.txt”) as f:
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 the Opens a file for writing and reading, overwrites
pointer at the beginning of the file. 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 stored
called a text file. (.txt) in the memory.

A text file is simply a sequence of ASCII or Unicode Best way to store program information.
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 path: For example: Absolute path: C:\


“function.py” Users\hp\Desktop\cs\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”, “from_where”) fileobjectname.tell()
Example:
“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 be A binary file stores the data in Data is stored in the form of
viewed using a text editor is the same way as as stored in rows and column i.e in tabular
called a text file. (.txt) the memory. (.dat) form. (.csv)

A text file is simply a sequence Can store different types of They are plain text files having
of ASCII or Unicode characters. data (audio, text,image) in a ASCII/Unicode Characters
single file.

EOL (new line character i.e. No EOL occurs Language which support text
enter) or internal translation files will also support csv files.
occurs

TEXT FILE AND CSV FILE


TEXT FILE CSV(COMMA SEPARATED VALUES) FILE
Text files contain text which can be opened by CSV also contain text data but in a format where
any text editor and there is plain text with no each line is considered as row/record which has
format many fields(columns).
EOL (new line character i.e. enter) or internal fields are the values separated by a
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 truncates Creates a new file if it does not exist.
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 is Unpickling is the process by which a byte stream
converted into a byte 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 of
that line 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 end
when the end of file is reached. 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 F #find no of lines
f=open(“firewall.txt") f=open(“firewall.txt")
c=0 t=f.readlines()
for i in f.readline(): print(len(t))
if(i=='F'):
c=c+1
print(c)
#count no of digits #count no of alphabets
f=open(“firewall.txt") f=open(“firewall.txt")
t=f.read() t=f.read()
c=0 c=0
for i in t: for i in t:
if(i>='0' and i<='9') if(i>='a' and i<='z')or(i>='A' and i<='Z')
: c=c+1 : c=c+1
print(c) 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.read()
print(len(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.read() t=f.read()
c=0 c=0
d=0 for i in t.split():
for i in t.split(): if(i=='firewall')or (i=='is'):
if(i=='firewall'): c=c+1
c=c+1 print(c)
elif(i=='to'):
d=d+1
print(c,d)

#print 5 lines from file #display first 3 lines


f=open(“firewall.txt") f=open(“firewall.txt")
print(f.readlines(5)) print(f.readline())
print(f.readline())
print(f.readline())

or
f=open(“firewall.txt")
for i in range(3):
print(f.readline())

f=open(“firewall.txt") Write a program that reads character from the


print(f.read(20)) #0 to 20 keyboard one by one. All lower case
bytes characters get store inside
print(f.read(30)) #next 30 bytes i.e. 21 to 30 the file LOWER, all upper case characters
(upto 50 bytes) get stored inside the file UPPER and all 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")
f3=open("others.txt","a")
print(d)
r=f.read()

for i in r:
if(i>='a' and i<='z'):
f1.write(i)
Write a program in python to read first 5 elif(i>='A' and
characters from the file("data.txt") i<='Z'): f2.write(i)
else:
f=open(“data.txt”,”r”) f3.write(i)
d=f.read(5) f.close()
print(d) f1.close()
f2.close()
f3.close()
Write a program in python to display number Write a program in python to display first line
of lines in a file("data.txt"). from the file("data.txt") using readlines().

f=open(“data.txt”,”r”) f=open(“data.txt”,”r”)
d=f.readlines() d=f.readlines()
print(d) 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 file("data.txt"). lines from the file("data.txt") with first character
f=open(“data.txt”,”r”) in uppercase.
d=f.readlines() f=open(“data.txt”,”r”)
for i in d: 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 two
of characters in first line of file ("data.txt") 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 from Write a program to count all the upper case
the file("data.txt") and display in uppercase. characters from the file ("data.txt").

f=open(“data.txt”,’r’) f=open(“data.txt”,’r’)
t=f.read() t=f.read()
print(t.upper()) c=0
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 in
from the file ("data.txt"). a file ("data.txt").
f =open(“data.txt”,’r’)
t=f.read() f =open(“data.txt”,’r’)
c=0 t=f.read()
for i in t: c=0
if(i.isspace() and i!=’\n’): for i in t:
c=c+1 if(i==’a’ or i==’e’ or i==’o’ or i==’i’ or i==’u’):
print(“total spaces”,c) 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 is display the total number of words present in
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 = open("Quotes.txt","r")
r = f.read() f = s.read()
for x in r: z = f.split ()
if x[0] == “W” or x[0] == “w”: count = 0
W=W+1 for i in z:
elif x[0] == “H” or x[0] == “h”: count = count + 1
H=H+1 print ("Total number of words:", count)
f.close()
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 = open("Quotes.txt","r") def COUNT_AND( ):
f = s.read() count=0
z = f.split () file=open(‘STORY.TXT','r')
count = 0 line = file.read()
for i in z: word = line.split()
count = count + 1 for w in word:
print ("Total number of words:", count) if w ==’AND’:
count=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 “T” number of 5 letter words in a text file “Sample.txt
in a text file ‘STORY.TXT’. def count_words( ):
def COUNT_AND( ): c=0
count=0 f = open("Sample.txt")
file=open(‘STORY.TXT','r') line = f.read()
line = file.read() word = line.split()
word = line.split() for w in word:
for w in word: if len(w) == 5:
if w[0] ==’t’ or w[0]==’T’: c += 1
count=count+1 print(c)
print(count)
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 “Sample.txt number of 5 letter words in a text file “Sample.txt
def count_words( ): def count_words( ):
c=0 c=0
f = open("Sample.txt") f = open("Sample.txt")
line = f.read() line = f.read()
word = line.split() word = line.split()
for w in word: for w in word:
if len(w) == 5: if len(w) == 5:
c += 1 c += 1
print(c) print(c)

Write a function that counts and display the Write a function to display those lines which start
number of 5 letter words in a text file “Sample.txt with the letter “G” from the text file
def count_words( ): “MyNotes.txt”
c=0 def count_lines( ):
f = open("Sample.txt") c=0
line = f.read() f = open("MyNotes.txt")
word = line.split() line = f.readlines()
for w in word: for w in line:
if len(w) == 5: if w[0] == 'G':
c += 1 print(w)
print(c) f.close()
f.close()
Write a function in python to read lines from file Write a function COUNT() in Python to read
“POEM.txt” and display all those words, which contents from file “REPEATED.TXT”, to count and
has two characters in it. display the occurrence of the word “Catholic” or
def TwoCharWord(): “mother”.
f = open('poem.txt') def COUNT():
count = 0 f = open('REPEATED.txt')
for line in f: count = 0
words = line.split() for line in f:
for w in words: words = line.split()
if len(w)==2: for w 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 REPORT.TXT, python to read contents from a text file ABC.TXT
and COUNT those lines which are starting either and display those lines which have occurrence of
with ‘E’ and starting with ‘T’ respectively. And the word ‘‘TO’’ or ‘‘DO’’.
display the Total count separately. def SHOW_TODO():
def COUNTLINES_ET(): f=open(“ABC.TXT”)
f=open(“REPORT.TXT”) d=f.readlines()
d=f.readlines() for i in d:
le=0 if “TO” in i or “DO” in i:
lt=0 print(i)
for i in d: f.close()
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 the
def displayMeMy(): occurrences of alphabets A and M (including
num=0 small cases a and m too).
f=open("story.txt","rt") def AMCount():
N=f.read() f=open("story.txt","r")
M=N.split() A,M=0,0
for x in M: r=f.read()
if x=="Me" or x== "My": for x in r:
print(x) if x[0]=="A" or x[0]=="a" :
num=num+1 A=A+1
print("Count of Me/My in file:",num) elif x[0]=="M" or x[0]=="m":
f.close() M=M+1
print("A or a: ",A)
f.close()

Write a function in python that displays the Write a function countmy() in Python to read file
number of lines starting with ‘H’ in the file Data.txt and count the number of times “my”
“para.txt”. occur in file.
def countH(): def countmy():
f=open("para.txt","r") f=open(“Data.txt”,”r”)
lines=0 count=0
l=f.readlines() x=f.read()
for i in l: word=x.split()
if i[0]='H': for i in word:
lines+=1 if i ==”my” :
print("NO of lines are:",lines) count=count+1
f.close() 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","r")
d=f.readlines() c=0
count=len(d) line = file.read()
print(count) word = line.split()
f.close() for w in word:
if w=='if':
print( w)
c=c+1
print(c)
file.close()
Write a method in python to read lines from a Write a method/function ISTOUPCOUNT() in
text file DIARY.TXT and display those lines which python to read contents from a text file
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.readlines() c=0
for i in l: file=open('sample.txt','r')
if i[0]='P': line = file.read()
lines+=1 word = line.split()
print("No of lines are:",lines) cnt=0
for w in word:
if w=='TO' or w=='UP' or w=='IS':
cnt+=1
print(cnt)
file.close()
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 the
c=0 occurrence of alphabets vowels.
f=open('MY_TEXT_FILE.TXT', 'r') :
d=f.read() def VowelCount():
w=d.split() count_a=count_e=count_i=count_o=count_u=0
for i in w: f= open('MY_TEXT_FILE.TXT', 'r')
if i.upper()== 'THE' or i.upper()== 'THIS' : d=f.read()
c+=1 for i in d:
print(c) if i.upper()=='A':
count_a+=1
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] == ‘@’:
continue
f2.write(text)
f1.close()
f2.close()

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 the ITEMS.DAT,
form of list. (items.dat- id,gift,cost).Assume that info is stored
''' in the form of list
#Sol : '''
import pickle #Sol:
def itemadd (): import pickle
f=open("items.dat","wb") def SHOWINFO():
n=int(input("enter how many records")) f=open("items.dat","rb")
for i in range(n): while True:
r=int(input('enter id')) try:
n=input("enter gift name") g=pickle.load(f)
p=float(input("enter cost")) print(g)
v=[r,n,p] except:
pickle.dump(v,f) break
f.close() 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
which are priced less than 50. are priced between 50 to 60.
(items.dat- id,gift,cost).Assume that info is stored (items.dat- id,gift,cost).Assume that info is stored
in the form of list in the form of list
''' '''
#sol #sol
def COSTLY(): def COSTLY():
f=open("items.dat","rb") f=open("items.dat","rb")
c=0 while True:
while True: try:
try: r=pickle.load(f)
r=pickle.load(f) if(r[2]>=50 and r[2]<=60):
if(r[2]<50): print(r)
c=c+1 except:
print(r) break
except: f.close()
break
print(c)
f.close()
''' '''
Write a function for function to SEARCH()for a Write a function in to search and display details
item from a binary file "items.dat" of all flights, whose
The user should enter the itemno and function destination is “Mumbai” from a binary file
should search and “FLIGHT.DAT”.
display the detail of items.(items.dat- id,gift,cost). (flight.dat- fno,from (starting point), to
Assume that info is stored in the form of list (destination)).
''' Assume that info is stored in the form of list
import pickle '''
def SEARCH(): import pickle
f=open("items.dat","rb") def FUN():
n=int(input("enter itemno which u want to f=open("FLIGHT.DAT","rb")
search"))
while True: while True:
try: try:
r=pickle.load(f) r=pickle.load(f)
if(r[0]==n): if(r[2]=="Mumbai"):
print(r) print(r)
except: except:
break break
f.close() 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 name creates a file named BASKET.DAT copying only
and function should search and those records from GAME.DAT where
update the entered itemno info the game name is “BasketBall”.(game.dat -
(items.dat- id,gift,cost). gamename, participants).
Assume that info is stored in the form of list Assume that info is stored in the form of list
''' '''
import pickle import pickle
import os def fun():
def UPDATEINFO(): f=open("GAME.DAT","rb")
f=open("items.dat","rb") f1=open("BASKET.DAT","wb")
f2=open("temp.dat","wb") while True:
s=[] try:
a=input("enter item name which we want to r=pickle.load(f)
update") if(r[0]=="BasketBall"):
while True: pickle.dump(r,f1)
try: except:
r=pickle.load(f) break
if(r[1]==a): print(c)
r[0]=int(input("enter new item id")) f.close()
r[1]=input("enter item name") f1.close()
r[2]=int(input("enter cost of item"))
s.append(r)
except:
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 [EID,
name, marks]. Ename, designation, salary].
i. Write a user defined function insertRec() to i. Write a user defined function CreateEmp() to
input data for a student and add to input data for a record and create a file
student.dat. emp.dat.
ii. Write a function searchRollNo( r ) in Python ii. Write a function display() in Python to display
which accepts the student’s rollno as parameter the detail of all employees whose salary is more
and searches the record in the file than 50000.
“student.dat” (i)
and shows the details of student i.e. rollno, name import pickle
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 pickle designation=input("Enter Designation")
def insertRec(): salary=int(input("Enter 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
pickle.dump( rec, f ) def display():
f.close() f2=open("emp.dat","rb")
(ii) try:
def searchRollNo( r ): while True:
f=open("student.dat","rb") rec=pickle.load(f2)
flag = False if rec[3]>5000:
while True: print(rec[0],rec[1],rec[2],rec[3])
try: except:
rec=pickle.load(f) f2.close()
if rec[0] == r :
print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag == True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
Write a python program to append a new records Write a python program to search and display
in a binary file –“student.dat”. The record can the record of the student from a binary file
have Rollno, Name and Marks. “Student.dat” containing students records
import pickle (Rollno, Name and Marks). Roll number of the
while True: student to be searched will be entered by the
rollno = int(input("Enter your rollno: ")) user.
name = input("Enter your name: ")
marks = int(input("enter marks obtained: ")) import pickle
d = [rollno, name, marks] f1 = open("Student.dat", "rb")
f1 = open("Student.dat", "wb") rno = int(input(“Enter the roll no to search: ”))
pickle.dump(d, f1) flag = 0
choice = input("enter more records: y/n") try:
if choice== "N": while True:
break r = pickle.load(f1)
f1.close() if rno == r[0]:
print (rollno, name, 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 to records of the structure [EmpNo, EName, Post,
add more records of employes in existing file Salary]
emp.dat. (a) Create a binary file “EMP.dat” that stores
ii. Write a function Show() in Python that would the records of employees and display them one
read detail of employee from file “emp.dat” and by one.
display the details of those employee whose (b) Display the records of all those employees
designation is “Salesman”. who are getting salaries between 25000 to
(i) 30000.
import pickle (a)
def createemp: import pickle
f1=open("emp.dat",'ab') f1 = open('emp.dat','rb')
eid=input("Enter E. Id") try:
ename=input("Enter Name") while True:
designation=input("Enter Designation") e = pickle.load(f1)
salary=int(input("Enter Salary")) print(e)
l=[eid,ename,designation,salary] except:
pickle.dump(l,f1) f1.close()
f1.close()
(ii) (b)
def display(): import pickle
f2=open("emp.dat","rb") f1 = open('emp.dat','rb')
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], rec[2],rec[3]) print(e)
except: except:
break f1.close()
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.dat”
(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,Price]
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.close()
return num
A binary file student.dat has structure A binary file “STUDENT.DAT” has structure
(rollno,name,class,percentage). Write a program (admission_number, Name, Percentage). Write a
to updating a record in the file requires roll function countrec() in Python that would read
number to be fetched from the user whose contents of the file “STUDENT.DAT” and display
name is to be updated the details of those students whose percentage is
import pickle above 75. Also display number of students
import os scoring above 75%
f1 = open(‘student.dat','rb')
f2=open(“temp.dat”,”wb”) import pickle
r=int(input(“enter rollno which you want def CountRec():
to search”)) f=open("STUDENT.DAT","rb")
try: num = 0
while True: try:
e = pickle.load(f1) while True:
if e[0]==r: rec=pickle.load(f)
e[1]=input(“enter name”) if rec[2] > 75:
pickle.dump(e,f2) print(rec[0],rec[1],rec[2])
else: num = num + 1
pickle.dump(e,f2) except:
except: f.close()
f1.close() return num
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 [ Code,
records of the structure [EmpNo, EName, Post, Description, Price ].
Salary] i. Write a user defined function MakeFile( ) to
(a) Write a user-defined function named input multiple items from the user and add
NewEmp() to input the details of a new employee to Items.dat
from the user and store it in EMP.dat. ii. Write a function SearchRec(Code) in Python
(b) Write a user-defined function named which will accept the code as parameter and
SumSalary(Post) that will accept an argument search and display the details of the
the post of employees & read the contents of corresponding code on screen from
EMP.dat and calculate the SUM of salary of all Items.dat. (i)
employees of that Post. import pickle
(a) def MakeFile( ):
import pickle while True:
def NewEmp ( ): code = input(“Enter Item Code :”)
f = open(“EMP.dat”,”wb”) desc = input(“Enter description
EmpNo = int(input(“Enter employee :”) price = float(input(“Enter
number: “)) price:”)) d= [code,desc,price]
EName = input(“Enter name:”) f = open (“Items.dat”, “ab”)
Post = input(“Enter post:”) pickle.dump( d,f )
Salary = int(input(“Enter salary”)) ch = input(“Add more record? (y/n)
rec = [EmpNo, Ename, Post,Salary] :”) if ch==’n’:
pickle.dump(rec, f) break
f.close() f.close( )
(b) (ii)
def SumSalary(Post): def SearchRec(code):
f = open("EMP.dat", "rb") f = open("Items.dat", "rb")
c=0 found = False
while True: while True:
try: try:
g = p.load(f) g = p.load(f)
if g[2]==Post: if g[0]==code:
c=c+g[3] print(g[0],g[1],g[2])
except: found=True
f.close() break
print("sum of salary", c) except:
if found == False:
print("No such record")
f.close()

A binary file named “TEST.dat” has some records Consider a binary file emp.dat having records in
of the structure [TestId, Subject, MaxMarks, the form of dictionary. E.g {eno:1, name:”Rahul”,
ScoredMarks] Write a function in Python named sal: 5000} write a python function to display the
DisplayAvgMarks(Sub) that will accept a subject records of above file for those employees who
as an argument and read the contents of get salary between 25000 and 30000
TEST.dat. The function will calculate & display
the Average of the ScoredMarks of the passed
Subject on screen.
def SumSalary(Sub): import pickle
f = open("ABC.dat", "rb") def search():
c=0 f=open(“emp.dat”,”rb”)
s=0 while True:
while True: try:
try: d=pickle.load(f)
g = p.load(f) if(d[‘sal’]>=25000 and d[‘sal’]<=30000):
print(g) print(d)
if g[1]==Sub: except EOFError:
s=s+g[3] break
c=c+1 f.close()
except:
f.close()
print("sum of salary", s/c)
f.close()
A binary file “Bank.dat” has structure as Consider an employee data, Empcode,
[account_no, cust_name, balance]. empname and salary.
i. Write a user-defined function addfile( ) and (i) Write python function to create
add a record to Bank.dat. binary file emp.dat and store
ii. Create a user-defined function CountRec( ) to their records.
count and return the number of customers (ii) write function to read and display
whose balance amount is more than 100000. all the records
(i) Ans
import pickle import pickle
def addfile( ): def add_record():
f = open(“bank.dat”,”wb”) f = open(“emp.dat”,”ab”)
acc_no = int(input(“Enter account empcode =int(input(“employee code:”))
number: “)) empname = int(input(“empName:”))
cust_name = input(“Enter name:”) salary = int(input(“salary:”))
bal = int(input(“Enter balance”)) d = [empcode, empname, salary]
rec = [acc_no, cust_name, bal] pickle.dump(d,f)
p.dump(rec, f) f.close()
f.close() import pickle
(ii)
def CountRec( ): def search():
f = open(“bank.dat”,”rb”) f=open(“emp.dat”,”rb”)
c=0 while True:
try: try:
while True: d=pickle.load(f)
rec = p.load(f) print(d)
if rec[2] > 100000: except EOFError:
c += 1 break
except: f.close()
f.close()
return c
Write a function SCOUNT( ) to read the content Given a binary file “emp.dat” has structure
of binary file “NAMES.DAT‟ and display number (Emp_id, Emp_name, Emp_Salary). Write a
of records (each name occupies 20 bytes in file function in Python countsal() in Python
) where name begins from “S‟ in it that
def SCOUNT( ): would read contents of the file “emp.dat” and
s=' ' display the details of those employee whose
count=0 salary is greater than 20000
f=open('Names.dat', 'rb'): import pickle
while True: def countsal():
s = f.read(20) f = open (“emp.dat”, “rb”)
if len(s)!=0: n=0
if s[0].lower()=='s': try:
while True:
count+=1 rec = pickle.load(f)
print('names beginning from "S" are ',count) if rec[2] > 20000:
print(rec[0], rec[1], rec[2])
n=n+1
except:
print(n)
f.close()

Write Python function DISPEMP( ) to read the Consider the following CSV file (emp.csv):
content of file emp.csv and display only those Sl,name,salary
records where salary is 4000 or above 1,Peter,3500
import csv 2,Scott,4000
def DISPEMP(): 3,Harry,5000
csvfile=open('emp.csv'): 4,Michael,2500
myreader = csv.reader(csvfile,delimiter=',') 5,Sam,4200
print(EMPNO,EMP NAME,SALARY) Write Python function DISPEMP( ) to read the
for row in myreader: content of file emp.csv and display only those
if int(row[2])>4000: records where salary is 4000 or above
print(row[0], row[1],row[2]) import csv
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 = open(“Stu.dat”,”ab”) f = open(“Stu.dat”, “rb”)
rollno =int(input(“Roll no:”)) stu_rec = pickle.load(f)
name = int(input(“Name:”)) found = 0
marks = int(input(“Marks:”)) rno = int(input(“roll number to search:”))
data = [rollno, name, marks] try:
pickle.dump(data,fobj) for R in stu_rec:
fobj.close() if R[0] == 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 the write a python function writecsv () to write the
following information into following information into product.csv.Heading
product.csv. of the product .csv is as follows

pid,pname,cost,quantity pid,pname,cost,quantity
p1,brush,50,200 '''
p2,toothbrush,120,150 def writecsv(pid,pname,cost,quantity):
p3,comb,40,300 f=open("marks.csv","w")
p4,sheets,100,500 r=csv.writer(f,newline="")
p5,pen,10,250 r.writerow([pid,pname,cost,quantity])
''' f.close()
#solution

def writecsv():
f=open("product.csv","w")
r=csv.writer(f,lineterminator='\n')
r.writerow(['pid','pname','cost','qty'])
r.writerow(['p1','brush','50','200'])
r.writerow(['p2','toothbrush','12','150'])
r.writerow(['p3','comb','40','300'])
r.writerow(['p5','pen','10','250'])
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 already product.csv. assume that following info is already
present in the file. 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 csv import csv
def readcsv(): def readcsv():
f=open("product.csv","r") f=open("product.csv","r")
r=csv.reader(f) r=csv.reader(f)
for i in r: for i in r:
print(i) print(i[0],i[1],i[2],i[3])
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=',') #Line4 Ans:
ans='y' a) csv
while ans=='y':
found=False b) writerow(fields)
emplid=(input("Enter employee id to search="))
for row in csv_r: c) writerows(rows)
if len(row)!=0:
if ==emplid: #Line5 d) csv.reader
print("Name :
",row[1]) e) row[0]
print("Mobile No : ",row[2])
found=True
break
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,2500
5,Sam,4200 Ans
import # Line 1 (a) csv
def SNAMES():
with open( ) as csvfile: # Line 2 (b) read mode
myreader = csv. (csvfile, delimiter=',') # Line (c) 'emp.csv'
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
print("Number of 'S' names are ",count_s,"/",count_rec) (d) reader

(a) Name the module he should import in Line 1 (e)2,Scott,4


(b) In which mode, Priti should open the file to print data. 000
(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 into (a) Line 1 : csv
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,PassWord]) (e) Line 5 :
f.close() #csv file reading code Arjun 123@456
Arunima aru@nima
def readCsvFile(): # to read data from CSV file Frieda myname@FRD
with open(' user.csv','r') as newFile:
newFileReader = csv. (newFile) # Line
3 for row in newFileReader:
print (row[0],row[1])
newFile. # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“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 # Line 1 a) Line 1 : csv
f = open(“Sports.csv”,”a”)
wobj = csv. (f, delimiter = ‘\t’) # Line b) Line 2 : writer
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:”))
record = # Line 3 c) Line 3 : [sport, comp, prize]
wobj. (rec) # Line 4 d) Line 4 : writerow
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 programmer, you have Ans
to help him to successfully execute the program. (a) csv
import # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a new record in
CSV file
f=open(“CAPITAL.CSV”, ) # Statement-2 (b) “a”
fwriter=csv.writer(f) fwriter.writerow([Country,Capital])
f. # Statement-3 (c) close()

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


with open(“CAPITAL.CSV”,”r”) as NF:
NewReader=csv. (NF) # Statement- (d)reader
4 for rec in NewReader:
print(rec[0],rec[1])

AddNewRec(“INDIA”,”NEW DELHI”)
AddNewRec(“CHINA”,”BEIJING”) (e)
ShowRec() # Statement-5 INDIA NEW DELHI
CHINA BEIJING
(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.

import # Line 1 (a) Line 1 : csv


def addCsvFile(UserName,PassWord): # to write / add
data f=open(' mydata.csv',' ') # Line 2 (b) Line 2 : a
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) # Line (c) Line 3 : reader
3 for row in newFileReader:
print (row[0],row[1])
newFile. # Line 4 (d) Line 4 : close()

addCsvFile(“Aman”,”123@456”)
addCsvFile(“Anis”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”) (e) Line 5 :
readCsvFile() #Line 5 Aman 123@456
Anis aru@nima
(a) Give Name of the module he should import in Line 1. Raju myname@FRD
(b) In which mode, Aman 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.

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 programmer, Ans
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) #Line 2 (b) LINE 2 : writer
writer.writerow([empcode,name])
fo.close() #csv file reading code
def reademp():
with open('emp.csv',' ') as fin: #Line (c) LINE 3: r
3 filereader=csv.reader(fin)
for row in filereader:
for data in row:
print(data,end='\t')
print(end='\n')
fin. #Line 4 (d) LINE 4: close()
addemp('E105','Parth')
addemp("E101",'Arunima')
addemp("E102",'Prahalad')
reademp() #Line 5
(e)
(a) Name the module he should import in Line 1. E105 Parth
(b) Fill in the blank in Line 2 to write the data in a CSV file. E101 Arunima
(c) In which mode, Parth should open the file to read the E102 Prahalad
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", ) # Statement 2 (b) “r”
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 following Write push(edetail) and pop(edetail) in python
information: to add and remove the employee detail in a stack
a. Roll Number of student 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
Ans. employee Ans.
‘’’ ‘’’
List=[] edetail = []
def add(List): def push(edetail):
rno=int(input("Enter roll number")) name = input("Enter name")
name=input("Enter name") sal = int(input("Enter
item=[rno,name] Salary")) item = [name, sal]
List.append(item) edetail.append(item)

def pop(List): def pop(edetail):


if len(List)>0: if len(edetail) > 0:
List.pop() edetail.pop()
else: else:
print("Stack is empty") print("Stack is empty")
''' Write a function Push() which takes "name" as
Write addsal(sal) and removesal(sal) functions in argument and add in a stack named "MyStack".
python to add and remove salary from a list of After calling push() three times, a message
salary in a list "sal", considering these methods to should be displayed "Stack is Full"
act as push and pop operations of data structure Ans.
stack. '''
Ans. MyStack=[]
''' StackSize=3
sal = [] def Push(Value):
def addsal(sc): if len(MyStack) < StackSize:
sal.append(sc) MyStack.append(Value)
else:
def pop(): print("Stack is full!")
if len(sal) > 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 "MyStack" from stack named "MyStack".
'''
Mynames=[] def Pop(MyStack):
def Push(Value): if len(MyStack) > 0:
Mynames.append(Value) MyStack.pop()
else:
print("Stack is empty.")
Write add(bookname) and delete() method in Q1. Organization of data means .
python to add bookname and remove bookname Q2. Write the full form of the
considering following:
them to act as push() and pop() operations in a. LIFO
stack. b. FIFO
''' Q3. Which data structure is represented as FIFO?
MyStack=[] Q4. Insertion into stack is called
def add(bname): (push/pop)
MyStack.append(bname) Q5. Giving printing command to printer is
an example of
def delete(MyStack): (stack/queue)
if len(MyStack) > 0: Q6. Reversing a number or a word/string is an
MyStack.pop() example of
else: (stack or queue)
print("Stack is empty. There is no book name") Q7. In stack addition or removal of elements
takes place at
(one/both) end of the list.
Write add(no) and delete() method in python Q8. In queue, addition of elements take place at
to add no and remove no considering one end and
them to act as enqueue () and dequeue() removal of elements takes place at other
operations in queue. end. (T/F)
Q9. If the elements "A", "B", "C" are added in the
qe=[] queue in the
def Enqueue(no): #inserting into the queue following order,
qe.append(no) first A then B and in last C.
In what order, it will come out
of queue?
def dequeue(): Q10. function is used to add an
if(qe==[]): element in stack.
print("underflow/empty queue")
else: Ans 1. Data Structure
qe.pop(0) Ans 2.
a. Last In First Out
b. First In First Out
Ans 3. Queue
Ans 4. Push
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) in Write a function DeleteCustomer() to delete a


Python to add a new Customer information Customer information from a list of CStack. The
NAME into the List of CStack and display the function delete the name of customer from the
information. stack.
CStack=[] CStack=[]
def AddCustomer(Customer): def DeleteCustomer():
CStack.append(Customer) if (CStack ==[]):
if len(CStack)==0: print(“There is no Customer!”)
print (“Empty Stack”) else:
else: print(“Record deleted:”,CStack.pop())
print (CStack)

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 them
and pop operations of the Stack data structure. to act as insert and delete operations of the
def MakePush(Package): Queue data structure.
a=int(input("enter package title:")) def InsQueue (Passenger):
Package.append(a) a=int(input("enter passenger name:"))
Passenger.append(a)
def MakePop(Package):
if(Package==[]): def DelQueue (Passenger):
print("Stack empty") if(Passenger ==[]):
else: print("queue empty")
print("Deleted element:",Package.pop()) else:
print(Passenger.pop(0))

Write AddCustomer(Customer) method in Python Write RemoveCustomer(Customer) method in


to add a new customer, considering it to act as a Python to remove a Customer, considering it to
PUSH operation of the stack datastructure. Also act as a POP operation of the stack
display the contents of the Stack after PUSH datastructure. Also return the value deleted from
operation. Details of the Customer are : CID and stack.
Name.
def AddCustomer(Customer): def RemoveCustomer(Customer):
cid = int(input(“Enter customer id:”)) if Customer == [ ]:
Name = input(“Enter customer name:”)) print(“Underflow”)
Customer.append ( [cid,Name] ) else:
p = Customer.pop( )
return p
Write a function in python named PUSH(STACK, Write a function in python named POP(STACK)
SET) where STACK is list of some numbers where STACK is a stack implemented by a list of
forming a stack and SET is a list of some numbers. The function will display the popped
numbers. The function will push all the EVEN element after function call.
elements from the SET into a STACK def POP(STACK):
implemented by using a list. Display the stack if STACK==[]:
after push operation. print(“underflow”)
def PUSH(STACK,SET): else:
for i in SET: print(STACK.pop())
if i%2==0:
STACK.append(i)
print(STACK)
Write a function in Python PUSH(Arr), where Arr Write a function in Python POP(Arr), where Arr
is a list of numbers. From this list push all is a stack implemented by a list of numbers. The
numbers divisible by 5 into a stack implemented function returns the value deleted from the
by using a list. Display the stack if it has at least stack.
one element, otherwise display appropriate error
message. def popStack(st) :
def PUSH(Arr,value): if len(st)==0:
s=[] print("Underflow")
for x in range(0,len(Arr)): else:
if Arr[x]%5==0: print(st.pop())
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(s)
Write a function in Python PUSH (Lst), where Lst Write a function in python, PushEl(e) to add a
is a list of numbers. From this list push all new element and PopEl(e) to delete a element
numbers not divisible by 6 into a stack from a List ,considering them to act as push
implemented by using a list. Display the stack if it and pop operations of the Stack data structure
has at least one element, otherwise display .
appropriate error message.
def PUSH(Arr,value): def PushEl(element):
s=[] a=int(input("enter package title : "))
for x in range(0,len(Arr)): element.append(a)
if Arr[x]%6!=0:
s.append(Arr[x]) def PopEl(element):
if len(s)==0: if (element==[]):
print("Empty Stack") print( "Stack empty")
else: else:
print(s) print (element.pop())

Write InsertQ(C) and DeleteQ(C) Write a function DELQ(Customer) in Python to


methods/functions in Python to add a new delete a Customer from a Queue implemented
Customer and delete a Customer from a list of using list.
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 name :”) print (“Queue is empty…..”)
queue.append(a) else:
print(queue.pop(0))
def DeleteQ(queue):
if (queue==[]):
print (“Queue is empty…..”)
else:
print(queue.pop(0))

Write a function POP(Book) in Python to delete a Write a function in Python PushBook(Book) to


Book from a list of Book titles, considering it to add a new book entry as book_no and
act as a pop operation of the Stack data book_title in the list of Books , considering it to
structure. 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 title:”)
print(Book.pop()) 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
Create Insert
Drop Update
Alter Delete
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 statement
create database database-name; (i) To insert records into specific columns
Example Syntax:
create database Test; insert into table_name(column_name1,
------------------------------------------- column_name2…)values
CREATE TABLE Command: Create table (value1,value2….);
command is used to create a table in SQL.
Syntax : e.g. INSERT INTO student
CREATE TABLE tablename (rollno,name )VALUES(101,'Rohan');
(column_name data_type(size),
column_name2 data_type(size)…. (ii) insert records in all the columns
); insert into table_name
values(value1,value2……);
e.g. create table student (rollno integer(2),
name char(20), dob date); e.g.INSERT INTO student
(VALUES(101,'Rohan','XI',400,'Jammu');

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

e.g.
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 that i. Not Null constraint : It ensures that the
can be enforced on the attributes of a relation. column cannot contain a NULL value.
The constraints come in play whenever we try to
insert, delete or update a record in a relation. ii. Unique constraint : A candidate key is a
They are used to ensure integrity of a combination of one or more columns, the value
relation, hence named as integrity constraints. of which uniquely identifies each row of a table.
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 Primary
5. CHECK Key constraint can contain a NULL value.
6. DEFAULT

Example:

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

Example:
create table Employee v. Check Constraint : Sometimes we may
(EmpNo integer(4) Primary Key, require that values in some of the columns of our
Name char(20) Not Null, table are to be within a certain range or they
Salary integer(6,2) check (salary > 0), must satisfy certain conditions.
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 Key, column. The default value will be added to all
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 all Like clause- pattern matches
the conditions are true Wildcard operators - used in like clause.
(i) Percent sign % : represents zero, one
EXAMPLE or more than one character.
TO return records where salary is less than (ii) Underscore sign _ : represents only
10000 and age greater than 25. one character.
SELECT * from Emp WHERE salary < 10000 Example of LIKE clause
AND age > 25; 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 functions Distinct keyword- it is used


return a single value after calculating from a with Select statement to retrieve unique values
group of values. from the table. Distinct removes all the duplicate
frequently used Aggregrate functions. records while retrieving from database.
Avg(), Sum(), max(), min(),
count(column_name),count(distinct) Syntax :
count(column name)- Count returns the SELECT distinct column-name from table-name;
number of rows present in the table either based Example
on some condition or without condition. To display only the unique salary
COUNT(distinct) from Emp table
SELECT COUNT(distinct salary) from emp; 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-list|* SELECT column_name,
from table-name aggregate_function(column_name)
order by asc / desc; FROM table_name
WHERE condition
To display all records in ascending order of GROUP BY
the salary. column_name;
SELECT * from Emp order by salary;
To display all records in descending order of To find name and age of employees grouped
the salary. by their salaries
SELECT * from Emp order by salary DESC; Example
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 Which keyword is used to select


change the number of columns in rows containing
a table? column that match a wildcard pattern?
Ans ALTER Ans LIKE
Differentiate between Degree All aggregate functions except
and Cardinality. ignore null values in their input
Ans Degree – it is the total collection.
number of columns in the table. a) Count (attribute)b) Count (*)
Cardinality – it is the total number of c) Avg () d) Sum
tuples/Rows in the table. () Ans count(*)
Group functions can be applied Which command is used to
to any numeric values, some text change the existing information of
types and DATE values. table?
(True/False) Ans update
Ans True
Expand the term: RDBMS Write an Aggregate function that is
Ans Relational Database used in MySQL to find No. of Rows in
Management System the database Table
Ans count(*)
For each attribute of a relation, In SQL, write the query to display the list
there is a set of permitted values, of databases stored in MySQL.
called the of that 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
a) Unique b) Distinct structure of the table/relation.
c) Primary key d) a) view b) describe
check Ans (b) c) show d)
Distinct select Ans (b)
describe
A virtual table is called a ............. Which clause is used to
Ans view remove the duplicating rows of
the table?
i) or ii) distinct iii) any
iv)unique Ans (ii) distinct
Which clause is used in query to Which command is used for
place the condition on groups in counting the number of rows in a
MySql? 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 In SQL, name the clause that is used to
returned when a cursor object is place condition on groups
used to query a table. True/False Ans Having
Ans True
In SQL, which command is used to Which operator performs pattern
change the structure of already created matching in SQL?
table. Ans Like
Ans Alter table
What does the following function In SQL, what are aggregate
result into? count(field_name) functions? Ans These functions work
Ans It returns the number of non-null with data of multiple rows at a time
records from the field. and return a single value.

How many Primary and Foreign keys In SQL, write the name of the
can a table have? aggregate function which is used to
Ans Primary Key – 1 Foreign Key – Many calculate & display the average of
numeric values in an attribute of a
relation.
Ans AVG()
Write an SQL query to display all the What is the use of LIKE keyword in
attributes of a relation named “TEST” SQL? Ans LIKE keyword is used to
along with their description. find matching CHAR values with
Ans DESCRIBE TEST; or DESC TEST; WHERE clause.

Which of the following is NOT a What is the purpose of following


DML command? a). SELECT b). SQL command: SHOW
DELETE c). UPDATE d). DROP DATABASES;
Ans (d) DROP Ans This command will print name
of all the databases present in
RDBMS.
Identify the error in the following SQL In SQL, name the command/clause that
query which is expected to delete all is used to display the rows in
rows of a table TEMP without deleting its descending order of a column. Ans
structure and write the correct one: Order By …… Desc
DELETE TABLE
TEMP;
Ans DELETE FROM TEMP;
In SQL, what is the error in Write any two aggregate functions
following query : SELECT NAME, used in 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 In SQL, write the query to display the list
command? of databases.
a) SELECT b) Update Ans SHOW DATABASES’
c) INSERT d)
All Ans (d) All
Which of the following will suppress the A non-key attribute, whose values
entry of duplicate value in a column? are derived from primary key of
a) Unique b) Distinct some other 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 command in SQL to display the
table command (iii) Drop table records in ascending order of an
Command (iv) Delete command attribute?
Ans (ii) Create table command (iii) Drop Ans Order by
table Command

A relation has 45 tuples & 5 attributes, In SQL, which aggregate function is used
what will be the Degree & Cardinality to count all records of a table?
of that 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 Sunita executes following two
getting the appropriate output, help statements but got the variation in
her to do the correction. result 6 and 5 why?
Select name from teacher (i)select count(*) from user ;
where subject=Null; (ii)select count(name)
Ans Select name from teacher where from user ;
subject is Null; (iii) Ans
Count(*) will count rows where as
count(name) will count name
column only which is having one
null value.
What is the difference between Write a command to add new
where and having in SQL. column marks in table ‘student’
Ans Where is used apply data type int. Ans Alter table
condition in query, where as student add marks int(3)
having is used only with group.
Write query to display the In SQL, what is the use of
structure of table teacher. BETWEEN 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 In SQL, what is the use of IS
display the tuples in ascending order of NULL operator?
an attribute. Ans To check if the column has null
Ans Orderby value
/ no value
Write any one aggregate function Which of the following is a DDL
used in SQL. command?
Ans SUM / AVG / COUNT / MAX / MIN a) SELECT b) ALTER
c) INSERT

d) UPDATE
Ans (b) ALTER
In SQL, write the query to display the list Which of the following types of table
of tables stored in a database constraints will prevent the entry of
Ans Show tables; duplicate rows?
a) check b) Distinct
c) Primary Key d)
NULL Ans (c) Primary Key
Which is known as range operator in If column “salary” of table “EMP”
MySQL. contains the dataset {10000, 15000,
a) IN b) BETWEEN 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 Name the clause used in query to
to find the largest value from the given place the condition on groups in
data in MySQL? MySQL?
a) MAX ( ) b) MAXIMUM ( ) Ans having
c) LARGEST ( ) d) BIG ( )
Ans (a) MAX()
Write SQL statement to find total Write command to list the
number of records in table EMP? available databases in MySQL.
Ans count(*) Ans show databases

In SQL, name of the keyword In SQL, what is the use of ORDER


used to display unique values of BY clause ?
an attribute. 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
current date command?
Ans curdate() a) CREATE b)ALTER c) INSERT
d) DROP
Ans (c) insert
In SQL, write the command / query to Which of the following type of column
display the structure of table ‘emp’ constraints will allow the entry of unique
stored in a database. and not null values in the column?
Ans desc emp a) Unique b) Distinct
c) Primary Key

d) NULL
Ans (c) Primary Key
In SQL, name the clause that is used to In SQL, what is the use of
display the unique values of an <> operator?
attribute of a table. Ans not equal to
Ans distinct
Write any two aggregate function Which of the following is/ are
used in SQL DML command(s)?
Ans max/min/avg/sum/count(*) a) SELECT b) ALTER
c) DROP

d) UPDATE
Ans (a) select (d) update
In SQL, write the query to Which of the following types of table
display the list databases. constraints will not prevent NULL
Ans show databases entries in a 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
VisitorID VisitorName ContactNumber
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
1
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;

1
b) DROP TABLE VISITOR;

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
C204 DDTP 9000 2019-09-15 104
C205 DHN 20000 2019-08-01 101
C206 O LEVEL 18000 2018-07-25 105

(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) DISTIN
CT 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
M_ID M_Company M_Name M_Price M_Mf_Date
MB001 SAMSUNG GALAXY 4500 2013-02-12
MB003 MOKIA N1100 2250 2011-04-15
MB004 MICROMAX UNITE3 4500 2016-10-17
MB005 SONY XPERIAM 7500 2017-11-20
MB006 OPPO SELFIEEX 8500 2010-08-21

TABLE: MOBILESTOCK
S_ID M_ID M_QTY M_SUPPLIER
S001 MB004 450 NEW VISION
S002 MB003 250 PRAVEEN GALLERY
S003 MB001 300 CLASSIC MOBILE STORE
S004 MB006 150 A-ONE MOBILES
S005 MB003 150 THE MOBILE
S006 MB006 50 MOBILE CENTRE

(i) Display the Mobile Company, 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;
(v) SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;
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
TID TNAME CITY HIREDATE SALARY
101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARH 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000

CID CNAME FEES STARTDATE TID


C201 AGDCA 12000 2018-07-02 103
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C204 DDTP 9000 2018-09-15 104
C205 DHN 20000 2018-08-01 101
C206 O LEVEL 18000 2019-07-25 105

(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 P K 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 M
4 Sangeeta 35 History 01/07/2015 40000 F
5 Rakesh 42 Mathematics 05/09/2007 25000 M
6 Shyam 50 History 27/06/2008 30000 M
7 Shiv Om 44 Computer Sc 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

Advantages-
Two or more computing devices connected to one another in order to exchange information or
share resources, form a computer network.
Share resources- Share Storage Share Software and hardware Security Back up and Roll back is easy

TYPES OF NETWORK-based on geographical spread


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

Switching Techniques

Packet Switching Message Switching Circuit Switching


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

Follows Store(RAM) and forward Each message is stored (usually on In circuit switching, data is not
technique hard drive) before being transmitted stored.
to the next switch.

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


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

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

Full Form of networking Terms

SSL- Secure Sockets IMAP-Internet FTP- File transfer WiFi-Wireless HTTPs- Hyper Text
Layer Message Access protocol Fidelity Transfer Protocol
Protocol Secure

WAP-Wireless VoIP- Voice Over SMTP-Simple Mail TDMA- Time DIvision CDMA- Code Division
Application Protocol Internet Protocol Transfer Protocol Multiple Access Multiple Access

TCP/IP-Transmission LAN- Local WAN- Wide Area MAN- Metropolitan PAN-Personal Area
Control Area Network Network Area Network Network
Protocol/Internet
Protocol

IR-Infrared IRC-Internet Relay GPRS-General Packet GSM- Global System e-mail-Electronic


Chat Radio Service for Mobile Mail
Communications

ASP-Active Server JSP-Java XML-eXtensible HTML-Hyper Text Bps- Bytes per


Pages Server/Script Pages Markup Language Markup Language Second

bps- bits per second ARPAnet- Advanced POP- Post office nfc- Near field VoIP-voice over
Research Project Protocol Communication internet protocol
Agency Network

Network Devices

Hub-connects multiple computers Switch- connects multiple Modem-used to access the


in a single LAN network. It computers in a single LAN internet , converts analog
distributes the bandwidth equally network but doesn’t distribute signal into digital and vice
to all computers equal bandwidth to all. It is versa.
intelligent hub. It sends
information only to intended (modulation/demodulation)
computer/node
Router- to receive packets from Gateway-connects dissimilar Repeater-(amplify )
one connected network and pass networks regenerates the signal and
them to second connected forwards these signal with
network.(for routing) more power.

Connects multiple networks with Bridge- connects similar


different protocols networks

Network Protocols

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

IMAP-for receiving SMTP-for sending mails VoIP-for video calling or voice TCP/IP-for
mails call using internet connection communication

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


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

Networking-1 marks Questions

is a network Give one example of each – Guided


device that connects dissimilar media and Unguided media
networks. Ans Guided – Twisted pair, Coaxial
Ans Gateway Cable, Optical Fiber (any one)
Unguided – Radio waves, Satellite, Micro
Waves (any one)
Ravi received a mail from IRS is a specific condition in a
department on clicking “Click –Here”, network when more data packets are
he was taken to a site designed to coming to network device than they
imitate an official looking website, can handle and process at a time.
such as IRS.gov. He uploaded some Ans Network Congestion
important information on it
Ans Phishing
Name the protocol that is used to Raj is a social worker, one day he
transfer file from one computer to noticed someone is writing insulting or
another. demeaning comments on his post. What
Ans FTP kind of Cybercrime Raj is facing?
Ans Identity Theft
Name the Transmission media Write the expanded form of GPRS?
which consists of an inner copper Ans General Packet Radio Service
core and a second conducting (GPRS)
outer sheath.
Ans Co-axial cable
Define Bandwidth? --------------describe the maximum
Ans a band of frequencies data transfer rate of a network or
used for sending electronic Internet connection.
signals Ans Bandwidth
Mahesh wants to transfer data within What is a Firewall in Computer
a city at very high speed. Write the Network? A). The physical
wired transmission medium and type boundary of Network
of network. Ans Wired transmission B). An operating System of
medium – Optical fiber cable Computer 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 Name the wired transmission media
cyber criminals? which has a higher bandwidth. Ans
a)Unauthorized account access Optical 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 Arrange the following media in
connects dissimilar networks. decreasing order 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 Website incharge KABIR of a school is
login. handling downloading/uploading
Ans TELNET 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 Give the full form of the following:
a network communication? (a) URL (b)
Ans Data encryption is the process of TDMA Ans
converting a message into an (a) URL – Uniform Resource
unmeaningful form. It is used to Locator (b)TDMA – Time Division
ensure data security while Multiple Access
communication.
Differentiate between Bps & bps. Identify the Guided and Un-Guided
Ans Bps is Byte per second and Transmission Media out of the
bps is bits per second which following: Satellite, Twisted Pair
tells the variation in data Cable, Optical Fiber, Infra- Red waves
transmission speed. Ans Guided: Twisted Pair Cable,
Optical Fiber Unguided: Satellite,
Infra-Red waves
Protocol is used to send email ………… Your friend Sunita complaints that
Ans SMTP (simple mail transfer protocol) somebody 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 Write the expanded
suitable for connecting to desert form of VPN. Ans Virtual
areas. Ans microwave Private Network

Rearrange the following terms in What is Telnet?


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

State whether the following statements Expand the term a). XML b). SMS
is True or False. When two entities are
communicating and do not want a third Ans
party to listen, this situation is defined (a) XML-Extensible Markup Language
as secure communication. (b) SMS–Short Messaging Service
Ans True
Name two web scripting languages Which of these is not an
Ans VBScript, JavaScript, ASP, PHP, example of unguided media?
PERL 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
Ans HTML (Hyper Text Markup and download files on internet.
Language) is used to create Hypertext Ans FTP or HTTP
documents (web pages) for websites.

Your friend kaushal complaints that Which is not a network


somebody accessed his mobile device topology? a)BUS b).
remotely and deleted the important STAR c). LANd). RING
files. Also he claims that the password Ans (c) LAN
of his social media accounts were
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 Name the protocol that is used to send
harmless but actually performs emails.
malicious functions such as deleting Ans SMTP
or damaging files.
(a) WORM (b)Virus
(c) Trojan Horse
(d) Ma
lwar e
Ans (c) Trojan Horse
Your friend Ranjana complaints that Name The transmission media
somebody has created a fake profile best suitable for connecting to
on Facebook and defaming her hilly areas Ans
character with abusive comments and microwave/radiowave
pictures. Identify the type of
cybercrime for these situations.
Ans Cyber Stalking / Identity theft
Write the expanded form of TCP/IP stands for-
Wi- Fi. Ans Wireless-Fidelity Ans Transmission Control
Protocol/Internet Protocol
An attack that encrypts files in a Write the name of topology in which
computer and only gets decrypted all the nodes are connected through
after paying money to the attacker. a single 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 In a Multi-National company Mr. A
transfer of hypertext content over the steals Mr. B’s intellectual work and
web. representing it as A’s own work without
Ans HTTP 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
Unguided Transmission Media in and GSM Ans
networking. Ans Guided Media: Twisted WiFi : Wireless Fidelity
pair Cable, Coaxial Cable , Fiber Optic GSM : Global System for
Cable Mobile Communication
Unguided Media: Microwave /
Radio wave , Infrared, Satellite
Rearrange the following terms in Name the protocol that is used to
increasing order of data transfer rates. transfer files.
Gbps, Mbps, Tbps, Kbps, bps Ans FTP

Ans bps, Kbps, Mbps, Gbps,

Tbps

Your friend’s mother receives an e- Name the fastest available


mail to access the additional services transmission media.
of bank at zero cost from some agency Ans Optical Fibre cable( OFC)
asking her to fill her 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
Ans order of data transfer rates.
Local Area Network UTP CAT - 5 , UTP CAT – 6, IR,
Bluetooth, OFC
. Metropolitan Area Ans IR, Bluetooth, UTP CAT - 5, UTP CAT –
Network 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( ): #def
x = input(“Enter a number”) x = int(input(“Enter a number”)) #int
if (x % 2 = 0) : if (x % 2 == 0) : # ==
print (“even number”) 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 number") x = int(input(“Enter a number”)) #int()
if x % 2 =0: if x % 2 =0:
print (x, "is even") print (x, "is even")
elseif x<0: elif x<0: #elif
print (x, "should be positive") print (x, "should be positive")
else; else: # colon
print (x, "is odd") 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 capital
print (K*4) print(K*4)
Else: else: #else ‘e’ small
print (K+3) print(K+3)
for name in [‘Shruthi’,’Priya’,’Pradeep’,’Vaishnav’): for name in [‘Shruthi’,’Priya’,’Pradeep’,’Vaishnav’]:
print name #]
if name[0] = ‘P’ print (name) # ()
break if name[0] == ‘P’ # ==
else: break
print(‘Over”) else:
print(“Done”) print(“Over”) # ” “
print(“Done”)

Y=integer(input(“Enter 1 or 10”)) Y=int(input(“Enter 1 or 10”)) #int


if Y==10 if Y==10: #colon
for Y in range(1,11): for Y in range(1,11): #indentation
print(Y) print(Y) #indentation
else: else:
for m in range(5,0,-1): for m in range(5,0,-1):
print(thank you) print(“thank you”) # “ “ missing
p=30 p=30
for c in range(0,p) for c in range(0,p):
If c%4==0: if c%4==0: #if
print (c*4) print (c*4)
Elseif c%5==0: elif c%5==0: #elif
print (c+3) print (c+3)
else else: #colon
print(c+10) print(c+10)
x=int(“Enter value for x:”) x=int(input((“Enter value for x:”) ) #input
for y in range[0,11]: for y in range(0,11): #round brackets
if x=y if x==y : #== and colon
print(x+y) print(x+y)
else: else:
Print x-y print (x-y) #print()
Def func(a): def func(a): #def
for i in (0,a): s=m=n=0 #local variable
if i%2 =0: for i in (0,a):
s=s+1 if i%2==0:
else if i%5= =0 s=s+1
m=m+2 elif i%5= =0: #elif and colon
else: m=m+2
n=n+i else:
print(s,m,n) n=n+i
func(15) print(s,m,n) #indentation
func(15)
Value=30 Value=30 #val=30
for val in range(0,Value) for val in range(0,Value): #colon
If val%4==0: If val%4==0:
print (val*4) print (val*4)
Elseif val%5==0: elif val%5==0: #elif
print (val+3) print (val+3)
Else Else : #else and colon
print(val+10) print(val+10)
Num = int(input("Number:") Num = int(input("Number:")) # )
s=0 s=0
for i in range(1,Num,3) for i in range(1,Num,3): #colon
s+=1 s+=1
if i%2=0: if i%2==0: # ==
print(i*2) print(i*2)
Else else: # else and colon
print(i*3) print(i*3)
print (s) print (s)
DEF execmain(): def execmain(): #def
x = int( input("Enter a number:")) x = int( input("Enter a
if (abs(x) = x): number:")) if (abs(x)== x):# ==
print"You entered a positive number" print("You entered a positive number") #()
else: else:
x=*-1 x*=-1 # *=
print("Number made positive :",x) print("Number made positive :",x)
execmain() execmain()
a = 200 a = 200
b = 33 b = 33
if b > a if b > a: # colon
Print("b is greater than a") print("b is greater than a") # small p of print()
elseif a == b: elif a == b: #elif
print(a and b are equal) print(“a and b are equal”) # “ “
else: else:
print("a is greater than b") print("a is greater than b")
x=int("enter value of x:") x=int(input("enter value of x:")) #input()
for i in range[0,10]: for i in range(0,10): # ()
if x=y if x==y: # == and colon
print("they are equal") print("they are equal")
else: else:
Print("they are unequal") print("they are unequal")

a,b=0 a=b=0 # = in place of ,


if(a=b) if(a==b): # == and colon
a+b=c c=a+b # c=a+b
print(z) print(c) # c

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


ar=0 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=250 fee=250
0=i i=0 # i=0
while fee=<2000: while fee<=2000: # <=
if fee<=750: if fee<=750:
print(fee) print(fee)
fee=+250 fee=+250 # +=
else: else:
print(("fee*i) print(fee*i) # ( and “
i=i+1 i=i+1
fee=Fee+250 fee=fee+250 # fee

10=step step=10 # variable on left side


for e in the range(0,step): for e in range(0,step): # extra 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 Blog str="Welcome to my Blog” # missing “
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 range


if(i==5) if(i==5): # colon
break: break # no colon
else: else:
print(i) print(i)
continue continue

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


if a%2=0: if a%2==0: # ==
print("Even number) print("Even number)
Else else: # else and colon
print("Odd number") print("Odd number")

a=int(Input("enter any number")) a=int(input("enter any number")) # input


b=int(input("enter any b=int(input("enter any number"))
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 number")} a=int(input("Enter any number")) # ()


for i IN range(1:11): for i in range(1:11): # in
print(a,"*",i,"=",a*i) print(a,"*",i,"=",a*i) #indentation

def sum(c) def sum(c): # colon


s=0 s=0 #indentation
for i in Range(1,c+1) for i in range(1,c+1): # range and colon
s=s+i s=s+i # indentation
return s return s
print(sum(5) print(sum(5)) # ) and indentation

Print("Anuj") print("Anuj") # print


For i in range(2,4): for i in range(2,4): # for
for i in for i in range(3,9): #range and indentation
Range(3,9): def def title(): #colon
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 range(1,N,2) for i in range(1,N,2): # colon
s+=1 s+=1
if i%2=0: if i%2==0: # == and colon
print("i"*2) print("i"*2)
else: else:
print("i"*3) print("i"*3)
print[S] 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: # colon
break break
else: else:
print("A") print("A") #indentation

a={'6': "Amit", '2' : "Sunil" : '3' : a={'6': "Amit", '2' : "Sunil" ,'3' : "Naina"} # comma
"Naina"} for i in a: for i in a:
if(int(i)%3=0 if(int(i)%3==0: # == and colon
print(a(i)) print(a(i)) #indentation

30=max max=30
For N in range(0,max) for N in range(0,max) : # for and colon
IF n%3==0: if N%3==0: # if and capital N
print(N*3) print(N*3)
ELSE: else: #else
print(N+3) print(N+3)

def checksum: def checksum(): # missing


x=input(“enter a () x=int(input(“enter a
number”) if(x%2==0): number”)) #int() if(x
for i %2==0):
range(2*x for i in range(2*x): #missing
): print(i) in print(i)
loop else: else: #else
print(“#”) print(“#”)
Salary=4000, Salary=4000,
Bonus==8900 Bonus=8900 # single =
For I in range(0,6) For I in range(0,6) : # colon
If Bonus>=5000 If Bonus>=5000: #colon
Print(Salary+400) print(Salary+400) # small p of print
Else if Bonus<5000 elif Bonus<5000: # elif and colon
print(Salary+500) print(Salary+500)
else: else:
Print(“ no increment”) Print(“ no increment”)

Find and write the output of the following Python codes:


def makenew(mystr): s="welcome2kv"
newstr = " " n = len(s)
count = 0 m=""
for i in mystr: for i in range(0, n):
if count%2 !=0: if (s[i] >= 'a' and s[i] <= 'm'):
newstr = newstr+str(count) m = m +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 = newstr+i else:
count +=1 m = m +'#'
newstr = newstr+mystr[:1] print(m)
print("The new string is :", newstr)
Ans vELCcME#Kk
#function calling
makenew("sTUdeNT")

Ans: The new string is : S1U3E5Ts


def display(s): def change(s):
l = len(s) d = {"UPPER" : 0, "LOWER" : 0 }
m="" for c in s:
for i in range(0,l): if c.isupper():
if s[i].isupper(): d["UPPER"] += 1
m=m+s[i].lower() elif c.islower():
elif s[i].isalpha(): d["LOWER"] += 1
m=m+s[i].upper() else:
elif s[i].isdigit(): pass
m=m+"$" print("Upper case count :", d["UPPER"])
else: print("Lower case count :",
m=m+"*" d["LOWER"])
print(m)
#function calling
display("[email protected]") change("School Days are Happy")

Ans exam$$*CBSE*COM Ans


Upper case count : 3
Lower case count : 15
def Convert(Old): def Show(str):
l=len(Old) m=""
New=”” for i in range(0,len(str)):
for i in range(0,1): if(str[i].isupper()):
if Old[i].isupper(): m=m+str[i].lower()
New=New+Old[i].lower() elif str[i].islower():
elif Old[i].islower(): m=m+str[i].upper()
New=New+Old[i].upper() else: if i%2==0:
elif Old[i].isdigit(): m=m+str[i-1]
New=New+”*” else:
else: m=m+"#"
New=New+”%” print(m)
return New
Show('HappyBirthday')
Older = “InDIa@2020”
Newer=Convert(Older) Ans
print(“New string is: “,Newer) hAPPYbIRTHDAY

Ans New string is : iNdiA%****

def replaceV(st): def swap(P ,Q):


newstr = '' “ P,Q=Q,P
for character in st: print( P,"#",Q)
if character in 'aeiouAEIOU': return (P)
newstr += '*'
else: R=100
newstr += character S=200
return newstr R=swap(R,S)
print(R,"#",S)
st = “Hello how are you”
st1 = replaceV(st) Ans
print("The original String is:", st) 200 # 100
print("The modified String is:", 200 # 200
st1)

Ans
The original String is: Hello how are you
The modified String is: H*ll* h*w *r* y**
def Display(str): Text="Welcome Python"
m="" L=len(Text)
for i in range(0,len(str)): ntext=""
if(str[i].isupper()): for i in range (0,L):
m=m+str[i].lower() if Text[i].isupper():
elif str[i].islower(): ntext=ntext+Text[i].lower()
m=m+str[i].upper() elif Text[i].isalpha():
else: ntext=ntext+Text[i].upper()
if i%2==0: else:
m=m+str[i-1] ntext=ntext+"!!"
else: print (ntext)
m=m+"#"
print(m) Ans wELCOME!!
pYTHON
Display('[email protected]')

Ans fUN#pYTHONn#
def mainu(): s=”United Nations”
Moves=[11, 22, 33, 44] for i in range(len(s)):
Queen=Moves if i%2==0:
Moves[2]+=22 print(s[i],end= ‘ ‘)
L=len(Moves) elif s[i]>=’a’ and s[i]<=’z’:
for i in range (L): print(‘*’, end= ‘ ‘)
print(Queen[L-i-1], "#", Moves [i]) elif s[i]>=’A’ and s[i] <=’Z’:
print(s[i:],end= ‘ ‘)
#function calling
mainu()
Ans
Ans U * i * e * Nations a * i * n *
44 # 11
55 # 22
22 # 55
11 # 44
tup=(10,30,15,9) L =["X",20,"Y",10,"Z",30]
s=1 CNT = 0
t=0 ST = ""
for i in range(s,4): INC = 0
t=t+tup[i] for C in range(1,6,2):
print(i,":",t) CNT= CNT + C
t=t+tup[0]*10 ST= ST + L[C-1] + "@"
print(t) INC = INC + L[C]
Ans print(CNT, INC, ST)
1:
30 Ans
130 1 20 X@
2 : 145 4 30 X@Y@
245 9 60 X@Y@Z@
3 : 254
354

def increment(n): def display(x=2,y=3):


n.append([4]) x=x+y
return n y += 2
print(x,y)
L=[1,2,3] display()
M=increment(L) display(5,1)
print(L, M) display(9)

Ans [1, 2, 3, [4]] [1, 2, 3, [4]] Ans


55
63
12 5
mystr=”cs2study@” data=[‘d’,’o’,’ ‘,’k’,’t’,’ ‘,’@’,’ ‘,’1’,’2’,’3’,’ ‘,’!’]
newstr = " " for i in range(len(data)-1):
count = 0 if(data[i].isupper()):
for i in mystr: data[i]=data[i].lower()
if count%2 !=0: elif(data[i].isspace()):
newstr = newstr+str(count) data[i]=data[i+1]
else: print (data)
if islower(i):
newstr = newstr+upper(i)
else:
newstr = newstr+i Ans
count +=1 ['d', 'o', 'k', 'k', 't', '@', '@', '1', '1', '2', '3', '!', '!']
newstr = newstr+mystr[:1]
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 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 minimum values that can be assigned specify the maximum values that can be assigned
to each of the variables BEGIN and LAST. to each of the variables FROM and TO.
import random import random AR=[20,30,40,50,60,70]
VALUES = [10, 20, 30, 40, 50, 60, 70, 80] FROM=random.randint(1,3)
BEGIN = random.randint (1, 3) TO=random.randint(2,4)
LAST = random.randint(2, 4) for K in range(FROM,TO):
for I in range (BEGIN, LAST+1): print (AR[K],end=”#“)
print (VALUES[I], end = "-") (i)10#40#70# (ii)30#40#50#
(i) 30-40-50- (ii) 10-20-30-40- (iii)50#60#70# (iv)40#50#70#
(iii) 30-40-50-60- (iv) 30-40-50-60-70-
Ans Ans
OUTPUT – (i) 30-40-50- Maximum value of FROM = 3
Minimum value of BEGIN: 1 Maximum value of TO = 4
Minimum value of LAST: 2 (ii) 30#40#50#

Consider the following code: import math import Consider the following code and find out the
random possible output(s) from the options given below.
print(str(int(math.pow(random.randint(2,4),2)))) Also write the least and highest value that can
print(str(int(math.pow(random.randint(2,4),2)))) 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) , end =
given four choices? ‘ ‘) print(10 + r.randint(10,15) , end
i) 2 3 4 ii) 9 4 4 = ‘ ‘) print(10 + r.randint(10,15))
iii)16 16 16 iv)2 4 9 i) 25 25 25 21 iii) 23 22 25 20
ii) 23 27 22 20 iv) 21 25 20 24
Ans
Possible outputs : ii) , iii) Ans
randint will generate an integer between 2 to Possible outputs :
4 which is then raised to power 2, so possible i), iii) and iv)
outcomes can be 4,9 or 16 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
assigned to each of the variables BEG and END. to each of the variables Lower and Upper. import
random
import random AR=[20,30,40,50,60,70]
heights=[10,20,30,40,50] Lower =random.randint(1,4)
beg=random.randint(0,2) Upper =random.randint(2,5)
end=random.randint(2,4) for K in range(Lower, Upper +1):
for x in range(beg,end): print (AR[K],end=”#“)
print(heights[x],end=’@’)
(a) 30 @ (b) 10@20@30@40@50@ (i) 10#40#70# (ii) 30#40#50#
(c) 20@30 (d) 40@30@ (iii) 50#60#70# (iv) 40#50#70#
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 of displayed on screen at the time of execution of
the program from the following code? Import the program from the following code. Select
random which option/s is/are correct
Ar=[20,30,40,50,60,70] import random
From print(random.randint(15,25) , end='
=random.randint(1,3) ')
To=random.randint(2,4) print((100) + random.randint(15,25) , end = ' ' )
for k in range(From,To+1): print((100) -random.randint(15,25) , end = ' ' )
print(ar[k],end=”#”) print((100) *random.randint(15,25) )
(i) 10#40#70# (iii) 50#60#70#
(ii) 30#40#50# (iv) 40#50#70# (i) 15 122 84 2500 (ii) 21 120 76 1500
(iii) 105 107 105 1800 (iv) 110 105 105 1900
Ans
(ii) 30#40#50# Ans
(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 of displayed on screen at the time of execution of
the program from the following code? Also the program from the following code?
specify the minimum and maximum values that
can be assigned to the variable End . import random
import random X= random.random()
Colours = ["VIOLET","INDIGO","BLUE","GREEN", Y=
"YELLOW","ORANGE","RED"] random.randint(0,4)
End = randrange(2)+3 print(int(),":",Y+int(X))
Begin = randrange(End)+1
for i in range(Begin,End): (i) 0:5 (ii) 0:3
print(Colours[i],end="&")
(iii) 0:0 (iv) 2:5
(i) INDIGO&BLUE&GREEN&
(ii) VIOLET&INDIGO&BLUE&
(iii) BLUE&GREEN&YELLOW& Ans
(iv) GREEN&YELLOW&ORANGE& (ii) and (iii)

Ans
(i) INDIGO&BLUE&GREEN&
Minimum Value of End = 3
Maximum Value of End = 4
import random (e) Observe the following Python code and find
x=random.random() out which of the given options (i) to (iv) are the
y=random.randint(0,4) expected correct output(s). Also, assign
print(int(x),":",y+int(x)) maximum and minimum values that can be
Choose the possible output(s) from the given assigned to the variable ‘Go’.
options. Also write the least and highest value
that may be generated. import random
(i) 0:0 ii.) 1:6 X=[100,75,10,125]
iii.) 2:4 iv.) 0:3 Go =random.randint(0,3)
Ans min value of x 0.01 and max value will be for i in range(Go):
0.99899 print(X[i],"$$")
Min value of y 0 and max value will be
4 Corrected options will be (i) and (iv) (i) 100$$ (ii) 100$$
75$$ 99$$
10$$
(ii) 150$$ (iv) 125$$
100$$ 10$$
Ans
(i) 100 $$
75$$
10$$

import random import random


pick=random.randint(0,3) p='my program'
city=["delhi","mumbai","chennai","kolkata"] i=0
for i in city: while p[i]!='y':
for j in range(1,pick): t=random.randint(0,3)+5
print(i,end=" ") print(p[t],'-')
i=i+1
Ans
delhi mumbai chennai Kolkata Ans
g –O- r- a-
delhi delhi mumbai mumbai chennai order can vary but print only these 4
chennai kolkata kolkata characters

import random import random


sel=random.randint(0,3) picker=random.randint(0,3)
animal=["deer","monkey","cow","kangaroo"] color=["blue","pink","green","red"]
for a in animal: for i in color:
for aa in range(1,sel): for j in range(1,picker):
print(a, end="") print(i, end="")
print() print()

Ans Ans
deer blue
monkey pink
cow green
kangaroo red

or or

deer blue
deer blue
monkey pink
monkey pink
cow green
cow green
kangaroo red
kangaroo red

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