CS Unitwise Case Based Questions
CS Unitwise Case Based Questions
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 Explain Keyword .
Ans Keywords are the reserve words/pre-defined words/special words of python
Keyword Identifier
These are system defined words These are user defined words
These can have only letters these can have letters, digits and a symbols underscore.
These are reserved These are not reserved
For example : if, else, elif etc. For example : chess, _ch, etc.
Question: What are literals in Python ? How many types of literals are allowed in Python ?
Answer:
Literals mean constants i.e. the data items that never change value during a program run. Python allow five types of literals :
String literals Numeric literals, Boolean literals, Special literal (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
arithmetic +,-,/,*,%,**,//
bitwise &, ^, |
Identity is, is not
(these are used to compare the memory locations of two objects). These can be used in place of
== (is) and != (is not)
Relational >,<,>=,<=,==,!=
(comparison ) (these operators are used to compare the values)
logical and, or, not
(these are used to perform logical operations on the given two variables or values.)
shift <<, >>
Assignment =
(these are used to assign values)
Membership in, not in
(these operators used to validate whether a value is found within a sequence such as such as
strings, lists, or tuples.)
arithmetic- +=, -=, //=, **=, *=, /=
assignment
Write the full form of IDLE Which of the following is not an assignment operator?
Ans integrated development learning environment
i.) **= ii.) /= iii.) == iv.)%=
Ans (iii) ==
Write the type of tokens from the following. Find the correct identifiers out of the following, which can be
used for naming Variable, Constants or Functions in a 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.
Parentheses|Exponentiation|Multiplication|Division|Addition|Subtraction
Operators Meaning
() Parentheses
** Exponent
*,/, //, % Multiplication, Division, Floor, Division, Modulus
3. An escape sequence always starts with backslash followed by one or more special characters.
4. Escape Sequences must be enclosed in single quotes or in double
quotes. few Escape sequences are:
Question : What will be the size of the following constants : “\a”. “\a”, “Manoj\’s”, ‘\”, “XY\ YZ”
Answer:
‘\a’. “\a” “Manoj\’s” “\” “XY\
YZ
size is 1 as 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
DATA TYPES
Data types are used to identify the type of data and set of valid operations which can be performed on it.
Mutable is behaving like pass by reference Immutable is behaving like pass by value
Mutable objects: list, dictionary Immutable objects: int, float, complex,
string, tuple
Everything in Python is an object ,and every objects in Python can be either mutable or
immutable.
>>>x=10
>>>id(x)
Q Which function is used to find the data type of an variable
Ans type() function is used to find the data type of any variable,object or function.
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.
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
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
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
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
+ (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”)
here, 'a', 'b', 'c', 'd', 'e' are the keys & 1,2,3,4,5 are the values
• 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.
Module Package
A module is a single file (or files) that are A package is a collection of modules in
imported under one import and used. directories that give a package hierarchy.
No _init_.py is required in module In a package _init_.py file should be included
Which module is used for working with CSV files in Python? Ans csv
Name the built-in function / method that is used to return the lengthof the object. Ans len()
Name the function/method required for
(a) Finding second occurrence of m in madam. Ans (a) index or find()
(b) Get the position of an item in the list Ans (b) find() or index ()
Observe the following Python code and write the name(s) of the header file(s), which will be
essentially required to run in a Python compiler.
X=randint(1,3)
Y=pow(X,3)
print(“hello”.upper()) Ans random,math,string
Name the built-in mathematical function / method that is used to return square root of a number
Ans sqrt()
Name the Python library module(s) which needs to be imported to run the following program:
print(sqrt(random.randint(1,16)))
Ans math,random
Which of the following function is used to write data in binary mode?
a) write ( ) b) output ( ) c) dump ( ) d) send ( ) Ans (c) dump
Function
A function is a subprogram that acts on data and often returns a
value ADVANTAGES
Types of Functions
Built –in functions Functions defined in the modules User defined functions
(Pre-defined functions) (function using (defined by the 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
x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)
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)
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
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.
syntax:
with open(<file_name>, <access_mode>) as
file_object/file_handler
Q Name two important functions of CSV module which are used for reading and writing.
csv.reader() returns a reader object which iterates over lines of a CSV file
csv.writer() returns a writer object that converts the user's data into a delimited string. This string can later be used to write
into CSV files using the writerow() or the writerows() function.
r+ and w+
r+ w+
Opens a file for reading and writing, placing 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
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
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()
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
‘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() writelines()
write() function write a single string at a time writelines() methods can be used to write a
sequence of strings
PICKLING UNPICKLING
Pickling is the process whereby a Python object 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.
or
f=open(“firewall.txt")
for i in range(3):
print(f.readline())
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 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.
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()
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.
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.
(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)
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);
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)
);
WHERE clause
Where clause is used to specify condition while retrieving data from table. Where clause is used mostly with
Select, Update and Delete query. If condition specified by where clause is true then only the result from table is returned.
Syntax
SELECT column-name1, column-name2, column-name3, column-nameN
from table-name
WHERE [condition];
Relational Operator (comparison ) IN- used to show the records from a LIST
>, <, >=, <=, <> (not equal to ) =( equal to )
Display all records of those employees
whose belong to mumbai,delhi,jaipur
only
HAVING Clause
It is used to give more precise condition for a statement. It is used to mention condition in Group based
SQL functions, just like WHERE clause.
Syntax:
select column_name, function(column_name)
FROM table_name
WHERE column_name condition
GROUP BY column_name
HAVING function(column_name) condition;
Consider the following Sale table.
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 clause is used mostly with Having clause is used only with group by clause
Select, Update and Delete command/query
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.
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
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 :
The attributes of WORKER are as follows: WORKER_ID - character of size 3 FIRST_NAME – character of size 10
LAST_NAME– character of size 10 SALARY - numeric
JOINING_DATE – Date
DEPARTMENT – character of size 10
WORKER_I D FIRST_NA ME LAST_NAM E SALARY JOINING_D ATE DEPARTM ENT
d) Karan wants to remove all the data from table WORKER from the database
Department. Which command will he use from the following:
i) DELETE FROM WORKER;
ii) DROP TABLE WORKER;
iii) DROP DATABASE Department;
iv) DELETE * FROM WORKER;
e) Write a query to display the Structure of the table WORKER, i.e. name of
the attribute and their respective data types.
Ans
Observe the following table and answer the question (a) to (e) (Any 04)
TABLE: VISITOR
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
1
b) DROP TABLE VISITOR;
TABLE: ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD
a)
i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;
ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE DESIGNATION = ‘COORDINATOR’
AND SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
Ans
i) ENGLISH 51 PHYSICS 76 MATHS 24 CHEMISTRY 27
ii) PRIYA RAI FEMALE LISA ANAND FEMALE
iii)4
b)
i) To decrease period by 10% of the teachers of English subject.
ii) To display TEACHERNAME, CODE and DESIGNATION from tables SCHOOL and ADMIN whose gender is male.
iii) To Display number of teachers in each subject.
iv) To display details of all teachers who have joined the school after 01/01/1999 in descending order of experience.
v) Delete all the entries of those teachers whose experience is less than 10 years in SCHOOL table.
Ans
Relation : Employee
id Name Designation Sal
101 Naresh Clerk 32000
102 Ajay Manager 42500
103 Manisha Clerk 31500
104 Komal Advisor 32150
105 Varun Manager 42000
106 NULL Clerk 32500
Ans
i) id
ii) Ans. select avg(sal) from employee;
iii) Ans. select designation, count(*) from employee group by designation;
iv) Ans. select designation, count(*), sum(sal) from employee group by designation having count(*)>1;
v) Degree : 4 Cardinality : 6
Write the outputs of the SQL queries (i) to (iii) based on the relation
COURSE CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C204 DDTP 9000 2019-09-15 104
C205 DHN 20000 2019-08-01 101
C206 O LEVEL 18000 2018-07-25 105
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
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
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
(a)
(i) SELECT DISTINCT(CITY) FROM TRAINER WHERE SALARY>80000;
(ii) SELECT TID, COUNT(*), MAX(FEES) FROM COURSE GROUP BY TID HAVING COUNT(*)>1;
(iii) SELECT T.TNAME, C.CNAME FROM TRAINER T, COURSE C WHERE T.TID=C.TID AND T.FEES
Ans (a)
(i)
MUMBAI
DELHI
CHANDIGARH
CHENNAI
(ii)
TID COUNT(*) MAX(FEES)
101 2 20000
(iii)
T.TNAME C.CNAME
MEENAKSHI DDTP
(b)
(i) Display all details of Trainers who are living in city CHENNAI.
(ii) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(iii) Count & Display the number of Trainers in each city.
(iv) Display the Course details which have Fees more than 12000 and name ends with ‘A’.
(v) Display the Trainer Name & Course Name from both tables where Course Fees is less than 10000.
Ans
(i) SELECT * FROM TRAINER WHERE CITY IS “CHENNAI”;
(ii) SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE DESC;
(iii) SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;
(iv) SELECT * FROM COURSE WHERE FEES>12000 AND CNAME LIKE ‘%A’;
(v) SELECT T.TNAME, C.CNAME FROM TRAINER T, COURSE C WHERE T.TID=C.CID AND C.FEES;
Modern Public School is maintaining fees records of students. The database administrator Aman decided that- • Name
of the database -School
• Name of the table – Fees
• The attributes of Fees are as follows:
Rollno - numeric Name – character of size 20
Class - character of size 20
Fees – Numeric
Qtr – Numeric
(i) Identify the attribute best suitable to be declared as a primary key
(ii) Write the degree of the table.
(iii) Insert the following data into the attributes Rollno, Name, Class, Fees and Qtr in fees table.
(iv) Aman want to remove the table Fees table from the database School. Which command will he use from
the following:
a) DELETE FROM Fees;
b) DROP TABLE Fees;
c) DROP DATABASE Fees;
d) DELETE Fees FROM Fees;
(v) Now Aman wants to display the structure of the table Fees, i.e, name of the attributes and their respective
data types that he has used in the table. Write the query to display the same.
Ans
i)Primary Key – Rollno
ii)Degree of table= 5
iii)Insert into fees values(101,’Aman’,’XII’,5000);
iv)DELETE FROM Fees
v)Describe Fees
Consider the table TEACHER given below. Write commands in SQL for (i) to (iii)
TABLE: TEACHER
ID Name Department Hiredate Category Gender Salary
1 Taniya SocialStudies 03/17/1994 TGT F 25000
2 Abhishek Art 02/12/1990 PRT M 20000
3 Sanjana English 05/16/1980 PGT F 30000
4 Vishwajeet English 10/16/1989 TGT M 25000
5 Aman Hindi 08/1/1990 PRT F 22000
6 Pritam Math 03/17/1980 PRT F 21000
7 RajKumar Science 09/2/1994 TGT M 27000
8 Sital Math 11/17/1980 TGT F 24500
i. To display all information about teachers of Female PGT Teachers.
ii. To list names, departments and date of hiring of all the teachers in descending order of date of joining.
iii. To count the number of teachers and sum of their salary department
wise Ans
Write SQL commands for the queries (i) to (iii) and output for (iv) & (v) based on a table COMPANY and CUSTOMER .
TABLE:COMPANY
CID NAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE
666 DELL DELHI LAPTOP
TABLE:CUSTOMER
CUSTID NAME PRICE QTY CID
101 Rohan Sharma 70000 20 222
102 Deepak Kumar 50000 10 666
103 Mohan Kumar 30000 5 111
104 SahilBansal 35000 3 333
105 NehaSoni 25000 7 444
106 SonalAggarwal 20000 5 333
107 Arjun Singh 50000 15 666
(i) To display those company name which are having price less than 30000.
(ii) To display the name of the companies in reverse alphabetical order.
(iii) To increase the price by 1000 for those customer whose name starts with ‘S’
(iv) SELECT PRODUCTNAME,CITY, PRICE FROM COMPANY,CUSTOMER WHERE COMPANY.CID=CUSTOMER.CID
AND PRODUCTNAME=”MOBILE”;
(v) SELECT AVG(QTY) FROM CUSTOMER WHERE NAME LIKE “%r%;
Ans
i) SELECT COMPANY.NAME FROM COMPANY,CUSTOMER WHERECOMPANY.CID = CUSTOMER.CID
AND CUSTOMER.PRICE<30000;
ii) SELECT NAME FROM COMPANY ORDER BY NAME DESC;
iii) UPADE CUSTOMER SET PRICE = PRICE+1000 WHERE NAME LIKE ‘S%’;
iv) PRODUCTNAME CITY PRICE
MOBILE MUMBAI 70000
MOBILE MUMBAI 25000
v) 12
ABC school is considering to maintain their student’s information using SQL to store the data. As a database
administrator Harendra has decided that:
Name of database : school
Name of table : student
Attributes of the table are as follow:
AdmissionNo-numeric
FirstName –character of size 30
LastName - character of size 20
DOB - date
Table student
AdmissionNo FirstName LastName DOB
012355 Rahul Singh 2005-05-16
012358 Mukesh Kumar 2004-09-15
012360 Pawan Verma 2004-03-03
012366 Mahesh Kumar 2003-06-08
012367 Raman Patel 2007-03-19
Ans
i. Degrre-4 Cardinility-5
ii. AdmissionNo
iii. insert into student values(012368,’Kamlesh’,’Sharma’,’2004-01-01’)
iv. Delete command
v. Drop table student
Table : Employee
EmployeeId Name Sales JobId
E1 Sumit Sinha 110000 102
E2 Vijay Singh Tomar 130000 101
E3 Ajay Rajpal 140000 103
E4 Mohit Kumar 125000 102
E5 Sailja Singh 145000 103
Table: Job
JobId JobTitle Salary
101 President 200000
102 Vice President 125000
103 Administrator Assistant 80000
104 Accounting Manager 70000
105 Accountant 65000
106 Sales Manager 80000
Give the output of following SQL statement:
(i) Select max(salary),min(salary) from job
(ii) Select Name,JobTitle, Sales from Employee,Job where Employee.JobId=Job.JobId and JobId in (101,102)
(iii) Select JobId, count(*) from Employee group by JobId;
Ans
i.200000, 65000
ii.
Vijay Singh Tomar President 130000
Sumit Sinha Vice President 110000
Mohit Kumar Vice President 125000
iii. 101 1
102 2
103 2
Write SQL Commands for the following queries based on the relations PRODUCT and CLIENT given below.
Table: Product
P_ID ProductName Manufacturer Price ExpiryDate
TP01 Talcum Powder LAK 40 2011-06-26
FW05 Face Wash ABC 45 2010-12-01
BS01 Bath Soap ABC 55 2010-09-10
SH06 Shampoo XYZ 120 2012-04-09
FW12 Face Wash XYZ 95 2010-08-15
Table: Client
C_ID ClientName City P_ID
1 Cosmetic Shop Delhi FW05
6 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty One Delhi FW05
16 Dreams Bengaluru TP01
14 Expressions Delhi NULL
(i) To display the ClientName and City of all Mumbai- and Delhi-based clients in Client table.
(ii) Increase the price of all the products in Product table by 10%.
(iii) To display the ProductName, Manufacturer, ExpiryDate of all the products that expired on or before ‘2010-12-31’.
(iv)To display C_ID, ClientName, City of all the clients (including the ones that have not purchased a product) and
their corresponding ProductName sold.
(v) To display productName, Manufacturer and ClientName of Mumbai City.
Ans
(i) select ClientName, City from Client where City = ‘Mumbai’ or City = ‘Delhi’;
(ii) update Product set Price = Price + 0.10 * Price;
(iii) select ProductName, Manufacturer, ExpiryDate from Product where ExpiryDate < = ‘2010-12-31’;
(iv) select C_ID, ClientName, City, ProductName from Client Left Join Product on Client. P_ID = Product.P_ID;
(v) select ProductName, Manufacturer, ClientName from product,client Where product.P_ID=Client.P_ID
and city=’Mumbai’;
A school KV is considering to maintain their eligible students’ for scholarship’s data using SQL to store the data. As a
database administer, Abhay has decided that :
• Name of the database - star
• Name of the table - student
• The attributes of student table as follows:
No. - numeric
Name – character of size 20
Stipend - numeric
Stream – character of size 20
AvgMark – numeric
Grade – character of size 1
Class – character of size 3
Table ‘student’
No. Name Stipend Stream AvgMark Grade Class
1 Karan 400.00 Medical 78.5 B 12B
2 Divakar 450.00 Commerce 89.2 A 11C
3 Divya 300.00 Commerce 68.6 C 12C
4 Arun 350.00 Humanities 73.1 B 12C
5 Sabina 500.00 Nonmedical 90.6 A 11A
6 John 400.00 Medical 75.4 B 12B
7 Robert 250.00 Humanities 64.4 C 11A
8 Rubina 450.00 Nonmedical 88.5 A 12A
9 Vikas 500.00 Nonmedical 92.0 A 12A
10 Mohan 300.00 Commerce 67.5 C 12C
Ans
(i) create table student(no integer,name char(20), stipend integer,stream char(20),avgmark integer, grade
char(1),class char(3));
(ii)No is Best suitable primary key
(iii) Degree = 7, cardinality = 10
(iv) select * from student order by name;
(v) update student set grade=’A’ where name=’Karan’;
Consider the following tables Sender and Recipient. Write SQL commands for the statements (a) to (c) and give the
outputs for SQL queries (d) to (e).
Table: Sender
SenderID SenderName SenderAddress Sendercity
ND01 R Jain 2, ABC Appls New Delhi
MU02 H Sinha 12 Newtown Mumbai
MU15 S Jha 27/A, Park Street Mumbai
ND50 T Prasad 122-K,SDA New Delhi
Table: Recipients
RecID SenderID RecName RecAddress recCity
KO05 ND01 R Bajpayee 5, Central Avenue Kolkata
ND08 MU02 S Mahajan 116, A-Vihar New Delhi
MU19 ND01 H Singh 2A, Andheri East Mumbai
MU32 MU15 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
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
(b)
i. To show all information about the teacher of History department.
ii. To list the names of female teachers who are in Mathematics department.
iii. To list the names of all teachers with their date of joining in ascending order.
iv. To display teacher’s name, salary, age for male teachers only.
v. To display name, bonus for each teacher where bonus is 10% of salary.
Ans
i. SELECT * FROM teacher WHERE department= “History”; 5
ii. SELECT name FROM teacher WHERE department= “Mathematics” AND gender= “F”;
iii. SELECT name FROM teacher ORDER BY date_of_join;
iv. SELECT name, salary, age FROM teacher WHERE gender=’M’;
v. SELECT name, salary*0.1 AS ‘Bonus’ FROM teacher;
An organization SoftSolutions is considering to maintain their employees records using SQL to store the data. As a
database administer, Murthy has decided that :
• Name of the database - DATASOFT
• Name of the table - HRDATA
• The attributes of HRDATA are as follows:
ECode – Numeric
EName – character of size 30
Desig – Character of size 15
Remn – numeric
Table: HRDATA
ECode EName Desig Remn
80001 Lokesh Programmer 50000
80004 Aradhana Manager 65000
80007 Jeevan Programmer 45000
80008 Arjun Admin 55000
80012 Priya Executive 35000
Ans
a) Ecode
b) Degree: 4, Cardinality: 5
c) Insert into HRDATA (Ecode, Ename, Remn) VALUES (80015, “Allen”, 43000)
d) DELETE FROM HRDATA WHERE ENAME LIKE “Jeevan”;
e) UPDATE HRDATA SET REMN = REMN * 1.10;
Consider the following tables: COMPANY and MODEL. Write the outputs of the SQL queries (a) to (c) based on the
relations COMPANY and MODEL given below:
Table: COMPANY
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
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
Ans
(a) ino
(b) Degree= 6 Cardinality =7
(c) UPDATE MEDICINE set iname= ‘Paracetamol Tablet’,mcode=25, qty=100 where ino = 1003 ;
(d) DROP TABLEMEDICINE;
(e) Select distinct mcode from MEDICINE;
Write SQL commands for the following queries (i) to (v) based on the relations Vehicle and Travel given below.
Table :Travel
NO NAME TDATE KM CODE NOP
101 Janish Kin 2015-11-13 200 101 32
103 Vedika Sahai 2016-04-21 100 103 45
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed Khan 2015-01-10 75 104 2
104 Raveena 2016-05-28 80 105 4
Table : Vehicle
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
i. To display NO, NAME, TDATE from the table Travel in descending order of NO.
ii. To display the NAME of all the travelers from the table Travel who are travelling by vehicle with code 101 or 102.
iii. To display the NO and NAME of those travelers from the table Travel who travelled between ‘2015-12-31’
and ‘2016-04-01’.
iv. To display the CODE,NAME,VTYPE from both the tables with distance travelled (km) less than 90 Km.
v. To display the NAME of those traveler whose name starts with the alphabet ‘R’.
Ans
To fetch some useful information from the database, can use either
fetchone() method to fetch single record
fetchall() method to fetch multiple values from a database table.
fetchmany()- to fetch limited no of records
Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
NETWORKING
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
Switching Techniques
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.
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
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
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
Layout-draw block diagram to show interconnecting blocks. Prefer the block with maximum devices as
main server to connect other blocks
Cost effective medium for internet- Broadband connection over telephone lines
Communication media for LAN-Ethernet/Co-axial cable for high speed within LAN
TOPOLOGIES
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.
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
Tbps
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
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)
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
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$$
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.
Ans 35#40#60#
Maximum Values: First: 40, Second: 45, Third: 60