537 Questions | Arranged by Topic & Subtopic
Generated by CBSE Question Paper Analyzer
State True or False.
"Identifiers are names used to identify a variable, function in a program".
Which of the following is a valid keyword in Python ?
(a) false
(b) return
(c) non_local
(d) none
Given the following Tuple
Tup= (10, 20, 30, 50)
Which of the following statements will result in an error ?
(a) print (Tup[0])
(b) Tup.insert (2,3)
(c) print (Tup[1:2])
(d) print(len(Tup) )
Consider the given expression :
5<10 and 12>7 or not 7>4
Which of the following will be the correct output, if the given expression is evaluated ?
(a) True
(b) False
(c) NONE
(d) NULL
Select the correct output of the code :
S= "Amrit Mahotsav @ 75"
A=S.partition (" ")
print (a)
(a) ('Amrit Mahotsav','@','75')
(b) ['Amrit', 'Mahotsav','@','75']
(c) ('Amrit', 'Mahotsav @ 75')
(d) ('Amrit', '', 'Mahotsav @ 75')
Fill in the blank.
________ function is used to arrange the elements of a list in ascending order.
(a) sort()
(b) arrange ()
(c) ascending()
(d) asort()
Which of the following operators will return either True or False ?
(a) +=
(b) !=
(c) =
(d) x=
Which of the following statement(s) would give an error after executing the following code ?
Stud={"Murugan":100, "Mithu":95} # Statement 1
print (Stud[95]) # Statement 2
Stud ["Murugan"]=99 # Statement 3
print (Stud.pop() ) # Statement 4
print (Stud) # Statement 5
(a) Statement 2
(b) Statement 3
(c) Statement 4
(d) Statements 2 and 4
What will the following expression be evaluated to in Python ?
print (4+3*5/3-5%2)
(a) 8.5
(b) 8.0
(c) 10.2
(d) 10.0
Which function returns the sum of all elements of a list ?
(a) count ()
(b) sum()
(c) total()
(d) add()
(a) Given is a Python list declaration :
Listofnames=["Ankit", "Ashish", "Rajan", "Rajat"]
Write the output of :
print (Listofnames [-1:-4:-1])
(b) Consider the following tuple declaration :
tupl=(10,20,30,40)
Write the output of :
print (tupl.index(20))
State True or False:
"Python is a high level language."
Which of the following is a valid identifier ?
(A) break
(B) global
(C) 2bin
(D) except
What will be the output of the following code ?
L=[10,20,30,40,50]
print(L[2:4])
(A) [20,30]
(B) [10,20,30,40]
(C) [30,40]
(D) [30,40,50]
Fill in the blank:
________ is the process of identifying and fixing errors in a program.
(A) Debugging
(B) Testing
(C) Executing
(D) Evaluating
Which of the following is an invalid datatype in Python ?
(A) Set
(B) None
(C) Integer
(D) String
Which of the following are the valid logical operators in Python ?
(A) and, or, not
(B) AND, OR, NOT
(C) &&, ||, !
(D) &, |, ~
What will be the output of the following code ?
S='New Delhi'
S=S.replace('e','*')
print(S)
(A) N*w D*lhi
(B) New Delhi
(C) N*w D*lhi
(D) *ew D*lhi
Fill in the blank:
________ is the method of a list which is used to add an element in the end of the existing list.
(A) append()
(B) add()
(C) insert()
(D) extend()
State True or False:
The count() method of a string returns the number of occurrences of a substring in the string.
State True or False:
In Python, the upper() method returns the given string by converting all the lower case letters to upper case.
Differentiate between Break and Continue statements in Python.
Write the output of the following Python code:
List=[10,20,30]
List.extend([40,50])
print(List)
print(List.index(40))
print(List.count(10))
State True or False:
"A Python List must always contain all its elements of same data type."
What will be the output of the following statement?
print(14%3**2*4)
(A) 16
(B) 64
(C) 20
(D) 256
Identify the correct output of the following code snippet:
game="Olympic2024"
print(game.index("C"))
(A) 0
(B) 6
(C) -1
(D) ValueError
Which of the following is the correct identifier?
(A) global
(B) Break
(C) def
(D) with
Identify the invalid Python statement out of the following options:
(A) print("A",10,end="*")
(B) print("A",sep="*",10)
(C) print("A",10,sep="*")
(D) print("A"*10)
Consider the statements given below and then choose the correct output from the given options:
L=['TIC', 'TAC']
print(L[::-1])
(A) ['crT', 'caT']
(B) ['TIc', 'TAC']
(C) ['car', 'CIT']
(D) ['TAC', 'TIC']
Which of the following operator evaluates to True if the variable on either side of the operator points towards the same memory location and False otherwise?
(A) is
(B) is not
(C) and
(D) or
Consider the statements given below and then choose the correct output from the given options:
D={'S01':95, 'S02':96}
for I in D:
print(I,end='#')
(A) S01#S02#
(B) 95#96#
(C) s01,95#S02,96#
(D) S01#95#S02#96#
Which of the following built-in function/method returns a dictionary?
(A) dict()
(B) keys()
(C) values()
(D) items()
(a) Given A = -2 and B = 7, find:
A >= -3 or B > 10
(b) Given X = True, evaluate:
not X
Write the Python code for the following output (pattern):
0
12
345
6789
OR
Write a user defined function in Python named display() which takes a string as an argument and creates a pattern as shown below:
For example: if the string passed as argument is "hello"
then the output will be:
h
he
hel
hell
hello
State True or False :
In Python, data type of 74 is same as the data type of 74.0.
Identify the output of the following code snippet :
s = "the Truth"
print(s.capitalize())
(A) The truth
(B) THE TRUTH
(C) The Truth
(D) the Truth
Which of the following expressions in Python evaluates to True ?
(A) 2>3 and 2<3
(B) 3>1 and 2
(C) 3>1 and 3>2
(D) 3>1 and 3<2
What is the output of the following code snippet ?
s = 'War and Peace by Leo Tolstoy'
print(s.partition("by"))
(A) ('War and Peace ', 'by', ' Leo Tolstoy')
(B) ['War and Peace ', 'by', ' Leo Tolstoy']
(C) ('War and Peace ', ' Leo Tolstoy')
(D) ['War and Peace ', ' Leo Tolstoy']
What will be the output of the following statement ?
print("PythonProgram"[-1:2:-2])
What will be the output of the following code snippet ?
t = tuple('tuple')
t2 = t[2],
t += t2
print(t)
(A) ('tuple')
(B) ('tuple','p')
(C) ('t', 'u', 'p', 'l', 'e', 'p')
(D) ('t', 'u', 'p', 'l', 'e')
Which of the following statements is true about dictionaries in Python ?
(A) A dictionary is an example of sequence datatype.
(B) A dictionary cannot have two elements with same key.
(C) A dictionary cannot have two elements with same value.
(D) The key and value of an element cannot be the same.
If L is a list with 6 elements, then which of the following statements will raise an exception ?
(A) L.pop(1)
(B) L.pop(6)
(C) L.insert(1,6)
(D) L.insert(6,1)
Assertion (A) : [1,2,3]+'123' is an invalid expression in Python.
Reason (R) : In Python, a list cannot be concatenated with a string.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
(B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.
Write a Python statement to perform the following tasks : (USE BUILT_IN FUNCTIONS / METHODS ONLY)
(i) To create a new list L1 containing the elements of list L arranged in ascending order, without modifying list L.
(ii) A statement to check whether the given character, ch is an alphabet or a number.
Assuming that D1 is a dictionary in Python,
(i) (a) Write a Python expression to check if the key, 'RNo' is present in D1.
OR
(b) Write a Python expression to check if any key in D1 has a value 12.
(ii) (a) Write a single statement using a BUILT_IN function to add the key : value pair 'RNo' : 12, if the key 'RNo' is not present in D1. However, if the key 'RNo' is present, the function should return its value.
OR
(b) Write a single statement to delete all the elements from D1.
State True or False.
"Comments are not executed by interpreter."
Which of the following is not a sequential datatype in Python ?
(a) Dictionary
(b) String
(c) List
(d) Tuple
Given the following dictionary
Day={1:"Monday", 2: "Tuesday", 3: "Wednesday" }
Which statement will return "Tuesday".
(a) Day.pop()
(b) Day.pop(2)
(c) Day.pop(1)
(d) Day.pop("Tuesday")
Consider the given expression :
7<4 or 6>3 and not 10==10 or 17>4
Which of the following will be the correct output if the given expression is evaluated ?
(a) True
(b) False
(c) NONE
(d) NULL
Select the correct output of the code :
S="Amrit Mahotsav @ 75"
A=S.split(" ",2)
print (A)
(a) ('Amrit', 'Mahotsav', '@', '75')
(b) ['Amrit', 'Mahotsav', '@ 75']
(c) ('Amrit', 'Mahotsav', '@75')
(d) ['Amrit', 'Mahotsav', '@', '75']
Fill in the blank :
________ is not a valid built-in function for list manipulations.
(a) count()
(b) length()
(c) append()
(d) extend()
Which of the following is an example of identity operators of Python ?
(a) is
(b) on
(c) in
(d) not in
Which of the following statement(s) would give an error after executing the following code ?
S="Happy" # Statement 1
print (S*2) # Statement 2
S+="Independence" # Statement 3
S.append ("Day") # Statement 4
print (S) # Statement 5
(a) Statement 2
(b) Statement 3
(c) Statement 4
(d) Statement 3 and 4
What will the following expression be evaluated to in Python ?
print (6/3 + 4**3//8-4)
(a) 6.5
(b) 4.0
(c) 6.0
(d) 4
Which of the following functions is a valid built-in function for both list and dictionary datatype ?
(a) items()
(b) len()
(c) update()
(d) values()
(a) Given is a Python string declaration :
NAME = "Learning Python is Fun"
Write the output of : print (NAME [-5:-10:-1])
(b) Write the output of the code given below :
dict1={1: ["Rohit",20], 2: ["Siya",90]}
dict2={1: ["Rahul",95], 5: ["Rajan",80]}
dict1.update (dict2)
print (dict1.values())
State True or False :
"In Python, tuple is a mutable data type".
What will be the output of the following statement ?
print(6+5/4**2//5+8)
(A) –14.0
(B) 14.0
(C) 14
(D) –14
Select the correct output of the code :
S = "text#next"
print(S.strip("t"))
(A) ext#nex
(B) ex#nex
(C) text#nex
(D) ext#next
Identify the valid Python identifier from the following :
(A) 2user
(B) user@2
(C) user_2
(D) user 2
Consider the statements given below and then choose the correct output from the given options :
Game="World Cup 2023"
print(Game[-6::-1])
(A) CdrW
(B) ce o
(C) puC dlroW
(D) Error
For the following Python statement :
N = (25)
What shall be the type of N ?
(A) Integer
(B) String
(C) Tuple
(D) List
Observe the following code carefully and rewrite it after removing all syntactical errors. Underline all the corrections made.
def 1func():
a=input("Enter a number")
if a>=33
print("Promoted to next class")
ELSE:
print("Repeat")
Predict the output of the following code :
d={"IND":"DEL","SRI":"COL","CHI":"BEI"}
str1=""
for i in d:
str1=str1+str(d[i])+"@"
str2=str1[:-1]
print (str2)
(a) Write the Python statement for each of the following tasks using BUILT-IN functions/methods only :
(i) To delete an element 10 from the list lst.
(ii) To replace the string "This" with "That" in the string str1.
OR
(b) A dictionary dict2 is copied into the dictionary dict1 such that the common key's value gets updated. Write the Python commands to do the task and after that empty the dictionary dict1.
Predict the output of the Python code given below :
s="India Growing"
n = len(s)
m=""
for i in range (0, n) :
if (s[i] >= 'a' and s[i] <= 'm') :
m = m + s [i].upper()
elif (s[i] >= 'O' and s[i] <= 'z') :
m = m +s [i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m + '@'
print (m)
State if following statement is True or False:
If T is a tuple and L is a list, then T+L is a valid statement in Python.
Identify the output of the following code segment:
s = "an apple. a toy."
s=s.find('a',2)
print(s)
(A) 0
(B) 1
(C) 3
(D) 'a'
What is the value of the following expression ?
3 + 3.00, 3**3.0
(A) [6.0, 27.0]
(B) (6.0, 9.0)
(C) (6, 27)
(D) (6.0, 27.0)
What is the output of the following expression ?
Sports="Paralympic Games"
print (Sports.split("m"))
(A) ['Paraly','m','pic Ga','m','es']
(B) ('Paraly','m','pic Games')
(C) ('Paraly','pic Ga','es')
(D) ['Paraly','pic Ga','es']
What will be the output of the following code segment ?
p=list("Session 2024–25")
print(p[10:20:])
Which of the following is a mapped data type ?
(A) List
(B) Sets
(C) Dictionary
(D) Boolean
If the dictionary D1 is defined as :
D1={1:'a',2:'b'}
then which of the following statements is incorrect and hence will result in an error ?
(A) D1.get(1)
(B) D1.get(3)
(C) D1.del(1)
(D) D1.clear()
Which of the following list methods accepts exactly 2 parameters ?
(A) append()
(B) extend()
(C) insert()
(D) pop()
State whether the following statement is True or False.
In Python, the print() evaluates the expression before displaying it on the screen.
Assertion (A) : Every object in Python is assigned a unique identity (ID).
Reason (R) : ID remains the same for the lifetime of that object.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of the Assertion (A).
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of the Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.
What is the difference between = and == in Python ? Give an example of each.
Give an example of each of the following :
(i) An expression using any one identity operator.
(ii) An arithmetic expression which uses any one augmented assignment operator.
Assuming that D1 and D2 are Python dictionaries, write the following statements using built-in functions/methods :
(I) (a) To delete all the elements of D1
OR
(b) To generate a list of values of D1
(II) (a) To update dictionary D2 with the elements of D1
OR
(b) To generate a tuple of keys of D2
The code provided below is intended to input a positive integer from the user and display the total number of its factors. However, there are syntax and logical errors in the code. Rewrite the code after removing all the errors. Underline all the corrections made.
n=int(input("Enter a positive integer:")
c=0
for i in range(n+1):
if n%i=0:
c+=1
print(c)
Find the invalid identifier from the following:
a) none
b) address
c) Name
d) pass
Consider a declaration L = (1, 'Python', '3.14').
Which of the following represents the data type of L?
a) list
b) tuple
c) dictionary
d) string
Given a Tuple tup1= (10, 20, 30, 40, 50, 60, 70, 80, 90).
What will be the output of print(tup1[3:7:2])?
a) (40,50,60,70,80)
b) (40,50,60,70)
c) [40,60]
d) (40,60)
The return type of the input() function is:
a) string
b) integer
c) list
d) tuple
Which of the following operator cannot be used with string data type?
a) +
b) in
c) *
d) /
Consider a tuple tup1 = (10, 15, 25, 30). Identify the statement that will result in an error.
a) print(tup1[2])
b) tup1[2] = 20
c) print(min(tup1))
d) print(len(tup1))
Which one of the following is the default extension of a Python file?
a) .exe
b) .p++
c) .py
d) .p
Which of the following symbol is used in Python for single line comment?
a) /
b) /*
c) //
d) #
Which of these about a dictionary is false?
a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren't ordered
d) Dictionaries are mutable
What is the output of following code:
T=(100)
print(T*2)
a) Syntax error
b) (200,)
c) 200
d) (100,100)
Identify the output of the following Python statements.
x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]]
y = x[1][2]
print(y)
a) 12.0
b) 13.0
c) 14.0
d) 15.0
Identify the output of the following Python statements.
x = 2
while x < 9:
print(x, end='')
x = x + 1
a) 12345678
b) 123456789
c) 2345678
d) 23456789
Identify the output of the following Python statements.
b = 1
for a in range(1, 10, 2):
b += a + 2
print(b)
a) 31
b) 33
c) 36
d) 39
Identify the output of the following Python statements.
lst1 = [10, 15, 20, 25, 30]
lst1.insert(3, 4)
lst1.insert(2, 3)
print(lst1[-5])
a) 2
b) 3
c) 4
d) 20
Evaluate the following expression and identify the correct answer.
16 - (4 + 2) * 5 + 2**3 * 4
a) 54
b) 46
c) 18
d) 32
Find the output of the following code:
Name="PythoN3.1"
R=""
for x in range(len(Name)):
if Name[x].isupper():
R=R+Name[x].lower()
elif Name[x].islower():
R=R+Name[x].upper()
elif Name[x].isdigit():
R=R+Name[x-1]
else:
R=R+"#"
print(R)
a) pYTHOn##@
b) pYTHOnN#@
c) pYTHOn#@
d) pYTHOnN@#
What will be the output of the following code?
tup1 = (1,2,[1,2],3)
tup1[2][1]=3.14
print(tup1)
a) (1,2,[3.14,2],3)
b) (1,2,[1,3.14],3)
c) (1,2,[1,2],3.14)
d) Error Message
State True or False:
"Variable declaration is implicit in Python."
Which of the following is an invalid datatype in Python?
a) Set
b) None
c) Integer
d) Real
Given the following dictionaries:
dict_exam={"Exam":"AISSCE", "Year":2023}
dict_result={"Total":500, "Pass_Marks":165}
Which statement will merge the contents of both dictionaries?
a) dict_exam.update(dict_result)
b) dict_exam + dict_result
c) dict_exam.add(dict_result)
d) dict_exam.merge(dict_result)
Consider the given expression:
not True and False or True
Which of the following will be correct output if the given expression is evaluated?
a) True
b) False
c) NONE
d) NULL
Select the correct output of the code:
a = "Year 2022 at All the best"
a = a.split('2')
b = a[0] + ". " + a[1] + ". " + a[3]
print(b)
a) Year . 0. at All the best
b) Year 0. at All the best
c) Year . 022. at All the best
d) Year . 0. at all the best
Which of the following statement(s) would give an error after executing the following code?
S="Welcome to class XII" # Statement 1
print(S) # Statement 2
S="Thank you" # Statement 3
S[0]= '@' # Statement 4
S=S+"Thank you" # Statement 5
a) Statement 3
b) Statement 4
c) Statement 5
d) Statement 4 and 5
What will the following expression be evaluated to in Python?
print(15.0 / 4 + (8 + 3.0))
a) 14.75
b) 14.0
c) 15
d) 15.5
(a) Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-2])
(b) Write the output of the code given below:
my_dict = {"name": "Aman", "age": 26}
my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.items())
State True or False:
"In a Python program, if a break statement is given in a nested loop, it terminates the execution of all loops in one go."
What will be the output of the following statement:
print(3-2**2**3+99/11)
a) 244
b) 244.0
c) -244.0
d) Error
Select the correct output of the code:
s = "Python is fun"
l = s.split()
s_new = "-".join([l[0].upper(), l[1], l[2].capitalize()])
print(s_new)
a) PYTHON-IS-Fun
b) PYTHON-is-Fun
c) Python-is-fun
d) PYTHON-Is -Fun
Which of the following will delete key-value pair for key = "Red" from a dictionary D1?
a) delete D1("Red")
b) del D1["Red"]
c) del.D1["Red"]
d) D1.del["Red"]
Consider the statements given below and then choose the correct output from the given options:
pride="#G20 Presidency"
print(pride[-2:2:-2])
a) ndsr
b) ceieP0
c) ceieP
d) yndsr
Which of the following statement(s) would give an error during execution of the following code?
tup = (20,30,40,50,80,79)
print(tup) #Statement 1
print(tup[3]+50) #Statement 2
print(max(tup)) #Statement 3
tup[4]=80 #Statement 4
a) Statement 1
b) Statement 2
c) Statement 3
d) Statement 4
Assertion(A): List is an immutable data type.
Reasoning(R): When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable is created by the same name in memory.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True
Predict the output of the following code:
S = "LOST"
L = [10,21,33,4]
D={}
for I in range(len(S)):
if I%2==0:
D[L.pop()] = S[I]
else:
D[L.pop()] = I+3
for K,V in D.items():
print(K,V,sep="*")
Predict the output of the Python code given below:
Text1="IND-23"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val)
elif Text1[I]>="A" and Text1[I]<="Z":
Text2=Text2 + (Text1[I+1])
else:
Text2=Text2 + "*"
I+=1
print(Text2)
State True or False:
The Python interpreter handles logical errors during code execution.
Identify the output of the following code snippet:
text = "PYTHONPROGRAM"
text=text.replace('PY','#')
print(text)
a) #THONPROGRAM
b) ##THON#ROGRAM
c) #THON#ROGRAM
d) #YTHON#ROGRAM
Which of the following expressions evaluates to False?
a) not(True) and False
b) True or False
c) not(False and True)
d) True and not(False)
What is the output of the expression?
country='International'
print(country.split("n"))
a) ('I', 'ter', 'atio', 'al')
b) ['I', 'ter', 'atio', 'al']
c) ['I', 'n', 'ter', 'n', 'atio', 'n', 'al']
d) Error
What will be the output of the following code snippet?
message= "World Peace"
print(message[-2::-2])
What will be the output of the following code?
tuple1 = (1, 2, 3)
tuple2 = tuple1
tuple1 += (4,)
print(tuple1 == tuple2)
a) True
b) False
c) tuple1
d) Error
If my_dict is a dictionary as defined below, then which of the following statements will raise an exception?
my_dict = {'apple': 10, 'banana': 20, 'orange': 30}
a) my_dict.get('orange')
b) print(my_dict['apple', 'banana'])
c) my_dict['apple']=20
d) print(str(my_dict))
What does the list.remove(x) method do in Python?
a) Removes the element at index x from the list
b) Removes the first occurrence of value x from the list
c) Removes all occurrences of value x from the list
d) Removes the last occurrence of value x from the list
How is a mutable object different from an immutable object in Python?
Identify one mutable object and one immutable object from the following:
(1,2), [1,2], {1:1,2:2}, '123'
Give two examples of each of the following:
(I) Arithmetic operators
(II) Relational operators
If L1=[1,2,3,2,1,2,4,2, . . . ], and L2=[10,20,30, . . .], then (Answer using builtin functions only)
(I)
A) Write a statement to count the occurrences of 4 in L1.
OR
B) Write a statement to sort the elements of list L1 in ascending order.
(II)
A) Write a statement to insert all the elements of L2 at the end of L1.
OR
B) Write a statement to reverse the elements of list L2.
The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the corrections made.
def swap_first_last(tup)
if len(tup) < 2:
return tup
new_tup = (tup[-1],) + tup[1:-1] + (tup[0])
return new_tup
result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result)
Predict the output of the following code:
d = {"apple": 15, "banana": 7, "cherry": 9}
str1 = ""
for key in d:
str1 = str1 + str(d[key]) + "@" + "\n"
str2 = str1[:-1]
print(str2)
OR
Predict the output of the following code:
line=[4,9,12,6,20]
for I in line:
for j in range(1,I%5):
print(j,'#',end="")
print()
What will be the output of the following code?
L = ["India", "Incredible", "Bharat"]
print(L[1][0] + L[2][-1])
a) IT
b) it
c) It
d) iT
Consider the given expression:
print(19<11 and 29>19 or not 75>30)
Which of the following will be the correct output of the given expression?
a) True
b) False
c) Null
d) No output
What will be the output of the following Python code?
str= "Soft Skills"
print(str[-3::-3])
a) lSf
b) Stkl
c) StKi
d) l
Write the output of the following Python code:
for k in range(7,40,6):
print ( k + '-' )
What will be the output of the following Python statement:
print(10-3**2**2+144/12)
What will be the output of the following Python code?
my_dict = {"name": "Alicia", "age": 27, "city": "DELHI"}
print(my_dict.get("profession", "Not Specified"))
a) Alicia
b) DELHI
c) None
d) Not Specified
What is the output of the given Python code?
st='Waterskiing is thrilling!'
print(st.split("i"))
a) ['Watersk', 'ng ', 's thr', 'll', 'ng!']
b) ['Watersk', '', 'ng ', 's thr', 'll', 'ng!']
c) ['Watersk', 'i', 'ng ', 's thr', 'll', 'ng!']
d) Error
Assertion (A): The expression (1, 2, 3, 4).append(5) in Python will modify the original sequence datatype.
Reason (R): The append() method adds an element to the end of a list and modifies the list in place.
a) Both A and R are True and R is the correct explanation for A.
b) Both A and R are True and R is not the correct explanation for A.
c) A is True but R is False.
d) A is False but R is True.
A. Explain the difference between explicit and implicit type conversion in Python with a suitable example.
B. Explain the difference between break and continue statements in Python with a suitable example.
A. (Answer using Python built-in methods/functions only):
I. Write a statement to find the index of the first occurrence of the substring "good" in a string named review.
II. Write a statement to sort the elements of list L1 in descending order.
B. Predict the output of the following Python code:
text="Learn Python with fun and practice"
print(text.partition("with"))
print(text.count("a"))
Predict the output of the Python code given below:
emp = {"Arv": (85000,90000),"Ria": (78000,88000),"Jay": (72000,80000),"Tia": (80000,70000)}
selected = [ ]
for name in emp:
salary = emp[name]
average = (salary[0] + salary[1]) / 2
if average > 80000:
selected.append(name)
print(selected)
A. Predict the output of the following Python code:
s1="SQP-25"
s2=""
i=0
while i<len(s1):
if s1[i]>='0' and s1[i]<='9':
Num=int(s1[i])
Num-=1
s2=s2+str(Num)
elif s1[i]>='A' and s1[i]<='Z':
s2=s2+s1[i+1]
else:
s2=s2+'^'
i+=1
print(s2)
B. Predict the output of the following Python code:
wildlife_sanctuary = ["Kaziranga", "Ranthambhore", "Jim Corbett", "Sundarbans", "Periyar", "Gir", "Bandipur"]
output = [ ]
for sanctuary in wildlife_sanctuary:
if sanctuary[-1] in 'aeiou':
output.append(sanctuary[0].upper())
print(output)
Atharva is a Python programmer working on a program to find and return the maximum value from the list. The code written below has syntactical errors. Rewrite the correct code and underline the corrections made.
def max num (L)
max=L (0)
for a in L
if a > max
max=a
return max
Write a function EOReplace() in Python, which accepts a list L of numbers. Thereafter, it increments all even numbers by 1 and decrements all odd numbers by 1.
Example :
If Sample Input data of the list is :
L=[10,20,30,40, 35,55]
Output will be :
L=[11,21,31,41,34,54]
Assertion (A): We can use a dictionary as an argument in a function.
Reason (R): A dictionary can be passed as an argument in a function and function can access and modify the dictionary elements inside it.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A).
(B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation of Assertion (A).
(C) Assertion (A) is true but Reason (R) is false.
(D) Assertion (A) is false but Reason (R) is true.
Write a user defined function in Python named show() which takes a list of integers as an argument and displays only those numbers from the list which are perfect squares.
For example: If the list is [10, 21, 36, 14, 81, 100] then the function should display:
36
81
100
Write a user defined function in Python named Display(List) which takes a list of integers as an argument and displays only even numbers from the list.
OR
Write a user defined function in Python named COUNT() which counts and displays the number of lines which do not start with the vowels 'A' or 'E' in the file, "Paragraph.txt".
What will be the output of the following code ?
def f1(a,b=1):
print(a+b,end='-')
c=f1(1,2)
print(c,sep='*')
(A) 3-2
(B) 3-2*
(C) 3-None
(D) 3*None-
The function given below is written to accept a string s as a parameter and return the number of vowels appearing in the string. The code has certain errors. Observe the code carefully and rewrite it after removing all the logical and syntax errors. Underline all the corrections made.
def CountVowels(s):
c=0
for ch in range(s):
if 'aeiouAEIOU' in ch:
c=+1
return(ch)
(a) Write the output of the following code :
def Exam2026(given) :
new=[]
for ch in given[1:-1]:
if ch.isupper():
new.reverse()
elif ch not in new:
new.append(ch)
elif ch in new:
new.pop()
print(new)
Exam2026("Gold-24Medals")
OR
(b) Write the output of the following code :
def Exam2026(given) :
new = 0
while given:
if new % 2:
new += given % 10
else:
new += given % 5
print(new, end='-')
given //= 10
Exam2026(123456)
Ravi, a Python programmer, is working on a project in which he wants to write a function to count the number of even and odd values in the list. He has written the following code but his code is having errors. Rewrite the correct code and underline the corrections made.
define EOCOUNT(L):
even_no=odd_no=0
for i in range(0,len(L))
if L[i]%2=0:
even_no+=1
Else:
odd_no+=1
print (even_no, odd_no)
Write a function search_replace() in Python which accepts a list L of numbers and a number to be searched. If the number exists, it is replaced by 0 and if the number does not exist, an appropriate message is displayed.
Example :
L = [10,20,30,10,40]
Number to be searched = 10
List after replacement :
L = [0,20,30,0,40]
(a) Write the definition of a method/function SearchOut(Teachers, TName) to search for TName from a list Teachers, and display the position of its presence.
For example :
If the Teachers contain ["Ankit", "Siddharth", "Rahul", "Sangeeta", "rahul"] and TName contains "Rahul"
The function should display
Rahul at 2
rahul at 4
OR
(b) Write the definition of a method/function Copy_Prime(lst) to copy all the prime numbers from the list lst to another list lst_prime.
Predict the output of the following code :
def Total (Num=10):
Sum=0
for C in range(1,Num+1):
if C%2!=0:
continue
Sum+=C
return Sum
print(Total(4),end="$")
print(Total(),sep="@")
Which of the following components are part of a function header in Python?
a) Function Name
b) Return Statement
c) Parameter List
d) Both a and c
Which of the following is the correct way to call a function?
a) my_func()
b) def my_func()
c) return my_func
d) call my_func()
What will be the output of the following Python code?
def add(num1, num2):
sum = num1 + num2
sum = add(20,30)
print(sum)
a) 50
b) 0
c) Null
d) None
Rao has written a code to input a number and check whether it is prime or not. His code is having errors. Rewrite the correct code and underline the corrections made.
def prime():
n=int(input("Enter number to check :: ")
for i in range (2, n//2):
if n%i=0:
print("Number is not prime \n")
break
else:
print("Number is prime \n')
Predict the output of the Python code given below:
def Diff(N1,N2):
if N1>N2:
return N1-N2
else:
return N2-N1
NUM= [10,23,14,54,32]
for CNT in range(4,0,-1):
A=NUM[CNT]
B=NUM[CNT-1]
print(Diff(A,B),'#', end=' ')
OR
Predict the output of the Python code given below:
tuple1 = (11, 22, 33, 44, 55, 66)
list1 =list(tuple1)
new_list = []
for i in list1:
if i%2==0:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The function returns another list named 'indexList' that stores the indices of all Non-Zero Elements of L.
For example:
If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
The code given below accepts a number as an argument and returns the reverse number. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.
define revNumber(num):
rev = 0
rem = 0
While num > 0:
rem ==num %10
rev = rev*10 + rem
num = num//10
return rev
print(revNumber(1234))
Write a function countNow(PLACES) in Python, that takes the dictionary PLACES as an argument and displays the names (in uppercase) of the places whose names are longer than 5 characters.
For example, Consider the following dictionary:
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
The output should be:
LONDON
NEW YORK
OR
Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun", the tuple will have (4, 3, 2, 4, 4, 3)
The code provided below is intended to remove the first and last characters of a given string and return the resulting string. However, there are syntax and logical errors in the code.
Rewrite it after removing all the errors. Also, underline all the corrections made.
define remove_first_last(str):
if len(str) < 2:
return str
new_str = str[1:-2]
return new_str
result = remove_first_last("Hello")
Print("Resulting string: " result)
A. Write a function remove_element() in Python that accepts a list L and a number n. If the number n exists in the list, it should be removed. If it does not exist, print a message saying "Element not found".
B. Write a Python function add_contact() that accepts a dictionary phone_book, a name, and a phone number. The function should add the name and phone number to the dictionary. If the name already exists, print "Contact already exists" instead of updating it.
(a) Write the output of the code given below :
def short_sub (lst,n):
for i in range (0,n):
if len (lst[i])>4:
lst [i]=lst [i]+lst[i]
else:
lst [i]=lst[i][1]
subject=['CS', 'HINDI', 'PHYSICS', 'CHEMISTRY', 'MATHS']
short_sub(subject,5)
print (subject)
OR
Write the output of the code given below :
a =30
def call (x):
global a
if a%2==0:
x+=a
else:
x-=a
return x
x=20
print (call(35),end="#")
print (call(40),end="@")
Write the output of the following Python code:
def Mycode(a,b=10):
c=a+b
a=c-2*b
print(a,b,c,sep="#")
Mycode(b=3,a=5)
Consider the statements given below and then choose the correct output from the given options:
def Change(N):
N=N+10
print(N,end='$$')
N=15
Change(N)
print(N)
(A) 25$$15
(B) 15$$25
(C) 25$$25
(D) 2525$8
Write the output of the following Python code:
def Newdict(dict1):
dict1['R']='S01'
dict1['T']='S02'
print(dict1)
dict1={'P':10,'Q':20}
Newdict(dict1)
print(dict1)
What is the difference between default parameters and positional parameters in Python ? Also give an example of a function header which uses both.
(a) Write the output of the Python code given below :
g=0
def fun1(x,y):
global g
g=x+y
return g
def fun2 (m,n):
global g
g=m-n
return g
k=fun1 (2,3)
fun2 (k,7)
print (g)
OR
(b) Write the output of the Python code given below :
a=15
def update (x):
global a
a=2
if x%2==0:
a*=x
else:
a//=x
a=a+5
print (a,end="$")
update (5)
print (a)
What will be the output of the given code ?
a=10
def convert(b=20):
a=30
c=a+b
print(a,c)
convert(30)
print(a)
Assertion (A) : Global variables are accessible in the whole program.
Reason (R) : Local variables are accessible only within a function or block in which it is declared.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A).
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.
What will be the output of the following code segment ?
a=5
def func_1(b=10):
global a
a=b–10
b+=a
print(a,b)
func_1(a)
(A) 0 5
(B) 5 0
(C) 0 –5
(D) –5 0
(a) Write the output on execution of the following Python code :
P=[3,5,7,4]
P.insert(2,3)
P.extend([10, 6])
print(P)
print(P.index(7))
print(P[::2])
OR
(b) Write the output on execution of the following Python code :
def ALTER(Y=25):
global X
Y += X
X += Y
print(X,Y,sep="#")
X=5; Y=15
ALTER(Y)
ALTER()
print(X,Y,sep="@")
Which of the following function header is correct?
a) def cal_si(p=100, r, t=2)
b) def cal_si(p=100, r=8, t)
c) def cal_si(p, r=8, t)
d) def cal_si(p, r=8, t=2)
What will be the output of the following code?
def my_func(var1=100, var2=200):
var1+=10
var2 = var2 - 10
return var1+var2
print(my_func(50),my_func())
a) 100 200
b) 150 300
c) 250 75
d) 250 300
What will be the output of the following code?
value = 50
def display(N):
global value
value = 25
if N%7==0:
value = value + N
else:
value = value - N
print(value, end="#")
display(20)
print(value)
a) 50#50
b) 50#5
c) 50#30
d) 5#50#
What is the output of the following code snippet?
def ChangeVal(M,N):
for i in range(N):
if M[i]%5 == 0:
M[i]//=5
if M[i]%3 == 0:
M[i]//=3
L = [25,8,75,12]
ChangeVal(L,4)
for i in L:
print(i,end="#")
a) 5#8#15#4#
b) 5#8#5#4#
c) 5#8#15#14#
d) 5#18#15#4#
What will be the output of the following code?
x = 3
def myfunc():
global x
x+=2
print(x, end=' ')
print(x, end=' ')
myfunc()
print(x, end=' ')
a) 3 3 3
b) 3 4 5
c) 3 3 5
d) 3 5 5
Assertion (A): If the arguments in function call statement match the number and order of arguments as defined in the function definition, such arguments are called positional arguments.
Reasoning (R): During a function call, the argument list first contains default argument(s) followed by positional argument(s).
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True
Consider the code given below:
b=100
def test(a):
__________________ # missing statement
b=b+a
print(a,b)
test(10)
print(b)
Which of the following statements should be given in the blank for #Missing Statement, if the output produced is 110?
a) global a
b) global b=100
c) global b
d) global a=100
Predict the output of the following code:
def Changer(P,Q=10):
P=P/Q
Q=P%Q
return P
A=200
B=20
A=Changer(A,B)
print(A,B, sep='$')
B=Changer(B)
print(A,B, sep='$', end='###')
What will be the output of the following code?
c = 10
def add():
global c
c = c + 2
print(c,end='#')
add()
c=15
print(c,end='%')
a) 12%15#
b) 15#12%
c) 12#15%
d) 12%15#
Assertion (A): Positional arguments in Python functions must be passed in the exact order in which they are defined in the function signature.
Reason (R): This is because Python functions automatically assign default values to positional arguments.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is False but R is True
What will be the output of the following Python code?
i = 5
print(i,end='@@')
def add():
global i
i = i+7
print(i,end='##')
add()
print(i)
a) 5@@12##15
b) 5@@5##12
c) 5@@12##12
d) 12@@12##12
Assertion (A) : To use a function from a particular module, we need to import the module.
Reason (R) : import statement can be written anywhere in the program, before using a function from that module.
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but (R) is true.
What possible output(s) from the given options will NOT be displayed when the following code is executed ? Also, mention, for how many iterations the for loop in the given code will run ?
import random
a = [1,2,3,4,5,6]
for i in range(4):
j = random.randrange(i,5)
print(a[j],end='-')
print()
Options :
(A) 3-4-5-4-
(B) 2-2-4-5-
(C) 4-3-3-5-
(D) 5-1-2-4-
Predict the output of the following Python statements :
>>>import statistics as s
>>>s.mode ([10, 20, 10, 30, 10, 20, 30])
(A) 30
(B) 20
(C) 10
(D) 18.57
Which of the following output will never be obtained when the given code is executed ?
import random
Shuffle = random.randrange(10)+1
Draw = 10*random.randrange(5)
print ("Shuffle", Shuffle, end="#")
print ("Draw", Draw)
(A) Shuffle 1 # Draw 0
(B) Shuffle 10 # Draw 10
(C) Shuffle 10 # Draw 0
(D) Shuffle 11 # Draw 50
Identify the correct possible output(s) of the following code segment. Also write the minimum and the maximum possible values of the variable b.
import random
s="War and Peace"
a=len(s)//2
for i in range(4):
b=random.randrange(i,a)
print(s[b],end='+')
(A) n+P+d+a+
(B) W+r+n+n+
(C) e+r+W+a+
(D) a+P+e+r+
What will be the output of the following code?
import random
List=["Delhi","Mumbai","Chennai","Kolkata"]
for y in range(4):
x = random.randint(1,3)
print(List[x],end="#")
a) Delhi#Mumbai#Chennai#Kolkata#
b) Mumbai#Chennai#Kolkata#Mumbai#
c) Mumbai# Mumbai #Mumbai # Delhi#
d) Mumbai# Mumbai #Chennai # Mumbai
What possible output(s) will be obtained when the following code is executed?
import random
myNumber=random.randint(0,3)
COLOR=["YELLOW","WHITE","BLACK","RED"]
for I in range(1,myNumber):
print(COLOR[I],end="*")
print()
a) RED*
WHITE*
BLACK*
b) WHITE*
BLACK*
c) WHITE* WHITE*
BLACK* BLACK*
d) YELLOW*
WHITE*WHITE*
BLACK* BLACK* BLACK*
Assertion(A): Python Standard Library consists of various modules.
Reasoning(R): A function in a module is used to simplify the code and avoids repetition.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True
Write the Python statement for each of the following tasks using BUILT-IN functions/methods only:
(i) To insert an element 200 at the third position, in the list L1.
(ii) To check whether a string named message ends with a full stop / period or not.
OR
A list named studentAge stores age of students of a class. Write the Python command to import the required module and (using built-in function) to display the most common age value from the given list.
Identify the correct output(s) of the following code. Also write the minimum and the maximum possible values of the variable b.
import random
a="Wisdom"
b=random.randint(1,6)
for i in range(0,b,2):
print(a[i],end='#')
a) W#
b) W#i#
c) W#s#
d) W#i#s#
State if the following statement is True or False:
Using the statistics module, the output of the below statements will be 20:
import statistics
statistics.median([10, 20, 10, 30, 10, 20, 30])
What possible output is expected to be displayed on the screen at the time of execution of the Python program from the following code?
import random
L=[10,30,50,70]
Lower=random.randint(2,2)
Upper=random.randint(2,3)
for K in range(Lower, Upper+1):
print(L[K], end="@")
a) 50@70@
b) 90@
c) 10@30@50@
d) 10@30@50@70@
Consider the statements given below and then choose the correct output from the given options:
N='5'
try:
print('WORD' + N, end='#')
except:
print('ERROR', end='#')
finally:
print('OVER')
(A) ERROR#
(B) WORD5#OVER
(C) WORD5#
(D) ERROR#OVER
State whether the following statement is True or False :
In Python, Logical errors can be handled using try...except...finally statement.
State whether the following statement is True or False:
An exception may be raised even if the program is syntactically correct.
State whether the following statement is True or False:
The finally block in Python is executed only if no exception occurs in the try block.
What will be the output of the following Python code?
try:
x = 10 / 0
except Exception:
print("Some other error!")
except ZeroDivisionError:
print("Division by zero error!")
a) Division by zero error!
b) Some other error!
c) ZeroDivisionError
d) Nothing is printed
Which of the following mode keeps the file offset position at the end of the file ?
(a) r+
(b) x
(c) w
(d) a
Which of the following file opening mode is used to open a file in append and read mode ?
(A) r+
(B) w+
(C) a+
(D) x+
Consider the statement given below :
f1 = open("pqr.dat","_______")
Which of the following is the correct file mode to open the file in read only mode ?
(A) a
(B) rb
(C) r+
(D) rb+
Which of the following modes in Python creates a new file, if file does not exist and overwrites the content, if the file exists ?
(a) r+
(b) r
(c) w
(d) a
__________ files are stored in a computer in a sequence of bytes.
(A) Text
(B) Binary
(C) CSV
(D) Notepad
Consider the following directory structure.
(Root: School → Subdirectories: Academics [contains Syllabus.jpg], Examination [contains Result.png], Sports [contains Achievement.jpg])
Suppose root directory (School) and present working directory are the same. What will be the absolute path of the file Syllabus.jpg?
a) School/syllabus.jpg
b) School/Academics/syllabus.jpg
c) School/Academics/../syllabus.jpg
d) School/Examination/syllabus.jpg
The syntax of seek( ) is
file object.seek(offset[,reference point] )
What is the default value of reference point ?
(a) 0
(b) 1
(c) 2
(d) 3
(a) Write the definition of a Python function named LongLines() which reads the contents of a text file named 'LINES.TXT' and displays those lines from the file which have at least 10 words in it.
For example, if the content of 'LINES.TXT' is as follows :
Once upon a time, there was a woodcutter
He lived in a little house in a beautiful, green wood.
One day, he was merrily chopping some wood.
He saw a little girl skipping through the woods, whistling happily.
The girl was followed by a big gray wolf.
Then the function should display output as:
He lived in a little house in a beautiful, green wood.
He saw a little girl skipping through the woods, whistling happily.
OR
(b) Write a function count_Dwords() in Python to count the words ending with a digit in a text file "Details.txt".
Example:
If the file content is as follows :
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Output will be:
Number of words ending with a digit are 4
(a) Write the user defined function count_words() in Python to count the number of words in a text file "Story.txt".
OR
(b) Write the user defined function display() in Python to read the content of a text file "Story.txt" and display those words which are less than 4 characters.
(a) Write a Python function that counts and returns the number of digits appearing in the text file "Space.txt". For example, if the file contains :
Space exploration has unlocked incredible
advancements in technology and science. Since the
first moon landing in 1969, space agencies have sent
probes to Mars, Jupiter and beyond. The ISS,
orbiting Earth at about 400 km, serves as a hub for
research. With missions planned for 2030, humanity's
cosmic journey continues!
Then the function should return 11.
OR
(b) Write a Python function that displays the words in which the lowercase letter 'e' appears at least twice in the text file 'Space.txt'. For example, if the file contains :
Space exploration has unlocked incredible
advancements in technology and science. Since the
first moon landing in 1969, space agencies have sent
probes to Mars, Jupiter and beyond. The ISS,
orbiting Earth at about 400 km, serves as a hub for
research. With missions planned for 2030, humanity's
cosmic journey continues!
Then the function should display :
incredible advancements science. agencies serves research.
The correct syntax of tell() is:
(a) tell.file object ()
(b) file object.tell()
(c) tell.file object (1)
(d) file object.tell1(1)
Assertion(A): xreadlines() reads all the lines from a text file and returns the lines along with newline as a list of strings.
Reasoning (R): readline() can read the entire text file line by line without using any looping statements.
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but (R) is true.
(a) Write a function in Python that displays the book names having 'Y' or 'y' in their name from a text file "Bookname.txt".
Example :
If the file 'Bookname.txt' contains the names of following books :
One Hundred Years of Solitude
The Diary of a Young Girl
On the Road
After execution, the output will be :
One Hundred Years of Solitude
The Diary of a Young Girl
OR
(b) Write a function RevString() to read a textfile "Input.txt" and prints the words starting with 'O' in reverse order. The rest of the content is displayed normally.
Example :
If content in the text file is :
UBUNTU IS AN OPEN SOURCE OPERATING SYSTEM
Output will be :
UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM
(words 'OPEN' and 'OPERATING' are displayed in reverse order)
Assertion (A) : If numeric data are to be written to a text file, the data needs to be converted into a string before writing to the file.
Reason (R) : write() method takes a string as an argument and writes it to the text file.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A).
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.
(a) Write a method/function COUNTWORDS() in Python to read contents from a text file DECODE.TXT, to count and return the occurrence of those words, which are having 5 or more characters.
OR
(b) Write a method/function COUNTLINES() in Python to read lines from a text file CONTENT.TXT, and display those lines, which have @ anywhere in the line.
For example :
If the content of the file is :
Had an amazing time at the concert last night with
@MusicLoversCrew.
Excited to announce the launch of our new website!
G20 @ India
The method/function should display
Had an amazing time at the concert last night with
@MusicLoversCrew
G20 @ India
A text file 'song.txt' contains the following contents in it :
Life goes on as it never ends
What will be the output of the following code snippet ?
f1=open("song.txt","r")
s1=f1.read(5)
s2=f1.readline(4)
s3=f1.read(3)
print(s1,s3,sep="#")
(A) goes# on
(B) Life #goes# on
(C) Life # on
(D) Error
(a) Write a Python function that displays all the lines ending with a dot (.) from a text file, "Colors.txt". For example, if the file "Colors.txt" contains :
White is a mix of seven colors.
What are these seven colors ?
VIBGYOR – violet, indigo, blue, green, orange and red.
When we mix all these colors we just get one light which is the WHITE light.
Then the output should be :
White is a mix of seven colors.
VIBGYOR – violet, indigo, blue, green, orange and red.
which is the WHITE light.
(Hint : You will have to ignore trailing white spaces to check the last character)
OR
(b) Write a function in Python to display the line which has the maximum number of vowels from a text file, "Novel.txt"
Which of the following option is not correct?
a) if we try to read a text file that does not exist, an error occurs.
b) if we try to read a text file that does not exist, the file gets created.
c) if we try to write on a text file that does not exist, no error occurs.
d) if we try to write on a text file that does not exist, the file gets created.
Which of the following options can be used to read the first line of a text file Myfile.txt?
a) myfile = open('Myfile.txt'); myfile.read()
b) myfile = open('Myfile.txt','r'); myfile.read(n)
c) myfile = open('Myfile.txt'); myfile.readline()
d) myfile = open('Myfile.txt'); myfile.readlines()
Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the following option can be used to read all the remaining lines?
a) myfile.read()
b) myfile.read(n)
c) myfile.readline()
d) myfile.readlines()
A text file student.txt is stored in the storage device. Identify the correct option out of the following options to open the file in read mode.
i. myfile = open('student.txt','rb')
ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r')
iv. myfile = open('student.txt')
a) only i
b) both i and iv
c) both iii and iv
d) both i and iii
What is the significance of the tell() method?
a) tells the path of file
b) tells the current position of the file pointer within the file
c) tells the end position within the file
d) checks the existence of a file at the desired location
Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is the file object. What is the default value of reference_point?
a) 0
b) 1
c) 2
d) 3
Suppose content of 'Myfile.txt' is:
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
What will be the output of the following code?
myfile = open("Myfile.txt")
data = myfile.readlines()
print(len(data))
myfile.close()
a) 3
b) 4
c) 5
d) 6
Suppose content of 'Myfile.txt' is:
Humpty Dumpty sat on a wall
Humpty Dumpty had a great fall
All the king's horses and all the king's men
Couldn't put Humpty together again
What will be the output of the following code?
myfile = open("Myfile.txt")
record = myfile.read().split()
print(len(record))
myfile.close()
a) 24
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is:
Honesty is the best policy.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()
a) 5
b) 25
c) 26
d) 27
Suppose content of 'Myfile.txt' is:
Culture is the widening of the mind and of the spirit.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()
a) 2
b) 3
c) 4
d) 5
Suppose content of 'Myfile.txt' is:
Ek Bharat Shreshtha Bharat
What will be the output of the following code?
myfile = open("Myfile.txt")
vlist = list("aeiouAEIOU")
vc=0
x = myfile.read()
for y in x:
if(y in vlist):
vc+=1
print(vc)
myfile.close()
a) 6
b) 7
c) 8
d) 9
Suppose content of 'Myfile.txt' is:
Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle twinkle little star
What will be the output of the following code?
myfile = open("Myfile.txt")
line_count = 0
data = myfile.readlines()
for line in data:
if line[0] == 'T':
line_count += 1
print(line_count)
myfile.close()
a) 2
b) 3
c) 4
d) 5
Assume the content of text file, 'student.txt' is:
Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran
What will be the data type of data_rec?
myfile = open("Myfile.txt")
data_rec = myfile.readlines()
myfile.close()
a) string
b) list
c) tuple
d) dictionary
Which of the following mode in file opening statement results or generates an error if the file does not exist?
a) a+
b) r+
c) w+
d) None of the above
The correct syntax of seek() is:
a) file_object.seek(offset [, reference_point])
b) seek(offset [, reference_point])
c) seek(offset, file_object)
d) seek.file_object(offset)
Write a method COUNTLINES() in Python to read lines from text file 'TESTFILE.TXT' and display the lines which are not starting with any vowel.
Example:
If the file content is as follows:
An apple a day keeps the doctor away.
We all pray for everyone's safety.
A marked difference will come in our country.
The COUNTLINES() function should display the output as:
The number of lines not starting with any vowel - 1
OR
Write a function ETCount() in Python, which should read each character of a text file "TESTFILE.TXT" and then count and display the count of occurrence of alphabets E and T individually (including small cases e and t too).
Example:
If the file content is as follows:
Today is a pleasant day.
It might rain today.
It is mentioned on weather sites
The ETCount() function should display the output as:
E or e: 6
T or t : 9
Which of the following functions changes the position of file pointer and returns its new position?
a) flush()
b) tell()
c) seek()
d) offset()
Write a function in Python to read a text file, Alpha.txt and displays those lines which begin with the word 'You'.
OR
Write a function, vowelCount() in Python that counts and displays the number of vowels in the text file named Poem.txt.
Write the missing statement to complete the following code:
file = open("example.txt", "r")
data = file.read(100)
____________________ #Move the file pointer to the beginning of the file
next_data = file.read(50)
file.close()
A) Write a Python function that displays all the words containing @cmail from a text file "Emails.txt".
OR
B) Write a Python function that finds and displays all the words longer than 5 characters from a text file "Words.txt".
A. Write a Python function that displays the number of times the word "Python" appears in a text file named "Prog.txt".
B. Write and call a Python function to read lines from a text file STORIES.TXT and display those lines which doesn't start with a vowel (A, E, I, O, U) irrespective of their case.
Shreyas is a programmer, who has recently been given a task to write a user defined function named write_bin() to create a binary file called Cust_file.dat containing customer information — customer number (c_no), name (c_name), quantity (qty), price (price) and amount (amt) of each customer.
The function accepts customer number, name, quantity and price. Thereafter, it displays the message 'Quantity less than 10..... Cannot SAVE', if quantity entered is less than 10. Otherwise the function calculates amount as price * quantity and then writes the record in the form of a list into the binary file.
import pickle
def write_bin():
bin_file= ______ #Statement 1
while True:
c_no=int(input("enter customer number"))
c_name=input("enter customer name")
qty=int(input("enter qty"))
price=int(input("enter price"))
if ______: #Statement 2
print ("Quantity less than 10..Cannot SAVE")
else:
amt=price * qty
c_detail=[c_no, c_name, qty, price, amt]
______ #Statement 3
ans=input("Do you wish to enter more records y/n")
if ans.lower()=='n':
______ #Statement 4
______ #Statement 5
______ #Statement 6
(i) Write the correct statement to open a file 'Cust_file.dat' for writing the data of the customer.
(ii) Which statement should Shreyas fill in Statement 2 to check whether quantity is less than 10.
(iii) Which statement should Shreyas fill in Statement 3 to write data to the binary file and in Statement 4 to stop further processing if the user does not wish to enter more records.
OR
(Option for part (iii) only)
(iii) What should Shreyas fill in Statement 5 to close the binary file named Cust_file.dat and in Statement 6 to call a function to write data in binary file ?
Write a program in Python to create a binary file Employee.dat and write the following data into it:
Employee ID, Employee Name, Department, Salary
OR
Write a program in Python to read the content of a text file Story.txt and count and display the number of lines that start with the letter 'A'.
Assertion (A): For a binary file opened using 'rb' mode, the pickle.dump() method will display an error.
Reason (R): The pickle.dump() method is used to read from a binary file.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
(B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A).
(C) Assertion (A) is true but Reason (R) is false.
(D) Assertion (A) is false but Reason (R) is true.
NextStep is an organization which has a pool of resource persons to conduct training workshops on various topics related to ICT. The data of all its Resource Persons is stored in a binary file RESOURCES.DAT using the following record structure (each record is a tuple) :
(R_ID, R_Name, R_Expertise, Charges)
where :
· R_ID – Resource Person's ID (An integer)
· R_Name – Resource Person's Name (A string)
· R_Expertise – Area of expertise of the Resource Person
· Charges – Charges (in rupees) per hour to conduct a workshop
For example, a record in the file is :
(12, 'P. Velusami', 'Machine Learning', 5000)
In this context, write the following user defined functions in Python :
(i) Append() – To input the data of a Resource Person and write it in the file RESOURCES.DAT.
(ii) Update() – To increase the Charges of each resource person by 500.
Atharva is a programmer, who has recently been given a task to write a Python code to perform the following binary file operation with the help of a user defined function/module :
- Copy_new() : to create a binary file new_items.dat and write all the item details stored in the binary file, items.dat, except for the item whose item_id is 101. The data is stored in the following format :
{item_id:[item_name,amount]}
import ______ # Statement 1
def Copy_new():
f1= ______ # Statement 2
f2= ______ # Statement 3
item_id=int(input("Enter the item id"))
item_detail= ______ # Statement 4
for key in item_detail:
if ______: # Statement 5
pickle. ______ # Statement 6
f1.close()
f2.close()
He has succeeded in writing partial code and has missed out certain statements. Therefore, as a Python expert, help him to complete the code based on the given requirements :
(i) Which module should be imported in the program ? (Statement 1)
(ii) Write the correct statement required to open the binary file "items.dat". (Statement 2)
(iii) Which statement should Atharva fill in Statement 3 to open the binary file "new_items.dat" and in Statement 4 to read all the details from the binary file "items.dat".
OR
(Option for part iii only)
(iii) What should Atharva write in Statement 5 to apply the given condition and in Statement 6 to write data in the binary file "new_items.dat".
(a) (i) What is the main purpose of seek() and tell() method ?
(ii) Consider a binary file, Cinema.dat containing information in the following structure :
[Mno, Mname, Mtype]
Write a function, search_copy(), that reads the content from the file Cinema.dat and copies all the details of the "Comedy" movie type to file named movie.dat.
OR
(b) (i) Give one difference between write() and writeline() function in text file.
(ii) A Binary file, "Items.dat" has the following structure :
[Icode, Description, Price]
Where
Icode – Item code
Description – Detail of item
Price – Price of item
Write a function Add_data(), that takes Icode, Description and Price from the user and writes the information in the binary file "Items.dat".
Keshav is the IT Head in a hospital. He needs to manage the records of all the doctors in the hospital. For this, he wants to store the following information of each doctor in a file :
D_ID – An integer to store Doctor ID.
D_Name – A string to store doctor's name.
D_Dept – A string to store the Department of the doctor. (Surgery, Radiology, etc.)
Experience – An integer to store doctor's experience (in years)
For example, a doctor's information may be : [1256, 'R. Gupta', 'Cardiology', 15]
As an applicant for the post of a Programmer, you have to answer the following questions in this context :
(I) Write one difference of storing this data in a binary file over a CSV file.
(II) Assume that the data is stored in a binary file, named DOCTORS.DAT, and each record is stored as a list. Write a function, in Python, to read and display all the records from the file DOCTORS.DAT.
(III) Write a function addDoctor(), in Python, which accepts a doctor's data from the user and writes it in the file DOCTORS.DAT.
Which of the following statement is incorrect in the context of binary files?
a) Information is stored in the same format in which the information is held in memory.
b) No character translation takes place.
c) Every line ends with a new line character.
d) pickle module is used for reading and writing.
Which of the following statement is true?
a) pickling creates an object from a sequence of bytes
b) pickling is used for object serialization
c) pickling is used for object deserialization
d) pickling is used to manage all types of files in Python
Which of the following statement opens a binary file record.bin in write mode and writes data from a list lst1 = [1,2,3,4] on the binary file?
a) with open('record.bin','wb') as myfile:
pickle.dump(lst1,myfile)
b) with open('record.bin','wb') as myfile:
pickle.dump(myfile,lst1)
c) with open('record.bin','wb+') as myfile:
pickle.dump(myfile,lst1)
d) with open('record.bin','ab') as myfile:
pickle.dump(myfile,lst1)
Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on a binary file test.bin. Consider the following code written by him.
import pickle
tup1 = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle._______ #Statement 1
myfile.close()
Identify the missing code in Statement 1.
a) dump(myfile,tup1)
b) dump(tup1, myfile)
c) write(tup1,myfile)
d) load(myfile,tup1)
A binary file employee.dat has the following data:
| Empno | Empname | Salary |
|---|---|---|
| 101 | Anuj | 50000 |
| 102 | Arijita | 40000 |
| 103 | Hanika | 30000 |
| 104 | Firoz | 60000 |
| 105 | Vijaylakshmi | 40000 |
def display(eno):
f=open("employee.dat","rb")
totSum=0
try:
while True:
R=pickle.load(f)
if R[0]==eno:
__________ #Line1
totSum=totSum+R[2]
except:
f.close()
print(totSum)
When the above mentioned function display(103) is executed, the output displayed is 190000.
Write appropriate jump statement from the following to obtain the above output.
a) jump
b) break
c) continue
d) return
Aman is a Python programmer. He has written a code and created a binary file record.dat with employeeid, ename and salary. The file contains 10 records.
He now has to update a record based on the employee id entered by the user and update the salary. The updated record is then to be written in the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat. If the employee id is not found, an appropriate message should be displayed.
import _______ #Statement 1
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary :: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat and in Statement 4 to write the updated data in the file, temp.dat?
(i) Differentiate between r+ and w+ file modes in Python.
(ii) Consider a file, SPORT.DAT, containing records of the following structure:
[SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the records with Sport name as "Basket Ball" to the file named BASKET.DAT. The function should return the total number of records copied to the file BASKET.DAT.
OR
(i) How are text files different from binary files?
(ii) A Binary file, CINEMA.DAT has the following structure:
{MNO:[MNAME, MTYPE]}
Where MNO – Movie Number, MNAME – Movie Name, MTYPE is Movie Type.
Write a user defined function, findType(mtype), that accepts mtype as parameter and displays all the records from the binary file CINEMA.DAT, that have the value of Movie Type as mtype.
Surya is a manager working in a recruitment agency. He needs to manage the records of various candidates. For this, he wants the following information of each candidate to be stored:
- Candidate_ID – integer
- Candidate_Name – string
- Designation – string
- Experience – float
You, as a programmer of the company, have been assigned to do this job for Surya.
(I) Write a function to input the data of a candidate and append it in a binary file.
(II) Write a function to update the data of candidates whose experience is more than 10 years and change their designation to "Senior Manager".
(III) Write a function to read the data from the binary file and display the data of all those candidates who are not "Senior Manager".
Mr. Ravi, a manager at a tech company, needs to maintain records of employees. Each record should include: Employee_ID, Employee_Name, Department and Salary.
Write the Python functions to:
I. Input employee data and append it to a binary file. (2 marks)
II. Update the salary of employees in the "IT" department to 200000. (3 marks)
(a) Write one difference between CSV and text files.
Write a program in Python that defines and calls the following user defined functions :
(i) COURIER_ADD(): It takes the values from the user and adds the details to a csv file 'courier.csv'. Each record consists of a list with field elements as cid, s_name, Source, destination to store Courier ID, Sender name, Source and destination address respectively.
(ii) COURIER_SEARCH() : Takes the destination as the input and displays all the courier records going to that destination.
OR
(b) Why it is important to close a file before exiting ?
Write a program in Python that defines and calls the following user defined functions :
(i) Add_Book(): Takes the details of the books and adds them to a csv file 'Book.csv'. Each record consists of a list with field elements as book_ID, B_name and pub to store book ID, book name and publisher respectively.
(ii) Search_Book(): Takes publisher name as input and counts and displays number of books published by them.
Write the user defined function to modify the quantity of a product.
The function should accept the product number, and the new quantity as arguments and update the quantity of that product in a CSV file "Product.csv".
OR
Write the user defined function Modify() to read a text file "data.txt" and replace all the occurrences of "COmputer" with "Computer" and display all the lines on screen.
Write a user defined function in Python named write_data() to write the data in a CSV file Stock.csv with field names Product_Name, Product_ID, Quantity, Price as shown below:
| Product_Name | Product_ID | Quantity | Price |
|---|---|---|---|
| Keyboard | P101 | 10 | 800 |
| Mouse | P102 | 12 | 600 |
| Monitor | P103 | 5 | 5000 |
| CPU | P104 | 8 | 10000 |
OR
Write the following Python functions:
(i) push_record(): To push the product details of the products whose price is more than 500 into the stack Record.
(ii) pop_record(): To pop the elements from the stack and display. Also display "No Record" when there are no elements in the stack.
Consider the table RESULT given below.
| ROLL | SUBJECT | MARKS |
|---|---|---|
| S01 | Physics | 90 |
| S02 | Chemistry | 98 |
| S03 | Maths | 80 |
| S04 | Physics | 95 |
| S05 | Chemistry | 75 |
| S06 | Maths | 97 |
Write a program in Python to write the above data in a CSV file named RESULT.csv and display the records of all those students who are getting marks more than 80.
OR
Write a program in Python to create a text file MARKS.TXT and write the names of all those students and their total marks obtained in Physics, Chemistry and Maths whose total marks are greater than 220.
A csv file "States.csv" contains some data about all the states of India. Each record of the file contains the following data :
· Name of the State
· Capital of the State
· Population of the State
· Official Language of the State
For example, a sample record in the file is :
['Andhra Pradesh', 'Amaravati', 52221000, 'Telugu']
Write a Python program which reads the data from this file and appends all those records where population is more than 10000000 into another csv file 'More.csv'.
Note : "States.csv" also contains the Header row. The Header row should NOT be copied to "More.csv".
(a) Write a point of difference between append (a) and write (w) modes in a text file.
Write a program in Python that defines and calls the following user defined functions :
(i) Add_Teacher() : It accepts the values from the user and inserts record of a teacher to a csv file "Teacher.csv". Each record consists of a list with field elements as T_id, Tname and desig to store teacher ID, teacher name and designation respectively.
(ii) Search_Teacher() : To display the records of all the PGT (designation) teachers.
OR
(b) Write one point of difference between seek() and tell() functions in file handling.
Write a program in Python that defines and calls the following user defined functions :
(i) Add_Device() : The function accepts and adds records of the peripheral devices to a csv file 'peripheral.csv'. Each record consists of a list with field elements as P_id, P_name and Price to store peripheral device ID, device name, and price respectively.
(ii) Count_Device() : To count and display number of peripheral devices, whose price is less than or equal to 1000.
Mr. Mahesh is a Python Programmer working in a school. He has to maintain the records of the sports students. He has created a csv file named sports.csv, to store the details. The structure of sports.csv is :
[sport_id, competition, prize_won]
where
sport_id, is Sport id (integer)
competition is competition name (string)
prize_won is ("Gold", "Silver", "Bronze")
Mr. Mahesh wants to write the following user-defined functions :
Add_detail() : to accept the detail of a student and add to a csv file, "sports.csv".
Count_Medal() : to display the name of competitions in which students have won "Gold" medal.
Help him in writing the code of both the functions.
Suman is an intern at a software startup. The company has assigned her a task to create a CSV file named CLUB.CSV, to store the records of the Club members. After discussing with Club Incharge, Suman has planned to store the following content of members in the file CLUB.CSV :
[Mno, Name, Mobile, Fee]
Where Mno – Member Number, Name – Name of the Member, Mobile – Member's Mobile Number, Fee – Fee amount
Assuming you are asked to help Suman in her assignment, write a Python code for performing the following tasks with the help of user-defined functions :
NewMembers() : to accept records of members from the user and add them to the file CLUB.CSV
PriorityMember() : to find and display those members from the file CLUB.CSV, who are paying Fee more than 35000.
Which of the following character acts as default delimiter in a csv file?
a) (colon) :
b) (hyphen) -
c) (comma) ,
d) (vertical line) |
Syntax for opening Student.csv file in write mode is myfile = open("Student.csv","w",newline='').
What is the importance of newline=''?
a) A newline gets added to the file
b) Empty string gets appended to the first line.
c) Empty string gets appended to all lines.
d) EOL translation is suppressed
What is the correct expansion of CSV files?
a) Comma Separable Values
b) Comma Separated Values
c) Comma Split Values
d) Comma Separation Values
Which of the following is not a function/method of csv module in Python?
a) read()
b) reader()
c) writer()
d) writerow()
Rohit, a student of class 12, is learning CSV File Module in Python. During examination, he has been assigned an incomplete python code to create a CSV File 'Student.csv' with content:
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code:
import _____ #Statement-1
fh = open(_____, _____, newline='') #Statement-2
stuwriter = csv._____ #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [_____] #Statement-4
data.append(_____) #Statement-5
stuwriter._____(data) #Statement-6
fh.close()
Identify the suitable code for blank space in the line marked as Statement-1.
a) csv file
b) CSV
c) csv
d) cvs
Identify the missing code for blank space in line marked as Statement-2.
(Refer to the CSV file creation code in the case study: fh = open(_____, _____, newline=''))
a) "Student.csv","wb"
b) "Student.csv","w"
c) "Student.csv","r"
d) "Student.cvs","r"
Choose the function name (with argument) that should be used in the blank space of line marked as Statement-3.
(Refer to the CSV file creation code in the case study: stuwriter = csv._____)
a) reader(fh)
b) reader(MyFile)
c) writer(fh)
d) writer(MyFile)
Identify the suitable code for blank space in line marked as Statement-4.
(Refer to the CSV file creation code in the case study: rec = [_____])
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section'
d) roll_no,name,Class,section
Identify the suitable code for blank space in the line marked as Statement-5.
(Refer to the CSV file creation code in the case study: data.append(_____) )
a) data
b) record
c) rec
d) insert
Choose the function name that should be used in the blank space of line marked as Statement-6 to create the desired CSV File.
(Refer to the CSV file creation code in the case study: stuwriter._____(data))
a) dump()
b) load()
c) writerows()
d) writerow()
Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a text file.
Reason (R): The information is organized with one record on each line and each field is separated by comma.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True
What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of an employee to a CSV file 'record.csv'. Each record consists of a list with field elements as empid, name and mobile to store employee id, employee name and employee salary respectively.
(ii) COUNTR() – To count the number of records present in the CSV file named 'record.csv'.
OR
Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
(i) add() – To accept and add data of an employee to a CSV file 'furdata.csv'. Each record consists of a list with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price respectively.
(ii) search() – To display the records of the furniture whose price is more than 10000.
Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has created a csv file named Result.csv, to store the results of students in different sports events. The structure of Result.csv is:
[St_Id, St_Name, Game_Name, Result]
Where:
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating (string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user defined functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.
A csv file "Happiness.csv" contains the data of a survey. Each record of the file contains the following data:
- Name of a country
- Population of the country
- Sample Size (Number of persons who participated in the survey in that country)
- Happy (Number of persons who accepted that they were Happy)
For example, a sample record of the file may be: ['Signiland', 5673000, 5000, 3426]
Write the following Python functions to perform the specified operations on this file:
(I) Read all the data from the file in the form of a list and display all those records for which the population is more than 5000000.
(II) Count the number of records in the file.
Raj is the manager of a medical store. To keep track of sales records, he has created a CSV file named Sales.csv, which stores the details of each sale.
The columns of the CSV file are: Product_ID, Product_Name, Quantity_Sold and Price_Per_Unit.
Help him to efficiently maintain the data by creating the following user-defined functions:
I. Accept() – to accept a sales record from the user and add it to the file Sales.csv.
II. CalculateTotalSales() – to calculate and return the total sales based on the Quantity_Sold and Price_Per_Unit.
"Stack is a linear data structure which follows a particular order in which the operations are performed."
What is the order in which the operations are performed in a Stack ?
Name the List method/function available in Python which is used to remove the last element from a list implemented stack.
Also write an example using Python statements for removing the last element of the list.
Write the definition of a user defined function PushNv(N) which accepts a list of strings in the parameter N and pushes all strings which have no vowels present in it, into a list named NoVowel.
Write a program in Python to input 5 words and push them one by one into a list named All.
The program should then use the function PushNV() to create a stack of words in the list NoVowel so that it stores only those words which do not have any vowel present in it, from the list All.
Thereafter, pop each word from the list NoVowel and display the popped word. When the stack is empty display the message "EmptyStack".
For example :
If the Words accepted and pushed into the list All are
['DRY', 'LIKE', 'RHYTHM', 'WORK', 'GYM']
Then the stack NoVowel should store
['DRY', 'RHYTHM', 'GYM']
And the output should be displayed as
GYM RHYTHM DRY EmptyStack
OR
Write the definition of a user defined function Push3_5(N) which accepts a list of integers in a parameter N and pushes all those integers which are divisible by 3 or divisible by 5 from the list N into a list named Only3_5.
Write a program in Python to input 5 integers into a list named NUM.
The program should then use the function Push3_5() to create the stack of the list Only3_5. Thereafter pop each integer from the list Only3_5 and display the popped value. When the list is empty, display the message "StackEmpty".
For example :
If the integers input into the list NUM are :
[10, 6, 14, 18, 30]
Then the stack Only3_5 should store
[10, 6, 18, 30]
And the output should be displayed as
30 18 6 10 StackEmpty
Assertion (A) : A stack is a LIFO structure.
Reason (R) : Any new element pushed into the stack always gets positioned at the index after the last existing element in the stack.
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but (R) is true.
(a) A list contains following record of customer:
[Customer name, Room Type]
Write the following user defined functions to perform given operations on the stack named 'Hotel':
(i) Push_Cust() — To Push customers' names of those customers who are staying in 'Delux' Room Type.
(ii) Pop_Cust() — To Pop the names of customers from the stack and display them. Also, display "Underflow" when there are no customers in the stack.
For example :
If the lists with customer details are as follows :
["Siddarth", "Delux"]
["Rahul", "Standard"]
["Jerry", "Delux"]
The stack should contain
Jerry
Siddharth
The output should be:
Jerry
Siddharth
Underflow
OR
(b) Write a function in Python, Push(Vehicle) where, Vehicle is a dictionary containing details of vehicles — {Car Name: Maker}.
The function should push the name of car manufactured by 'TATA' (including all the possible cases like Tata, TaTa, etc.) to the stack.
For example:
If the dictionary contains the following data:
Vehicle={"Santro": "Hyundai", "Nexon": "TATA", "Safari": "Tata"}
The stack should contain
Safari
Nexon
A list contains the details of Employees working in an organization. Write the following user defined functions in Python to perform the given operations:
(i) Push_Employee(EmpList) : To push the details of the employees into the stack EmpStack who are working in Admin department.
(ii) Pop_Employee() : To pop the elements from the stack and display. Also display "Empty" when there are no elements in the stack.
For example:
If the list contains the details as:
['EMP01','Raj','Admin']
['EMP02','Shreya','HR']
['EMP03','Rohan','Admin']
['EMP04','Anita','Admin']
['EMP05','Priya','HR']
The output should be:
Anita
Rohan
Empty
Write a user defined function in Python Push() which takes a list named DATA as an argument and pushes all elements which contain the substring 'books' (case insensitive) onto the list SBOOKS.
OR
Write a user defined function in Python Push() which takes a list named DATA as an argument and pushes all even numbers in the list on to the list EVENLIST.
A list contains the names of boys who participated in an inter school level swimming competition. Write the following user defined functions in Python to perform given operations:
(i) Push_element(Boys) : To push the names of boys in the stack where the length of the name is more than 5 characters.
(ii) Pop_element() : To pop the elements from the stack and display them. Also display "Stack Empty" when there are no elements in the stack.
For example:
If the list of boys who participated in the competition is :
['Rohit', 'Rahul', 'Rishabh', 'Virat', 'Hardik']
The stack should contain
['Rishabh', 'Hardik']
The output should be displayed as:
Hardik
Rishabh
Stack Empty
(a) A stack named FruitStack, implemented using list, contains records of some fruits. Each record is represented as a dictionary with keys 'Name', 'Origin', 'Price', and 'Expiry'.
A sample record is given here :
{'Name':'Apple', 'Origin':'France', 'Price':120, 'Expiry':'12-08-2025'}
Write the following user-defined functions in Python to perform the specified operations on FruitStack :
(i) push_fruit(FruitStack, Fruit): This function takes the stack FruitStack and a new record Fruit as arguments and pushes the record stored in Fruit onto FruitStack if the Price is less than 100.
(ii) pop_fruit(FruitStack) : This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display "UNDERFLOW".
(iii) display(FruitStack) : This function displays all the elements of the stack starting from the topmost element. If the stack is empty, the function should display 'EMPTY STACK'.
OR
(b) Write a Python program to accept 10 integers from the user. If the entered number is a three-digit even integer, push it onto a stack. After all inputs are taken, pop all the three-digit even integers from the stack and display them. For example, if the user enters 12, 31, 320, 457, 6, 92, 924, 220, 1, 218, then the stack should contain :
320, 924, 220, 218
and the output of the program should be :
218 220 924 320
Differentiate between Push and Pop operations in the context of stacks.
(a) Write separate user defined functions for the following :
(i) PUSH (N) — This function accepts a list of names, N as parameter. It then pushes only those names in the stack named OnlyA which contain the letter 'A'.
(ii) POPA(OnlyA) — This function pops each name from the stack OnlyA and displays it. When the stack is empty, the message "EMPTY" is displayed.
For example :
If the names in the list N are
['ANKITA', 'NITISH', 'ANWAR', 'DIMPLE', 'HARKIRAT']
Then the stack OnlyA should store
['ANKITA', 'ANWAR', 'HARKIRAT']
And the output should be displayed as
HARKIRAT ANWAR ANKITA EMPTY
OR
(b) Write the following user defined functions :
(i) pushEven(N) — This function accepts a list of integers named N as parameter. It then pushes only even numbers into the stack named EVEN.
(ii) popEven(EVEN) — This function pops each integer from the stack EVEN and displays the popped value. When the stack is empty, the message "Stack Empty" is displayed.
For example :
If the list N contains
[10,5,3,8,15,4]
Then the stack, EVEN should store
[10,8,4]
And the output should be
4 8 10 Stack Empty
Assertion (A): In Python, a stack can be implemented using a list.
Reasoning (R): A stack is an ordered linear list of elements that works on the principle of First In First Out (FIFO).
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but (R) is true.
A list contains following record of course details for a University :
[Course name, Fees, Duration]
Write the following user defined functions to perform given operations on the stack named 'Univ' :
(i) Push_element() — To push an object containing the Course_name, Fees and Duration of a course, which has fees greater than 100000 to the stack.
(ii) Pop_element() — To pop the object from the stack and display it. Also, display "Underflow" when there is no element in the stack.
For example :
If the lists of courses details are :
["MCA",200000,3]
["MBA",500000,2]
["BA",100000,3]
The stack should contain :
["MBA",500000,2]
["MCA",200000,3]
A dictionary, d_city contains the records in the following format :
{state:city}
Define the following functions with the given specifications :
(i) push_city(d_city) : It takes the dictionary as an argument and pushes all the cities in the stack CITY whose states are of more than 4 characters.
(ii) pop_city() : This function pops the cities and displays "Stack empty" when there are no more cities in the stack.
(a) A stack named KeyStack contains records of some computer keyboards. Each record is represented as a list containing Make, Keys, Connectivity. The Make and Connectivity are strings, and Keys is an integer. For example, a record in the stack may be ('Hitech', 105, 'USB').
Write the following user-defined functions in Python to perform the specified operations on KeyStack :
(I) push_key(KeyStack, new_key) : This function takes the stack KeyStack and a new record as arguments new_key and pushes this new record onto the stack.
(II) pop_key(KeyStack) : This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display the message "Underflow".
(III) isEmpty(KeyStack) : This function checks whether the stack is empty. If the stack is empty, the function should return True, otherwise the function should return False.
OR
(b) Write the following user-defined functions in Python :
(I) push_vowels(S,St) : Here S is a string and St is a list representing a stack. The function should push all the vowels of the string S onto the stack St. For example, if the string S is "Easy Concepts", then the function push_vowels() should push the elements 'E','a','o','e' onto the stack.
(II) pop_one(St) : The function should pop an element from the stack St, and return this element. If the stack is empty, then the function should display the message 'Stack Underflow', and return None.
(III) display_all(St) : The function should display all the elements of the stack St, without deleting them. If the stack is empty, the function should display the message 'Empty Stack'.
A list contains following record of a customer:
[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack named 'status':
(i) Push_element() - To Push an object containing name and Phone number of customers who live in Goa to the stack.
(ii) Pop_element() - To Pop the objects from the stack and display them. Also, display "Stack Empty" when there are no elements in the stack.
For example:
If the lists of customer details are:
["Gurdas", "99999999999","Goa"]
["Julee", "8888888888","Mumbai"]
["Murugan","77777777777","Cochin"]
["Ashmit", "1010101010","Goa"]
The stack should contain:
["Ashmit","1010101010"]
["Gurdas","9999999999"]
The output should be:
["Ashmit","1010101010"]
["Gurdas","9999999999"]
Stack Empty
OR
Write a function in Python, Push(SItem) where SItem is a dictionary containing the details of stationary items – {Sname:price}.
The function should push the names of those items in the stack who have price greater than 75. Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
The stack should contain:
Notebook
Pen
The output should be:
The count of elements in the stack is 2
A list, NList contains following record as list elements:
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined functions in Python to perform the specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object containing name of the city and country, which are not in India and distance is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the function should display "Stack Empty" when there are no elements in the stack.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar']
['Dubai', 'UAE']
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
A) You have a stack named BooksStack that contains records of books. Each book record is represented as a list containing book_title, author_name, and publication_year.
Write the following user-defined functions in Python to perform the specified operations on the stack BooksStack:
(I) push_book(BooksStack, new_book): This function takes the stack BooksStack and a new book record new_book as arguments and pushes the new book record onto the stack.
(II) pop_book(BooksStack): This function pops the topmost book record from the stack and returns it. If the stack is already empty, the function should display "Underflow".
(III) peep(BookStack): This function displays the topmost element of the stack without deleting it. If the stack is empty, the function should display 'None'.
OR
B) Write the definition of a user-defined function push_even(N) which accepts a list of integers in a parameter N and pushes all those integers which are even from the list N into a Stack named EvenNumbers.
Write function pop_even() to pop the topmost number from the stack and returns it. If the stack is already empty, the function should display "Empty".
Write function Disp_even() to display all elements of the stack without deleting them. If the stack is empty, the function should display 'None'.
For example:
If the integers input into the list VALUES are: [10, 5, 8, 3, 12]
Then the stack EvenNumbers should store: [10, 8, 12]
A list containing records of products as
L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]
Write the following user-defined functions to perform operations on a stack named Product to:
I. Push_element() – To push an item containing the product name and price of products costing more than 50 into the stack.
Output: [('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]
II. Pop_element() – To pop the items from the stack and display them. Also, display "Stack Empty" when there are no elements in the stack.
Output:
('Headphones', 1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Empty
Expand ARPANET.
Fill in the blank :
In ________ switching, before a communication starts, a dedicated path is identified between the sender and the receiver.
(a) Packet
(b) Graph
(c) Circuit
(d) Plot
Write two points of difference between Circuit Switching and Packet Switching.
OR
Write two points of difference between XML and HTML.
Fill in the blank:
In case of _____________ switching, before a communication starts, a dedicated path is identified between the sender and the receiver.
Which switching technique breaks data into smaller packets for transmission, allowing multiple packets to share the same network resources?
Expand the following abbreviations:
1. NIU
2. MAC
3. TCP/IP
4. PAN
5. LAN
6. MAN
Expand the following abbreviations:
1. EMI
2. SIM
3. EDGE
4. UMTS
5. LTE
6. GPRS
Define baud, bps and Bps. How are these interlinked?
Differentiate between circuit switching and message switching.
Fill in the blank :
________ is used for point-to-point communication or unicast communication such as radar and satellite.
(a) INFRARED WAVES
(b) BLUETOOTH
(c) MICROWAVES
(d) RADIOWAVES
(a) Differentiate between wired and wireless transmission.
OR
(b) Differentiate between URL and domain name with the help of an appropriate example.
Which of the following is not a guided medium?
(A) Twisted pair cable
(B) Co-axial cable
(C) Fibre optic cable
(D) Microwave
(a) Write any two differences between Fiber-optic cable and Coaxial cable.
OR
(b) Write one advantage and one disadvantage of wired over wireless communication.
Expand the following abbreviations:
1. WAN
2. UTP
3. STP
4. RJ
5. Wi-Fi
6. VPN
Give one example of each – Guided media and Unguided media.
Name the transmission media best suitable for connecting to desert areas.
Rearrange the following terms in increasing order of speedy medium of data transfer:
Telephone line, Fiber Optics, Coaxial Cable, Twisted Paired Cable.
Name the transmission media suitable to establish PAN.
Name the transmission media best suitable for connecting to hilly areas.
Name the fastest available transmission media.
Which of the following communication medium requires line of sight communication?
Microwave, radio wave, infrared, Bluetooth
Write any two differences between a Hub and a Switch.
OR
Write any two differences between a Router and a Gateway.
Which of the following networking devices is used to regenerate and transmit the weakened signal ahead?
(A) Hub
(B) Ethernet Card
(C) Repeater
(D) Modem
With respect to computer networks, which of the following is the correct expanded form of RJ 45 ?
(A) Radio Jockey 45
(B) Registered Jockey 45
(C) Radio Jack 45
(D) Registered Jack 45
Which network device serves as the entry and exit point of a network, as all data coming in or going out of a network must first pass through it in order to use routing paths ?
(A) Modem
(B) Gateway
(C) Switch
(D) Repeater
Ethernet card is also known as :
(A) LIC
(B) MIC
(C) NIC
(D) OIC
Which of the following devices is essential to set up a wired LAN ?
(A) Modem
(B) NIC
(C) Repeater
(D) Firewall
Which network device serves as the entry and exit point of a network, as all data coming in or going out of a network must first pass through it ?
(A) Modem
(B) Gateway
(C) Switch
(D) Repeater
(I) (a) Expand the following terms : POP, TCP
OR
(II) (a) Write any one difference between a hub and a switch used in computer networks.
OR
(b) Write any one difference between HTTP and HTTPS.
(b) Write names of any two wireless transmission media.
Fill in the blank:
The modem at the sender's computer end acts as a ____________.
a) Model
b) Modulator
c) Demodulator
d) Convertor
Which network device is used to connect two networks that use different protocols?
a) Modem
b) Gateway
c) Switch
d) Repeater
Which of the following is correct about using a Hub and Switch in a computer network?
a) A hub sends data to all devices in a network, while a switch sends data to the specific device.
b) A hub sends data only to the devices it is connected to, while a switch sends data to all devices in a network.
c) A hub and switch function the same way and can be used interchangeably.
d) A hub and switch are both wireless networking devices.
A. Define the following terms:
I. Modem
II. Gateway
Expand the following abbreviations:
1. NIC
2. IAAS
3. PAAS
4. SAAS
5. DAAS
6. IOT
What is the difference between hub and switch? Which is more preferable in a large network of computers and why?
Define network interface card.
Define the following:
(i) RJ-45
(ii) modem
(iii) Ethernet card
(iv) firewall
(v) Switch
Differentiate between:
(a) hub and switch
(b) Bridge and gateway
(i) Differentiate between Bus Topology and Tree Topology. Also, write one advantage of each of them.
OR
Differentiate between HTML and XML.
(ii) What is a web browser ? Write the names of any two commonly used web browsers.
Galaxy Provider Ltd. is planning to connect its office in Texas, USA with its branch at Mumbai. The Mumbai branch has 3 Offices in three blocks located at some distance from each other for different operations — ADMIN, SALES and ACCOUNTS.
Layout of the Offices in the Mumbai branch :
Admin Block, Sales Block, Accounts Block
Shortest distances between various locations :
ADMIN Block to SALES Block 300 m
SALES Block to ACCOUNTS Block 175 m
ADMIN Block to ACCOUNTS Block 350 m
MUMBAI Branch to TEXAS Head Office 14000 km
Number of Computers installed at various locations are as follows :
ADMIN Block 255
ACCOUNTS Block 75
SALES Block 30
TEXAS Head Office 90
(a) It is observed that there is a huge data loss during the process of data transfer from one block to another. Suggest the most appropriate networking device out of the following, which needs to be placed along the path of the wire connecting one block office with another to refresh the signal and forward it ahead.
(i) MODEM
(ii) ETHERNET CARD
(iii) REPEATER
(iv) HUB
(b) Which hardware networking device out of the following, will you suggest to connect all the computers within each block ?
(i) SWITCH
(ii) MODEM
(iii) REPEATER
(iv) ROUTER
(c) Which service/protocol out of the following will be most helpful to conduct live interactions of employees from Mumbai Branch and their counterparts in Texas ?
(i) FTP
(ii) PPP
(iii) SMTP
(iv) VoIP
(d) Draw the cable layout (block to block) to efficiently connect the three offices of the Mumbai branch.
Quickdev, an IT based firm, located in Delhi is planning to set up a network for its four branches within a city with its Marketing department in Kanpur. As a network professional, give solutions to the questions (i) to (v), after going through the branches locations and other details which are given below :
DELHI BRANCH
BRANCH A BRANCH B
BRANCH C BRANCH D
Distance between various branches is as follows:
| Branch | Distance |
|---|---|
| Branch A to Branch B | 40 m |
| Branch A to Branch C | 80 m |
| Branch A to Branch D | 65 m |
| Branch B to Branch C | 30 m |
| Branch B to Branch D | 35 m |
| Branch C to Branch D | 15m |
| Delhi Branch to Kanpur | 300 km |
Number of computers in each of the branches :
| Branch | Number of Computers |
|---|---|
| Branch A | 15 |
| Branch B | 25 |
| Branch C | 40 |
| Branch D | 115 |
(i) Suggest the most suitable place to install the server for the Delhi branch with a suitable reason.
(ii) Suggest an ideal layout for connecting all these branches within Delhi.
(iii) Which device will you suggest, that should be placed in each of these branches to efficiently connect all the computers within these branches ?
(iv) Delhi firm is planning to connect to its Marketing department in Kanpur which is approximately 300 km away. Which type of network out of LAN, WAN or MAN will be formed ? Justify your answer.
(v) Suggest a protocol that shall be needed to provide help for transferring of files between Delhi and Kanpur branch.
Which topology requires a central controller or hub?
(A) Mesh
(B) Star
(C) Ring
(D) Tree
Sonal is working in Infosys Technologies Ltd. located in Bangalore. The company has 4 wings of the same building named Wing 1, Wing 2, Wing 3 and Wing 4 in the same premises.
The distance between various wings are as follows:
Wing 1 to Wing 2: 55 m
Wing 1 to Wing 3: 65 m
Wing 1 to Wing 4: 120 m
Wing 2 to Wing 3: 50 m
Wing 2 to Wing 4: 115 m
Wing 3 to Wing 4: 60 m
Wing 1 has 60 computers, Wing 2 has 80 computers, Wing 3 has 70 computers and Wing 4 has 65 computers.
(a) Suggest the most suitable place to install the server in the network with a suitable reason.
(b) Suggest the most suitable place to install the Repeater to get good connectivity among all the wings.
(c) Suggest the most suitable cable layout for connecting all four wings in the same premises.
(d) Identify the topology that is being used here.
(a) List one advantage and one disadvantage of Bus topology.
OR
(b) What is protocol in the context of computer networks? Which protocol is used to transmit hypertext across the web?
Sanjeevani is a big group of educational institutions with its head office in Hyderabad. It is planning to set up a new University in Amritsar. The Amritsar University Campus will have four blocks/buildings – ADMIN, ACADEMIC, HOSTEL, SPORTS. You, as a network expert, need to suggest the best network-related solutions for them to resolve the issues/problems mentioned in points (i) to (v), keeping in mind the distances between various blocks/buildings and other given parameters.
Amritsar University Campus
ADMIN Block ACADEMIC Block
HOSTEL Block SPORTS Block
Block to Block distances (in Mtrs.)
| FROM | TO | DISTANCE |
|---|---|---|
| ADMIN | ACADEMIC | 60 M |
| ADMIN | HOSTEL | 160 M |
| ADMIN | SPORTS | 80 M |
| ACADEMIC | HOSTEL | 40 M |
| ACADEMIC | SPORTS | 120 M |
| HOSTEL | SPORTS | 150 M |
Distance of Hyderabad Head Office from Amritsar University Campus = 2000 km.
Number of computers in each block is as follows :
ADMIN 25
ACADEMIC 600
HOSTEL 120
SPORTS 50
(i) Suggest the most appropriate location of the server inside the Amritsar University Campus. Justify your choice.
(ii) Draw the cable layout to efficiently connect various blocks within the Amritsar University Campus.
(iii) Name any two wired media that can be used to connect various computers of a block inside Amritsar Campus.
(iv) For the academic purpose, the University will provide its own 24 x 7 FM channel within the University Campus. Which communication medium, out of the following, is used by FM ?
(A) Radio Waves
(B) Micro Waves
(C) Infrared Waves
(v) (a) The students will be attending a lot of online academic sessions and workshops. These will involve audio-visual communication. Write the full name of the protocol which will be used for such a communication through the internet.
OR
(b) Where should a repeater be installed in Amritsar University campus to boost the signal between blocks ? Justify your answer.
(a) (i) Mention any two characteristics of BUS Topology.
OR
(ii) Differentiate between the terms Domain Name and URL in the context of World Wide Web.
(b) Write the names of two wired and two wireless data transmission mediums.
The government has planned to develop digital awareness in the rural areas of the nation. According to the plan, an initiative is taken to set up Digital Training Centers in villages across the country with its Head Office in the nearest cities. The committee has hired a networking consultancy to create a model of the network in which each City Head Office is connected to the Training Centers situated in 3 nearby villages.
Layout of the City Head Office and Village Training Centers :
City Head Office, Village 1 Training Center, Village 2 Training Center, Village 3 Training Center
Shortest distances between various Centers :
Village 1 Training Center to City Head Office 2 KM
Village 2 Training Center to City Head Office 1.5 KM
Village 3 Training Center to City Head Office 3 KM
Village 1 Training Center to Village 2 Training Center 3.5 KM
Village 1 Training Center to Village 3 Training Center 4.5 KM
Village 2 Training Center to Village 3 Training Center 3.5 KM
Number of Computers installed at various centers are as follows :
Village 1 Training Center 10
Village 2 Training Center 15
Village 3 Training Center 15
City Head Office 100
(a) It is observed that there is a huge data loss during the process of data transfer from one village to another. Suggest the most appropriate networking device out of the following, which needs to be placed along the path of the wire connecting one village with another to refresh the signal and forward it ahead.
(i) MODEM
(ii) ETHERNET CARD
(iii) REPEATER
(iv) HUB
(b) Draw the cable layout (location-to-location) to efficiently connect various Village Training Centers and the City Head Office for the above shown layout.
(c) Which hardware networking device, out of the following, will you suggest to connect all the computers within the premises of every Village Training Center ?
(i) SWITCH
(ii) MODEM
(iii) REPEATER
(iv) ROUTER
(d) Which protocol, out of the following, will be most helpful to conduct online interactions of Experts from the City Head Office and people at the three Village Training Centers ?
(i) FTP
(ii) PPP
(iii) SMTP
(iv) VoIP
ABC Consultants are setting up a secure network for their office campus at Noida for their day-to-day office and web-based activities. They are planning to have connectivity between three buildings and the head office situated in Bengaluru. As a network consultant, give solutions to the questions (i) to (v), after going through the building locations and other details which are given below :
NOIDA BRANCH
BUILDING 1
BUILDING 2
BUILDING 3
BENGALURU BRANCH
HEAD OFFICE
Distance between various blocks/locations :
| Building | Distance |
|---|---|
| Building 1 to Building 3 | 120 m |
| Building 1 to Building 2 | 50 m |
| Building 2 to Building 3 | 65 m |
| Noida Branch to Head Office | 1500 km |
Number of computers
| Building | Number of Computers |
|---|---|
| Building 1 | 25 |
| Building 2 | 51 |
| Building 3 | 150 |
| Head Office | 10 |
(i) Suggest the most suitable place to install the server for this organization. Also, give reason to justify your suggested location.
(ii) Suggest the cable layout of connections between the buildings inside the campus.
(iii) Suggest the placement of the following devices with justification :
- Switch
- Repeater
(iv) The organization is planning to provide a high-speed link with the head office situated in Bengaluru, using a wired connection. Suggest a suitable wired medium for the same.
(v) The System Administrator does remote login to any PC, if any requirement arises. Name the protocol, which is used for the same.
Logistic Technologies Ltd. is a Delhi based organization which is expanding its office set-up to Ambala. At Ambala office campus, they are planning to have 3 different blocks for HR, Accounts and Logistics related work. Each block has a number of computers, which are required to be connected to a network for communication, data and resource sharing.
As a network consultant, you have to suggest the best network related solutions for them for issues/problems raised in (i) to (v), keeping in mind the distances between various block/locations and other given parameters.
Distances between various blocks/locations :
HR Block to Accounts Blocks 400 meters
Accounts Block to Logistics Block 200 meters
Logistics Block to HR Block 150 meters
Delhi Head Office to Ambala Office 220 Km
Number of computers installed at various blocks are as follows :
HR Block 70
Accounts Block 40
Logistics Block 30
(i) Suggest the most appropriate block/location to house the SERVER in the Ambala office. Justify your answer.
(ii) Suggest the best wired medium to efficiently connect various blocks within the Ambala office compound.
(iii) Draw an ideal cable layout (Block to Block) for connecting these blocks for wired connectivity.
(iv) The company wants to schedule an online conference between the managers of Delhi and Ambala offices. Which protocol will be used for effective voice communication over the Internet ?
(v) Which kind of network will it be between Delhi office and Ambala office ?
'CKNG Auto' is a big car-selling agency having its Head Office in Delhi. It is planning to set up a new branch in Patiala. The Patiala branch will have four blocks – ADMIN, SALES, SERVICE and INSURANCE. You, as a network expert, need to suggest the best network-related solutions for them to resolve the issues/problems mentioned in points (I) to (V), keeping the following parameters in mind.
Block to Block distances (in Metres)
| From | To | Distance |
|---|---|---|
| ADMIN | SALES | 70 m |
| ADMIN | SERVICE | 60 m |
| ADMIN | INSURANCE | 65 m |
| SALES | SERVICE | 80 m |
| SALES | INSURANCE | 100 m |
| SERVICE | INSURANCE | 60 m |
Distance of Delhi Head Office from Patiala branch = 250 km
Number of computers in each block is as follows :
Block No. of Computers
ADMIN 18
SALES 30
SERVICE 20
INSURANCE 10
(I) Suggest the most appropriate location of the server inside the Patiala branch. Justify your choice.
(II) What kind of network (PAN/LAN/MAN/WAN) will be formed by interconnecting all the computers inside a block ?
(III) Draw the most effective cable layout to connect all four blocks of Patiala branch.
(IV) Which device should be used to provide Internet connection to all the computers in the Patiala branch ?
(V) (a) Which is the best wired medium to connect server of Patiala office to the head office at Delhi ?
OR
(b) Is there a need for repeater(s) in Patiala branch ? Why, or why not ?
MakeInIndia Corporation, an Uttarakhand based IT training company, is planning to set up training centres in various cities in next 2 years. Their first campus is coming up in Kashipur district. At Kashipur campus, they are planning to have 3 different blocks for App development, Web designing and Movie editing.
Distance between various blocks/locations:
| Block | Distance |
|---|---|
| App development to Web designing | 28 m |
| App development to Movie editing | 55 m |
| Web designing to Movie editing | 32 m |
| Kashipur Campus to Mussoorie Campus | 232 km |
Number of computers:
| Block | Number of Computers |
|---|---|
| App development | 75 |
| Web designing | 50 |
| Movie editing | 80 |
(i) Suggest the most appropriate block/location to house the SERVER in the Kashipur campus (out of the 3 blocks) to get the best and effective connectivity. Justify your answer.
(ii) Suggest a device/software to be installed in the Kashipur Campus to take care of data security.
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to economically connect various blocks within the Kashipur Campus.
(iv) Suggest the placement of the following devices with appropriate reasons:
a. Switch / Hub
b. Repeater
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between Kashipur Campus and Mussoorie Campus.
Riya wants to transfer pictures from her mobile phone to her laptop. She uses Bluetooth Technology to connect two devices. Which type of network will be formed in this case?
a) PAN
b) LAN
c) MAN
d) WAN
Meticulous EduServe is an educational organization. It is planning to setup its India campus at Chennai with its head office at Delhi. The Chennai campus has 4 main buildings – ADMIN, ENGINEERING, BUSINESS and MEDIA.
Block to Block distances (in Mtrs.):
| From | To | Distance |
|---|---|---|
| ADMIN | ENGINEERING | 55 m |
| ADMIN | BUSINESS | 90 m |
| ADMIN | MEDIA | 50 m |
| ENGINEERING | BUSINESS | 55 m |
| ENGINEERING | MEDIA | 50 m |
| BUSINESS | MEDIA | 45 m |
| DELHI HEAD OFFICE | CHENNAI CAMPUS | 2175 km |
Number of computers in each of the blocks/Center:
| Block | Computers |
|---|---|
| ADMIN | 110 |
| ENGINEERING | 75 |
| BUSINESS | 40 |
| MEDIA | 12 |
| DELHI HEAD | 20 |
a) Suggest and draw the cable layout to efficiently connect various blocks of buildings within the CHENNAI campus for connecting the digital devices.
b) Which network device will be used to connect computers in each block to form a local area network?
c) Which block, in Chennai Campus should be made the server? Justify your answer.
d) Which fast and very effective wireless transmission medium should preferably be used to connect the head office at DELHI with the campus in CHENNAI?
e) Is there a requirement of a repeater in the given cable layout? Why/Why not?
A) List one advantage and one disadvantage of star topology.
OR
B) Expand the term SMTP. What is the use of SMTP?
Event Horizon Enterprises is an event planning organization. It is planning to set up its India campus in Mumbai with its head office in Delhi. The Mumbai campus will have four blocks/buildings - ADMIN, FOOD, MEDIA, DECORATORS. You, as a network expert, need to suggest the best network-related solutions for them to resolve the issues/problems mentioned in points (I) to (V), keeping in mind the distances between various blocks/buildings and other given parameters.
Block to Block distances (in Mtrs.):
| From | To | Distance |
|---|---|---|
| ADMIN | FOOD | 42 m |
| ADMIN | MEDIA | 96 m |
| ADMIN | DECORATORS | 48 m |
| FOOD | MEDIA | 58 m |
| FOOD | DECORATORS | 46 m |
| MEDIA | DECORATORS | 42 m |
Distance of Delhi Head Office from Mumbai Campus = 1500 km
Number of computers in each of the blocks/Center:
| Block | Computers |
|---|---|
| ADMIN | 30 |
| FOOD | 18 |
| MEDIA | 25 |
| DECORATORS | 20 |
| DELHI HEAD OFFICE | 18 |
(I) Suggest the most appropriate location of the server inside the MUMBAI campus. Justify your choice.
(II) Which hardware device will you suggest to connect all the computers within each building?
(III) Draw the cable layout to efficiently connect various buildings within the MUMBAI campus. Which cable would you suggest for the most efficient data transfer over the network?
(IV) Is there a requirement of a repeater in the given cable layout? Why/Why not?
(V)
A) What would be your recommendation for enabling live visual communication between the Admin Office at the Mumbai campus and the DELHI Head Office from the following options:
a) Video Conferencing
b) Email
c) Telephony
d) Instant Messaging
OR
B) What type of network (PAN, LAN, MAN, or WAN) will be set up among the computers connected in the MUMBAI campus?
XYZNova Inc. is planning a new campus in Hyderabad while maintaining its headquarters in Bengaluru. The campus will have four buildings: HR, Finance, IT, and Logistics.
Distance table (in meters):
| From | To | Distance (in meters) |
|---|---|---|
| HR | Finance | 50 |
| HR | IT | 175 |
| HR | Logistics | 90 |
| Finance | IT | 60 |
| Finance | Logistics | 70 |
| IT | Logistics | 60 |
Number of Computers in Each Block:
| Block | Number of Computers |
|---|---|
| HR | 60 |
| Finance | 40 |
| IT | 90 |
| Logistics | 35 |
I. Suggest the best location for the server in the Hyderabad campus and explain your reasoning.
II. Suggest the placement of the following devices:
a) Repeater
b) Switch
III. Suggest and draw a cable layout of connections between the buildings inside the campus.
IV. The organisation plans to provide a high-speed link with its head office using a wired connection. Which of the cables will be most suitable for this job?
V. A. What is the use of VoIP?
OR
B. Which type of network (PAN, LAN, MAN, or WAN) will be formed while connecting the Hyderabad campus to Bengaluru Headquarters?
A company has a MUMBAI campus with four buildings ADMIN, ACCOUNTS, EXAMINATION, and RESULT. The number of computers installed at various buildings are as follows:
| Building | Number of Computers |
|---|---|
| ADMIN | 110 |
| ACCOUNTS | 75 |
| EXAMINATION | 40 |
| RESULT | 12 |
| DELHI HEAD OFFICE | 20 |
Shortest distances between various buildings:
| From | To | Distance |
|---|---|---|
| ADMIN | ACCOUNTS | 55m |
| ADMIN | EXAMINATION | 90m |
| ADMIN | RESULT | 80m |
| ACCOUNTS | EXAMINATION | 55m |
| ACCOUNTS | RESULT | 50m |
| EXAMINATION | RESULT | 45m |
| DELHI Head Office | MUMBAI | 2150m |
(i) Suggest the most appropriate location of the server inside the MUMBAI campus (out of the four buildings) to get the best connectivity for maximum number of computers. Justify your answer.
(ii) Suggest and draw cable layout to efficiently connect various buildings within the MUMBAI campus for a wired network connectivity.
(iii) Which networking device will you suggest to be procured by the company to interconnect all the computers of various buildings of MUMBAI campus?
(iv) Company is planning to get its website designed which will allow students to see their results after registering themselves on its server. Out of the static or dynamic, which type of website will you suggest?
(v) Which of the following will you suggest to set up the online face to face communication between the people in the ADMIN office of Mumbai campus and Delhi head office and also write the protocol name used in this technology?
a) Cable TV
b) Email
c) Videoconferencing
d) Text chat
(vi) Suggest the placement of the following devices with justification if the company wants minimized network traffic:
a) Repeater
b) Hub/Switch
(vii) The company is planning to link its head office situated in New Delhi with the offices in hilly areas. Suggest a way to connect it economically.
(viii) The company wants internet accessibility in all the departments. Suggest a suitable technology.
1. If speed is main priority for company
2. If cost factor is important for company
(ix) The company is planning to link its head office situated in New Delhi. Which type of network out of LAN, WAN, MAN can be considered? Justify.
(x) The company is planning to link its office with other office situated in New York. Suggest a way to connect it economically.
(xi) Company wants a network security system (Hardware or Software) that can prevent unauthorized access to a network. How can company achieve this?
(xii) Name the fastest medium of internet to connect all the buildings with suitable reason?
Which type of network (out of LAN, PAN and MAN) is formed, when you connect two mobiles using Bluetooth to transfer a video?
Ravi has purchased a new Smart TV and wants to cast a video from his mobile to his new Smart TV. Identify the type of network he is using and explain it.
Identify the type of topologies on the basis of the following:
1. Since every node is directly connected to the server, a large amount of cable is needed which increases the installation cost of the network.
2. It has a single common data path connecting all the nodes.
Arrange the following networks based in descending order of area covered:
WAN, MAN, PAN, LAN
What are the similarities and differences between bus and tree topologies?
What are the limitations of star topology?
When do you think, ring topology becomes the best choice for a network?
Write the two advantages and two disadvantages of Bus Topology in network.
Uplifting Skills Hub India is a knowledge and skill community which has an aim to uplift the standard of knowledge and skills in society. It is planning to set up its training centres in multiple towns and villages pan India with its head offices in the nearest cities. They have created a model of their network with a city, a town, and 3 villages as follows.
As a network consultant, you have to suggest the best network related solutions for their issues/ problems raised in (i) to (v) keeping in mind the distance between various locations and given parameters.
Note:
In Villages, there are community centers, in which one room has been given as a training center for this organization to install computers. The organization has got financial support from the government and top IT companies.
i. Suggest the most appropriate location of the SERVER in the B_HUB (out of the 4 locations), to get the best and effective connectivity. Justify your answer.
ii. Suggest the best-wired medium and draw the cable layout (location to location) to efficiently connect various locations within the B_HUB.
iii. Which hardware device will you suggest to connect all the computers within each location of B_HUB?
iv. Which service/protocol will be most helpful to conduct live interactions of Experts from Head Office and people at all locations of B_HUB?
v. What kind of network will be formed between city head office and town?
Rehaana Medicos Centre has set up its new centre in Dubai. It has four buildings as shown in the diagram given below:
Distances between various buildings are as follows:
| From | To | Distance |
|---|---|---|
| Accounts | Research Lab | 55 m |
| Accounts | Store | 150 m |
| Store | Packaging Unit | 160 m |
| Packaging Unit | Research Lab | 60 m |
| Accounts | Packaging Unit | 125 m |
| Store | Research Lab | 180 m |
No of Computers:
| Building | Computers |
|---|---|
| Accounts | 25 |
| Research Lab | 100 |
| Store | 15 |
| Packaging Unit | 60 |
As a network expert, provide the best possible answer for the following queries:
i) Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place (i.e. buildings) to house the server of this organization.
iii) Suggest the placement of the Repeater device with justification.
iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the network.
(v) Suggest the placement of the Hub/ Switch with justification.
PVS Computers decided to open a new office at Ernakulum, the office consist of Five Buildings and each contains number of computers. The details are shown below.
| Building | Computers |
|---|---|
| Building 1 | 10 |
| Building 2 | 20 |
| Building 3 | 125 |
| Building 4 | 10 |
| Building 5 | 30 |
Computers in each building are networked but buildings are not networked so far. The Company has now decided to connect building also.
(i) Suggest a cable layout for connecting the buildings
(ii) Do you think anywhere Repeaters required in the campus? Why?
(iii) The company wants to link this office to their head office at Delhi
(a) Which type of transmission medium is appropriate for such a link?
(b) What type of network would this connection result into?
(iv) Where server is to be installed? Why?
(v) Suggest the wired Transmission Media used to connect all buildings efficiently.
'VidyaDaan' an NGO is planning to setup its new campus at Nagpur for its web-based activities. The campus has four (04) UNITS as shown below:
(i) Suggest an ideal topology for connecting the above UNITs.
(ii) Suggest the most suitable place i.e. UNIT to install the server for the above NGO.
(iii) Which network device is used to connect the computers in all UNITs?
(iv) Suggest the placement of Repeater in the UNITs of above network.
(v) NGO is planning to connect its Regional Office at Kota, Rajasthan. Which out of the following wired communication, will you suggest for a very high-speed connectivity?
'China Middleton Fashion' is planning to expand their network in India, starting with two cities in India to provide infrastructure for distribution of their product. The company has planned to set up their main office units in Chennai at three locations and have named their offices as 'Production Unit', 'Finance Unit' and 'Media Unit'. The company has its corporate unit in New Delhi. A rough layout of the same is as follows:
Approximate distances between these Units is as follows:
i) Suggest the kind of network required (out of LAN, MAN, WAN) for connecting each of the following office units:
a. Production Unit and Media Unit
b. Production Unit and Finance Unit
ii) Which of the following communication media, will you suggest to be procured by the company for connecting their local offices in Chennai for very effective communication? Ethernet Cable, Optical Fiber, Telephone Cable.
iii) Which of the following devices will you suggest for connecting all the computers within each of their office units?
*Switch/Hub *Modem *Telephone
iv) Suggest a cable layout for connecting the company's local office units in Chennai.
v) Suggest the most suitable place to house the server for the organization with suitable reason.
'SmartEdu' is an educational organization is planning to setup its new campus at Cochin for its web based activities. The campus has four compounds as shown in the diagram.
Computers in each building are networked but buildings are not networked. The company has now decided to connect the buildings.
i) Suggest a most suitable cable layout for the above connection
ii) Suggest most suitable topology of the connection between the building.
iii) Suggest the most suitable building to place the server by giving suitable reason.
iv) Suggest the placement of the following devices
v) Organization is planning to link its head office in Chennai. Suggest an efficient medium for efficient data communication.
(i) Expand the following :
VoIP, PPP
(ii) Riya wants to transfer pictures from her mobile phone to her laptop. She uses Bluetooth technology to connect two devices. Which type of network (PAN/LAN/MAN/WAN) will be formed in this case ?
(a) Write the full forms of the following :
(i) HTML
(ii) TCP
(b) What is the need of Protocols ?
Which of the following options is the correct protocol used for phone calls over the internet?
(A) PPP
(B) FTP
(C) HTTP
(D) VoIP
(a) Expand FTP.
(b) Out of the following, which has the largest network coverage area ?
LAN, MAN, PAN, WAN
(a) Write the full forms of the following :
(i) XML
(ii) HTTPS
(b) What is the use of FTP ?
(a) (i) Expand the following terms :
URL, XML
(ii) Give one difference between HTTP and FTP.
OR
(b) (i) Define the term IP address with respect to network.
(ii) What is the main purpose of a Router ?
Which of the following IP addresses is valid ?
(A) 122.94.96.212
(B) 212.254.258.210
(C) 210.10.12.156.209
(D) 122.294.56.68
Fill in the blank:
_______ is a communication methodology designed to deliver both voice and multimedia communications over Internet protocol.
a) VoIP
b) SMTP
c) PPP
d) HTTP
(a) Write the full forms of the following:
(i) SMTP (ii) PPP
(b) What is the use of TELNET?
Which protocol is used to transfer files over the Internet?
a) HTTP
b) FTP
c) PPP
d) HTTPS
_________ is a protocol used for retrieving emails from a mail server.
a) SMTP
b) FTP
c) POP3
d) PPP
Expand the following abbreviations:
1. CSMA/CD
2. CSMA/CA
3. DNS
4. DHCP
5. ISP
6. URL
Expand the following abbreviations:
1. HTTP
2. FTP
3. FDMA
4. TDMA
5. CDMA
6. Mbps
Expand the following abbreviations:
1. ICMP
2. OSI
3. SMTP
4. VoIP
5. SIP
6. QoS
Expand the following abbreviations:
1. POP
2. IMAP
3. SCP
4. SSH
5. IEEE
6. NFC
Expand the following abbreviations:
1. NFS
2. NTP
3. SLIP
4. PPP
5. UDP
6. SNMP
Name the protocol that is used to transfer file from one computer to another.
Name the protocol that is used to upload and download files on internet.
Name the protocol that is used to send emails.
Name the protocol that is used to receive emails.
Out of SMTP and POP3 which protocol is used to receive emails?
Your friend Rakesh complaints that somebody accessed his mobile device remotely and deleted the important files. Also he claims that the password of his social media accounts were changed. Write the name of crime.
What do you mean by Protocol?
Which protocol is used to creating a connection with a remote machine?
Match the protocols with functions:
| Protocol | Function |
|---|---|
| 1. SMTP | a. Transfer of files over internet |
| 2. FTP | b. retrieve mails from recipient's server |
| 3. POP | c. Request response protocol between server and client |
| 4. HTTP | d. Transfer mail from one user to other user |
What is a web browser? Write any two examples.
Differentiate between XML and HTML with reference to data handling.
Expand the term XML.
'L' in HTML stands for :
(A) Large
(B) Language
(C) Long
(D) Laser
Fill in the blank :
The full form of WWW is __________.
(i) Expand the following terms:
POP3, URL
(ii) Give one difference between XML and HTML.
OR
(i) Define the term bandwidth with respect to networks.
(ii) How is http different from https?
Which of the following is used to create the structure of a web page?
a) CSS
b) HTML
c) JavaScript
d) FTP
B.
I. Expand the following terms: HTTP and FTP
II. Differentiate between web server and web browser.
Identify the parts of URL:
http://www.google.com/index.html
What is web hosting?
Differentiate between web server and web browser. Write any two popular web browsers.
Identify the Domain name and URL from the following:
http://www.income.in/home.aboutus.hml
Categorize the following under client-side and server-side scripts category:
1. Java Script
2. ASP
3. VB Script
4. JSP
Define web browser and web server.
Write two advantages of using SQL.
Differentiate between the terms Attribute and Domain in the context of Relational Data Model.
Differentiate between Candidate Key and Primary Key in the context of Relational Database Model.
OR
Consider the following table PLAYER :
Table : PLAYER
| PNO | NAME | SCORE |
|---|---|---|
| P1 | RISHABH | 52 |
| P2 | HUSSAIN | 45 |
| P3 | ARNOLD | 23 |
| P4 | ARNAV | 18 |
| P5 | GURSHARAN | 42 |
(a) Identify and write the name of the most appropriate column from the given table PLAYER that can be used as a Primary key.
(b) Define the term Degree in relational data model. What is the Degree of the given table PLAYER ?
Fill in the blank.
________ is a number of tuples in a relation.
(a) Attribute
(b) Degree
(c) Domain
(d) Cardinality
Explain the concept of "Alternate Key" in a Relational Database Management System with an appropriate example.
State True or False:
If table A has 6 rows and 3 columns, and table B has 5 rows and 2 columns, the Cartesian product of A and B will have 30 rows and 5 columns.
Differentiate between Primary Key and Foreign Key with reference to Relational Database.
OR
Differentiate between DDL and DML commands with one example of each.
A table has two candidate keys, one of which is chosen as the primary key. How many alternate keys does this table have ?
(A) 0
(B) 1
(C) 2
(D) 3
A relation in MySQL database consists of 2 tuples and 3 attributes. If 2 attributes are deleted and 4 tuples are added, what will be the cardinality of the relation ?
(A) 4
(B) 5
(C) 6
(D) 7
Assertion (A) : The PRIMARY KEY constraint in SQL ensures that each value in the column(s) is unique and cannot be NULL.
Reason (R) : Candidate keys are not eligible to become a primary key.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
(B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.
Differentiate between Degree and Cardinality in the context of Relational Data Model.
(a) Explain Primary Key in the context of Relational Database Model. Support your answer with suitable example.
OR
(b) Consider the following table BATSMEN :
Table : BATSMEN
| PNO | NAME | SCORE |
|---|---|---|
| P1 | RISHABH | 52 |
| P2 | HUSSAIN | 45 |
| P3 | ARNOLD | 23 |
| P4 | ARNAV | 18 |
| P5 | GURSHARAN | 52 |
(i) Identify and write the name of the Candidate Keys in the given table BATSMEN.
(ii) How many tuples are there in the given table BATSMEN ?
Fill in the blank :
In a relational model, tables are called ________, that store data for different columns.
(a) Attributes
(b) Degrees
(c) Relations
(d) Tuples
The primary key is selected from the set of ___________ .
(A) composite keys
(B) alternate keys
(C) candidate keys
(D) foreign keys
In a particular examination, there are 50 candidates with roll numbers from 997601 to 997650. The data of these candidates is stored in a table in a database. What is the domain of the column which stores the roll numbers of the candidates ?
Assertion (A) : Foreign key column of a table cannot have NULL entries.
Reason (R) : Primary key column of a table cannot have NULL entries.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of the Assertion (A).
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of the Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.
Fill in the blank:
_________ is a non-key attribute, whose values are derived from the primary key of some other table.
a) Primary Key
b) Foreign Key
c) Candidate Key
d) Alternate Key
Explain the use of 'Foreign Key' in a Relational Database Management System. Give example to support your answer.
Navdeep creates a table RESULT with a set of records to maintain the marks secured by students in Sem 1, Sem2, Sem3 and their division.
| ROLL_NO | SNAME | SEM1 | SEM2 | SEM3 | DIVISION |
|---|---|---|---|---|---|
| 101 | KARAN | 366 | 410 | 402 | I |
| 102 | NAMAN | 300 | 350 | 325 | I |
| 103 | ISHA | 400 | 410 | 415 | I |
| 104 | RENU | 350 | 357 | 415 | I |
| 105 | ARPIT | 100 | 75 | 178 | IV |
| 106 | SABINA | 100 | 205 | 217 | II |
| 107 | NEELAM | 470 | 450 | 471 | I |
(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If two columns are added and 2 rows are deleted from the table result, what will be the new degree and cardinality of the above table?
(iii) Write the statements to:
a. Insert the following record into the table: Roll No- 108, Name- Aadit, Sem1- 470, Sem2-444, Sem3-475, Div – I.
b. Increase the SEM2 marks of the students by 3% whose name begins with 'N'.
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing IV division.
b. Add a column REMARKS in the table with datatype as varchar with 50 characters.
In a table in MYSQL database, an attribute A of datatype varchar(20) has the value "Keshav". The attribute B of datatype char(20) has value "Meenakshi". How many characters are occupied by attribute A and attribute B?
a) 20,6
b) 6,20
c) 9,6
d) 6,9
Which of the following statements is FALSE about keys in a relational database?
a) Any candidate key is eligible to become a primary key.
b) A primary key uniquely identifies the tuples in a relation.
c) A candidate key that is not a primary key is a foreign key.
d) A foreign key is an attribute whose value is derived from the primary key of another relation.
If a table has one Primary key and two alternate keys. How many Candidate keys will this table have?
a) 1
b) 2
c) 3
d) 4
In which datatype is the value stored padded with spaces to fit the specified length?
a) DATE
b) VARCHAR
c) FLOAT
d) CHAR
Which SQL command can change the cardinality of an existing relation?
a) Insert
b) Delete
c) Both a) & b)
d) Drop
In SQL, a relation consists of 5 columns and 6 rows. If 2 columns and 3 rows are added to the existing relation, what will be the updated degree of a relation?
a) Degree: 7
b) Degree: 8
c) Degree: 9
d) Degree: 6
Assertion (A): A primary key must be unique and cannot have NULL values.
Reasoning (R): The primary key uniquely identifies each row in the table.
a) Both A and R are True and R is the correct explanation for A.
b) Both A and R are True and R is not the correct explanation for A.
c) A is True but R is False.
d) A is False but R is True.
(i) A SQL table ITEMS contains the following columns :
INO, INAME, QUANTITY, PRICE, DISCOUNT
Write the SQL command to remove the column DISCOUNT from the table.
(ii) Categorize the following SQL commands into DDL and DML:
CREATE, UPDATE, INSERT, DROP
Rohan is learning to work upon Relational Database Management System (RDBMS) application. Help him to perform following tasks :
(a) To open the database named "LIBRARY".
(b) To display the names of all the tables stored in the opened database.
(c) To display the structure of the table "BOOKS" existing in the already opened database "LIBRARY".
Differentiate between CHAR and VARCHAR data types in SQL with appropriate example.
OR
Name any two DDL and any two DML commands.
The school has asked their estate manager Mr. Rahul to maintain the data of all the labs in a table LAB. Rahul has created a table and entered data of 5 labs.
| LABNO | LAB_NAME | INCHARGE | CAPACITY | FLOOR |
|---|---|---|---|---|
| L001 | CHEMISTRY | Daisy | 20 | I |
| L002 | BIOLOGY | Venky | 20 | II |
| L003 | MATH | Preeti | 15 | I |
| L004 | LANGUAGE | Daisy | 36 | II |
| L005 | COMPUTER | Mary Kom | 37 | II |
Based on the data given above answer the following questions :
(i) Identify the columns which can be considered as Candidate keys.
(ii) Write the degree and cardinality of the table.
(iii) Write the statements to :
(a) Insert a new row with appropriate data.
(b) Increase the capacity of all the labs by 10 students which are on I Floor.
OR
(Option for part (iii) only)
(iii) Write the statements to :
(a) Add a constraint PRIMARY KEY to the column LABNO in the table.
(b) Delete the table LAB.
Which of the following is a DDL command ?
(A) SELECT
(B) INSERT
(C) CREATE
(D) UPDATE
While creating a table, which constraint does not allow insertion of duplicate values in the table?
(A) UNIQUE
(B) DISTINCT
(C) NOT NULL
(D) HAVING
In MYSQL, which type of value should not be enclosed within quotation marks?
(A) DATE
(B) VARCHAR
(C) FLOAT
(D) CHAR
Which of the following SQL command can change the degree of the existing relation ?
(A) DROP TABLE
(B) ALTER TABLE
(C) UPDATE...SET
(D) DELETE
Ms. Zoya is a Production Manager in a factory which packages mineral water. She decides to create a table in a database to keep track of the stock present in the factory. Each record of the table will have the following fields :
W_Code – Code of the item (type – CHAR(5))
W_Description – Description of the item (type – VARCHAR(20))
B_Qty – Balance quantity of the item (type – INTEGER)
U_Price – Unit Price of the item (type – FLOAT)
The name of the table is W_STOCK.
(i) (a) Write an SQL command to create the above table (W_Code should be the primary key).
OR
(b) Can U_Price be the primary key of the above table ? Justify your answer.
(ii) (a) Assuming that the table W_STOCK is already created, write an SQL command to add an attribute E_Date (of DATE type) to the table.
OR
(b) Assuming that the table W_STOCK is already created, write an SQL command to remove the column B_Qty from the table.
(a) A SQL table BOOKS contains the following column names :
BOOKNO, BOOKNAME, QUANTITY, PRICE, AUTHOR
Write the SQL statement to add a new column REVIEW to store the reviews of the book.
(b) Write the names of any two commands of DDL and any two commands of DML in SQL.
Rashmi has forgotten the names of the databases, tables and the structure of the tables that she had created in Relational Database Management System (RDBMS) on her computer.
(a) Write the SQL statement to display the names of all the databases present in RDBMS application on her computer.
(b) Write the statement which she should execute to open the database named "STOCK".
(c) Write the statement which she should execute to display the structure of the table "ITEMS" existing in the above opened database "STOCK".
The ABC Company is considering to maintain their salespersons records using SQL to store data. As a database administrator, Alia created the table Salesperson and also entered the data of 5 Salespersons.
Table : Salesperson
| S_ID | S_NAME | AGE | S_AMOUNT | REGION |
|---|---|---|---|---|
| 5001 | SHYAM | 35 | 20000 | NORTH |
| 5002 | RISHABH | 30 | 25000 | EAST |
| 5003 | SUNIL | 29 | 21000 | NORTH |
| 5004 | RAHIL | 39 | 22000 | WEST |
| 5005 | AMIT | 40 | 23000 | EAST |
Based on the data given above, answer the following questions :
(i) Identify the attribute that is best suited to be the Primary Key and why ?
(ii) The Company has asked Alia to add another attribute in the table. What will be the new degree and cardinality of the above table ?
(iii) Write the statements to :
(a) Insert details of one salesman with appropriate data.
(b) Change the Region of salesman 'SHYAM' to 'SOUTH' in the table Salesperson.
OR
(Option for part iii only)
(iii) Write the statement to:
(a) Delete the record of salesman RISHABH, as he has left the company.
(b) Remove an attribute REGION from the table.
Mr. Ravi is creating a field that contains alphanumeric values and fixed lengths. Which MySQL data type should he choose for the same ?
(A) VARCHAR
(B) CHAR
(C) LONG
(D) NUMBER
(a) Mr. Atharva is given a task to create a database, Admin. He has to create a table, users in the database with the following columns :
User_id – int
User_name – varchar(20)
Password – varchar(10)
Help him by writing SQL queries for both tasks.
OR
(b) Ms. Rita is a database administrator at a school. She is working on the table, student containing the columns like Stud_id, Name, Class and Stream. She has been asked by the Principal to strike off the record of a student named Rahul with student_id as 100 from the school records and add another student who has been admitted with the following details :
Stud_id – 123
Name – Rajeev
Class – 12
Stream – Science
Help her by writing SQL queries for both tasks.
Consider the table Rent_cab, given below :
| Vcode | VName | Make | Color | Charges |
|---|---|---|---|---|
| 101 | Big car | Carus | White | 15 |
| 102 | Small car | Polestar | Silver | 10 |
| 103 | Family car | Windspeed | Black | 20 |
| 104 | Classic | Studio | White | 30 |
| 105 | Luxury | Trona | Red | 9 |
Based on the given table, write SQL queries for the following :
(i) Add a primary key to a column name Vcode.
(ii) Increase the charges of all the cabs by 10%.
(iii) Delete all the cabs whose maker name is "Carus".
Write any two DDL commands.
What is the default format of date in MySQL ?
(A) MM-DD-YYYY
(B) DD-MM-YYYY
(C) YYYY-MM-DD
(D) YYYY-DD-MM
(I) (a) Write any one difference between CHAR and VARCHAR data types in MySQL.
OR
(b) Write one difference between Primary key and Unique constraint.
(II) (a) Write an SQL command to remove a column named ADDRESS, from a table named CUSTOMER.
OR
(b) Write an SQL command to add a column named ADDRESS, of type VARCHAR(20) in a table named CUSTOMER.
Fill in the blank:
______ command is used to remove primary key from the table in SQL.
a) update
b) remove
c) alter
d) drop
Which of the following commands will delete the table from MYSQL database?
a) DELETE TABLE
b) DROP TABLE
c) REMOVE TABLE
d) ALTER TABLE
Ms. Shalini has just created a table named "Employee" containing columns Ename, Department and Salary.
After creating the table, she realized that she has forgotten to add a primary key column in the table. Help her in writing an SQL command to add a primary key column EmpId of integer type to the table Employee.
Thereafter, write the command to insert the following record in the table:
EmpId- 999, Ename- Shweta, Department: Production, Salary: 26900
OR
Zack is working in a database named SPORT, in which he has created a table named "Sports" containing columns SportId, SportName, no_of_players, and category.
After creating the table, he realized that the attribute category has to be deleted from the table and a new attribute TypeSport of data type string has to be added. This attribute TypeSport cannot be left blank. Help Zack write the commands to complete both the tasks.
Which SQL command can change the degree of an existing relation?
(I)
A) What constraint should be applied on a table column so that duplicate values are not allowed in that column, but NULL is allowed.
OR
B) What constraint should be applied on a table column so that NULL is not allowed in that column, but duplicate values are allowed.
(II)
A) Write an SQL command to remove the Primary Key constraint from a table, named MOBILE. M_ID is the primary key of the table.
OR
B) Write an SQL command to make the column M_ID the Primary Key of an already existing table, named MOBILE.
Which SQL command is used to remove a column from a table in MySQL?
a) UPDATE
b) ALTER
c) DROP
d) DELETE
A. Write suitable commands to do the following in MySQL.
I. View the table structure.
II. Create a database named SQP
B. Differentiate between drop and delete query in SQL with a suitable example.
Table : PASSENGER
| PNO | NAME | GENDER | FNO |
|---|---|---|---|
| 1001 | Suresh | MALE | F101 |
| 1002 | Anita | FEMALE | F104 |
| 1003 | Harjas | MALE | F102 |
| 1004 | Nita | FEMALE | F103 |
Table : FLIGHT
| FNO | START | END | F_DATE | FARE |
|---|---|---|---|---|
| F101 | MUMBAI | CHENNAI | 2021-12-25 | 4500 |
| F102 | MUMBAI | BENGALURU | 2021-11-20 | 4000 |
| F103 | DELHI | CHENNAI | 2021-12-10 | 5500 |
| F104 | KOLKATA | MUMBAI | 2021-12-20 | 4500 |
| F105 | DELHI | BENGALURU | 2021-01-15 | 5000 |
(a) Write a query to change the fare to 6000 of the flight whose FNO is F104.
(b) Write a query to display the total number of MALE and FEMALE PASSENGERS.
(c) Write a query to display the NAME, corresponding FARE and F_DATE of all PASSENGERS who have a flight to START from DELHI.
(d) Write a query to delete the records of flights which end at Mumbai.
| S_ID | S_NAME | S_SALARY | S_DEPT | S_EXPERIENCE |
|---|---|---|---|---|
| S1 | Ananya | 85000 | Science | 6 |
| S2 | Bhavesh | 92000 | Commerce | 7 |
| S3 | Chavi | 75000 | Humanities | 4 |
| S4 | Deepak | 85000 | Science | 5 |
(a) To display the names and salary of the teachers whose experience is more than 5 years.
(b) To display the total salary of each department.
(c) To display the details of the teachers whose name starts with 'A' and ends with 'a'.
(d) To display the unique departments from the table.
| S_ID | S_NAME | CLASS | FEE |
|---|---|---|---|
| S1 | Ananya | XI | 45000 |
| S2 | Bhavesh | XII | 50000 |
| S3 | Chavi | XI | 42000 |
| S4 | Deepak | XII | 48000 |
| S5 | Esha | XI | 46000 |
(a) To display the names of the students whose name starts with 'A'.
(b) To display the total fee of each class.
(c) To count the number of students in class XII.
(d) To display the name and fee of the students whose fee is between 45000 and 50000.
OR
(a) SELECT COUNT(*) FROM Student WHERE FEE>45000;
(b) SELECT MAX(FEE), MIN(FEE) FROM Student;
(c) SELECT CLASS, SUM(FEE) FROM Student GROUP BY CLASS;
(d) SELECT S_NAME FROM Student WHERE S_NAME LIKE '_____' ORDER BY FEE DESC;
ABC Corporation has its head office in Delhi and branch offices in Chennai and Bengaluru. The details of the employees are stored in a table Employee in the database Company. The table has the following structure:
| E_ID | E_NAME | E_DEPT | E_SALARY |
|---|
(i) Identify the Primary Key and Candidate Key from the table Employee.
(ii) Write the SQL query to count the total number of employees in the HR department.
(iii) Write the SQL query to display the names of the employees whose salary is greater than 50000 in descending order of their salary.
(iv) Write the SQL query to add a column E_JOIN_DATE of DATE type in the table Employee.
Which of the following is a DML command in SQL?
(A) UPDATE
(B) CREATE
(C) ALTER
(D) DROP
Consider the table RESULT given below.
| ROLL | SUBJECT | MARKS |
|---|---|---|
| S01 | Physics | 90 |
| S02 | Chemistry | 98 |
| S03 | Maths | 80 |
| S04 | Physics | 95 |
| S05 | Chemistry | 75 |
| S06 | Maths | 97 |
(a) Identify the Primary Key in the table RESULT with valid justification.
(b) Write a query to display the total number of students having marks greater than 85.
(c) Write a Python statement to establish a connection to MySQL using the following credentials:
Username : abc
Password : xyz
Database : PQR
Consider the table SCHOOL given below:
| S_ID | NAME | PERCENT | CO_CURRICULAR |
|---|---|---|---|
| S1 | Rehan | 92 | Music |
| S2 | Anjali | 72 | Dance |
| S3 | Preeti | 91 | NULL |
| S4 | Karan | 88 | Music |
| S5 | Aditya | 82 | Dance |
Based on the above table, answer the questions given below:
(a) Write the degree and cardinality of the table.
(b) Identify the attribute best suited to be the primary key.
(c) Write the SQL query to display the names of the students who are getting less than 90 percentage.
(d) Write the SQL query to count the number of students who are having Music as their co_curricular activity.
OR
(a) Write the SQL query to display the names of the students and their co_curricular activity who are getting percentage between 75 and 95.
(b) Write the SQL query to add a column SPORTS in the table SCHOOL.
(c) Write the SQL query to display the name of students in descending order of their percentage.
What will be the output of the query ?
SELECT MACHINE_ID, MACHINE_NAME FROM INVENTORY
WHERE QUANTITY <= 100;
(A) All columns of INVENTORY table with quantity greater than 100
(B) ID and name of machines with quantity less than 100 from INVENTORY table
(C) All columns of INVENTORY table with quantity greater than or equal to 100
(D) ID and name of machines with quantity less than or equal to 100 from INVENTORY table.
Abhishek has created a table, named STOCK, with a set of records to maintain the data of packaged milk in his shop. After creating the table, he entered the data and the table looked as follows :
| Code | Type | Volume | Qty | Price |
|---|---|---|---|---|
| AF0.5 | F | 0.5 | 300 | 38.00 |
| MF0.5 | F | 0.5 | 250 | 36.50 |
| MT1.0 | T | 1.0 | 150 | 64.00 |
| AT1.0 | T | 1.0 | 100 | 66.00 |
| PD1.0 | D | 1.0 | 50 | 52.00 |
| PT0.5 | T | 0.5 | 78 | 30.00 |
(a) Based on the data given above, write the SQL queries for the following tasks :
(i) To display Type and the maximum Price for each Type of milk.
(ii) For each record, increase the Price by 0.5 where Type is 'F'.
(iii) To display the total value of the stock (total of Qty x Price).
(iv) To display the details of all records where Code starts with 'A'.
OR
(b) Considering the table STOCK as given above, write the output on execution of the following queries :
(i) SELECT Volume, Qty, Price FROM STOCK WHERE Type IN ('F','D');
(ii) SELECT Code, Qty FROM STOCK WHERE Price BETWEEN 30 AND 50;
(iii) SELECT DISTINCT Type FROM STOCK;
(iv) SELECT Volume, count(*) FROM STOCK GROUP BY Volume;
Table : CUSTOMER
| CNO | NAME | GENDER | ADDRESS | PHONE |
|---|---|---|---|---|
| 1001 | Suresh | MALE | A-123, West Street | 9310010010 |
| 1002 | Anita | FEMALE | C-24, Court Lane | 9121211212 |
| 1003 | Harjas | MALE | T-1, Woods Avenue | 9820021001 |
Table : TRANSACT
| TNO | CNO | AMOUNT | TTYPE | TDATE |
|---|---|---|---|---|
| T1 | 1002 | 2000 | DEBIT | 2021-09-25 |
| T2 | 1003 | 1500 | CREDIT | 2022-01-28 |
| T3 | 1002 | 3500 | CREDIT | 2021-12-31 |
| T4 | 1001 | 1000 | DEBIT | 2022-01-10 |
(a) Write the SQL statements to delete the records from table TRANSACT whose amount is less than 1000.
(b) Write a query to display the total AMOUNT of all DEBITs and all CREDITs.
(c) Write a query to display the NAME and corresponding AMOUNT of all CUSTOMERS who made a transaction type (TTYPE) of CREDIT.
(d) Write the SQL statement to change the Phone number of customer whose CNO is 1002 to 9988117700 in the table CUSTOMER.
Fill in the blank :
________ statement of SQL is used to insert new records in a table.
(a) ALTER
(b) UPDATE
(c) INSERT
(d) CREATE
In SQL, which command will be used to add a new record in a table ?
(A) UPDATE
(B) ADD
(C) INSERT
(D) ALTER TABLE
Consider the table STAFF given below :
| STAFF_ID | STAFF_NAME | SALARY | DEPARTMENT | DESIGNATION |
|---|---|---|---|---|
| S101 | SUNITA | 26000 | MATHS | TGT |
| S201 | SUNIL | 80000 | COMMERCE | PGT |
| S301 | NEHA | 35000 | SCIENCE | TGT |
| S102 | MANJEET | 25000 | MATHS | TGT |
| S202 | MANNAN | 45000 | COMPUTER | TGT |
(a) Write the suitable SQL queries to perform the following tasks :
(I) To display the average salary of each department.
(II) To insert the following record in the table, STAFF.
STAFF_ID : S333
STAFF_NAME : GURMEET
SALARY : 15000
DEPARTMENT : ADMIN
DESIGNATION : CLERK
(III) To display the unique designations from the table.
(IV) To display all the details of the staff whose name is of four letters.
OR
(b) Write the output for the queries given below :
(I) SELECT STAFF_NAME FROM STAFF WHERE SALARY BETWEEN 25000 AND 30000;
(II) SELECT * FROM STAFF WHERE DEPARTMENT = "MATHS" AND SALARY > 25000;
(III) SELECT STAFF_NAME, STAFF_ID FROM STAFF WHERE DEPARTMENT LIKE "%S";
(IV) SELECT MAX(SALARY)FROM STAFF;
Consider the table Personal given below:
| P_ID | Name | Desig | Salary | Allowance |
|---|---|---|---|---|
| P01 | Rohit | Manager | 89000 | 4800 |
| P02 | Kashish | Clerk | NULL | 1600 |
| P03 | Mahesh | Superviser | 48000 | NULL |
| P04 | Salil | Clerk | 31000 | 1900 |
| P05 | Ravina | Superviser | NULL | 2100 |
Based on the given table, write SQL queries for the following:
(i) Increase the salary by 5% of personals whose allowance is known.
(ii) Display Name and Total Salary (sum of Salary and Allowance) of all personals. The column heading 'Total Salary' should also be displayed.
(iii) Delete the record of personals who have salary greater than 25000.
Fill in the blank :
________ clause is used with SELECT statement to display data in a sorted form with respect to a specified column.
(a) WHERE
(b) ORDER BY
(c) HAVING
(d) DISTINCT
Which clause is used with SELECT statement to sort the result in ascending or descending order of specific column(s)?
(A) ORDER BY
(B) HAVING
(C) GROUP BY
(D) DISTINCT
Table : TRAVEL
| T_ID | START | END | T_DATE | FARE |
|---|---|---|---|---|
| 101 | DELHI | CHENNAI | 2021-12-25 | 4500 |
| 102 | DELHI | BENGALURU | 2021-11-20 | 4000 |
| 103 | MUMBAI | CHENNAI | 2020-12-10 | 5500 |
| 104 | DELHI | MUMBAI | 2019-12-20 | 4500 |
| 105 | MUMBAI | BENGALURU | 2022-01-15 | 5000 |
(a) SELECT START, END FROM TRAVEL WHERE FARE <= 4000 ;
(b) SELECT T_ID, FARE FROM TRAVEL WHERE T_DATE LIKE '2021-12-%' ;
(c) SELECT T_ID, T_DATE FROM TRAVEL WHERE END = 'CHENNAI' ORDER BY FARE ;
(d) SELECT START, MIN(FARE) FROM TRAVEL GROUP BY START ;
(a) Differentiate between IN and BETWEEN operators in SQL with appropriate examples.
OR
(b) Which of the following is NOT a DML command.
DELETE, DROP, INSERT, UPDATE
Which of the following is not a valid relational operator used with WHERE clause in SQL ?
(A) >
(B) <=
(C) =>
(D) <>
Fill in the blank:
The SELECT statement when combined with __________ clause, returns records without repetition.
a) DESCRIBE
b) UNIQUE
c) DISTINCT
d) NULL
Consider the table CLUB given below and write the output of the SQL queries that follow.
| CID | CNAME | AGE | GENDER | SPORTS | PAY | DOAPP |
|---|---|---|---|---|---|---|
| 5246 | AMRITA | 35 | FEMALE | CHESS | 900 | 2006-03-27 |
| 4687 | SHYAM | 37 | MALE | CRICKET | 1300 | 2004-04-15 |
| 1245 | MEENA | 23 | FEMALE | VOLLEYBALL | 1000 | 2007-06-18 |
| 1622 | AMRIT | 28 | MALE | KARATE | 1000 | 2007-09-05 |
| 1256 | AMINA | 36 | FEMALE | CHESS | 1100 | 2003-08-15 |
| 1720 | MANJU | 33 | FEMALE | KARATE | 1250 | 2004-04-10 |
| 2321 | VIRAT | 35 | MALE | CRICKET | 1050 | 2005-04-30 |
(i) SELECT COUNT(DISTINCT SPORTS) FROM CLUB;
(ii) SELECT CNAME, SPORTS FROM CLUB WHERE DOAPP<"2006-04-30" AND CNAME LIKE "%NA";
(iii) SELECT CNAME, AGE, PAY FROM CLUB WHERE GENDER = "MALE" AND PAY BETWEEN 1000 AND 1200;
What will be the output of the query?
SELECT * FROM products WHERE product_name LIKE 'App%';
a) Details of all products whose names start with 'App'
b) Details of all products whose names end with 'App'
c) Names of all products whose names start with 'App'
d) Names of all products whose names end with 'App'
Consider the table SALES as given below:
| sales_id | customer_name | product | quantity_sold | price |
|---|---|---|---|---|
| S001 | John Doe | Laptop | 5 | 50000 |
| S002 | Jane Smith | Smartphone | 10 | 30000 |
| S003 | Michael Lee | Tablet | 3 | 15000 |
| S004 | Sarah Brown | Headphones | 7 | 2000 |
| S005 | Emily Davis | Smartwatch | 8 | 8000 |
| S006 | David | Smartwatch | 3 | 16000 |
| S007 | Mark | Tablet | 5 | 34000 |
B. Predict the output of the following:
I. SELECT * FROM Sales where product='Tablet';
II. SELECT sales_id, customer_name FROM Sales WHERE product LIKE 'S%';
III. SELECT COUNT(*) FROM Sales WHERE product in ('Laptop', 'Tablet');
IV. SELECT AVG(price) FROM Sales where product='Tablet';
TABLE : VACCINATION_DATA
| VID | Name | Age | Dose1 | Dose2 | City |
|---|---|---|---|---|---|
| 101 | Jenny | 27 | 2021-12-25 | 2022-01-31 | Delhi |
| 102 | Harjot | 55 | 2021-07-14 | 2021-10-14 | Mumbai |
| 103 | Srikanth | 43 | 2021-04-18 | 2021-07-20 | Delhi |
| 104 | Gazala | 75 | 2021-07-31 | NULL | Kolkata |
| 105 | Shiksha | 32 | 2022-01-01 | NULL | Mumbai |
(a) SELECT Name, Age FROM VACCINATION_DATA WHERE Dose2 IS NOT NULL AND Age > 40;
(b) SELECT City, COUNT(*) FROM VACCINATION_DATA GROUP BY City;
(c) SELECT DISTINCT City FROM VACCINATION_DATA;
(d) SELECT MAX (Dose1), MIN (Dose2) FROM VACCINATION_DATA;
Which aggregate function in SQL returns the total number of values in the specified column ignoring the NULL values?
(A) COUNT(*)
(B) COUNT(columnname)
(C) SUM(columnname)
(D) MAX(columnname)
Consider the table Doctor given below.
| DID | DNAME | SPECIALIZATION | FEES |
|---|---|---|---|
| D01 | Ravi | Cardiologist | 600 |
| D02 | Seema | Dermatologist | 800 |
| D03 | Neeta | Dentist | 500 |
| D04 | Saurabh | Cardiologist | 800 |
| D05 | Priyanka | Dentist | 900 |
Write the output for the queries given below:
(a) SELECT COUNT(*) FROM Doctor WHERE Fees>500;
(b) SELECT MIN(Fees) FROM Doctor WHERE Specialization="Dentist";
(c) SELECT SPECIALIZATION, SUM(Fees) FROM Doctor GROUP BY SPECIALIZATION;
(d) SELECT DNAME, FEES*2 FROM Doctor WHERE SPECIALIZATION="Dentist";
| B_ID | B_NAME | B_AUTHOR | B_PRICE | B_QTY |
|---|---|---|---|---|
| B101 | Python | Rohit | 450 | 8 |
| B102 | SQL | Neha | 350 | 10 |
| B103 | C++ | Raj | 500 | 5 |
| B104 | Java | Priya | 550 | 7 |
| B105 | Python | Amit | 400 | 9 |
(a) SELECT COUNT(DISTINCT B_NAME) FROM Books;
(b) SELECT B_AUTHOR, SUM(B_QTY) FROM Books GROUP BY B_AUTHOR HAVING COUNT(*)>1;
(c) SELECT B_NAME, B_PRICE*2 FROM Books WHERE B_QTY>5;
(d) SELECT B_NAME, B_AUTHOR FROM Books WHERE B_NAME LIKE 'P%' ORDER BY B_PRICE DESC;
Which aggregate function in SQL displays the number of values in the specified column ignoring the NULL values?
(A) len()
(B) count()
(C) number()
(D) num()
| DNO | DNAME | SALARY |
|---|---|---|
| D01 | Vivek | 120000 |
| D02 | Rishi | 160000 |
| D03 | Kumar | 140000 |
| D04 | Goyal | 170000 |
(a) SELECT COUNT(DNO) FROM DOCTOR WHERE SALARY>150000;
(b) SELECT DISTINCT COUNT(SALARY) FROM DOCTOR;
(c) SELECT MIN(SALARY), MAX(SALARY) FROM DOCTOR;
(d) SELECT SUM(SALARY), AVG(SALARY) FROM DOCTOR WHERE SALARY BETWEEN 130000 AND 160000;
| M_ID | NAME | POST | AGE | SALARY |
|---|---|---|---|---|
| M01 | Rajesh | P1 | 36 | 17000 |
| M02 | Rahul | P2 | 45 | 25000 |
| M03 | Priya | P3 | 56 | 16000 |
| M04 | Rakesh | P1 | 37 | 32000 |
| M05 | Sona | P2 | 55 | 34000 |
(a) To display the number of managers having a post other than P1.
(b) To display the average salary of managers whose age is greater than 40.
OR
(a) To display the maximum salary of manager who has post P2.
(b) To display the name of managers in descending order of their age.
Which aggregate function in SQL returns the smallest value from a column in a table ?
(A) MIN()
(B) MAX()
(C) SMALL()
(D) LOWER()
Explain the usage of HAVING clause in GROUP BY command in RDBMS with the help of an example.
Consider the table Stationery given below and write the output of the SQL queries that follow.
Table : Stationery
| ITEMNO | ITEM | DISTRIBUTOR | QTY | PRICE |
|---|---|---|---|---|
| 401 | Ball Pen 0.5 | Reliable Stationers | 100 | 16 |
| 402 | Gel Pen Premium | Classic Plastics | 150 | 20 |
| 403 | Eraser Big | Clear Deals | 210 | 10 |
| 404 | Eraser Small | Clear Deals | 200 | 5 |
| 405 | Sharpener Classic | Classic Plastics | 150 | 8 |
| 406 | Gel Pen Classic | Classic Plastics | 100 | 15 |
(i) SELECT DISTRIBUTOR, SUM(QTY) FROM STATIONERY GROUP BY DISTRIBUTOR;
(ii) SELECT ITEMNO, ITEM FROM STATIONERY WHERE DISTRIBUTOR = "Classic Plastics" AND PRICE > 10;
(iii) SELECT ITEM, QTY * PRICE AS "AMOUNT" FROM STATIONERY WHERE ITEMNO = 402;
Ginni has created a table, SCORES in MySQL to store runs scored by players in a cricket match. The table contains the following records :
| PLAYER | SCORE |
|---|---|
| Ranveer | 50 |
| Sukesh | 35 |
| Mirza | 10 |
| John | 51 |
| Murugan | 70 |
Which of the following statements will give 10 as output ?
(A) SELECT MAX(Score) FROM Scores;
(B) SELECT MIN(Score) FROM Scores;
(C) SELECT SUM(Score) FROM Scores;
(D) SELECT AVG(Score) FROM Scores;
Which function is used to display the total number of records from table in a database?
a) sum(*)
b) total(*)
c) count(*)
d) return(*)
Differentiate between count() and count(*) functions in SQL with appropriate example.
OR
Categorize the following commands as DDL or DML:
INSERT, UPDATE, ALTER, DROP
Which aggregate function can be used to find the cardinality of a table?
a) sum()
b) count()
c) avg()
d) max()
Assertion (A): A SELECT command in SQL can have both WHERE and HAVING clauses.
Reason (R): WHERE and HAVING clauses are used to check conditions, therefore, these can be used interchangeably.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is False but R is True
Consider the table ORDERS as given below:
| O_Id | C_Name | Product | Quantity | Price |
|---|---|---|---|---|
| 1001 | Jitendra | Laptop | 1 | 12000 |
| 1002 | Mustafa | Smartphone | 2 | 10000 |
| 1003 | Dhwani | Headphone | 1 | 1500 |
Note: The table contains many more records than shown here.
A) Write the following queries:
(I) To display the total Quantity for each Product, excluding Products with total Quantity less than 5.
(II) To display the orders table sorted by total price in descending order.
(III) To display the distinct customer names from the Orders table.
(IV) Display the sum of Price of all the orders for which the quantity is null.
OR
B) Write the output:
(I) Select c_name, sum(quantity) as total_quantity from orders group by c_name;
(II) Select * from orders where product like '%phone%';
(III) Select o_id, c_name, product, quantity, price from orders where price between 1500 and 12000;
(IV) Select max(price) from orders;
Consider the given SQL Query:
SELECT department, COUNT(*) FROM employees HAVING COUNT(*) > 5 GROUP BY department;
Saanvi is executing the query but not getting the correct output. Write the correction.
Consider the table SALES as given below:
| sales_id | customer_name | product | quantity_sold | price |
|---|---|---|---|---|
| S001 | John Doe | Laptop | 5 | 50000 |
| S002 | Jane Smith | Smartphone | 10 | 30000 |
| S003 | Michael Lee | Tablet | 3 | 15000 |
| S004 | Sarah Brown | Headphones | 7 | 2000 |
| S005 | Emily Davis | Smartwatch | 8 | 8000 |
| S006 | David | Smartwatch | 3 | 16000 |
| S007 | Mark | Tablet | 5 | 34000 |
A. Write the following queries:
I. To display the total quantity sold for each product whose total quantity sold exceeds 12.
II. To display the records of SALES table sorted by Product name in descending order.
III. To display the distinct Product names from the SALES table.
IV. To display the records of customers whose names end with the letter 'e'.
Table : DOCTOR
| DNO | DNAME | FEES |
|---|---|---|
| D1 | AMITABH | 1500 |
| D2 | ANIKET | 1000 |
| D3 | NIKHIL | 1500 |
| D4 | ANJANA | 1500 |
Table : PATIENT
| PNO | PNAME | ADMDATE | DNO |
|---|---|---|---|
| P1 | NOOR | 2021-12-25 | D1 |
| P2 | ANNIE | 2021-11-20 | D2 |
| P3 | PRAKASH | 2020-12-10 | NULL |
| P4 | HARMEET | 2019-12-20 | D1 |
(a) SELECT DNAME, PNAME FROM DOCTOR NATURAL JOIN PATIENT;
(b) SELECT PNAME, ADMDATE, FEES FROM PATIENT P, DOCTOR D WHERE D.DNO = P.DNO AND FEES > 1000;
Consider the following tables — LOAN and BORROWER :
Table : LOAN
| LOAN_NO | B_NAME | AMOUNT |
|---|---|---|
| L-170 | DELHI | 3000 |
| L-230 | KANPUR | 4000 |
Table : BORROWER
| CUST_NAME | LOAN_NO |
|---|---|
| JOHN | L-171 |
| KRISH | L-230 |
| RAVYA | L-170 |
(a) How many rows and columns will be there in the natural join of these two tables ?
(b) Write the output of the queries (i) to (iv) based on the table, WORKER given below :
TABLE: WORKER
| W_ID | F_NAME | L_NAME | CITY | STATE |
|---|---|---|---|---|
| 102 | SAHIL | KHAN | KANPUR | UTTAR PRADESH |
| 104 | SAMEER | PARIKH | ROOP NAGAR | PUNJAB |
| 105 | MARY | JONES | DELHI | DELHI |
| 106 | MAHIR | SHARMA | SONIPAT | HARYANA |
| 107 | ATHARVA | BHARDWAJ | DELHI | DELHI |
| 108 | VEDA | SHARMA | KANPUR | UTTAR PRADESH |
(i) SELECT F_NAME, CITY FROM WORKER ORDER BY STATE DESC;
(ii) SELECT DISTINCT (CITY) FROM WORKER;
(iii) SELECT F_NAME, STATE FROM WORKER WHERE L_NAME LIKE 'SH%';
(iv) SELECT CITY, COUNT(*) FROM WORKER GROUP BY CITY;
(a) Write the outputs of the SQL queries (i) to (iv) based on the relations COMPUTER and SALES given below :
Table : COMPUTER
| PROD_ID | PROD_NAME | PRICE | COMPANY | TYPE |
|---|---|---|---|---|
| P001 | MOUSE | 200 | LOGITECH | INPUT |
| P002 | LASER PRINTER | 4000 | CANON | OUTPUT |
| P003 | KEYBOARD | 500 | LOGITECH | INPUT |
| P004 | JOYSTICK | 1000 | IBALL | INPUT |
| P005 | SPEAKER | 1200 | CREATIVE | OUTPUT |
| P006 | DESKJET PRINTER | 4300 | CANON | OUTPUT |
Table : SALES
| PROD_ID | QTY_SOLD | QUARTER |
|---|---|---|
| P002 | 4 | 1 |
| P003 | 2 | 2 |
| P001 | 3 | 2 |
| P004 | 2 | 1 |
(i) SELECT MIN(PRICE), MAX(PRICE) FROM COMPUTER;
(ii) SELECT COMPANY, COUNT(*) FROM COMPUTER GROUP BY COMPANY HAVING COUNT (COMPANY) > 1;
(iii) SELECT PROD_NAME, QTY_SOLD FROM COMPUTER C, SALES S WHERE C.PROD_ID=S.PROD_ID AND TYPE = 'INPUT';
(iv) SELECT PROD_NAME, COMPANY, QUARTER FROM COMPUTER C, SALES S WHERE C.PROD_ID=S.PROD_ID;
(b) Write the command to view all databases.
Consider the tables Employee and Dept given below.
Table: Employee
| EID | ENAME | DEPTID | SALARY |
|---|---|---|---|
| E1 | Ananya | D2 | 80000 |
| E2 | Bhavesh | D1 | 90000 |
| E3 | Chavi | D2 | 85000 |
| E4 | Deepak | D3 | 75000 |
Table: Dept
| DEPTID | DNAME |
|---|---|
| D1 | Sales |
| D2 | Marketing |
| D3 | Finance |
(a) SELECT DNAME FROM Dept WHERE Deptid='D3';
(b) SELECT ENAME FROM Employee WHERE SALARY>80000;
(c) SELECT Employee.Ename, Dept.Dname FROM Employee, Dept WHERE Employee.Deptid=Dept.Deptid;
(d) SELECT Deptid, COUNT(*) FROM Employee GROUP BY Deptid;
OR
(a) To display the Ename and Dname of the employee whose salary is greater than 80000.
(b) To display the total salary department wise.
(c) To count the number of employees whose salary is greater than 85000.
(d) To display the details of the employee whose name starts with 'A'.
Assertion (A): We can retrieve records from more than one table in MYSQL.
Reason (R): Foreign key is used to establish a relationship between two tables.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation for Assertion (A).
(B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation for Assertion (A).
(C) Assertion (A) is true but Reason (R) is false.
(D) Assertion (A) is false but Reason (R) is true.
Table : CLIENT
| C_ID | NAME | PERCENT |
|---|---|---|
| C1 | Amrita | 90 |
| C2 | Pankaj | 76 |
| C3 | Amisha | 83 |
Table : VENUE
| V_ID | CITY | MAX |
|---|---|---|
| V1 | Delhi | 200 |
| V2 | Mumbai | 100 |
(a) SELECT COUNT(C_ID), AVG(PERCENT) FROM CLIENT WHERE C_ID IN ('C1','C2');
(b) SELECT CLIENT.NAME, VENUE.CITY FROM CLIENT, VENUE WHERE CLIENT.C_ID='C1' AND VENUE.V_ID='V2';
Assume that you are the Manager of the Loans department of a Finance House. To keep track of the loans you have created two tables : CUSTOMERS and LOANS. The sample data in these tables is given below :
Table: CUSTOMERS
| C_ID | C_Name | Phone |
|---|---|---|
| 00001 | Raj Malhotra | 1234567890 |
| 00003 | David Xavier | 3456789012 |
| 00004 | Damini Iyer | 3156789012 |
| 00008 | Abdul | 2345678901 |
Table: LOANS
| SNo | C_ID | L_Amt | L_Date | Terms | RoI |
|---|---|---|---|---|---|
| 1 | 00003 | 200000 | 2025-12-06 | 60 | 7.80 |
| 2 | 00008 | 2500000 | 2023-08-09 | 60 | 9.00 |
| 3 | 00001 | 500000 | 2025-08-13 | 48 | 6.00 |
| 4 | 00003 | 300000 | 2026-12-07 | 36 | 8.00 |
| 5 | 00004 | 600000 | 2026-12-07 | 60 | 6.00 |
Note : The tables may contain more records than shown here.
The management of the Finance House needs certain reports from you. Write the queries to extract the following data to create the reports :
(i) Number of records from LOANS table where Rate of Interest (RoI) is above 7.0.
(ii) Names of the customers whose loan amount (L_Amt) is above 1000000.
(iii) C_ID, C_Name and Terms of all those records where Loan Date (L_Date) is after 31st December, 2024.
(iv) (a) Details of all the loans in the descending order of RoI.
OR
(b) C_ID and average term for each C_ID from the LOANS table.
Table : FLIGHT
| FNO | DEPART | ARRIVE | FARE |
|---|---|---|---|
| F101 | DELHI | CHENNAI | 4500 |
| F102 | DELHI | BENGALURU | 4000 |
| F103 | MUMBAI | CHENNAI | 5500 |
| F104 | DELHI | MUMBAI | 4500 |
| F105 | MUMBAI | BENGALURU | 5000 |
Table : PASSENGER
| PNO | NAME | FLIGHTDATE | FNO |
|---|---|---|---|
| P1 | PRAKASH | 2021-12-25 | F101 |
| P2 | NOOR | 2021-11-20 | F103 |
| P3 | HARMEET | 2020-12-10 | NULL |
| P4 | ANNIE | 2019-12-20 | F105 |
(a) SELECT NAME, DEPART FROM FLIGHT NATURAL JOIN PASSENGER ;
(b) SELECT NAME, FARE FROM PASSENGER P, FLIGHT F WHERE F.FNO = P.FNO AND F.DEPART = 'MUMBAI'
(a) Consider the following tables — Student and Sport :
Table : Student
| ADMNO | NAME | CLASS |
|---|---|---|
| 1100 | MEENA | X |
| 1101 | VANI | XI |
Table : Sport
| ADMNO | GAME |
|---|---|
| 1100 | CRICKET |
| 1103 | FOOTBALL |
What will be the output of the following statement ?
SELECT * FROM Student, Sport;
(b) Write the output of the queries (i) to (iv) based on the table, GARMENT given below :
TABLE : GARMENT
| GCODE | TYPE | PRICE | FCODE | ODR_DATE |
|---|---|---|---|---|
| G101 | EVENING GOWN | 850 | F03 | 2008-12-19 |
| G102 | SLACKS | 750 | F02 | 2020-10-20 |
| G103 | FROCK | 1000 | F01 | 2021-09-09 |
| G104 | TULIP SKIRT | 1550 | F01 | 2021-08-10 |
| G105 | BABY TOP | 1500 | F02 | 2020-03-31 |
| G106 | FORMAL PANT | 1250 | F01 | 2019-01-06 |
(i) SELECT DISTINCT (COUNT (FCODE)) FROM GARMENT;
(ii) SELECT FCODE, COUNT(*), MIN(PRICE) FROM GARMENT GROUP BY FCODE HAVING COUNT(*)>1;
(iii) SELECT TYPE FROM GARMENT WHERE ODR_DATE > '2021-02-01' AND PRICE <1500;
(iv) SELECT * FROM GARMENT WHERE TYPE LIKE 'F%';
Write the output of any three SQL queries (i) to (iv) based on the tables COMPANY and CUSTOMER given below :
Table : COMPANY
| CID | C_NAME | CITY | PRODUCTNAME |
|---|---|---|---|
| 111 | SONY | DELHI | TV |
| 222 | NOKIA | MUMBAI | MOBILE |
| 333 | ONIDA | DELHI | TV |
| 444 | SONY | MUMBAI | MOBILE |
| 555 | BLACKBERRY | CHENNAI | MOBILE |
| 666 | DELL | DELHI | LAPTOP |
Table : CUSTOMER
| CUSTID | CID | NAME | PRICE | QTY |
|---|---|---|---|---|
| C01 | 222 | ROHIT SHARMA | 70000 | 20 |
| C02 | 666 | DEEPIKA KUMARI | 50000 | 10 |
| C03 | 111 | MOHAN KUMAR | 30000 | 5 |
| C04 | 555 | RADHA MOHAN | 30000 | 11 |
(i) SELECT PRODUCTNAME, COUNT(*) FROM COMPANY GROUP BY PRODUCTNAME HAVING COUNT(*)>2;
(ii) SELECT NAME, PRICE, PRODUCTNAME FROM COMPANY C, CUSTOMER CU WHERE C.CID = CU.CID AND C_NAME = 'SONY';
(iii) SELECT DISTINCT CITY FROM COMPANY;
(iv) SELECT * FROM COMPANY WHERE C_NAME LIKE '%ON%';
Consider the tables GAMES and PLAYERS given below :
Table : GAMES
| GCode | GameName | Type | Number | PrizeMoney |
|---|---|---|---|---|
| 101 | Carrom Board | Indoor | 2 | 5000 |
| 102 | Badminton | Outdoor | 2 | 12000 |
| 103 | Table Tennis | Indoor | 4 | NULL |
| 104 | Chess | Indoor | 2 | 9000 |
| 105 | Lawn Tennis | Outdoor | 4 | 25000 |
Table : PLAYERS
| PCode | Name | GCode |
|---|---|---|
| 1 | Nabi Ahmad | 101 |
| 2 | Ravi Sahai | 108 |
| 3 | Jatin | 101 |
| 4 | Nazneen | 103 |
Write SQL queries for the following :
(i) Display the game type and average number of games played in each type.
(ii) Display prize money, name of the game, and name of the players from the tables Games and Players.
(iii) Display the types of games without repetition.
(iv) Display the name of the game and prize money of those games whose prize money is known.
Assume that you are working for ABC Corporation (ABCC). ABCC allots contracts to different contractors for some of its works. The data of Contracts and Contractors are kept in the tables Work and Contractor respectively. Following are a few records from these two tables of ABCC's database.
Table : Work
| W_ID | C_ID | W_Name | W_Amt |
|---|---|---|---|
| P0001 | C_01 | Painting | 20000 |
| E0001 | C_01 | Electrical | 50000 |
| D0001 | C_02 | Dumping | 10000 |
Table : Contractor
| C_ID | C_Name | Phone | |
|---|---|---|---|
| C_01 | M. Khan & Sons | 1232311 | MK@xyz.com |
| C_02 | Acharya Pvt. Ltd. | 2323311 | APL@xyz.com |
| C_03 | Charu Corp. | NULL | CCP@pqr.xyz |
Note : The tables contain many more records than shown here.
As an employee of ABCC, you are required to write the SQL queries for the following :
(I) To display all the records from the Work table in alphabetical order of W_Name.
(II) To display the names of contractors where W_Amt is more than 15000.
(III) To display the structure of Work table.
(IV) (a) To count total number of records present in Work table.
OR
(b) To delete the records of contractors whose phone number is not known.
(a) Consider the following tables – Bank_Account and Branch:
Table: Bank_Account
| ACode | Name | Type |
|---|---|---|
| A01 | Amrita | Savings |
| A02 | Parthodas | Current |
| A03 | Miraben | Current |
Table: Branch
| ACode | City |
|---|---|
| A01 | Delhi |
| A02 | Mumbai |
| A01 | Nagpur |
What will be the output of the following statement?
SELECT * FROM Bank_Account NATURAL JOIN Branch;
(b) Write the output of the queries (i) to (iv) based on the table TECH_COURSE given below:
Table: TECH_COURSE
| CID | CNAME | FEES | STARTDATE | TID |
|---|---|---|---|---|
| C201 | Animation and VFX | 12000 | 2022-07-02 | 101 |
| C202 | CADD | 15000 | 2021-11-15 | NULL |
| C203 | DCA | 10000 | 2020-10-01 | 102 |
| C204 | DDTP | 9000 | 2021-09-15 | 104 |
| C205 | Mobile Application Development | 18000 | 2022-11-01 | 101 |
| C206 | Digital marketing | 16000 | 2022-07-25 | 103 |
(i) SELECT DISTINCT TID FROM TECH_COURSE;
(ii) SELECT TID, COUNT(*), MIN(FEES) FROM TECH_COURSE GROUP BY TID HAVING COUNT(TID)>1;
(iii) SELECT CNAME FROM TECH_COURSE WHERE FEES>15000 ORDER BY CNAME;
(iv) SELECT AVG(FEES) FROM TECH_COURSE WHERE FEES BETWEEN 15000 AND 17000;
(a) Write the outputs of the SQL queries (i) to (iv) based on the relations Teacher and Placement given below:
Table: Teacher
| T_ID | Name | Age | Department | Date_of_join | Salary | Gender |
|---|---|---|---|---|---|---|
| 1 | Arunan | 34 | Computer Sc | 2019-01-10 | 12000 | M |
| 2 | Saman | 31 | History | 2017-03-24 | 20000 | F |
| 3 | Randeep | 32 | Mathematics | 2020-12-12 | 30000 | M |
| 4 | Samira | 35 | History | 2018-07-01 | 40000 | F |
| 5 | Raman | 42 | Mathematics | 2021-09-05 | 25000 | M |
| 6 | Shyam | 50 | History | 2019-06-27 | 30000 | M |
| 7 | Shiv | 44 | Computer Sc | 2019-02-25 | 21000 | M |
| 8 | Shalakha | 33 | Mathematics | 2018-07-31 | 20000 | F |
Table: Placement
| P_ID | Department | Place |
|---|---|---|
| 1 | History | Ahmedabad |
| 2 | Mathematics | Jaipur |
| 3 | Computer Sc | Nagpur |
(i) SELECT Department, avg(salary) FROM Teacher GROUP BY Department;
(ii) SELECT MAX(Date_of_Join),MIN(Date_of_Join) FROM Teacher;
(iii) SELECT Name, Salary, T.Department, Place FROM Teacher T, Placement P WHERE T.Department = P.Department AND Salary>20000;
(iv) SELECT Name, Place FROM Teacher T, Placement P WHERE Gender ='F' AND T.Department=P.Department;
(b) Write the command to view all tables in a database.
In MYSQL database, if a table Alpha has degree 5 and cardinality 3, and another table Beta has degree 3 and cardinality 5, what will be the degree and cardinality of the Cartesian product of Alpha and Beta?
a) 5,3
b) 8,15
c) 3,5
d) 15,8
Consider the tables PRODUCT and BRAND given below:
Table: PRODUCT
| PCode | PName | UPrice | Rating | BID |
|---|---|---|---|---|
| P01 | Shampoo | 120 | 6 | M03 |
| P02 | Toothpaste | 54 | 8 | M02 |
| P03 | Soap | 25 | 7 | M03 |
| P04 | Toothpaste | 65 | 4 | M04 |
| P05 | Soap | 38 | 5 | M05 |
| P06 | Shampoo | 245 | 6 | M05 |
Table: BRAND
| BID | BName |
|---|---|
| M02 | Dant Kanti |
| M03 | Medimix |
| M04 | Pepsodent |
| M05 | Dove |
Write SQL queries for the following:
(i) Display product name and brand name from the tables PRODUCT and BRAND.
(ii) Display the structure of the table PRODUCT.
(iii) Display the average rating of Medimix and Dove brands.
(iv) Display the name, price, and rating of products in descending order of rating.
Saman has been entrusted with the management of Law University Database. He needs to access some information from FACULTY and COURSES tables for a survey analysis. Help him extract the following information by writing the desired SQL queries as mentioned below.
Table: FACULTY
| F_ID | FName | LName | Hire_Date | Salary |
|---|---|---|---|---|
| 102 | Amit | Mishra | 12-10-1998 | 12000 |
| 103 | Nitin | Vyas | 24-12-1994 | 8000 |
| 104 | Rakshit | Soni | 18-5-2001 | 14000 |
| 105 | Rashmi | Malhotra | 11-9-2004 | 11000 |
| 106 | Sulekha | Srivastava | 5-6-2006 | 10000 |
Table: COURSES
| C_ID | F_ID | CName | Fees |
|---|---|---|---|
| C21 | 102 | Grid Computing | 40000 |
| C22 | 106 | System Design | 16000 |
| C23 | 104 | Computer Security | 8000 |
| C24 | 106 | Human Biology | 15000 |
| C25 | 102 | Computer Network | 20000 |
| C26 | 105 | Visual Basic | 6000 |
(I) To display complete details (from both the tables) of those Faculties whose salary is less than 12000.
(II) To display the details of courses whose fees is in the range of 20000 to 50000 (both values included).
(III) To increase the fees of all courses by 500 which have "Computer" in their Course names.
(IV)
A) To display names (FName and LName) of faculty taking System Design.
OR
B) To display the Cartesian Product of these two tables.
In SQL, which type of Join(s) may contain duplicate column(s)?
Pranav is managing a Travel Database and needs to access certain information from the Hotels and Bookings tables for an upcoming tourism survey.
Table: Hotels
| H_ID | Hotel_Name | City | Star_Rating |
|---|---|---|---|
| 1 | Hotel1 | Delhi | 5 |
| 2 | Hotel2 | Mumbai | 5 |
| 3 | Hotel3 | Hyderabad | 4 |
| 4 | Hotel4 | Bengaluru | 5 |
| 5 | Hotel5 | Chennai | 4 |
| 6 | Hotel6 | Kolkata | 4 |
Table: Bookings
| B_ID | H_ID | Customer_Name | Check_In | Check_Out |
|---|---|---|---|---|
| 1 | 1 | Jiya | 2024-12-01 | 2024-12-05 |
| 2 | 2 | Priya | 2024-12-03 | 2024-12-07 |
| 3 | 3 | Alicia | 2024-12-01 | 2024-12-06 |
| 4 | 4 | Bhavik | 2024-12-02 | 2024-12-03 |
| 5 | 5 | Charu | 2024-12-01 | 2024-12-02 |
| 6 | 6 | Esha | 2024-12-04 | 2024-12-08 |
| 7 | 6 | Dia | 2024-12-02 | 2024-12-06 |
| 8 | 4 | Sonia | 2024-12-04 | 2024-12-08 |
I. To display a list of customer names who have bookings in any hotel of 'Delhi' city.
II. To display the booking details for customers who have booked hotels in 'Mumbai', 'Chennai', or 'Kolkata'.
III. To delete all bookings where the check-in date is before 2024-12-03.
IV. A. To display the Cartesian Product of the two tables.
OR
IV. B. To display the customer's name along with their booked hotel's name.
Consider the following SQL table MEMBER in a SQL Database CLUB :
Table : MEMBER
| M_ID | NAME | ACTIVITY |
|---|---|---|
| M1001 | Amina | GYM |
| M1002 | Pratik | GYM |
| M1003 | Simon | SWIMMING |
| M1004 | Rakesh | GYM |
| M1005 | Avneet | SWIMMING |
Assume that the required library for establishing the connection between Python and MYSQL is already imported in the given Python code. Also assume that DB is the name of the database connection for table MEMBER stored in the database CLUB.
Predict the output of the following code :
MYCUR = DB.cursor()
MYCUR.execute ("USE CLUB")
MYCUR.execute ("SELECT * FROM MEMBER WHERE ACTIVITY= 'GYM' ")
R=MYCUR.fetchone()
for i in range(2):
R=MYCUR.fetchone()
print (R[0], R[1], sep = "#")
fetchall() method fetches all rows in a result set and returns a:
(a) Tuple of lists
(b) List of tuples
(c) List of strings
(d) Tuple of strings
(a) What possible output(s) are expected to be displayed on screen at the time of execution of the following program :
import random
M=[5,10,15,20,25,30]
for i in range(1,3):
first=random.randint(2,5)-1
sec=random.randint(3,6)-2
third=random.randint(1,4)
print(M[first],M[sec],M[third],sep="#")
(i) 10#25#15
(ii) 5#25#20
(iii) 20#25#25
(iv) 30#20#20
(b) The code given below deletes the record from the table employee which contains the following record structure :
E_code - String
E_name - String
Sal - Integer
City - String
Note the following to establish connectivity between Python and MySQL :
- Username is root
- Password is root
- The table exists in a MySQL database named emp.
- The details (E_code, E_name, Sal, City) are the attributes of the table.
Write the following statements to complete the code :
Statement 1 — to import the desired library.
Statement 2 — to execute the command that deletes the record with E_code 'E101'.
Statement 3 — to delete the record permanently from the database.
import ______ as mysql # Statement 1
def delete():
mydb=mysql.connect(host="localhost",user="root",
passwd="root",database="emp")
mycursor=mydb.cursor()
______ # Statement 2
______ # Statement 3
print ("Record deleted")
OR
(a) Predict the output of the code given below :
def makenew(mystr):
newstr=""
count=0
for i in mystr:
if count%2!=0:
newstr=newstr+str(count)
else:
if i.lower():
newstr=newstr+i.upper()
else:
newstr=newstr+i
count+=1
print(newstr)
makenew("No@1")
(b) The code given below reads the following records from the table employee and displays only those records who have employees coming from city 'Delhi':
E_code - String
E_name - String
Sal - Integer
City - String
Note the following to establish connectivity between Python and MySQL :
- Username is root
- Password is root
- The table exists in a MySQL database named emp.
- The details (E_code, E_name, Sal, City) are the attributes of the table.
Write the following statements to complete the code :
Statement 1 — to import the desired library.
Statement 2— to execute the query that fetches records of the employees coming from city 'Delhi'.
Statement 3— to read the complete data of the query (rows whose city is Delhi) into the object named details, from the table employee in the database.
import ______ as mysql # Statement 1
def display():
mydb=mysql.connect(host="localhost",user="root",
passwd="root", database="emp")
mycursor=mydb.cursor()
______ # Statement 2
details = ______ # Statement 3
for i in details:
print(i)
Assertion (A): The fetchone() method fetches only one row from the cursor and returns the data as a tuple.
Reason (R): The fetchone() method fetches only one row from the cursor.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A).
(B) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation of Assertion (A).
(C) Assertion (A) is true but Reason (R) is false.
(D) Assertion (A) is false but Reason (R) is true.
Consider the following table STUDENT in a SQL database DB:
| ADMNO | NAME | PERCENT |
|---|---|---|
| A1 | Preeti | 82 |
| A2 | Latika | 92 |
| A3 | Priya | 76 |
| A4 | Karan | 95 |
| A5 | Kunal | 90 |
Assume that the required library for establishing the connection between Python and MYSQL is already imported. Also assume that CONN is the name of the database connection for the table STUDENT stored in the database DB.
Predict the output of the following code:
MY_CURSOR = CONN.cursor()
MY_CURSOR.execute("USE DB")
MY_CURSOR.execute("SELECT * FROM STUDENT WHERE PERCENT>85")
R = MY_CURSOR.fetchone()
for i in range(3):
print(R[0],R[2])
R = MY_CURSOR.fetchone()
Peter has created a table named Account in MySQL database, SCHOOL, having following structure :
· Stud_id – integer
· Sname – string
· Class – string
· Fees – float
Help him in writing a Python program to display records of those students whose fees is less than 5000.
Note the following to establish connectivity between Python and MySQL :
· Username – admin
· Password – root
· Host – localhost
Consider the following table EMPLOYEE in a Database COMPANY :
Table : EMPLOYEE
| E_ID | NAME | DEPT |
|---|---|---|
| H1001 | Avneet | AC |
| A1002 | Rakesh | HR |
| A1003 | Amina | AC |
| H1002 | Simon | HR |
| A1004 | Pratik | AC |
Assume that the required library for establishing the connection between Python and MySQL is already imported in the given Python code.
Also assume that DB is the name of the database connection for the given table EMPLOYEE stored in the database COMPANY.
Predict the output of the following Python code :
CUR=DB.cursor()
CUR.execute ("USE COMPANY" )
CUR.execute ("SELECT * FROM EMPLOYEE WHERE DEPT = 'AC' ")
for i in range(2):
R=CUR.fetchone()
print(R[0], R[1], sep="#")
fetchone() method fetches only one row in a ResultSet and returns a
(a) Tuple
(b) List
(c) Dictionary
(d) String
(a) (i) What possible output(s) are expected to be displayed on screen at the time of execution of the following code ?
import random
S=["Pen", "Pencil", "Eraser", "Bag", "Book"]
for i in range (1,2):
f=random.randint(0,3)
s=random.randint(i+1,4)
print (S[f],S[s],sep=":")
Options:
(I) Pencil:Book
(II) Pencil:Book
Eraser:Bag
(III) Pen:Book
Bag:Book
(IV) Bag:Eraser
(ii) The table Bookshop in MySQL contains the following attributes :
B_code — Integer
B_name — String
Qty — Integer
Price — Integer
Note the following to establish connectivity between Python and MySQL on a 'localhost' :
- Username is 'shop'
- Password is 'Book'
- The table exists in a MySQL database named Bstore.
The code given below updates the records from the table Bookshop in MySQL.
Statement 1 — to form the cursor object.
Statement 2 — to execute the query that updates the Qty to 20 of the records whose B_code is 105 in the table.
Statement 3 — to make the changes permanent in the database.
import mysql.connector as mysql
def update_book():
mydb=mysql.connect (host="localhost",
user="shop",passwd="Book",database="Bstore")
mycursor= ______ # Statement 1
qry= "update Bookshop set Qty=20 where B_code=105"
______ # Statement 2
______ # Statement 3
OR
(b) (i) Predict the output of the code given below :
text="LearningCs"
L=len(text)
ntext=""
for i in range (0,L):
if text[i].islower():
ntext=ntext+text[i].upper()
elif text[i].isalnum():
ntext=ntext+text[i-1]
else:
ntext=ntext+'&'
print(ntext)
(ii) The table Bookshop in MySQL contains the following attributes :
B_code — Integer
B_name — String
Qty — Integer
Price — Integer
Note the following to establish connectivity between Python and MySQL on a 'localhost' :
- Username is 'shop'
- Password is 'Book'
- The table exists in a MySQL database named Bstore.
The code given below reads the records from the table Bookshop and displays all the records :
Statement 1 — to form the cursor object.
Statement 2 — to write the query to display all the records from the table.
Statement 3 — to read the complete result of the query into the object named B_Details, from the table Bookshop in the database.
import mysql.connector as mysql
def Display_book():
mydb=mysql.connect (host="localhost",
user="shop",passwd="Book",database="Bstore")
mycursor= ______ # Statement 1
mycursor.execute (" ") # Statement 2
B_Details= ______ # Statement 3
for i in B_Details:
print(i)
(a) (i) Define the term foreign key with respect to RDBMS.
(ii) Sangeeta wants to write a program in Python to delete the record of a candidate "Raman" from the table named Placement in MySQL database, Agency.
The table Placement in MySQL contains the following attributes :
CName – String
Dept – String
Place – String
Salary – integer
Note the following to establish connectivity between Python and MySQL :
· Username – root
· Password – job
· Host – localhost
Help Sangeeta to write the program in Python for the above mentioned task.
OR
(b) (i) Give one difference between CHAR and VARCHAR datatype in MySQL.
(ii) Rahim wants to write a program in Python to insert the following record in the table named Bank_Account in MySQL database, Bank
· Accno – integer
· Cname – string
· Atype – string
· Amount – float
Note the following to establish connectivity between Python and MySQL :
· Username – admin
· Password – root
· Host – localhost
The values of fields Accno, Cname, Atype and Amount have to be accepted from the user. Help Rahim to write the program in Python.
Nutan Kumar is using Python connectivity with MySQL for maintaining data for a table named MEDICINES in a database PHARMACY. The table has the following attributes :
• MId (Medicine number) – string
• Mname (Medicine Name) – string
• Expiry (Expiry Date) – Date
• Status (Active/Discard) – string
Consider the following to establish connectivity between Python and MySQL :
• Username – root
• Password – tiger
• Host – localhost
Help Nutan to write the definition of a user-defined function named ChangeStatus() in Python to change the Status of the Medicines whose Expiry is before '2022-12-31' as 'DISCARD'.
To establish a connection between Python and SQL database, connect() is used. Which of the following arguments may not necessarily be given while calling connect()?
a) host
b) database
c) user
d) password
(a) Write the output of the code given below:
p=5
def sum(q,r=2):
global p
p=r+q**2
print(p, end='#')
a=10
b=5
sum(a,b)
sum(r=5,q=1)
(b) The code given below inserts the following record in the table Student:
RollNo – integer, Name – string, Clas – integer, Marks – integer
Note: Username is root, Password is tiger, database named school.
The details (RollNo, Name, Clas and Marks) are to be accepted from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3 – to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="tiger", database="school")
mycursor=_________________ #Statement 1
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
clas=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
querry="insert into student values({},'{}',{},{})" .format(rno,name,clas,marks)
______________________ #Statement 2
______________________ #Statement 3
print("Data Added successfully")
OR
(a) Predict the output of the code given below:
s="welcome2cs"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)
(b) The code given below reads records from the table named student and displays only those records who have marks greater than 75.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of students whose marks are greater than 75.
Statement 3 – to read the complete result of the query into the object named data.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",
password="tiger", database="school")
mycursor=_______________ #Statement 1
print("Students with marks greater than 75 are : ")
_________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()
(i) Define the term Domain with respect to RDBMS. Give one example to support your answer.
(ii) Kabir wants to write a program in Python to insert the following record in the table named Student in MYSQL database, SCHOOL:
rno (Roll number) – integer
name (Name) – string
DOB (Date of birth) – Date
Fee – float
Note: Username - root, Password - tiger, Host - localhost
The values of fields rno, name, DOB and fee have to be accepted from the user. Help Kabir to write the program in Python.
OR
(i) Give one difference between alternate key and candidate key.
(ii) Sartaj has created a table named Student in MYSQL database, SCHOOL (rno, name, DOB, Fee).
Note: Username - root, Password - tiger, Host - localhost
Sartaj now wants to display the records of students whose fee is more than 5000. Help Sartaj to write the program in Python.
A table, named STATIONERY, in ITEMDB database, has the following structure:
| Field | Type |
|---|---|
| itemNo | int(11) |
| itemName | varchar(15) |
| price | float |
| qty | int(11) |
Write the following Python function to perform the specified operation:
AddAndDisplay(): To input details of an item and store it in the table STATIONERY. The function should then retrieve and display all records from the STATIONERY table where the Price is greater than 120.
Assume the following for Python-Database connectivity:
Host: localhost, User: root, Password: Pencil
MySQL database named WarehouseDB has a product_inventory table in MySQL which contains the following attributes:
- Item_code: Item code (Integer)
- Product_name: Name of product (String)
- Quantity: Quantity of product (Integer)
- Cost: Cost of product (Integer)
Consider the following details to establish Python-MySQL connectivity:
- Username: admin_user
- Password: warehouse2024
- Host: localhost
Write a Python program to change the Quantity of the product to 91 whose Item_code is 208 in the product_inventory table.