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

Class 12th QuestionBank InformaticsPractices

Uploaded by

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

Class 12th QuestionBank InformaticsPractices

Uploaded by

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

Kendriya Vidyalaya Sangathan

MUMBAI REGION

INFORMATICS PRACTICES-XII

Question Bank

2023-2024

Key Features:

CBSE Question
SAMPLE MIND MAPS
Bank
PAPER

Latest Question Paper Includes question based on To memorize and review the
latest question papers. topics quickly
हमारे संर क
OUR PATRONS

ीमती सोना सेठ Mrs. SONA SETH


उपायु DEPUTY COMMISSIONER
के . िव. सं. मुंबई संभाग KVS MUMBAI REGION

ी रायम लू सोक ला Mr. RAYAMALLU SOKALLA


सहायक आयु ASSISTANT COMMISSIONER
के . िव. सं. मुंबई संभाग KVS MUMBAI REGION

ी कमल कशोर वामी Mr. KAMAL KISHOR SWAMI


पा म िनदशक COURSE DIRECTOR
ाचाय के िव चं पुर PRINCIPAL KV CHANDRAPUR

ी के . के .मोटला Mr. K.K MOTLA


सह .पा म िनदशक ASSOCIATE COURSE DIRECTOR
उप - ाचाय के िव भड़प(िश ट -2)VICE PRINCIPAL KV BHANDUP Shift -2

ी दपक पी वारजुरकर Mr. DIPAK P WARJURKAR


संसाधक RESOURCE PERSON
ातको र िश क संगणक िव ान PGT CS
के िव चं पुर KV WCL CHANDRAPUR

ी अ ण कु मार चौधरी Mr. Arun Kumar Choudhary


संसाधक RESOURCE PERSON
ातको र िश क संगणक िव ान PGT CS
के िव आम ए रया पुणे KV Army Area Pune
Unit 1: Data Handling using Pandas –I
CHAPTER – DATA HANDLING USING PANDAS-I

VSA – Very Short Answer Question (for 1 Mark)


Q.1 is a one dimensional labelled array capable of holding any data type.
Ans. Series

Q.2 If data is an ndarray, must be of same length as data.


Ans. Index

Q.3 Pandas was developed by in 2008


Ans. Wes Mckinney.

Q.4 is used for 2D plots of array in Python.


Ans. matplotlib.

Q.5 Pandas provides data structures for processing the data.


Ans. Two

Q.6 function is used to add series and other, elements wise.


Ans. add()

Q.7 head() function is used to get the n rows.


Ans. First

Q.8 if data is , an index must be provided.


Ans. Scalar value

Q.9 Given a Pandas series called Sample, the command which will display the last 3 rows
is .
Ans. print(Sample.tail(3))

Q.10 Given a Pandas series called Sequences, the command which will display
the first 4 rows is .
Ans. print(Sequence.head(4))

Q.11 Given the following Series T1 and T2:


T1 T2
A 10 A 80
B 40 B 20
C 34 C 74
D 60 D 90
Write the command to find the sum of series T1 and T2
Ans. print(T1+T2)
Q. 12 Given the following Series S1 and S2:
S1 S2
A 10 A 5
B 20 B 4
C 30 C 6
D 40 D 8
Write the command to find the multiplication of series S1 and
S2 Ans. print(S1*S2)

Q.13 Give the output of the following program:


import numpy as np
arr=np.array([21,22,23,24,25,26,27,28,29,30])
print(arr[4:9])
a. [25 26 27 28 29] b. [25 29] . 25 26 29] d. None of these
Ans. a. [25 26 27 28 29]

Q.14 is a two dimensional structure storing heterogeneous mutable data.


Ans. DataFrame

Q.15 Mention the different types of data structure in Pandas.


Ans. The two data structures which are supported by Pandas library are Series
and DataFrames.

Q.16 Which command is used to import


matplotlib?
Ans. import matplotlib.pyplot as plt

Q.17 How to create empty series


Ans. Series_Object = pandas.Series()

Q.18 Define add() function in Series ()


Ans. add() function is used to add series and other elements
wise Syntax : Series.add(other,fill_value=None, axis=0)

Q.19 What do mean by clear code API


Ans. The clear API of the Pandas allows you to focus on the core part of the code
SA – Short Answer Question (for 2 Marks)

Q.1 List two key features of Pandas.


Ans. The two features of Pandas are
:
(i) It can process a variety of data set in different formats : time series,
tabular heterogeneous arrays and matrix data.
(ii) If facilitates loading and importing data from varied sources such as CSV and
DB/SQL.

Q.2 What are the benefits of Pandas ?


Ans. Benefits of Pandas are :
(i) Data representation : It ca easily represent data in form naturally suited for
data analysis via its DataFrame and series data structures in a concise
manner.
(ii) Data sub setting and filtering : It provides for easy sub setting and filtering
of data, procedures that are a staple of doing analysis.
Q.3 What is series ? Explain with an example.
Ans. Pandas series is one dimensional labelled array capable of holding data of any
type (integer, string, float, Python objects etc.) The axis labels are collectively called
index. Example :
import pandas as pd
data=pd.Series([1,2,3,4,5])
print(data)

Q.4 Consider the following Series : Subject


INDEX MARK
ENGLISH 75
HINDI 78
MATHS 82
SCIENCE 86
Write a program in Python Pandas to create a
Series. Ans.
import pandas as pd
subject=pd.Series([75,78,82,86],index=['ENGLISH','HINDI','MATHS','SCIENCE'])

Q5. Consider the following Series object, “company” and its profit in Crores

TCS 350
Reliance 200
L&T 800
Wipro 150

(i) Write the command which will display the name of the company
having profit>250.
(ii) Write the command to name the series as Profit.
SA – Short Answer Question (for 3 Marks)

Q. 1 Consider two objects a and b.


a is a list whereas b is a Series. Both have values 10,20,25,50.

What will be the output of the following two statements considering that the above
objects have been created already
a. print(a*2) b. print(b*2)
Justify your answer.
Ans.
a. will give the output as:
[10,20,25,50,10,20,25,50]
b. will give the output as
0 20
1 40
2 50
3 100
Justification: In the first statement a represents a list so when a list is multiplied by a
number, it is replicated that many number of times.
The second b represents a series. When a series is multiplied by a value, then each
element of the series is multiplied by that number.
Q.2 Explain the data structure in Pandas
Ans. Data structure is defined as the storage and management of the data for its
efficient and easy access in the future where the data is collected, modified and the
various types of operations are performed on the data respectively.
Pandas provides two data structures for processing the data, which are described below :
(i) Series : It is an one dimensional object similar to an array, list or column in
a table. It will assign a labelled index to each item in the series. By default,
each item will receive an index label from 0 to N, where N is the length of
the series minus one.
(ii) DataFrame : It is a tabular data structure comprised of rows and columns.
Data Frame is defined as a standard way to store data and has two different
indexes i.e., row index and column index.
Q.3 What is slicing ?
Ans. Slicing is a powerful approach to retrieve subsets of data from a Pandas object. A
slice object is built using a syntax of start : end : step, the segments representing the first
item, last item and the increment between each item that you would like as the step.

Q.4 Define the following terms


(i) .loc[ ] (ii) .iloc [ ]
Ans. .loc [ ] :This attribute is used to access a group of rows and columns by label(s)
or a Boolean array in the given series object.
Syntax : Series.loc
.iloc[ ] : This attributes enables purely integer location based indexing for selection
by position over the given series object.
Syntax : Series.iloc
CHAPTER – DATAFRAME
VSA – Very Short Answer Question (for 1 Mark)

Q.1 DataFrame is dimensional data structure


Ans. two

Q.2 In DataFrame, is used for the row label.


Ans. Index

Q.3 is a general term for taking each item of something, one after another.
Ans. Iteration.

Q.4 function return last n rows from the object based on position.
Ans. tail( )

Q.5 can also be known as subset section.


Ans. Indexing

Q.6 Boolean indexing helps us to select the data from the DataFrame using .
Ans. boolean vector.

Q.7 CSV file are the


Ans. Comma Separated Values.

Q.8 function is used to import a CSV file to DataFrame format.


Ans. read_CSV( )

Q.9 Hitesh wants to display the last four rows of the dataframe df and has written the
following code :
df.tail( )
but last 5 rows are being displayed. Identify the errors and rewrite the correct code so that
last 4 rows get displayed.
Ans. df.tail(4)

Q.10 Consider the following Python code and write the output for
statement. import pandas as pd
values=[“India”, “Canada”]
code=[“IND”, “CAN”]
df=pd.DataFrame(values,Index=Code,columns=[‘Country’]
Ans.
Code Country
IND India
CAN Canada
Q.11 The teacher needs to know the marks scored by the student with roll number 4. Help her
to identify the correct set of statement/s from the given options :
a. df1=df[df[‘rollno’]==4]
print(df1)
b. df1=df[rollno==4]
print(df1)
c. df1=df[df.rollno=4]
print(df1)
d. df1=df[df.rollno==4]
print(df1)
Ans.
a. df1=df[df[‘rollno’]==4]
print(df1)
d. df1=df[df.rollno==4]
print(df1)

Q.12
In Pandas the function used to delete a column in a DataFrame is
a. remove
b. del
c. drop
d. cance
l Ans. (b) del

Q.13 function applies the passed function on each individual data element of
the dataframe.
a. apply() b. applymap() c. pivot() d. pivot_table()
Ans. a. apply()

Q.14 Which of the following statement/s will give the exact number of values
in each column of the dataframe?
i. print(df.count())
ii. print(df.count(0))
iii. print(df.count)
iv. print(df.count(axis=’index’))
Choose the correct option:
a. both (i) and (ii)
b. only (ii)
c. (i), (ii) and (iii)
d. (i), (ii) and (iv)
Ans. a. both (i) and (ii)
Q.15 Which of the following command will display the column labels of the DataFrame?
a. print(df.columns()) b. print(df.column()) c. print(df.column) d.
print(df.columns) Ans. a. print(df.columns()) or d. print(df.columns)

Q.16 State True / False:


A dataframe cannot be created using another dataframe.
Ans. False
Q.17 Which method is used to access vertical subset of a dataframe.?
(i) Iterrows()
(ii) Iteritems()
(iii) Itertuples()
Ans.(ii) Iteritems( )

Q.18 State whether True or False


a. A series object is size mutable.
b. A Dataframe object is value mutable
Ans. a. False
b. True

Q.19 Define the iterrows()


Ans. iterrows() returns the iterator yielding each index value along with a series containing
the data in each row.

Q.20 Which function is used to export DataFrame to a CSV file ?


Ans. To export a Pandas DataFrame to a CSV file, use to_CSV function.
Syntax : to_CSV(parameter)

SA – Short Answer Question (for 2 Marks)


Q.1What are the operation on Pandas DataFrame?
Ans. We can perform the following advanced operation on the DataFrame as
● Assignment
● Selection
● Pivoting
● Sorting
Aggregation
Q.2 Given the Output of the code
>>>import pandas as pd
>>>a= pd.DataFrame([1,1,1,None],index=[‘a’, ‘b’, ‘c’ , ‘d’], column = [‘One’])
>>>print(a)
Ans. One
a 1.0
b 1.0
c 1.0
d NaN
Q.3 Explain DataFrame. Can it be considered as 1D Array or 2D Array
Ans. DataFrame is two dimensional array with heterogeneous data usually represented
in tabular format. It can be considered as 2D array.
Q.4 Write the output of the following
code import pandas as pd
data=[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
df = pd.DataFrame(data)
print(df)
Ans. Output
0 a
1 b
2 c
3 d
4 e

Q.5 Write the output of the following


code import pandas as pd
data = [[‘Alex’,10], [‘Bob’,12], [‘Clarke’,13]]
df = pd.DataFrame(data,columns = [‘Name’ , ‘Age’])
print(df)
Ans. Name Age
0 Alex 10
1 Bob 12
0 Clarke 13

Q.6 Write the output of the following code


>>>import pandas as pd
>>>data = [[‘Alex’,10], [‘Bob’,12], [‘Clarke’,13]]
>>>df = pd.DataFrame(data,columns = [‘Name’ , ‘Age’],dtype=float)
>>>print(df)
Ans. Name Age
0 Alex 10.0
1 Bob 12.0
0 Clarke 13.0
Q.7 Write a Python code to create a dataframe with appropriate headings from the list
given below :
[‘S101’, ‘Amy’ ,70]
[‘S102’, ‘Bandhi’ ,69]
[‘S103’, ‘Cathy’ ,75]
[‘S104’, ‘Gundoho’ ,82]
Ans. import pandas as pd
data =[ [‘S101’, ‘Amy’ ,70],[‘S102’, ‘Bandhi’ ,69],[‘S103’, ‘Cathy’ ,75],[‘S104’, ‘Gundoho’ ,
df=pd.DataFrame(data,columns=[‘ID’, ‘NAME’, ‘MARKS’])
print(df)
LA – Long Answer Question (for 4 Marks/5 marks)
Q.1 Write the code in Pandas to create the following Data Frames.

Df1 Df2
Mark1 Mark2 Mark1 Mark2
0 10 20 0 10 15
1 40 45 1 20 25
2 15 30 2 25 30
3 40 70 3 50 30
Write the commands to do the following operations on the DataFrames given below :
(i) To add DataFrames Df1 and Df2
(ii) To subtract Df2 from Df1
(iii) To Rename column Mark1 as Marks1 in both the DataFrame Df1 and Df2
(iv) To Change index label of Df1 from 0 to zero and from 1 to one.
Ans.
import numpy as np
import pandas as pd
Df1=pd.DataFrame({‘Mark1’ :[10,40,15,40],’Mark2’ : [20,45,30,70]})
Df2=pd.DataFrame({‘Mark1’ :[10,20,25,50],’Mark2’ : [15,25,30,30]})
print(Df1)
print(Df2)
(i) print(Df1.add(Df2))
(ii) print(Df1.sub(Df2))
(iii) Df1.rename(columns={‘Mark1’ : ‘Marks1’}, inplace =True)
print(Df1)
(iv) Df1.rename(columns={0: ‘zero’,1: ‘one’}, inplace =True)
print(Df1)
Q.2 Consider the following DataFrame emp and answer any four questions from (i) to (v)
Empno Name Dept Salary Experience
(in years)
1 Ram Singh IT 15000 2.5
2 Shyam Singh HR 18000 3
3 Nidhi Gupta IT 9000 2
4 Pooja Sharma EXE 24000 8
5 Rohan Malik HR 20000 6
(i) Write down the command that will give the following
output.
Empno 5
Name Rohan Malik
Dept HR
Salary 20000
Experience 6
dtype: object
a. print(emp.max)
b. print(emp.max())
c. print(emp.max(axis=1))
d. print(emp.max,axis=1)
(ii) CEO needs to know the salary of the employee with empno 4. Help him
to identify the correct set of statement/s from the given options:
a. emp1=emp[emp[‘empno’]==4]
print(emp1)
b. emp1=emp[emp]
print(emp1)
c. emp1=emp[emp.empno=4]
print(emp1)
d. emp1=emp[emp.empno==4]
print(emp1)
(iii) Which of the following statement/s will give the exact number of values in
each column of the dataframe?
i. print(emp.count())
ii. print(emp.count(0))
iii print(emp.count)
iv. print(emp.count(axis=’index’))

Choose the correct option:


a. both (i) and(ii)
b. only(ii)
c. (i), (ii) and(iii)
d. (i), (ii) and(iv)
(iv) Which of the following command will display the column labels of
the DataFrame?
a. print(emp.columns())
b. print(emp.column())
c. print(emp.column)
d. print(emp.columns)
(v) Mr. Satvik Ahuja, the CEO wants to add a new column, the rating of the
performance of employees with the values, ‘A’, ‘A’, ‘B’, ‘A’, ‘B’, to the DataFrame. Help
him choose the command to do so:
a. emp.column=[’A’,’A’,’B’,’A’,’B’]
b. emp[‘Performance’]=[ ’A’,’A’,’B’,’A’,’B’]
c. emp.loc[‘Performance’]= [’A’,’A’,’B’,’A’,’B’]
d. Both (b) and (c) are correct
Ans.
(i) b. print(emp.max())

(ii) a. emp1=emp[emp[‘empno’]==4]
print(emp1)
d.emp1=emp[emp.empno==4]
print(emp1)
(iii) a. both (i) and (ii)
(iv) d. print(emp.columns)
(v) b. emp[‘Performance’]=[ ’A’,’A’,’B’,’A’,’B’]
Q.3 A dataframe fdf stores data about passengers, Flights and Years. First fews of the
dataframe are shown below.
Year Months
Passengers 0 2009
January 112
1 2009 February 118
2 2009 March 132
3 2009 April 129
4 2009 May 121
Using the above DataFrame, Write commands for the following:
(a) Compute total passengers per Year
(b) Compute average passengers per Month.
Ans.
(i) fdf.pivot_table(index='year', value='passengers', aggfunc='sum')
(ii) fdf.pivot_table(index='month', values='passengers', aggfunc='mean')

Q.4 Give the output of the following code:


import numpy as np
import pandas as pd
dict={'Name':pd.Series(['Anu','Abhishek','Rajeev','Ritu']),'Age':pd.Series([26,25,24,31]),
'Score':pd.Series([87,67,89,55])}
df=pd.DataFrame(dict)
print("Dataframe contents are")
print(df)
print(df.count())
OR

Write the code in Pandas to create the above dataframes and write the command to
perform following operations on the dataframes Cls1 and Cls2:
(i) To subtract Cls2 from Cls1.
(ii) To add Cls1 and Cls2.
(iii) To rename column Hindi as Science in Cls1.
(iv) To change the index label of Cls1 from 2 to two and from 3 to
three. Ans.
Dataframe contents are
Name Age Score
0 Anu 26 87
1 Abhishek 25 67
2 Rajeev 24 89
3 Ritu 31 55

Name 4
Age 4
Score 4
dtype: int64
OR
import numpy as np
import pandas as pd
Cls1=pd.DataFrame({'Eng':[43,23,65,12],'Maths':[42,41,57,14],
'Hindi':[40,53,62,17]})
Cls2=pd.DataFrame({'Eng':[32,54,31,21],'Maths':[53,21,73,51],
'Hindi':[31,65,36,43]})
(i) print(Cls1.subtract(Cls2))
(ii) print(Cls1.add(Cls2))
(iii) Cls1.rename(columns={'Hindi':'Science'},inplace=True)
(iv) Cls1.rename(index={2:"Two",3:"Three"},inplace=True)

Q.5 Suppose a data frame contains information about student having


columns
rollno, name, class and section.
Write the code for the
following:
(i) Add one more column as fee
(ii) Write syntax to transpose data frame.
(iii) Write python code to delete column fee of data frame.
(iv) Write the code to append df2 with df1
(v) Display data of 1st to 3rd rows
Ans.
(i) Df1[‘fee’]=([100,200,300])
(ii) Df1=Df1.T
(iii) del Df1[‘fee’]
(iv) Df2=Df2.append(Df1)
(v) data.iloc[1:4]
CHAPTER – DATA VISUALIZATION
VSA – Very Short Answer Question (for 1 Mark)
Q.1 The matplotlib Python library developed by
Ans. John Hunter

Q.2 is a module in the matplotlib package.


Ans. Pyplot

Q.3 The matplotlib API is imported using the .


Ans. standard convention

Q.4 The is bounding box with ticks and labels.


Ans. axes

Q.5 The can be plotted verticall or horizontally.


Ans. bar chart

Q.6 Histograms are used to show a/an .


Ans. distribution

Q.7 To add a tittle in a chart, function is used.


Ans. tittle()

Q.8 A bar graph uses bars to compare data among .


Ans. different categories.

Q.9 What is Pylab?


Ans. Pylab is a package that combine numpy,scipy ad matplotlib into a single namespace.

Q.10 Mr.Sanjay wants to plot a bar graph for the given set of values of subjects on x-axis
and number of students who opted for that subject on y-axis.
Complete the code to perform the following operation

(i) to plot the bar graph in statement 1


(ii) to display the graph in statement 2
x = [‘HINDI’, ‘ENGLISH’, ‘SCIENCE’ , ‘SST’]
y=[10,20,30,40]
# statement 1
# statement 2
Ans. (i) plt.bar(x,y)
(ii)plt.show( )

Q.11 How to import matplotlib?


Ans. form matplotlib import pyplot as plt.
Q.12 Which of the following is not a valid chart type?
a. line
b. bar
c. histogram
d. statistical
Ans. d.statistical

Q.13 The command used to show legends is


a. display()
b. show()
c. legend()
d. legends()
Ans. c.legend()

Q.14 The command used to give a heading to a graph is


a. plt.show()
b. plt.plot()
c. plt.xlabel()
d. plt.title()
Ans. d.plt.title()

Q.15 Using Python Matplotlib can be used to count how many values
fall into each interval
a. line plot
b. bar graph
c. histogram
Ans. c. histogram

Q.16 Mr. Harry wants to draw a line chart using a list of elements named LIST. Complete
the code to perform the following operations :
(i) To plot a line chart using the given LIST
(ii) To give a y-axis label to the line chart named sample
number. import matplotlib.pyplot as PLINE
LIST=[10,20,30,40,50,60]
#statement 1

#statement 2
Ans. (i) PLINE.plot(LIST)
(ii) PLINE.ylabel(“Sample number”)
Q.17 In matplotlib, what is ticks?
Ans. A standard graph shows the marks on the axis, in matplotlib library, it is called ticks.

Q.18 What is the use of label in plotting?


Ans. Label is used to add labels or names to respective x and y axis.

Q.19 are specified as consecutive, non overlapping intervals of a variable,


mainly used in histograms.
i) Series
ii) Bins
iii) Gaps
iv) Axis
Ans. ii) Bins

Q.20 Assuming that a line chart is plotted on x and y axis, write the command to give title
as ‘New Graph’ using Plt object

Ans. Plt.title(‘New Graph’)

SA – Short Answer Question (for 3 Marks)

Q.1 Consider the following graph. Write the code to plot it.

Ans.
import matplotlib.pyplot as
plt a = [0,1,2,3,4,5]
b = [10,31,26,24,20]
plt.plot(a,b
) plt.show()
Q.2 Write code to draw the following bar graph representing the number of students in
each class.

Ans.
import matplotlib.pyplot as
plt Classes = ['VII','VIII','IX','X']
Students = [40,45,35,44]
plt.barh(classes,
students) plt.show()

Q. 3 What will be the output of the follwing code ?


From matplotlib import pyplot as plt
X=[4,8,3]
Y=[1,6,9]
plt.plot(X,Y)
plt.title(‘Details)
plt.ylabel(‘Y axis’)
plt.xlabel(‘X axis’)
plt.show( )
Ans.
Q.4 Write the output graph
of : import
matplotlib.pyplot as p
x=[2,3,4,5,6,7]
y=[1,2,3,4,5,6]
p.plot(x,y)
p.show()
Ans.

Q.5 Write code to plot a line graph showing the relation between channel name and its
TRP rating ( 4 channels). Include the titles and formatting of your choice. The font size of
the x and y labels should be 15 and font color should be green

Ans.
import matplotlib.pyplot as p
x=["Sony","Star","SAB","Zee"]
y=[60,40,55,35]
p.plot(x,y, linestyle=":")
p.title('TRP of various channels')
p.xlabel('Name of Channel',fontsize="15",color="green")
p.ylabel('TRP',fontsize="15",color="green")
p.show()
Q.6 Consider the following graph. Write a program in python to draw it along with proper
labeling of X-axis, Y-axis and Title for the line Chart of your choice.

Ans.
import numpy as np
import matplotlib.pyplot as
plt x=np.linspace(-2, 2,50)
y=x*x
plt.plot(x,y)
plt.title('Y = x * x')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.show()

Q.7 Consider the following graph. Write a program in python to draw it. (Height of Bars are
10,1,0,33,6,8)
Ans.
import numpy as np
import matplotlib.pyplot as plt
plt.hist([0,10,20,30,40,50],bins=[0,10,20,30,40,50,60],weights=[10,1,0,3
3,6,8],edgecolor='yellow')
plt.title('Histogram of Student Data')
plt.xlabel('value')
plt.ylabel('Frequency')
plt.show()
Kendriya Vidyalaya Sangthan Mumbai Region

Question Bank for IP

2023-24

1 Mark questions-

S NO Questions Answer

_________ is a one dimensional labeled datatype capable of holding Series


1
any data type in pandas.

2 _______ library is used for 2D plots in Python. Matplotlib

3 How many data structure Pandas provide? 3

4 ______ function is used to add series, elements wise. Add()

5 head() function is used to get the ______ n rows. First

Which argument of bar() lets you set thickness of bar ?

a. thick

6 b. thickness Width

c. width

d. barwidth

7 Which is the standard data missing marker used in Pandas? Nan

Given the following Series S1:

S1

A 10
20
8 B 20
30
C 30

D 40

What will be the output of S1.iloc[1:3]?


Covid-19 Patient analysis in the Mumbai region is to be plotted. The

command used to give title

to x-axis as “No. of Patients” in the graph is ............. .

9 (a) plt.show() D

(b) plt.plot("No. of Patients")

(c) plt.xlabel("No. of Patients")

(d) plt.title("No. of Patients")

The correct statement to read from a CSV file in a dataframe is :

a.<DF>.read_csv(<file>)

10 b. <File>.read_csv(<DF>) A

c.<DF>=pandas.read(<file>)

d. <DF>=pandas.read_csv(<files>)

Given a Pandas Series called Sequences, the command which will


11 Sequences.head(4)
display the first 4 rows is---------------------

The ……………. Function is used to create histogram.

1. plt.show()

12 2. plt.plot() C

3. plt.hist()

4. plt.histt()

Which one of the following is not valid in terms of a DataFrame?

a. It is a part of Pandas

13 b. We can create 2 dimensional structure D

c. User can define index of his choice.

d. We cannot change the index once created


A series object S1 is created with the following details:

I 2

False
J 4
False
14 K 8
True

L 10 True

Write the output of the given commands

a. S1>4

Rakesh wants to plot a bar graph for CITIES and POPULATION

with labeling in x-axis and y-axis respectively. Assume that all

the required libraries have been imported.

15 import matplotlib.pyplot as pl pl.xlabel(“CITIES”)

CITIES = ['Delhi', 'Mumbai', 'Bangalore', 'Hyderabad']

POPULATION = [19000000, 18400000, 8430000, 6810000]

____________________ # write statement for x-axis labeling

In a DataFrame ………… is used to display the given rows


16 Loc
using labeled index values.

____________ method in Pandas can be used to change the integer

index of rows and columns of a Series or Dataframe :

a) rename()
17
b) reindex()

c) reframe()

d) None of the above


Fill in the blanks:

The _____________________function is used to plot line.


18 plt.plot()
1. plt.show() (b) plt.plot()

(c ) plt.xlabel() (d) plt.title()

Given the following Series, S1 and S2.

Write the command to find the difference of series S1 and S2

without using the minus operator.

A 30 A 80

19 S1.sub(S2)
B 70 B 60

C 44 C 94

D 80 D 40

Give the output of the following program:

import numpy as np

arr=np.array([21,22,23,24,25,26,27,28,29,30])
20 print(arr[4:9]) a

a. [25 26 27 28 29] b. [25 29]

c . 25 26 29] d. None of these

21 Write a command to create an empty series. S = pd.Series()


Which of the following is not a valid plotting function of pyplot ?

22 c
1. bar() (b) hist() (c) histh() (d)barh()

23 In a dataFrame, data is represented in ________ dimensional format. 2

In Pandas, _________________library is imported to insert NaN


24 Numpy
values in a DataFrame

Given the following Series S1:

S1

A 10
20
B 20
25 30

C 30 40

D 40

What will be the output of S1.loc[1:3]?

The command used to display graph is _________

1. plt.show()

26 2. plt.title() plt.show()
3. plt.xlabel()

4. plt.plot()
Mohan create a Pandas series with name Marks, he typed command

print(Marks.head())

how many rows will displayed by the above command.

27 1. First row only 5


2. All rows

3. First five rows only

4. No row will display

Given the following Series S1:

S1

A 10

28 B 20 print(S1/2)

C 30

D 40

Write the command to print the half the value of given series.

29 Axes of a graph can be labeled using _____ and ______ functions. xlabel and ylabel
What will be the output of the following code?

import pandas as pd
30 [6,6,6,6,6]
s = pd.Series(6,index=range(0,5))

print(s)

Fill in the blanks with correct library to execute the given code.

import____________________ as plt

import numpy as np
31 matplotlib.pyplot

ypoints = np.array([3, 8, 1, 10, 5, 7])

plt.plot(ypoints)

plt.show()

Rohan wants to print the row labels of the dataframe. He should use
32 index
the _____________ attribute of a dataframe.

What will be the output of the following code?

import pandas as pd

33 1
import numpy as np

s = pd.Series(np.random.randn(4))

print (s.ndim)
The command used to save the figure (graph) is savefig function. It
34 Name of the file
takes one compulsory argument. What does that specify?

35 In a DataFrame, Axis=1 represents the __________elements. Column


2 marks Question
Q.1 Consider the following Series : Subject
INDEX MARK
ENGLISH 75
HINDI 78
MATHS 82
SCIENCE 86
Write a program in Python Pandas to
create a Series.
Ans.
import pandas as pd
subject=pd.Series([75,78,82,86],index=['ENGLISH','HINDI','MATHS',
'SCIENCE'])

Q.2 Consider a given Series, M1 :

Names
Name1 Amit
Name2 Suraj
Name3 Srinidhi

Name1,Name2,Name3 are the indexes.


Write a program in Python to create the series.
Answer
import pandas as pd
M1=pd.Series([‘Amit’,’Surajj’,’Srinidhi’],index=['Name1’,’Name2’,Name3’])

Q.3 Consider the following Series object Samt

Table 350
Chair 200
Sofa 800
Stool 150
(i) Write the command which will display the name of the furniture having rent greater than
250
(ii) Write the command to name the series as Furniture

Ans: (i) S1 = Samt[Samt[>250]]


print(S1.index)

(ii) Samt=Samt.rename( ‘Furniture’)

Q.4 Consider the following DataFrame, Student


Name Age Marks Place
Amit 23 88 Delhi
Binu 43 99 Mumbai
Girish 12 95 Chennai

Write commands to
(a) Add a new column ‘percentage’ to the dataframe with a scalar value.
(b) Add a new row with values of your choice.

Ans: (a) Student[‘percentage’] = [0,0,0]

(b)

Q.5 Write program to create a Series have 10 random numbers in the range of 10 and 20.

Ans:

Q.6 Consider the following Series ‘s’


0 4.0
1 5.0
2 7.0
3 NaN
4 1.0
5 10.0
dtype: float64

(i) Write a Python code to add 1 to all the elements.


(ii) Rewrite the above code to add 1 to all the elements assuming NaN to be value 0.

Q.7 Given here is a


Dataframe of Sales data of
four months stored with
name sales_df.

(i) Write a Python code to find total sales of July month.


(ii) Write a Python code to add the sales of August month with [70,94,80,93] data.
Ans:

Q.8 Consider a given Series: S1:

100 500
101 500
102 500
103 500
104 500

index

Write a program in Python Pandas to create the series S1.

Ans:

Q.9 Consider the following DataFrame STUdf,


ROLLNO NAME CLASS MARKS
Stu1 1 AMAN IX 42
Stu2 2 RAMAN X 37
Stu3 3 SURAJ IX 40
Write python commands to:
a) Add a new row with values (4, Sheetal, X, 41)
b) Add a new column STREAM to the DataFrame with default value ‘COMMERCE’.
Ans:

Q.10 Consider the following Series Object, Ser1:

Pen 50
Pencil 100
Eraser 70
Sharpener 80

i. Write the command which will display the name of the item having price >70.
ii. Write the command to name the series as ITEM.
LONG QUESTION (3-4-5 Marks)
Q.1 Consider the following DataFrame, df

Write commands to :
i. Add a new column ‘Course’ to the Dataframe with values which are any computer science
related field.
ii. Add a new row with values (Sam,456,Chennai,Data Science)
iii. Display the average of TMarks column
Ans:

Q.2 Consider the two objects s1 and s2. s1 is a list whereas s2 is a Series. Both have values 10,
20, 30, 40, 50.
What will be the output of the following two statements considering that the above objects
have been created already
a. print(s1 * 2) b. print(s2 * 2)
Justify your answer
Ans:
Q.3 Consider the following graph . Write the code to plot it.

Ans:

Q.4 Draw the following bar graph representing the Production by Factory.
Q.5

5 Marks

Q.1 Write a program in python Pandas to create the following DataFrame Student from a
Dictionary.

Name Age Marks Place


Amit 23 88 Delhi
Binu 43 99 Mumbai
Girish 12 95 Chennai

(a) Display the Name(s) whose the age > 15


(b) Delete the column ‘place’ permanently.
(c) Display the contents of the dataframe

Ans:
Q.2 Consider the following DataFramen df as shown below :
Col1 Col2 Col3 Res
T1 62.893165 100.0 60.00 True
T2 94.734483 100.0 59.22 True
T3 49.090140 100.0 46.04 False
T4 38.487265 85.4 58.60 False

Create the dataframe.


What will be the output produced by following statements :-
a) print( ndf.loc [ :, ‘Col3’ : ] )
b) print( ndf.iloc[2: , : 3] )
c) print( ndf.iloc [ 1:3 , 2:3 ])

Ans:

Q.3 Write a program in Python Pandas to create the following DataFrame PLAYER from a
Dictionary:

P_NO PName Game1 Game2


1 Srikanth 24 22
2 Sindhu 23 22
3 Sriram 24 24
4 Gopichand 20 20

Perform the following operations on the DataFrame :

(a) Add both gamepoints and assign to column “Overall”


(b) Display the highest score in both Game1 and Game2 of the DataFrame.
Ans:

Q.4 Consider the following Dataframe named housing_df.

area_type location size society total_sqft bath balcony price


Super built- Electronic 2 BHK Coomee 1056 2 1 39.07
up Area City Phase II
Plot Area Chikka 4 Theanmp 2600 5 3 120
Tirupathi Bedroom
Built-up Uttarahalli 3 BHK 1440 2 3 62
Area
Super built- Lingadheeran 3 BHK Soiewre 1521 3 1 95
up Area ahalli
Super built- Kothanur 2 BHK 1200 2 1 51
up Area
Super built- Whitefield 2 BHK DuenaTa 1170 2 1 38
up Area
Super built- Old Airport 4 BHK Jaades 2732 4 204
up Area Road
Super built- Rajaji Nagar 4 BHK Brway G 3300 4 600
up Area

Write a Python program to


(i) Create the above Dataframe from a csv file named housing.csv and display it. Import
necessary libraries. 2
(ii) Display the houses having 2 bathrooms. 1
(iii) Display the price of house in lakhs. Assume the numbers in price column represent
price in lakhs. 1
(iv) Display first 3 rows of the Dataframe 1

Ans:

Q.5 Write a program in Python Pandas to create the following DataFrame stuDF from a
Dictionary of List:

Perform the following operations on


the DataFrame stuDF:
a. Add index as Sec A, Sec B, Sec C & Sec D in place 0,1,2 & 3
b. Print details of student secured marks 98.0

Ans:

Q.6 What will be the output of the following program?


import pandas pd
fst =[9, 10, 11]
scd = pd.Series(fst)
ob1= pd.Series(data= fst* 2)
ob2= pd. Series(data = scd*2)
print("ob1")
print(ob1)
print("ob2")
print(ob2)
print(ob1<0)
Ans:
Q.7 Given a dataframe namely data as shown in adjacent figure(fruit names are row labels).
Write code statement to:

i. List only the columns Color and Price using loc.


ii. List only columns 0 and 2 (column indexes) using iloc
iii. List only rows with labels ‘Apple’ and ‘Pear’ using loc
iv. List only rows 1, 3,4 using iloc.

Q.8 Write a program in Python Pandas to create the DataFrame Stationary from
following data:

Perform the following operations on the DataFrame :


a. Transfer the Dataframe to a csv file named “final.csv”.
b. Add a column discount with value of 5% for all items in the DataFrame at
the Position 1.
c. Display the final Dataframe updated.
Ans:
Q.9 ABC Enterprises is selling its products through three salesmen and keeping the records of
sales done quarterly of each salesman as shown below:

Company is storing the above information in a CSV file “Qtrly_Sales.csv”. Mr. Rohit is a
programmer. Company has given him the responsibility to create the program to visualise
the above data. He wrote Python code but he is facing some difficulties. Help him by giving
the solutions of following situation:
Python code:
import pandas as pd
import ________________ as plt
df=__________("Qtrly_Sales.csv")
df.plot(__________='bar',
color=['red','blue','brown',’green’])
plt.___________('Quarterly Report')
plt.xlabel('Salesman')
plt.ylabel('Sales')
plt._________()
Ans:
Q.10 Sanyukta is the event incharge in a school. One of her students gave her a suggestion to use
Python Pandas and Matplotlib for analysing and visualising the data, respectively. She has
created a Data frame “df” to keep track of the number of First, Second and Third prizes won
by different houses in various events.
Write Python commands to do the following:
a. Display the house names where the number of Second Prizes are in the range of 12 to 20.
b. Considering above DataFrame df which python command use to display all the records
in the reverse order.
c. Considering above DataFrame df which python command use Display the bottom 3
records.
d. What will be the output of the following command.
x=df.columns[:1]
print(x)

Ans:

Q.11 Mr. Pramod was planning to teach about the Olympics in one of his upcoming classes. He
took help from a student of class XII to prepare the data for analysis and visualization. In the
process there are a couple of problems that still need to be resolved. Kindly help them out.
import pandas as pd
import numpy as np
src='DataViz/master/India_at_Olympics_Medal_by_year.csv'
df=pd._________(src) # Statement 1
print(df.head())
print(df.______) # Statement 2

a. Which method should be placed in the blank space in statement 1 to read the data from the
csv file?
b. Which method should be placed in the blank space in statement 2 to display the last five
rows from the data frame?
c. Which statement will be used to save the data of 10 most recent olympics in a new object
df_last10?
d. Mr. Pramod only wants to display the summer olympic data (Row index 0, 2, 4.... represents
summer olympics), What would be an appropriate statement to do that?
e. Mr. Pramod wants to change the index of the Data Frame which should start with 1 instead
of 0. Identify the correct statement to change the index.

Ans:

Q.12 Mr. Sethi wants to write Python code to create the following data frame containing marks of
3 students. However, he is facing some problems. Help him by answering a few questions
below.

a. Write the code to create the dataframe.


b. Which of the following commands will output 2 for the above given DataFrame?
(a) df.size
(b) df.ndim
(c) df.shape
(d) df.index

c. He wants to rename the column M1 to MT1, Write the command should he execute?
d. He wants to obtain the sum of marks for each student as given below. 1 Choose the
correct statement to obtain the same.

e. He wants to modify the value 16 of S2, M3 to 20. Write command to do the same.

Q.13 Write a program in Python Pandas to create the following DataFrame df1 from a dictionary :
Perform the following operations on the DataFrame :-
a) Write command to compute sum of every column of the DataFrame.
b) Write command to compute mean of column Rainfall.
c) Write command to display maximum temperature of cities having rainfall less than 40cm.

Q.14 Write a program in Python Pandas to create the following DataFrame ‘Order’ for an online

shopping app:

(i) Display DataFrame ‘Order’.


(ii) Calculate the Total price of orders along with delivery charges and assign to a new
column Total.
(iii) Display records of those orders which have delivery charges greater than 30.

Ans:

Q.15 Consider the following graph. Write a program in python to draw it. (Height of Bars are
10,1,0,33,6,8) Take care of axis label and title.
Ans:
Dataframe attributes Create Dataframe
axes Return a list representing the axes of the
DataFrame. pandas.DataFrame( data, index, columns, dtype)
columns The column labels of the DataFrame. data : takes various forms like ndarray, series, map, lists, dict, constants and
dtypesReturn the dtypes in the DataFrame. also another DataFrame.
index The index (row labels) of the DataFrame. index : For the row labels,
Iteration over row ndim Return an int representing the number of axes / columns : For column labels
Features of Dataframe array dimensions. dtype : Data type of each column.
# row iteration - 2D structure shape Return a tuple representing the dimensionality of
i mpor t pandas as pd
import pandas as pd - Potentially columns are of different the DataFrame. l =[ [ 1, 10, ' a' ] , [ 2, 20, ' b' ] , [ 3, 30, ' c ' ] ]
dic={"SName":["Radha","Sam","Ameer","Aman"], types size Return an int representing the number of df = pd. Dat aFr ame( l )
"Gender":['F','M','M','M'],"Age":[17,18,20,18]} - Size ? Mutable elements in this object. pr i nt ( df )
df = pd.DataFrame(dic) - Labeled axes (rows and columns) values Return a Numpy representation of the
- Can Perform Arithmetic operations on 0 1 2
print(df) DataFrame.
rows and columns 0 1 10 a
print("Iterate using iterrows:") 1 2 20 b
for i,j in df.iterrows(): 2 3 30 c
print(j)
print("------") import pandas as pd
l=[[1,3,-9],[4,5,6],[7,5,8]]
print("Iterate using iteritems:") Observe the
df = pd.DataFrame(l,index=["r1","r2","r3"],columns=["c1","c2","c3"]) arrengement of
for key,value in df.iteritems(): print(df) row and
print(value) c1 c2 c3 columns
print("Iterate using itertuples:") r1 1 3 -9
for i in df.itertuples(): r2 4 5 6
print(i) r3 7 5 8
Observe the
#Dataframe using dictionary
Iteration over column import pandas as pd
arrengement of
row and
#column iteration dic = {'one':[1,2,3,4],'two':[5,6,7,8],'three':[9,10,11,12]} columns
import pandas as pd df = pd.DataFrame(dic)
dic={"Name":["Radha","Sam","Ameer","Aman"], Pandas print(df)
one two three
"Gender":['F','M','M','M'],"Age":[17,18,20,18]} Dataframe 0 1 5 9
df = pd.DataFrame(dic) 1 2 6 10 As no columns match the
print("Iterate over columns") 2 3 7 11 keys Dataframe is empty.
for i in df.columns: 3 4 8 12 Even if one column matches
print(df[i]) then the Dataframe would
import pandas as pd be created with that column
dic = {'one':[1,2,3,4],'two':[5,6,7,8],'three':[9,10,11,12]} vakues and remaining
df = pd.DataFrame(dic,columns=['c1','c2','c3']) columns NaN
print(df)
Empty DataFrame
Arithmetic Operations Columns: [c1, c2, c3]
Index: []
import pandas as pd
# Dataframe from dictionary using from_dict ( )
import numpy as np import pandas as pd Observe the
arr1 = np.random.randint(1,10,(3,3)) dic = {'one':[1,2,3,4],'two':[5,6,7,8],'three':[9,10,11,12]} effect of
arr2 = np.random.randint(1,10,(3,3)) df = pd.DataFrame.from_dict(dic,orient="index") orientation on
df1 = pd.DataFrame(arr1) print(df) the index and
df2 = pd.DataFrame(arr2) df = pd.DataFrame.from_dict(dic,orient='columns') column.
All the corresponding print(df)
df3 = df1 + df2 elements of both 0 1 2 3
print("The addition is:") dataframes would be one 1 2 3 4
print(df3) taken as two operans for two 5 6 7 8
df3 = df1 - df2 the operations. three 9 10 11 12
print("The subtraction is:") one two three
0 1 5 9
print(df3) 1 2 6 10 Any numpy
df3 = df1 * df2 2 3 7 11 method to create
print("The multiplication is:") 3 4 8 12 array can be
used.
print(df3)
df3 = df1 / df2 # Data frame using numpy array
import pandas as pd
print("The division is:")
import numpy as np
print(df3) a = np.random.randint(0,20,size=(3,3))
df3 = df1 % df2 df = pd.DataFrame(a) If there is NaN value in
print("The modulus is:") print(df) the data the complete
print(df3) 0 1 2 data is considered to
0 18 18 10 be a float.
1 17 4 1
2 13 0 16
Mathematical Operations with NaN values
# Dataframe using Series
import pandas as pd
import pandas as pd s1 = pd.Series([1,2,3,4])
import numpy as np s2 = pd.Series([5,6,7,8])
arr1 = np.random.randint(1,10,(3,4)) s3 = pd.Series([9,10,11,12])
s1 = pd.Series([2,3,5,6]) df = pd.DataFrame([s1,s2,s3]) Write complete
s2 = pd.Series([1,5,8,4]) print(df) path for the text
0 1 2 3 file. Header
df1 = pd.DataFrame(arr1) 0 1 2 3 4 specified the row
df2 = pd.DataFrame([s1,s2]) 1 5 6 7 8 that is to be taken
print("The Dataframe 1 is:") 2 9 10 11 12 as column labels.
print(df1)
print("The Dataframe 2 is:") # Dataframe using Text file
import pandas as pd
print(df2)
df=pd.read_table("data.txt",header=0)
df3 = df1.add(df2 , axis = 0) print(df)
print("The addition along axis = 0 is:")
print(df3) import pandas as pd
df3 = df1.add(df2, axis = 0,fill_value=1) df=pd.read_table("data.txt",header=0)
print(df)
print("The addition along axis = 0 is:") index_col gives
regno roll name
print(df3) 0 1 34 Rajesh the column to be
The Dataframe 1 is: 1 2 42 Suman used as index
0 1 2 3 label.
0 8 7 8 9 import pandas as pd
1 5 1 5 9 df=pd.read_csv("student1.csv",index_col=0)
print(df)
2 6 5 6 8 Name Eng Phy Chem Maths IP
The Dataframe 2 is: Roll No
0 1 2 3 12 Kishore 23 54 36 56 54
0 2 3 5 6 44 Tarun 34 65 45 46 52
1 1 5 8 4
df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
The addition along axis = 0 is: 'mask': ['red', 'purple'],
0 1 2 3 'weapon': ['sai', 'bo staff']})
0 10.0 10.0 13.0 15.0 df.to_csv(index=False)
1 6.0 6.0 13.0 13.0
2 NaN NaN NaN NaN
The addition along axis = 0 is:
0 1 2 3
0 10.0 10.0 13.0 15.0 Head and Tail function
1 6.0 6.0 13.0 13.0
2 7.0 6.0 7.0 9.0 import pandas as pd

df = pd.read_csv("StudentsPerformance.csv")
Selection using dot operator print(df.shape)
#first n rows
# selection using dot operator print(df.head(2))
import pandas as pd #last n rows
df = pd.read_csv("StudentsPerformance.csv",index_col=['Reg No']) print(df.tail(14))
print(df)
print("Selected column values for gender are : ") The columns Note : Default value of n is 5
print(df.gender) having labels i.e. df.tail() will display last 5 rows
with spaces can
not be accessed
Selection using [ ] with dot
operator. Rename Row / Column
# selection using [ ]
import pandas as pd import pandas as pd
df = pd.read_csv("StudentsPerformance.csv",index_col=['Reg No']) import numpy as np
print("Selected column values for reading score are : ") a = np.random.randint(1,10,(4,5))
print(df[['reading score','writing score']]) df = pd.DataFrame(a,columns = ['a','b','c','d','e'],index=['Row1','Row2','Row3','Row4'])
df2 = df.rename(index={'Row1':1,'Row2':2,'Row3':3,'Row4':4} )
print("The new Dataframe is:")
print(df2)
df2 = df.rename(columns={'a':1,'b':2,'c':3,'d':4,'e':5} )
print("The new Dataframe is:")
Selection using loc print(df2)

import pandas as pd
df = pd.read_csv("StudentsPerformance.csv",index_col="Reg No")
print(df)
#print("A selection of row based on label is:\n") Delete Row / Column
#print(df.loc[235 : 575,])
import pandas as pd
#print("A selection of multiple discrete rows based on label is:\n") import numpy as np
#print(df.loc[[231 , 475],]) a = np.random.randint(1,10,(3,5))
Remember : both df=pd.DataFrame(a)
#print("A selection of alternate rows based on label is:\n") the starting and print("The original Dataframe")
#print(df.loc[::2,]) print(df)
ending label is df.drop(0,axis=0,inplace=True)
#print("A selection cross section of a row and column is:\n") included in the print("The Dataframe after deleting 0th row")
#print(df.loc[[231,475],'race/ethnicity']) print(df)
range while using #discrete rows to be deleted.
#print("A selection cross section of a row and column is:\n") loc to make df.drop([0,3],axis=0,inplace = True)
#print(df.loc[[342,377],['race/ethnicity','math score']]) print("The Dataframe after deleting rows")
selection. print(df)
print("Selection using slicing of rows \n")
newdf=df.loc[332:543,'gender':'reading score':2]
print(newdf)

Selection using iloc


import pandas as pd Add a row
df= pd.read_csv("StudentsPerformance.csv",index_col='Reg No')
print(df) import pandas as pd
#print("The 3rd row of Dataframe is:") import numpy as np
#print(df.iloc[3]) a = np.random.randint(1,10,(3,5))
#print("\nThe Parental educational level of 4th row is:") df = pd.DataFrame(a,columns=['a','b','c','d','e'],index = [12,34,56])
#print(df.iloc[4,4]) df.loc[62]=[1,2,3,4,5]
#print("Select multiple rows using list") print(df)
#print(df.iloc[[2,3,8],]) df2 = df.append({'a':1,'b':2,'c':3,'d':4,'e':5},ignore_index = True)
Remember : while
#print("Select multiple columns using list") using range with
#print(df.iloc[:,[3,4,6]])
iloc lower range is
Add Column When values for
#print("Select multiple rows and multiple columns using list") included but
non-existent index are
#print(df.iloc[[2,6,7],[3,4,6,7]]) upper range is import pandas as pd given the new index is
excluded. import numpy as np created. Append also
print("Select multiple rows and multiple columns using slicing")
a = np.random.randint(1,10,(3,5))
print(df.iloc[2:3,1:4])
df = pd.DataFrame(a,columns=['a','b','c','d','e'],index = [12,34,56])
can be used to add a
print(df) row. But if dictionary is
Boolean Selection df['e']=[0,0,0] used the ingnore_index
df['f'] = [10,15,12] = True must be given
import pandas as pd df['g'] = 50
df = print(df)
pd.read_csv("StudentsPerformance.csv",index_col='Reg
No')
print(df['reading score']>80) df.insert(4,column = 'add',value = [-1,-1,-1])
print("Select students whose Reading scores are greater print(df) New column created when
than 80") values are given for a
non-existant column. In
print(df[df['reading score']>80]) column 'g' scalar value
given for all indexes. That
means the complete
#print("Data of Male students") insert ( ) can insert column will have same
#print(df[df['gender']=="male"]) the column in any value i.e. 50. Column thus
created is always the last
position. In the column.
example 4 is the
position and value
is for adding
values.
Line Plot
Basic steps to follow while plotting
- Choose appropriate plot type and then the function import matplotlib.pyplot as pl
- Bar plot : bar( )
- Line plot : plot( )
x = [1,2,3,4,5] #select data as given or as per the graph shown
- Histogram : hist( ) y = [23,41,26,10,31]
- Understand the data. Make a list of x axis data and y asix pl.plot(x,y,'r-',label = "Sales",linewidth = 4) # this label is going to be used in legend
data. If data is given in a Dataframe then select appropriate pl.title("Test Plot",loc="right")
column from dataframe for x axis and y axis. pl.xlabel("X - AXIS") # Give appropriate name
- Give the legend pl.ylabel("Y - AXIS") # Give appropriate name
Introduction to Matplotlib - Give the axis labels pl.legend()
matplotlib.pyplot is a collection of functions for - Give plot title
pl.show() # Import as the graph would be visible
2D plotting.
To install the library
- pip install matplotlib Multiple line plots
To import the library for plotting
import matplotlib.pyplot as pl
- import matplotlib.pyplot as pl import pandas as pd
df = pd.read_csv("temp.csv")
Some of the types of plots
- Line
x = df['year']
- Bar y1 = df['city1']
- Histogram y2 = df['city2']
- Pie
- Box
y3 = df['city3']
pl.plot(x,y1,'b-x',label = "City 1",linewidth = 2)
Data pl.plot(x,y2,'r-x',label = "City 2",linewidth = 2)
Visualisation pl.plot(x,y3,'k-x',label = "City 3",linewidth = 2)
pl.title("City temperature for 26 years",loc="right")
pl.xlabel("Year")
pl.ylabel("Temp in F")
pl.grid()
pl.legend()
pl.show()
Histogram
Bar Plot
import matplotlib.pyplot as pl
import numpy as np import matplotlib.pyplot as pl
x = np.arange(len(df)) x = ['English','Hindi','Maths','Science','SST']
math = [12,23,45,56,57,67,72,83,65,22,87,53,12,90,78,83,45,75,37,28] y = [34,54,41,44,37]
freq,bin,patches = pl.hist(math,bins=10,edgecolor = "black",label = "Math marks") pl.bar(x,y, width =0.8 ,label= "Marks",color="brown",edgecolor="black")
# frequency give the list of number of events in each bin pl.title("Marks of 5 subjects",loc="right")
# bin is the bin size taken for making 10 bins. pl.xlabel("Subject")
# Check the number of bins givenin the exam and accordingly give the bin size. pl.ylabel("Marks")
# patches is the individual rectangle object pl.legend()
pl.title("Performacne of students",loc="right") pl.show()
pl.xlabel("Mark in Maths")
pl.ylabel("Number of students") Multiple Bar Plots
pl.legend()
pl.show() import matplotlib.pyplot as pl
import pandas as pd
df = pd.read_csv("temp.csv")
x = df['year']
y1 = df['city1']
y2 = df['city2']
pl.bar(x,y1,width =0.4,label="City 1",color="yellow",edgecolor="black")
pl.bar(x+0.4,y2,width = 0.4 , label = "City 2",color="red",edgecolor = "black")
# offset the x axis and give same value as width for plotting second bar
pl.title("Temperature of two cities",loc="right")
pl.xlabel("Year")
pl.ylabel("Temp in F")
pl.legend()
pl.show()
QUESTION BANK
INFORMATICS PRACTICES (065 New)
UNIT-II:Database Query using SQL
UNIT-2
DATABASE QUERY USING SQL

Chapter Practice:

Multiple Choice Questions

1. Which Of The Following Is Not An Aggregate Function?


(a)AVG() (b) ADD()
(c) MAX() (d) COUNT()
Ans. (b) There is no aggregate function named ADD() but SUM() isanaggregate functionwhich
performsmathematicalsum of multiple rows having numerical values.
2. Which aggregate function returns the count of all rows in a specified table?
(a)SUM() (b) DISTINCT()
(c) COUNT() (d) None of these
Ans. (c) COUNT() function returns the total number of values or rows of the specified field or
column.
3. In which function, NULL values are excluded from the result returned?
(a)SUM() (b) MAX()
(c) MIN() (d) All of these
Ans. (d) NULL values are excluded from the result returned by all the aggregate functions.
4. The AVG() function in MySQL is an example of
(a)Math function (b) Text function
(c) Date function (d) Aggregate function
Ans. (d) The AVG() function returnsthe average value from a column or multiple-rows.
So, the AVG ( ) function in MySQL is an exampleof aggregate function.
5. Which of the following function count all the values except NULL?
(a)COUNT(*) (b) COUNT(column_name)
(c) COUNT(NOT NULL) (d) COUNT(NULL)
Ans. (a) All aggregate functions exclude NULLvalues while performingtheoperationand
COUNT(*) isanaggregate function.
6. What is themeaningof“GROUP BY” clausein MySQL?
(a)Group data by columnvalues
(b)Group data by rowvalues
(c) Group data by column and row values
(d)None of the mentioned
Ans. (a) ThroughGROUP BY clause wecancreategroupsfrom a column of data in atable.
7. Which clause is similar to “HAVING” clause in MySQL?
(a)SELECT (b) WHERE
(c) FROM (d) None of thementioned
Ans. (b) HAVING clause will act exactly same as WHERE clause.
i.e. filtering the rows based on certain conditions.
8. Which clause is used with an“aggregate functions”?
(b)GROUP BY (b) SELECT
(c) WHERE (d) Both (a) and(c)
Ans. (a) “GROUP BY” is used with an aggregate functions.
9. What is the significance ofthe statement“GROUP BY d.name” in the following MySQL
statement? SELECT name, COUNT (emp_id), emp_no
FROM department GROUP BY name;

(c) Counting of the field “name” on the table “department”


(d) Aggregation of the field “name” of table “department”
(e) Sorting of the field “name”
(f) None of the mentioned
Ans. (b)“GROUP BY” clause is used for aggregation of field. Above statement will find the
aggregation of the field “name” of table “department”.
10. What is the significance of the statement “HAVING COUNT (emp_id)>2” in the
following MySQL statement?
SELECT name, COUNT (emp_id),emp_no FROM department

GROUP BY name HAVING COUNT (emp_id)>2;

(g) Filter out all rows whose total emp_id below 2


(h) Selecting those rows whose total emp_id>2
(i) Both (a) and (b)
(j) None of the mentioned
Ans. (c) “HAVING” clause are worked similar as “WHERE” clause i.e. filtering the rows
based on certain conditions. GROUPBYcommandplacesconditionsinthequeryusing

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
HAVINGclause. So, allthegroupshavingemployeecount greater than 2 will bedisplayed.
11. What is the significance of “ORDER BY” in the following MySQL
statement? SELECT emp_id, fname, lname FROM person

ORDER BY emp_id;

(a) Data of emp_id will be sorted


(b) Data ofemp_id will be sorted in descendingorder
(c) Data ofemp_id will be sorted in ascending order
(d) All of the mentioned
Ans. (c) Sortinginascendingordescendingorderdependson keyword “DESC” and “ASC”. The
default order is ascending.
12. What will be the order of sorting in the following MySQL
statement? SELECT emp_id, emp_name FROM person

ORDER BY emp_id, emp_name;

(a)Sorting {emp_id, emp_name}


(b) Sorting {emp_name, emp_id}
(c) Sorting {emp_id} but notemp_name
(d) None of the mentioned
Ans. (a) In the query, first “emp_id” will be sorted then emp_name with respect to
emp_id.
13. Which of the following is not a valid SQL statement?
(a) SELECT MIN(pub_date) FROM books GROUPBY category HAVING pub_id = 4;
(b) SELECT MIN(pub_date) FROM books WHERE category = 'COOKING';
(c) SELECT COUNT(*) FROM orders WHERE customer#= 1005;
(d) SELECT MAX(COUNT(customer#)) FROM orders GROUP BY customer#;
Ans. (a) HAVING clause is wrongly applied on attribute “pub_id” rather than attribute “category”.
14. If emp_id contain the following set {9, 7, 6, 4, 3, 1, 2}, what will be the output on execution
of the following MySQL statement?
SELECT emp_id

FROM person ORDER BY emp_id;

(a) {1, 2, 3, 4, 6, 7, 9} (b) {2, 1, 4, 3, 7, 9, 6}


(c) {9, 7, 6, 4, 3, 1, 2} (d) Noneofthementioned
Ans. (a) “ORDER BY” clause sort the emp_id in the result set in ascending order and in absence
of keyword ASC or DESC in the ORDER BY clause the default order is ascending.
15. Find odd one out?
(a)GROUP BY (b) DESC (c) ASC (d) ORDER BY
Ans. (a) “ORDER BY”, “DESC”, “ASC” are related to sorting whereas “GROUP BY” is not
related to sorting.

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Case Based MCQs
Direction Read the case and answer the following questions.

16. A School in Delhi uses database management system to store student details. The
school maintains a database 'school_record' under which there are two tables.
Student Table Maintains general details about every student enrolled in school.

StuLibrary TableTostore detailsof issuedbooks. BookID is the unique identification


number issued toeach book. Minimum issue durationof a book is oneday.[CBSE
Question Bank 2021]

Student
Field Type
StuID numeric
StuName varchar(20)
StuAddress varchar(50)
StuFatherNam varchar(20)
e
StuContact numeric
StuAadhar numeric
varchar(5)
StuSection varchar(1)
StuLibrary
Field Type
BookID numbric
StuID numbric
Issued_d Date
ate
Return_d Date
ate

(i) Identify the SQL query which displays the data of StuLibrary table in ascending
order of student ID.
I. SELECT * FROM StuLibrary ORDER BY BookID;
II. SELECT * FROM StuLibrary ORDER BY StuID;
III. SELECT * FROM StuLibrary ORDER BY StuID ASC;
IV. SELECT * FROM StuLibrary ORDER BY StuID DESC;
Choosethecorrectoption,whichdisplaysthe desired data.

(a) Both Iand IV (b) Both Iand II


(c) Both III and IV (d) Both IIand III
Ans. (d) Since the default order of sorting is ASC or ascending, therefore if it is not mentioned
in the query the query will take the default order.
(ii) The primary key for StuLibrary table is/are …….
(a) BookID (b) BookID,StuID
(c) BookID,Issued_date (d) Issued_date
Ans. (a) Because BookID will have unique and NOT NULL values.
(iii) Which of the following SQL query will display datesonwhichnumberofissuedbooks
isgreater than 5?
(a) SELECT Issued_date FROM StuLibrary GROUPBY Issued_date WHERE COUNT(*)>5;
(b) SELECT Issued_date FROM StuLibrary GROUPBY Return_date HAVING COUNT(*)>5;
(c) SELECT Issued_date FROM StuLibrary GROUP BY Issued_date HAVING
COUNT(*)>5;
(d) SELECT Issued_date FROM StuLibrary GROUPBY Return_date WHERE COUNT(*)>5;
Ans. (c) SELECT Issued_date FROM StuLibrary GROUPBY Issued_date HAVING COUNT(*)>5;

17. Table: Book_Information Table: Sales

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Column Name
Book_ID
Book_Title
Price

Column Name
Store_ID
Sales_Date
Sales_Amount

(i) Which SQL statement allows you to find the highest pricefrom
thetable Book_Information?
(a) SELECT Book_ID,Book_Title,MAX(Price) FROM Book_Information;
(b) SELECT MAX(Price) FROMBook_Information;
(c) SELECT MAXIMUM(Price) FROM Book_Information;
(d) SELECT Price FROM Book_Information ORDERBY Price DESC ;
Ans. (b) SELECT MAX(Price) FROM Book_Information;
(ii) WhichSQL statement allows youto find sales amount for each store?
(a) SELECT Store_ID, SUM(Sales_Amount) FROMSales;
(b) SELECT Store_ID, SUM(Sales_Amount) FROM Sales ORDER BY Store_ID;
(c) SELECT Store_ID, SUM(Sales_Amount) FROMSales GROUP BY Store_ID;
(d) SELECT Store_ID, SUM(Sales_Amount) FROMSales HAVING UNIQUE Store_ID;
Ans. (c) SELECT Store_ID, SUM(Sales_Amount) FROMSales GROUP BY Store_ID;
(iii) Which SQL statement lets you to list all storename whose total sales amount is over 5000 ?
(a) SELECT Store_ID, SUM(Sales_Amount) FROMSales GROUP BY Store_ID
HAVING SUM(Sales_Amount) > 5000;
(b) SELECT Store_ID, SUM(Sales_Amount) FROMSales GROUP BY Store_ID HAVING
Sales_Amount >5000;
(c) SELECT Store_ID, SUM(Sales_Amount) FROMSales WHERE SUM(Sales_Amount) > 5000
GROUP BY Store_ID;
(d) SELECT Store_ID, SUM(Sales_Amount) FROMSales WHERE Sales_Amount > 5000
GROUP BYStore_ID;
Ans. (a) SELECT Store_ID, SUM(Sales_Amount) FROMSales GROUP BY Store_ID HAVING
SUM(Sales_Amount) > 5000;
(iv) Which SQL statement lets you find thetotal number of stores in the SALES table?
(a) SELECT COUNT(Store_ID) FROM Sales;
(b) SELECT COUNT(DISTINCT Store_ID) FROM Sales;
(c) SELECT DISTINCT Store_ID FROM Sales;
(d) SELECT COUNT(Store_ID) FROM Sales GROUPBY Store_ID;
Ans. (d) SELECT COUNT(Store_ID) FROM Sales GROUP BY Store_ID;
(v) Which SQL statement allows you to find the total sales amountfor Store_ID 25 and
the totalsales amount for Store_ID 45?
(e) SELECT Store_ID, SUM(Sales_Amount) FROM Sales WHERE Store_ID IN ( 25, 45)
GROUP BY Store_ID;
(f) SELECT Store_ID, SUM(Sales_Amount) FROM Sales GROUP BY Store_ID
HAVING Store_ID IN ( 25, 45);
(g) SELECT Store_ID, SUM(Sales_Amount) FROMSales WHERE Store_ID IN (25,45);
(h) SELECT Store_ID, SUM(Sales_Amount) FROM Sales WHERE Store_ID = 25 AND
Store_ID =45 GROUPBY Store_ID;
Ans. (b) SELECT Store_ID, SUM(Sales_Amount) FROM Sales GROUP BY Store_ID
HAVING Store_ID IN ( 25, 45);

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Subjective Questions

Short Answer Type Questions


1. What are the aggregate functions in SQL?
Ans. Aggregate function is a function where the values of multiple-rows are grouped
together as input on certain criteriatoforma single value ofmore significant
meaning. Some aggregate functions used in SQL are
SUM ( ), AVG( ), MIN(), etc.
2. What is the purpose of GROUP BY clause in MySQL? How is it different from ORDER
BY clause?
Ans. The GROUP BY clause can be used to combine all those records that have identical
value in a particular field or a group of fields. Whereas, ORDER BY clause is used to
displaytherecords either in ascending or descending order based on a particular
field. For ascending order ASC is used and for descending order, DESC is used. The
default order is ascending order.

3. Shanya Khanna is using atable EMPLOYEE. It has the following


columns: Admno, Name, Agg, Stream [column Agg contains Aggregate
marks]

ShewantstodisplayhighestAggobtainedineach Stream.

She wrote the following statement:

SELECT Stream, MAX(Agg) FROM EMPLOYEE;

But she did not get the desired result. Rewrite the abovequerywithnecessarychangestohelp
herget the desired output.

Ans. SELECT Stream, MAX(Agg)

FROM EMPLOYEE

GROUP BY Stream;

4. Whatisthedifferences between HAVINGclause and Group By clause?


Ans
S.No. Having Clause Group By Clause
1. It is used for applying some extra condition to The group by clause is used to group
the query. the data according to particular
column or row.
2. Having can be used without group by clause, in group by can be used without having
aggregate function, in that case it behaves like clause with the select statement.
where clause.
3. The having clause can contain aggregate It cannot contain aggregate functions.
functions.
4. It restrict the query output by using some It groups the output on basis of some
conditions rows or columns.
5. What is the difference between WHERE clause and HAVING clause?

Ans: A HAVING clause is like a WHERE clause, but applies only to groups as a whole (that is, to the
rows in the result set representing groups), whereas the WHERE clause applies to individual
rows. A query can contain both a WHERE clause and a HAVING clause.

6. Gopi Krishna is using a table Employee. It has the following


columns : Code, Name, Salary, Dept_code

Hewantstodisplaymaximumsalarydepartment wise. He wrote the following command :

SELECT Deptcode, Max(Salary) FROM Employee;

But he did not get the desired result.

Rewritetheabovequerywithnecessarychangesto help him get the desired output.

Ans. SELECT Deptcode, Max(Salary) FROM Employee

GROUP BY Deptcode;

7. Writeaquerythatcountsthenumberofdoctors registeringpatientsforeachday.(Ifa
doctorhas morethanonepatient onagivenday, he orshe should be counted only once.)
P_ID ProductName Manufact Price
ure
TP01 TALCOM POWDER LAK 40
FW05 FACE WASH ABC 45
BS01 BATH SOAP ABC 55
SH06 SHAMPOO XYZ 120
FW12 FACE WASH XYZ 95
Ans. SELECT ord_date, COUNT (DISTINCT doctor_code) FROM Patients

GROUP BY ord_date;

8. Consider the table DOCTOR given below. Write commands in SQL for (i) to (ii) and
output for (iii) to (v).
Table : DOCTOR
ID DOCName Department DOJ Gender Salary
1 Amit Kumar Orthopaedics 1993-02-12 M 35000
2 Anita Hans Paediatrics 1998-10-16 F 30000
3 Sunita Maini Gynaecology 1991-08-23 F 40000
4 Joe Thomas Surgery 1994-10-20 M 55000
5 Gurpreet Paediatrics 1999-11-24 F 52000
6 Anandini Oncology 1994-03-16 F 31000
(i) Displaythenamesandsalariesofdoctorsin descending order ofsalaries.
(ii) Displaynamesofeachdepartmentalongwithtotal salary being given to doctorsof
thatdepartment.
(iii) SELECT SUM(Salary) FROM DOCTOR WHERE
Department==‘Surgery’;
(iv) SELECT Department, COUNT(*) FROM DOCTOR GROUP BY
Department;
(v) SELECT DOCName FROM DOCTOR WHERE Department LIKE
‘%gery%’;
Ans. (i) SELECT DOCName, Salary FROM DOCTOR ORDER BY Salary DESC;

(ii) SELECT Department, SUM(Salary) FROM DOCTOR GROUP BY Department;

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
CHAPTER-3
Question
Bank Database
Query using SQL

[1 marks question]
1) The avg( ) function in MySQL is an example of ………………….
(i) Math Function
(ii) Text Function
(iii) Date Function
(iv) Aggregate Function
Ans:- (v) Aggregate Function
2) The Command can be used to make changes in the rows of table in SQL.
Ans:- UPDATE
3) The SQL Command that will display the current time and date.
Ans :- Select now();
4) The mid()function in MySql is an example of .
a. Math function
b. Text function
c. Date Function
d. Aggregate Function

Ans:- b. Text Function


5) The function is used in SQL to find one string into another.
Ans:- Instr( )
6) MID () and SUBSTR () function in SQL serves the same purpose. (Yes/No)
Ans:- Yes
7) Write the output for the following SQL command:
Select round(15.193 , -1);
Ans:- 10
8) Write a SQL query to display date after 10 days of current date on your system.
Ans:- Select curdate()+10;
1 mark for correct SQL command
9) Write the output for the following sql command:
Select SUBSTR(‘ABCDEFG’, -5 ,3)
Ans:- UBS
10) Which keyword is used to arrange the result of order by clause in descending order?
a. DSEC
b. DES
c. DESCE
d. DESNO
Ans:- a. DESC
11) The clause that is used to arrange the result of SQL command into groups

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Order by
a.
Group in
b.
Groups by
c.
Group by
d.
Ans :- d.Group By
12) Find the Output of SQL command :
select concat (concat (‘Inform’, ‘atics’),‘Practices’);

a. Informatics Practices
b. Informatic Practices
c. Inform practices
d. Inform atics practices
Ans :- a. InformaticsPractices
13) Write the output of the following SQL command.
select round (19.88,1);
a. 19.88 b. 19.8 c. 19.9 d. 20.0

Ans:- c. 19.9
14) The now() function in MySql is an example of .
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
Ans:- c. Date Function
15) The command can be used to makes changes in the structure of a table in SQL.
Ans:- ALTER
16) Write the SQL command that will display the time and date at which the command got
executed.
Ans :- Select sysdate();
17) Write the output of the following SQL
command. select round(15.872,1);
a. 15.87
b.15.9
c.15.8
d.16

Ans:- b. 15.9
18)
Manish wants to select all the records from a table named “Students” where the value of
the column “FirstName” ends with an “a”. Which of the following SQL statement willdo
this?

a. SELECT * FROM Students WHERE FirstName = ‘a’;


b. SELECT * FROM Students WHERE FirstName LIKE‘a%’;
c. SELECT * FROM Students WHERE FirstName LIKE ‘%a’;
d. SELECT * FROM Students WHERE FirstName = ‘%a%’;
KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page 2
No- 9
Ans:-
d. SELECT * FROM Students WHERE FirstName = ‘%a%’;

19) The command can be used to add a new column to the table.
Ans:- ALTER
20) Which SQL command is used to describe the structure of the table ?
Ans:- DESC
21) Foreign Key in a table is used to enforce
i) Data dependency
ii) Referential Integrity
iii) Views
iv) Index Locations
Ans:- ii) Referential Integrity
22) A table ‘Student’ contains 5 rows and 4 columns initially. 2 more rows are added and 1
more column is added . What will be the degree and cardinality of the table student
after adding these rows and columns?
i) 7, 5
ii) 5,7
iii) 5,5
iv) None of the above
Ans:- ii) 5,7
23) Insert into student values(1,’ABC’,’10 Hari Nagar’) is a type of which command :
i) DML
ii) DDL
iii) TCL
iv) DCL
Ans:- i) DML
24) What will be the output of - select mid('Pyhton Programming’,3,9);
i) ton Progr
ii) ton Progr
iii) hton Prog
iv) htonProg
Ans:- iii) hton Prog
25) Write the output of the following SQL statement:
SELECT TRUNCATE(15.79,-1) , TRUNCATE(15.79,0), TRUNCATE(15.79,1);

a. 15 15 15.7
b. 10 15.7 15.9
c. 10 15 15.7
d. 10 10 15.9

Ans:- c. 10 15 15.7
26) The COUNT( ) in MySQL is an example of :
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
Ans:- d. Aggregate Funcion
27) …….. which of the following sublanguages of SQL is used to query information from the
database and to insert tuples into, delete tuples from and modify tuples in the database?
KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page
No-
a. DML
b. DDL
c. Query
d. Relational Schema
Ans:- a. DML
28) The ……… clause of SELECT query allows us to select only those rows in the result that
satisfied a specified condition.
a. WHERE
b. FROM
c. HAVING
d. LIKE
Ans:- a. WHERE
29)
Write the output of the following SQL command.
select substr(“COMPUTER”,3,4);
a. MPUT
b. PUTE
c. PU
d. MP
Ans: - a. MPUT
30)
The now() function in MySql is an example of .
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
Ans :- c. Date Function
31) The command is used to make the changes in a table permanent.
Ans:- COMMIT
32) Give SQL command that will display the current month from the date and time.
Ans :- MONTH( )
33) Which of the following keywords will you use in the following query to display all the
records of students whose name start with S?
SELECT * from student where name “S%”

Ans :- LIKE
4) Which of the following is an aggregate function:
a. Upper()
b. Trim()
c. Date()
d. Sum()

Ans:- d. SUM()

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
35) Write the output of the following SQL command:
SELECT left(“Jammu Region”, 5);
a. Region
b. Jammu
c. Jammu Region
d. None of the above.
Ans:- b. Jammu
36)
What will be the output of the following code?

SELECT MOD(14,3);
Ans: 2
37) What will be the result of the following query based on the table given here.

SELECT COUNT(Salary) FROM Instructor;

COUNT(Salary)
Ans:- 5

38) Write the command to delete all the data of the table ‘activity’ retaining only structure.
Ans:- DELETE FROM ACTIVITY;
39) Write the output for the following SQL commands
Select round(15.193 , -1);
Ans:- 10
40) Write a SQL query to display date after 20 days of current date on your system.
Ans:- SELECT CURDATE( ) + 10;
41) Write the output for the following sql command
Select SUBSTR(‘ABCDEFG’, -5 ,3)
Ans:- CDE
42) Which keyword is used to arrange the result of order by clause in descending order?
a. DSEC
b. DES
c. DESC
d. DESNO
Ans: C. DESC
43) Write the output of the following SQL command.

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Select round(14.872,1)
a)14.87
b)14.9

c)14.8
d) 15
Ans:- b) 14.9
44) The command can be used to change the size of column to the
table.
Ans:- ALTER
45) The command can be used to makes changes in the
rows of a table in SQL.
Ans:- Update
46) Write the output of the following SQL command.
select round (49.88);
a. 49.88

b. 49.8
c. 49.0
d. 50
Ans:- d. 50
47) Write the output of the following SQL command.
select round (19.88,1);
a. 19.88 b. 19.8 c. 19.9 d. 20.0

Ans:- c. 19.9
48) Select count(*) from Employee;
The above query will not consider the following:

a) Numeric value b) Text value c) Null value d) Date value


Ans:- c) NULL Value
49) Which of the following is/are not correct aggregate functions in SQL:
a. AVG() b) COUNT() c) TOTAL() d) MAX()

Ans:- c) Total( )
50) The command can be used to make changes in the definition of a table in SQL.
Ans:- ALTER
51) Write the SQL clause used to sort the records of a table.
Ans:- ORDER BY
52) Write the output of the following SQL command.
select round(15.857,-1);
a. 15.8

b. 15.9
c. 15.0

d. 20
Ans:- 20
53) The now()function in MySql is an example of .

a. Math function
b. Text function
c. Date Function
d. Aggregate Function
KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page
No-
Ans:- c. Date Function
54) The command can be used to makes changes in the structure
of a table in SQL.
Ans:- ALTER
55) Write the SQL command that will display the time and date at which the
command got executed.
Ans: SELECT NOW();
56) In SQL NULL value means :
(i) 0 value (ii) 1 value (iii) None value (iv) None of the above
Ans:- iii) None value
57) Find the output of SQL Query:-
SELECT MOD(11, 3);
Ans:- 2
58) The MAX() function in MySql is an example of
.
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
Ans:- d. Aggregate Function
59) Write the output of the following SQL command.
select round(314.82,-1);
a. 314.0 b. 310.0 c. 314.8 d. 300.0
Ans:- d. 300
60) What will be the output of the following SQL command:
SELECT LTRIM(“ RAJKUMAR “);
Ans:- “RAJKUMAR “
(Removes spaces from left side)
61) Write the output of the following SQL command.
select pow(2.37,3.45);
a. 17.62
b. 19.62
c. 18.35
d. 15.82

Ans:- b. 19.62
62) Having clause is used with function.
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
Ans:- Aggregate Function
63) Write the output of the query:

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
select instr('Toolbarbar','bar');
Ans:- 5
64) alter() function in MySql is part of
a. DDL command
b. DML Command
c. TCL command

Ans a. DDL Command


1 mark for the correct answer
65) The command can be used to arrange data in some order in a table in SQL.
Ans:- ORDER BY
66) Write the name of the clause used with SELECT command to search for a specific pattern in
the strings.
Ans:- LIKE

[2 marks question]

1) State any two differences between single row functions and multiple row functions.
OR
What is the difference between the order by and group by clause when used along with the
select statement. Explain with an example.
Ans:- Differences between single row functions and multiple row functions. (i) Single row functions work
on one row only whereas multiple row functions group rows (ii) Single row functions return one
output per row whereas multiple row functions return only one output for a specified group of
rows.

OR The order by clause is used to show the contents of a table/relation in a sorted manner with
respect to the column mentioned after the order by clause. The contents of the column can be
arranged in ascending or descending order.

The group by clause is used to group rows in a given column and then apply an aggregate function
eg max(), min() etc on the entire group. (any other relevant answer)

Single row v/s Multiple row functions 1 mark for each valid point

Group by v/s Order by 1 mark for correct explanation 1 mark for appropriate example
2) Consider the decimal number x with value 8459.2654. Write commands in SQL to: i. round it off
to a whole number ii. round it to 2 places before the decimal.

Ans:- i. select round(8459.2654);


ii. select round(8459.2654,-2);

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
1 mark each for correct answer of part (i) , (ii)
3) Anjali writes the following commands with respect to a table employee having fields, empno,
name, department, commission.
Command1 : Select count(*) from employee;
Command2: Select count(commission) from employee;

She gets the output as 4 for the first command but gets an output 3 for the second command.
Explain the output with justification.
Ans:- This is because the column commission contains a NULL value and the aggregate functions do not
take into account NULL values. Thus Command1 returns the total number of records in the table
whereas Command2 returns the total number of non NULL values in the column commission.
4) Consider the following SQL string: “Preoccupied”

Write commands to display:

a. “occupied” b. “cup”

OR

Considering the same string “Preoccupied” Write SQL commands to display:

a. the position of the substring ‘cup’ in the string “Preoccupied” b. the first 4 letters of the string

Ans:- a. select substr("Preoccupied", 4);


or
select substring("Preoccupied", 4);
or
select mid("Preoccupied",4);
or
select right(("Preoccupied"”, 8);

b. select substr("Preoccupied" ,6,3);


or
select substring("Preoccupied", 6,3);
or
select mid(("Preoccupied" ,6,3);

OR

a. select instr 'Preoccupied' , ‘ 'cup'));


b. select left 'Preoccupied',4);

1 mark for each correct answer of part (a) , (b)


5) What is the difference between the where and Having clause when used along with
the select statement. Explain with an example.
OR

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Explain the difference between Update and Alter command with help of an
example.
Ans Where clause is used to apply condition on individual rows and not supports aggregate function
While Having clause is used to apply condition on groups and it supports aggregate functions.

Eg: SELECT * FROM EMP WHERE SALARY > 50000;

Eg: SELECT * FROM EMP GROUP BY DEPTNO HAVING COUNT(*) > 2;

OR

UPDATE command is a part of DML command and used to update the data of rows of a table.
While ALTER command is a part of DDL command and used to change the structure of a table like
adding column, removing it or modifying the datatype of columns.
Eg: UPDATE EMP SET SALARY = 20000;

ALTER EMP ADD EMP_DOJ DATE;


6) Write the output of following queries:-
i. SELECT SUBSTR('Aakila', -3);
ii. SELECT LEFT(‘Toolbar’, 4);
Ans:- I. ‘ila’
II. ‘Tool’
7) Raghav writes the following commands with respect to a table Flight having
Fields FLCODE, START, DESTINATION, NO_STOPS.
Command1 : Select count(*) from FLIGHT;
Command2: Select count(DESTINATION) from FLIGHT;
He gets the output as 5 for the first command but gets an output 3 for the
second command. Explain the output with justification.

Ans:- This is because the column DESTINATION contains a NULL value and the aggregate functions do not
take into account NULL values. Thus Command1 returns the total number of records in the table
whereas Command2 returns the total number of non NULL values in the column DESTINATION.
8) Write the output for following queries:
i. select MOD(11,4) "Modulus", power(3,2) "Raised";
ii. select CURDATE( )+10;
OR
i. select length('CORONA COVID-19');
ii. select lcase('COMputer Science');

Ans:- i. Modulus Raised

3 9

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
ii. currentdate + 10 days aftward date will come

or

i. 15
ii. ‘computer science’
9) Consider the decimal number x with value 7459.3654. Write commands in SQL
to:
i) round it off to a whole number
ii) round it to 2 places before the decimal.

Ans:- (i) select round(7459.3654, 0)


(ii) select round(7459.3654, -2)

10) Shailly writes the following commands with respect to a table Employee having
fields, empno, name, department, commission.
Command1 : SELECT COUNT(*) FROM EMPLOYEE; Command2 :
SELECT COUNT(COMMISSION) FROM EMPLOYEE;

She gets the output as 7 for the first command but gets an output 5 for the second
command. Explain the output with justification.

Ans:- This is because the column commission contains a NULL value and the aggregate
functions do not take into account NULL values. Thus Command1 returns the total
number of records in the table whereas Command2 returns the total number of non
NULL values in the column commission.

11) Consider the following SQL string: “SELFMOTIVATION”. Write commands to


display:
a. “MOTIVATION”
b. “MOT”

OR

Considering the same string “SELFMOTIVATION”. Write SQL commands to


display:
a. the position of the substring ‘MOTIV’ in the string “SELFMOTIVATION”
b. the last 6 letters of the string
Ans:- a. select substr(“SELFMOTIVATION”, 5)
b. select substr(“SELFMOTIVATION”, 5, 3)

OR

a. select instr(“SELFMOTIVATION”, “MOTIV”)


b. select right(“SELFMOTIVATION”, 6)

(student may use other functions like – substring/ mid/ right .. etc

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
12) State any two differences between Update and alter commands.
OR
What is datatype? What are the main objectives of datatypes?

Ans:- Data types are mean to identify the type of data and its associated functions.
The main objectives of datatypes is to clarify the type of data a variable can store and which
operations can be performed on it.
13) Consider the decimal number n with value 278.6975. Write commands in SQL :
i. That gives output 279
ii. That gives output 280

Ans:- i) select round(278.6975);


(ii) select round(278.6975,-1);
or some other queries that produces same results.
1 mark each for correct answer of part (i) , (ii)
14) (i) Consider a table “Employee” that have fields - empno, name, department, salary.
Based on the above table “Employee”, Manvendra has entered the following SQL command:
SELECT * FROM Employee where Salary = NULL;

But the Query is not executing successfully. What do you suggest to him in order to execute this
query i.e. write the correct query.

(ii) Write a SQL query to display the details of those employees whose Salary column has
some values.

Ans:- (i) select * from Employee where Salary is NULL;


(ii) select * from Employee where Salary is not NULL;

1 mark each for correct answer of part (i) , (ii)


15) Consider the following SQL string: “Master Planner”.
Write commands to display:
a. “Master”
b. “Plan”
OR
Considering the same string “Master Planner”.
Write SQL commands to display:
a. the position of the substring ‘Plan’ in the string “Master Planner”
b. the Last 4 letters of the string

Ans:- a. select substr("Master Planner",1,6);


b. select substr("Master Planner",8,4); or some other queries that produces same results.
1 mark each for correct answer of part (i) , (ii)

OR

a. select instr("Master Planner","Plan");


b. select right("Master Planner",4); or some other queries that produces same results.

1 mark each for correct answer of part (i) , (ii)


16) What are multiple row functions? Give examples

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
OR
What is Group by clause? How can we specify condition with Group by clause? Explain with an
example.
Ans:-
17) Consider the decimal number N with value 87654.9876. Write commands in SQL to:
i. round it off to a whole number
ii. round it to 2 places before the decimal.
Ans:-
18) State any two differences between single row functions and multiple row functions.
OR
What is the difference between the order by and group by clause when used along with the
select statement. Explain with an example.
Ans:- 19. Differences between single row functions and multiple row functions.
(i) Single row functions work on one row only whereas multiple row functions group rows
(ii) Single row functions return one output per row whereas multiple row functions return
only one output for a specified group of rows.
OR
The order by clause is used to show the contents of a table/relation in a sorted manner
with respect to the column mentioned after the order by clause. The contents of the
column can be arranged in ascending or descending order.
The group by clause is used to group rows in a given column and then apply an aggregate
function eg max(), min() etc on the entire group. (any other relevant answer)
Single row v/s Multiple row functions 1 mark for each valid point
Group by v/s Order by 1 mark for correct explanation 1 mark for appropriate example

19) Give the output of :


i) Select round(123.93);
ii) Select round(123.93,1);
Ans:- i) 124
ii) 123.9

20) Consider the following SQL string: “Mental Toughness Helps You
Succeed” Write commands to display following using functions:
a. “Toughness”
b. “Succeed”
OR
Considering the same string: “Mental Toughness Helps You Succeed”
Write SQL commands to display:
a. the position of the substring ‘’Helps’ in the string “Mental Toughness Helps You Succeed”
the first 6 letters of the string
Ans:- i) Select mid(‘Mental Toughness Helps You Succeed’, 8, 9)
ii) Select right(‘Mental Toughness Helps You Succeed’, 7);
OR
i) select instr("Mental Toughness Helps You Succeed",’Helps’);
ii) select left("Mental Toughness Helps You Succeed",6);
1 Mark each for correct function usage

21) Find out the error in the following SQL command and correct the same.
Select * from employee group by dept where sum(salary) > 2000000

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Ans:- Select * from employee group by dept where sum(salary) > 2000000 in this query in place of
WHERE clause HAVING clause to be used.
22) Helps Abhay to Compare Having clause and Order by clause?
Or

Shewani has recently started working in MySQL. Help her in understanding the
difference between where and having clause.
Ans:- Having clause is used in conjunction with group by clause in MySQL. It is used to provide
condition based on grouped data. On the other hand, order by clause is an independent
clause used to arrange records of a table in either ascending or descending order on the
basis of one or more columns
OR
COUNT(*) returns the number of items in a group, including NULL values and duplicates.
COUNT(expression) evaluates expression for each row in a group and returns the number
of non null values
2 marks of correct explanation & for any other relevant answer.
23) Write commands in SQL to:
i. round off value 56789.8790 to nearest thousand’s place.
ii. Display day from date 13-Apr-2020.
Ans:- i. Select ROUND(56789.8790,-3);
ii. Select DAY(‘2020-04-13’) 1 mark each for correct answer.
24) Given Table Course:

Find out the output for given SQL command:


SELECTTID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY
TID HAVING COUNT(*)>1;
Ans:- Ans:
TID COUNT(*) mIN(FEES)
101 2
12000

2 marks for correct output


25) Consider the following SQL strings: S1= “INDIA” S2=”MY” &
S3=”DI” Write commands to display:
a. “MYINDIA”
b. “india”
OR
Considering the same string as
above Write SQL commands to
KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page
No-
display:
a. The position of the string S3 in the string S1.
The first 4 letters of the concatenation of string S1 and S2.
Ans:- a. Select CONCAT(s2,S1);
b. Select LCASE(S1)
OR
a. Select INSTR(S1,S3);
b. Select LEFT(CONCAT(S1,S2));
1 mark each for correct SQL command.
26) What is importance of primary key in a table? How many primary keys can be there for a
table?
OR
Explain working of TRIM( ) function with proper examples.
Ans:- Primary Key : A column of collection of columns to identify a tuple in a relation. It is used

to search / locate row in a relation. There can be only one primary key in a table. 1 mark
for correct definition with proper significance.
1 mark for stating only one primary key in a table.

OR

TRIM () function is used to remove leading and trailing spaces from a string a table. It can
be used as
TRIM(String)
For example;
SELECT TRIM(' bar ');

-> 'bar'
1 mark for stating purpose of the functions 1 mark for correct example.
27)
Consider the following ‘Student’ table.

(i) What will be the most suitable datatype for the grade column and why?
(ii) Write a command to insert Suman’s record with the data as shown in the
table.
Ans:- (i) Gender column datatype char(1) as all the possible values can be accommodated and it
will be space efficient.

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
(ii) INSERT INTO Student (Rollno, Sname, Subject, Marks) VALUES (“003”,
”SUMAN”, “IP”, 75);
1 mark for each correct answer
28) Explain the working of ORDER BY clause of SELECT query with proper example.
Ans:- The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
1 mark for correct explanation. 1 mark for appropriate example
29)
Consider a string “AS YOU know MORE” 2
Write the queries for the following tasks.
(i) Write a command to display “know”.
(ii) Write a command to display number of characters in the string.
OR
Consider a string “You Grow more” stored in a
column str. What will be the output of the following
queries?
(i) SELECT UPPER(str);
(ii) SELECT substr(str,-9,4);
Ans:- (i) select mid(“AS YOU know MORE”,8,4);
(ii) select length(“AS YOU know MORE”);

OR

(i) YOU GROW MORE


(ii) Grow
1 mark for each correct answer

[3 marks question]

1) A relation Vehicles is given below :

Write SQL commands to:


KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page
No-
a. Display the average price of each type of vehicle having quantity more than 20.
b. Count the type of vehicles manufactured by each company.
c. Display the total price of all the types of vehicles.

Ans:- a. select Type, avg(Price) from Vehicle group by Type having Qty>20;
b. select Company, count(distinct Type) from Vehicle group by Company;
c. Select Type, sum(Price* Qty) from Vehicle group by Type;

a. ½ mark for the Select with avg(), ½ mark for the having clause
b. ½ mark for the Select with count() , ½ mark for group by clause
c. ½ mark for the Select with sum() , ½ mark for the group by clause
2) Consider the table Garment and write the query:

i. Display the Minimum price of the Garment.


ii. Count and display the number of GARMENT from each SIZE where number of
GARMENTS are more than 1
iii. Display the sum of price of each color garment
Ans:- i. SELECT MIN(PRICE) FROM GARMENT;
ii. SELECT SIZE,COUNT(*) FROM GARMENT
GROUP BY SIZE
HAVING COUNT(*)>1;
iii. SELECT COLOUR,SUM(PRICE) FROM GARMENT GROUP BY COLOUR;

3) A relation SALESMAN is given below:

SNO SNAME SALARY BONUS DATEOFJOIN AREA


A01 Kushagra Jain 30000 45.25 29-10-2019 Delhi
A02 Prakhar Sharma 50000 25.50 13-03-2018 Ajmer
B03 Trapti Singh 30000 35.00 18-03-2017 Jhansi
B04 Shailly 80000 45.00 31-12-2018 Delhi
C05 Lakshay Lawania 20000 10.25 23-01-1989 Jaipur
C06 Naresh 70000 12.75 15-06-1987 Ajmer
D07 Krishna Singh 50000 27.50 18-03-1999 Jhansi

Write SQL commands to perform the following operations:


i) Count the number of salesman area-wise.
ii) Display the month name for the date of join of salesman of area ‘Ajmer’
iii) Display the total salary paid to all salesman.

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Ans:- (i) select area, count(sname) as “Number of salesman” from Salesman group by area;
(ii) select monthname(dateofjoin) from Salesman where area=’Ajmer’;
(iii) select sum(salary) from Salesman;

4) Consider the given table Faculty :-


Faculty_Id First_name Last_name Hire_date Salary
1102 Sulekha Mishra 12-10-1997 25000
1203 Naveen Vyas 23-12-1994 18000
1404 Rakshit Soni 25-08-2003 32000
1605 Rashmi Malhotra 18-09-2004 21000
1906 Amit Srivastava 05-06-2007 28000
Write SQL commands to :

a. To display details of those faculty members whose First_name ends with ‘t’.
b. Display all records in descending order of Hire_date.
c. Find the maximum and minimum salary.
Ans:- a. Select * from Faculty where First_name like ‘%t’;
b. Select * from Faculty order by Hire_date desc;
c. Select max(Salary), min(Salary) from Faculty;
1 mark for each correct answer
5) Given the table CARDEN having following data:

CCode CarName Company Color Capacity Charges


501 A-Star Suzuki Red 3 14
503 Indigo Tata Silver 3 12
502 Innova Toyota White 7 15
509 Qualis Toyota Silver 4 14
510 Wagon R Suzuki Red 4 35
Write SQL Commands for the following :

a. Display the average charges of each type of car company having capacity more than 3.
b. Count the totalcars manufactured by each company.
c. Display the total charges of all the types of vehicles.
Ans a. select company, avg(charges) from carden group by company having capacity>3;
b. select Company, count(*) from carden group by Company;
c. Select company, sum(charges) from carden group by company;
1 mark each for correct answer
6) TABLE NAME : PHARMADB
KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page
No-

Write SQLcommands to a & b and ouput for c:

a. To display sum of price for each PharmacyName having more than 1 drug.
b. Display pharmacy name in descending order of drug id
c. SELECT PharmacyName, COUNT(*) FROM PharmaDB GROUP BY PHARMACY NAME

Ans:-
a. Select sum(price) from pharmadb group by pharmacyname having count(*)>1;
b. Select PharmacyName from Pharmadb order by DrugID;

a. ½ mark for the Select with sum(), ½ mark for the having clause
b. ½ mark for the Select ,½ mark for the order by
clause 1 marks for correct output.
7) Consider a MySQL table ‘product’

P_ID PROD_NAME PROD_PRICE PROD_QTY


P01 Notebook 85 500
P02 Pencil Box 76 200
P03 Water Bottle 129 50
P04 School Bag 739 70

(i) Display maximum PROD_QTY.

(i) Display the value of each product where the value of each product is
calculated as PROD_PRICE * PROD_QTY
(ii) Display average PROD_PRICE.

Ans:-
(i) SELECT MAX(PROD_QTY) FROM product;
(ii) SELECT PROD_PRICE*PROD_QTY AS ‘Value’ FROMproduct;
(iii) SELECT AVG(PROD_PRICE) FROM

product; 1 mark for each correct query


KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page
No-
[5 marks question]

1) Write the SQL functions which will perform the following operations:
i) To display the name of the month of the current date .
ii) To remove spaces from the beginning and end of a string, “ Panorama “.
iii) To display the name of the day eg, Friday or Sunday from your date of birth, dob.
iv) To display the starting position of your first name(fname) from your whole name (name).
v) To compute the remainder of division between two numbers, n1 and n2

OR

Consider a table SALESMAN with the following data:

Write SQL queries using SQL functions to perform the following operations:
a) Display salesman name and bonus after rounding off to zero decimal places.
b) Display the position of occurrence of the string “ta” in salesman names.
c) Display the four characters from salesman name starting from second character.
d) Display the month name for the date of join of salesman
e) Display the name of the weekday for the date of join of salesman
Ans:- i) monthname(date(now()))
ii) trim(“ Panaroma “)
iii) dayname(date(dob))
iv) instr(name, fname)
v) mod(n1,n2)
1 mark for each correct answer

OR

i) Select sname, round(bonus,0) from Salesman;


ii) Select instr(Sname, “ta”) from Salesman;
iii) Select mid(Sname,2,4) from Salesman; alternative answer
iv) Select Substring(Sname,2,4) from Salesman; iv) Select monthname(DateofJoin) from
Salesman;
v) Select dayname(DateofJoin) from Salesman;
1/2 mark each for correct usage of Select and round()
1/2 mark each for correct usage of Select and instr()
1/2 mark each for correct usage of Select and substr()
1/2 mark each for correct usage of Select and monthname()
1/2 mark each for correct usage of Select and dayname()
KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page
No-
Note : Instead of substr() , substring() may be accepted as correct

2) Consider a table Teacher with the following data:

Write SQL queries using SQL functions to perform the following operations:
a) Convert all the names into lower case.
b) Display the position of occurrence of the string “sh” in Name.
c) Display the four characters from Department starting from second character.
d) Display the month name for the date of admission.
e) Display the name of the weekday for the date of admission.
OR
Write the SQL functions which will perform the following operations:
i) To display the day of month of current date.
ii) To remove spaces from the beginning and end of a string, “ Informatics Practices “.
iii) To display the name of the day eg. Friday or Sunday from your date of birth, dob.
iv) To convert your name into Upper case.
v) To compute the mode of two numbers num1 and num2.

Ans:- i. SELECT LOWER(NAME) FROM TEACHER;


ii. SELECT INSTR(NAME, ‘sh’) FROM TEACHER;
iii. SELECT MID(Department, 2,4) FROM TEACHER;
iv. SELECT MONTHNAME(DateofAdm) FROM TEACHER;
v. SELECT DAYNAME(DateofAdm) FROM TEACHER;

OR

i. SELECT DAYOFMONT(CURDATE());
ii. SELECT TRIM(“ Informatics Practices “;
iii. SELECT DAYNAME(“2015-07-27”);
iv. SELECT UPPER(Name);
v. SELECT MOD(num1,num2);
3) Write the SQL functions which will perform the following operations:

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
i) To display the name of the month of the current date.
ii) To remove spaces from the beginning and end of a string, “ KV Sangathan “.
iii) To display the name of the day eg, Friday or Sunday from your date of birth, dob.
iv) To print the value of square root of 2 upto 2 decimal points.
v) To compute the remainder of division between two numbers, n1 and n2
OR
Write SQL for question from (i) to (iv) and output for SQL queries (v) and (vi), which are based on the
table: KV given below:

(i) Print the details of KVs whose StationCode between 300 and 500
(ii) Print the details of KVs whose name ends with AFS
(iii) Print the details of KVs of Jaipur region
(iv) Print the number of KVs Zone-wise
(v) Select Region, count(KVName) from KV where Zone=’West’ group by Region
(vi) Select * from KV where substr(KVName, 2, 3)=’and’ or StationCode=390;
(i) select month(current_date());
(ii) select trim(“ KV Sangathan “);
Ans:- (iii) select dayname(dob) from student;
(iv) select round(sqrt(2) , 2);
(v) s

;
O

(i) Select * from KV where StationCode between


300 and 500;
(ii) Select * from KV where KVName like ‘%AFS’;
(iii) select * from KV where Region=’Jaipur’;
(iv) select Zone, count(KVName) from KV group by
Zone;
(v)
R
e
g
i
o
n

c
o
u
n
t
(
K
V
N
a
m
e
)
A
h
m
e
d
a
b
a
d

2
Jaipur 3
(vi)
KVCode KVName StationCode Region Zone
1019 Gandhidham IFFCO 11 Ahmedabad West
1020 Gandhidham Railway 11 Ahmedabad West
1702 Uri 390 Jammu North

4) Write the SQL statement for the following:

i) To display names “Mr. James” and “Ms. Smith” in lower case.


ii) ToSANGATHAN
KENDRIYA VIDYALAYA display current date and
RANCHI time.
REGION Page
iii) No-
To remove trailing spaces from string “ Technology Works ”
iv)
To compute the remainder of division between 125 and 17.
OR
Consider the following table Garments. Write SQL commands for the following statements.

Table : Garments
GCode GName Price MCode Launch_Date
10001 Formal Shirt 1250 M001 2008-12-12
10020 Frock 750 M004 2007-09-07
10007 Formal Pant 1450 M001 2008-03-09
10024 Denim Pant 1400 M003 2007-04-07
10090 T-Shirt 800 M002 2009-05-12

To update the Price of Frock to 825.


To print the average price of all the Garments.
To display the Garments Name with their price increased by 15%.
To delete the rows having MCode as M002.
To display the details of all the Garments which have GCode less than 10030.
Ans:- (i) select lower(“Mr. James”), lower(“Ms. Smith”);
(ii) select now();
(iii) select date(“2020-12-21 09:30:37”);
(iv) select rtrim(“ Technology Works ”);
(v) select mod(125,17);
1 mark for each correct answer
OR
a. Update Garments set price=825 where GName=’Frock’;
b. select avg(price) from Garments;
c. select DName, price*1.15 as ‘Increased_Price’ from Garments;
d. delete from Garments where MCode=’M002’;
e. select * from Garments where GCode<10030;
1 mark for each correct answer

5) Write the SQL functions which will perform the following operations:
i) To display the name of the month of your birthdate .
ii) To remove spaces from the beginning of a string, “ Python“.
iii) To display the day of the week eg, Sunday from current date.
iv) To display the starting 3 characters from your name .
v) To compute the power of 2 to the power 3
OR

KENDRIYA VIDYALAYA SANGATHAN RANCHI REGION Page


No-
Consider the table : Shop
Id SName Area Bonus DateofOpen
S001 ABC CP 1000.89 2010-11-20
Computronics
S002 All Infotech GK II 2345.987 2015-09-12
S003 Tech Shoppe CP 761.46 2013-07-25
S004 Geek Tenco Soft Nehru 456.923 2019-10-10
Place
S005 Hitech Solution GK II 1000.025 2008-12-20

a) Display shop name and bonus after rounding off to zero decimal places.
b) Display the position of occurrence of the string “tech” in shop names.
c) Display three characters from shop name starting from second character.
d) Display the month name for the date of opening of shop
e) Display the name of the shop in all capitals.
Ans:- i)select monthname(‘1998-11-20’);
ii)select ltrim(‘ Python’);
iii)select dayname(now());
iv)select left(‘Nitin’,3);
v)Select power(2,3);
1 mark each for correct function
OR
a) Select Sname,round(Bonus,0) from Shop;
b) Select instr(SName,’tech’) from Shop;
c) Select mid(SName,2,3) from Shop;
d) Select monthname(DateOfOpen) from shop;
e) Select Upper(SName) from shop;
1 mark each for the correct query
6) Consider the following data frame of automobile

Write SQL queries using SQL functions to perform the following operations:
a) Display company name and body wheel base after rounding off to nearest ten’s decimalplaces.
b) Display the position of occurrence of the string “dan” in body style.
c) Display the 3 characters from company name starting from second character.
d) Display the year of manufacturing for sedan;

Page
No-
e) Display the name of the weekday for the manufacturing date.
Ans:- a) Select company, round(wheel-base,-1) from automobile;
b) Select instr(body-style,’dan’) from automobile;
c) Select substr(company,2,3) from automobile; /mid(company,2,3)
d) Select year(dateofmanufacture) from automobile where body-style=’sedan’;
e) Select dayname(dateofmanufacture) from automobile;

a) 1/2 mark each for correct usage of Select and round()


b) 1/2 mark each for correct usage of Select and instr()
c) 1/2 mark each for correct usage of Select and substr()
d) 1/2 mark each for correct usage of Select year and where
clause 1/2 mark each
7)
Consider the below mentioned table of ‘CLOTH’
DCODE DESCRIPTION PRICE MCODE LAUNCHDATE
10001 FORMAL SHIRT 1250 M001 12–JAN–08
10020 FROCK 750 M004 09–SEP–07
10012 INFORMAL SHIRT 1450 M002 06–JUN–08
10019 EVENING GOWN 850 M003 06–JUN–08
10090 TULIP SKIRT 850 M002 31–MAR–07
10023 PENCIL SKIRT 1250 M003 19–DEC–08
10089 SLACKS 850 M003 20–OCT–08
Write the commands for the following:

(i) Display first three letters of description e.g. ‘FRO’ for ‘FROCK’
(ii) Display the description after removing leading spaces if any.
(iii) Display number of characters taken by each description.
(iv) Display the number of MCODE in the table.
(v) Display the day of the LAUNCHDATE. Eg. ‘Monday’, ’Tuesday’ etc
OR

(i) Display total price of products launched in year 2008.


(ii) Display minimum price of product for each material code(MCODE).
(iii) Display the most recent LAUNCHDATE.
(iv) Display the description in lower case alphabets.
(v) Display remainder of price divided by 10.
Mind Map of Databases query using SQL

Databases query
using SQL

Text Functions Date functions Aggregate functions


Math functions
Querying
UCASE()/UPPER() MAX() & data
NOW() manipulati
POWER()
ng using
LCASE()/LOWER() MIN() group by
DATE()

AVG()
ROUND()
MID()/SUBSTRING()/ MONTH()
SUBSTR()
SUM()

MOD() MONTHNAME()
LENGTH() COUNT()

YEAR()

COUNT(*)
LEFT() DAYNAME()
RTRIM()
RIGHT() DAY()
LTRIM()

GROUP BY
ORDER BY
TRIM() ,HAVING
INSTR()
MCQ

1) What is an standalone computer system


a. It is a computer system with internet connectivity
b. It is a server
c. It is a computer without any networking
d. None is correct

2) The main computer in any network is called as


a. Client
b. Server
c. Hub
d. Switch
3) What is the full form of NIC
a. Network Interchange Card
b. Net Interconnect Card
c. Network Interface Card
d. Network Interconnection Card
4) Which is called a smart HUB
a. HUB with high speed ports
b. Switch
c. Router
d. All of the Above
5) A network with all client computer and no server is called
a. Networking
b. Peer to Peer Computing
c. Client Server Computing
d. Any of them
6) The wireless access point in the networking is also
An wireless switch
An Wireless Security Point
An Address where all the wifi devices
connect All of the above
7) Generally which topology is used in the backbone of Internet
a. BUS
b. STAR
c. RING
d. Any of them
8) IP Stands for
a. Internet Protocol
b. Intranet Protocol
c. Internet Practice
d. Intranet Practice
9) Which of this is not a part of URL
a. IP Address
b. Port Number
c. Domain Name
d. None of these
10) What is the example of Instant Messenger
a. Yahoo messenger
b. WhatApp messenger
c. iMessenger
d. All of them
11) Which of the following is an browser
a. Chrome
b. Whatsapp
c. Twitter
d. All of them
12) Repeaters work on the __________ layer
a. Network Layer
b. Physical Layer
c. Application Layer
d. All of the Above
13) Which device is used to transfer Communication Signal to Long Directions
a. Amplifier
b. Repeater
c. Router
d. All of the Above
14) Which topology in general uses less wire length compare to other
a. Star Topology
b. Ring Topology
c. Bus Topology
d. All use same Length of Wire
15) The device with smartly controls the flow of data over the network by hoping is
Router
Gateway
Switch
None of them
16) javascript is a ___________ based language
a. interpretor
b. compiler
c. None
17) Which one in a micro blogging software
a. Twitter
b. Facebook
c. Whatsapp
d. All of them
18) Sending the email to any cc means
a. Sending the mail with a carbon copy
b. Sending the mail without a carbon copy
c. Sending the email to all and hiding the address
d. All of the above
19) The backbone of internet is
a. WAN Network
b. Fibre optical networks across long distances like intercontinental or intra
continental
c. Wireless networks
d. All of them

20) Which is the physical address to identify the Machine uniquely in network
a. IP Address
b. MAC Address
c. Computer Name
d. Your Used ID
21) Online textual talk is called
a. Video Conference
b. Text Chat
c. Video Call
d. Audio Call
22) The First Page we generally view when we open the browser is called.
a. Default page
b. First page
c. Home page
d. Landing Page
23) URL stands for
a. Uniform Run Line
b. Uniform Resource Line
c. Uniform Resource Location
d. Uniform Resource Locator

24) What is noise in the voice channel


a. Cable disturbance
b. Cable sort length
c. Loss of Signal Strength
d. Unwanted disturbance with the genuine signal
25) PHP language is used to create
a. Dynamic Website
b. Static Website
c. Both the types of website
d. It is not a programming language
26) HTML language is used to create
a. Accounting Program
b. Static Website
c. Both website and accounting program
d. It is not a programming language

27) Google is a
a. Web service
b. Website
c. Program
d. All of it

28) When the signal from one wire bleeds into another wire , it is called as
a. Radio waves
b. Infrared
c. Laser
d. None of them
29) Communication Media can be of ___________ and _____________ type
a. Twisted pair , Shielded Twisted pair
b. Fiber optics , coaxial
c. Guided , Unguided
d. Wire , Laser
30) To prevent unauthorized access to and / or from the network, a system known as
____________, can be implemented by hardware and / or software
a. Antivirus
b. Firewall
c. Software
d. Hardware

1 MARKS QUESTION

1) What is the need for a network.


2) Write the full form of following :
a. NIC
b. ICT
c. PCB
d. DND
e. STP
f. UTP
g. CAT-6
h. CRT
i. TFT
j. LED
3) Expand WAN and MAN
4) Expand LAN and PAN
5) What is a Node
6) Why in NIC needed in the computer?
7) What is the use of a Server
8) What is the Latency in Bluetooth Headsets
9) What is an Networking Topology
10) How internet is difference from LAN or Networks?
11) To protect the data in the network from unauthorized access what device is used?
12) What is the use of ISP in internet networks?
13) Define the use of IP address
14) Why STAR network is more efficient in network fault tolerance in place of BUS
network.
15) Raju wants to save the password and other setting for the website he will use what
to save it in the computer.
16) Ravi is setting the home page of his browser. He will use ___________ of the
browser to set the set home page.
17) What is the use of modem.
18) Text chatting software used in computer network used which technology to
communicate?
19) What is the use of router?
20) Keeping Password and OTP in proper safty is called as ____________
21) What do you mean by URL
22) What is an absolute URL
23) What is history in the browser ?
24) What is the use of HyperLink.

2 Marks Questions
1) What is the difference between STAR and BUS topologies?
2) www mean internet or not ? Explain with example ?
3) What is the deference between the http and Https: websites
4) What are Plug-in or Add on or Extension
5) Email is our phone uses which protocal
6) Which address is used to uniquely identify the machines in a network
7) What s VoIP? Where is it used ?
8) Which protocol is used to upload files to webserver for creating websites.
9) Please help Amit to understand the parts of Email Address
10) What is difference between a website and an webpage 11) What is a gateway and
why is it used?
12) Router is needed for internet to work? Explain if true or false?
13) When can an HUB be used in place of Switch?
14) How website is not same as web portal?
15) What are the common services provided by any web portal?
16) Google.co.in is a static webpage . The statement is correct or wrong ? Help Raj to
define the correct webpage type ?
17) What browser setting is needed to do when we access any site in public computer
like cyber café?
18) What in a VPN software
19) Why we use a domain name address in place of IP address of the Server to access
any web site?
20) Redirection or Popups in the website are to be checked carefully before forwarding?
Why is this so important?

CASE BASED QUESTIONS (4 Marks)


1) KVS consultants are setting up a secured network for their office campus at Gurgaon.
They are planning to have connectivity between 3 blocks and the head office at
Mumbai. Answer the questions (a) to (d) after going through the block positions in
the campus and other details, which are given below:
Distances between various buildings:
Block A to Block C 120m
Block A to Block B 55m
Block B to Block C 85m
New Delhi Campus to Head office 2060 Km
Number of computers:
Block A 32

Block B 150
Block C 45

Head office 10

a. Suggest the most suitable place to house the server with justification.
b. Suggest a connection medium to connect Gurgaon campus with head office.
c. Suggest the placement of the following devices with justification:
i)Switch ii)Repeater
d. The organization is planning to provide a high speed link with its head office
situated in Mumbai using a wired connection. Which of the following cables
will be most suitable for this job?
i) Optical Fibre ii)Co-axial Cable iii)Ethernet Cable

2) Sarguja University is setting up its new academic block in KP Gaon. The University has
3 new academic block and 1 human resource centre.
The distance between the blocks are given below

Number of computer in the blocks

a. Where can we put the internet gateway server


b. Where can we put switch
c. Where we have to fix repeater
d. Where we can have Hub
3) Zetking industries has set up its new center at Ambikapur for its office and web
based activities. The company compound has 4 buildings as shown in the diagram
below:
Center to center distances between various building is as follows:
harsh building to raj building 50m raj building to fazz

building 60m fazz building to jazz building 25m jazz

building to harsh building 170m harsh building to fazz

building 125m raj building to jazz building 90m

Number of computers in each of the buildings is as follows:


harsh building 15

raj building 150

fazz building 15

jazz building 25

a. Suggest the most suitable place to house the server of this organization with a suitable
reason.
b. Suggest the placement of the following devices with justification.
i)Internet connecting device ii)switch

c. The organization is planning to link its sale counter situated in various parts of the same
city, which type of network out of LAN, MAN or WAN will be formed? Justify your
answer.
d. If there will be connection between all building using mesh topology, suggest where
need to place repeater.

4) “KVS” is planning to setup its new campus at Raipur for its educational activities. The
campus has four(04) UNITS as shown below:
a. Suggest an ideal cable layout for connecting the above UNITs
b. Suggest the most suitable place i.e. UNIT to install the server for KVS
c. Which network device is used to connect the computers in all UNITs
d. Suggest the placement of Repeater in the UNITs of above network.

5) Knowledge All Organization has set up its new center at Kolkata for its office and web
based activities. It has 4 blocks of building as shown in the diagram below
a. Suggest a layout of connections between the blocks
b. Suggest the most suitable place (i.e. block) to house the server of this
organization with a suitable reason
c. Suggest the placement of the following devices with justification
i. Repeater ii. Hub / Switch
d. The organization is planning to link its front office situated in the city in the
hilly region where cable connection is not feasible , suggest an economic way
to connect it with reasonably high speed

6) Ramji Training Educational Institute is setting up its centre in RAIPUR with four
specialized departments for Orthopaedics, Neurology and Paediatrics along with an
administrative office in separate buildings. The physical distances between these
department buildings and the number of computers to be installed in these departments
and administrative office are given as follows. Answer the queries as raised by them in (a) to
(d)

Shortest distances between various locations in metres:


Number of Computers installed at various locations are as follows :

a) Suggest the most suitable location to install the main server of this institution
to get efficient connectivity.
b) Suggest the best cable layout for effective network connectivity of the
building having server with all the other buildings.
c) Suggest the devices to be installed in each of these buildings for connecting
computers installed within the building out of the following : Gateway, switch,
Modem
d) Suggest the topology of the network and network cable for efficiently
connecting each computer installed in each of the buildings out of the following :
Topologies: Bus Topology, Star Topology
Network Cable: Single Pair Telephone Cable, Coaxial Cable, Ethernet Cable.

7) RAJKUMARMedicos Centre has set up its new centre in Bilaspur. It hasfour buildings
as shown in the diagram given below
Distances between various buildings are as follows:

Number of Computers

As a network expert, provide the best possible answer for the following queries:

a. Suggest a cable layout of connections between the buildings


b. Suggest the most suitable place (i.e. buildings) to house the server of this
organization.
c. Suggest the placement of the following device with justification
i. Repeater ii. Hub/Switch
d. Suggest a system (hardware/software) to prevent unauthorized access to or
from the network

ANSWER
1. C 2. B 3. C 4. B 5. B 6. D 7. A 8. A 9. A 10. A
11.A 12.B 13. B 14. C 15. A 16. A 17. A 18. A 19. B 20. B
21.B 22.C 23. D 24. D 25. C 26. B 27. A 28. C 29. C 30. B

1 MARKS QUESTIONS
1. Network is the interconnection between systems for resource sharing like printing
and internet sharing.
2. FULL ABBRIBIATION
NIC:-Network Interface Card
ICT:-Information and Communication Technology
PCB:-Printer Circuit Board
DND:-Do Not Disturb Directory
STP:-Shielded Twisted Pair
UTP:-Un-Shielded Twisted Pair
CAT-6:-Category 6 Cables
CRT:-Cathod Ray Tube
TFT:-Thin Film Transistor
LED:-Light Emmited Diode
3. WAN – WIDE AREA NETWORK / MAN – METROPLITON AREA NETWORK
4. LAN- LOCAL AREA NETWORK / PAN – PERSONAL AREA NETWORK
5. Node is the client computer that is connected to a computer
6. NIC is the card that create an interface between the computer and the internet or
network medium
7. Server is the Computer that serve as the main computer to serve information.
8. Bluetooth Headsets are used to get voice from the source but there is a delay in the
voice and the video played
9. Networking Topology is physical layout of the networking connection to the
computer
10. Internet is the network of networks and LAN is only a single network
11. Firewall is used to save the network from un-authorised access
12. It is the Internet Service Provider for the Clients
13. IP or Internet Protocol Address is the 32 Bit Address Logical Number to be given to
any network for uniquely identifying the Computers
14. Because each node is connected directly to the main server and any fault is highly
localised
15. He will us his cookies in the browser to save the password and details
16. Setting -> default page->home page address
17. Modem is used to connect Digital computer to Analog Line for Digital data Transfer
18. They use IM (Instance Messaging) for Text Chatting other then SMS
19. Router is used to connect all the different networks together. It also forwards and
receives different data packets from different places
20. Password Security Ethics
21. URL (Uniform Resource Locator) is the human understandable format for website
address.
22. An absolute URL is the complete website address with protocal and landing page
details also
23. History is the link to last visited websites in the browser
24. Hyperlink is link to another website or page from the current page
2 MARKS QUESTIONS
1) STAR Topology is topology in which the all the nodes are connected with central
computer. But is Bus topology a single wire runs across the network and all the
nodes are connected to the central bus
2) www is world wide web and it is the protocol to define the website or web
address.e.g.
http://www.google.co.in. This address defines that the website is in the internet.
3) http: is the normal Hyper Text Transfer Protocol but https: is the Secured Hyper Text
Transfer Protocal.
4) The software that are installed with the browser for better performance and utility
are called the Plug-in or Add On
5) Email in our phone uses POP3 protocol to access
6) The MAC address is used to uniquely identify the machine in a network
7) VoIP or Voice Over IP is a protocol used to transmit data
8) FTP or File Transfer Protocol is used to transfer files to the web server for creating
web site
9) Email has used id and the domain name in its complete address
kvs@kvs,gov.in where kvs is used id and kvs,gov.in is domain name
10) Website is the complete software and webpage is just one of the page from the
website like www.ambikapur.kvs.ac.in is website and
https://ambikapur.kvs.ac.in/admin/content?type=school_class_wise_enrolment_po
si is a single web page
11) Gateway is the computer used to connect different networks to one network
12) Router is a dynamic device to connect different networks in real time. Internet
cannot work without routers.
13) Hub is a device that broadcast all the signals so Hub is used in less computers with a
limited speed or bandwidth requirements
14) Website is a single software and web portal is a combination of both online and
offline services given by the webportal . like www.google.co.in is a website and
www.ola.com is aweb portal
15) The most common services provided by the web portal are web hosting and business
website developments.
16) Google is a dynamic website. It connects us directly to the related websites what are
searched. 17) We need to use incognito mode or public mode while accessing
internet in the public place.
18) A VPN software is a software that hides the machine address from the network so
that no one can trace the computer in the network
19) We use Domain name as it is more easy to remember that to remember the IP
Address of the Website.
20) The popups or redirection can be a trap form the hackers to hack your computer so
they needed to check carefully

CASE STUDY (4 MARKS)


1.
a. Block C because of the higest no of computer
b. VPN in Internet or Satellite communication can be use
c. Switch in Block A, B and C. repeater in Block C or Head Office
d. Optical Fiber
2.
a. Internet Gateway in the HR Block
b. Switch in Technology Block and HR Block
c. Between Law Block and HR Block
d. In Law Block and Business Block
3. .
a. Raj Building because of Max Number of Computers
b. Both in Raj Building
c. MAN
d. Jazz Building
4. .
a. BUS Topology
b. ADMIN Unit as Max computer are in the Building
c. Bus / Switch
d. Between Admin and Finance Building

COMPILED BY
VISHANT D KHOBRAGADE
PGT CS
K V VSN, NAGPUR
TYPES OF NETWORK
•LAN
•MAN
•WAN

NETWORK DEVICES
• MODEM
• HUB
• SWITCH
• REPEATER
• ROUTER
• GATEWAY

NETWORK TOPOLOGIES
• STAR
• BUS
• TREE
• MESH

INTRODUCTION TO INTERNET

WWW & ITS APPLICATION


* WEB
* EMAIL
* CHAT
* VOIP

WEBSITES

WEB BROWSERS

PREPARED BY
VISHANT D KHOBRAGADE
PGT CS
K V VSN NAGPUR
CLASS XII
INFORMATICS PRACTICES(065)
UNIT IV SOCIETAL IMPACTS
QUESTION BANK

1 Mark type questions


Q1. Which of the following is not a type of cybercrime?
i. Data theft
ii. Installing antivirus for protection
iii. Forgery
iv. Cyber bullying
Ans. ii. Installing antivirus for protection
Q2. What is an example of e-waste?
i. A ripened mango
ii. Unused old shoes
iii. Unused old computers
iv. Empty cola cans
Ans2. iii. Unused old computers
Q3. ‘O’ in FOSS stands for:
i. Outsource
ii. Open
iii. Original
iv. Outstanding
Ans3. ii. Open
Q4. Legal term to describe the rights of a creator of original creative or artistic work is:

i. Copyright
ii. Copyleft
iii. GPL
iv. FOSS
Ans4. i. Copyright

Q5. __________is the trail of data we leave behind when we visit any website (or use any
online application or portal) to fill-in data or perform any transaction.
i. Offline phishing
ii. Offline footprint
iii. Digital footprint
iv. Digital phishing

Ans5. iii. Digital footprint


Q6. A software company purchases new computers every year and discards the old ones into
the local dumping yard. Write the name of the most appropriate category of waste that the
organisation is creating every year, out of the following options :
(i) Business Waste
(ii) Commercial Waste
(iii) Solid Waste
(iv) E-Waste

Ans. iv. E-waste


Q7. Write names of any two common types of Intellectual Property Rights which are
protected by the law.
Ans. Copyright is a legal term used to describe the rights that creators have over their literary
and artistic works. Works covered by copyright range from books, music, paintings, sculpture
and films, to computer programs, databases, advertisements, maps and technical drawings.
The patent owner makes technical information about the invention publicly available in the
published patent document.
Q8. A research student is expected to write a thesis on a topic. The student browses Internet
for the topic and luckily finds it on the Internet. He copies and submits the entire thesis as his
own research work. Which of the following activities appropriately categorises the act of the
writer ?

(i) Spamming
(ii) Phishing
(iii) Plagiarism
(iv) Trojan
Ans. (iii) Plagiarism

Q9. State whether True or False :


i. A copyright is automatically granted to authors or creators of content. _________
ii. In FOSS source code is usually hidden from the users. _______________
Ans. i. True
ii.False
Q10. I can keep you signed in. I can remember your site preferences. I can give you locally
relevant content. Who am I ?
Ans. Cookies

Q11. Which amongst the following is not an example of browser ?


a. Chrome
b. Firefox
c. Avast
d. Edge
Ans. c. Avast

Q12. A mail or message sent to a large number of people indiscriminately without their
consent is called____________

Ans. spam
Q13. According to a survey, one of the major asian country generates approximately about 2
million tonnes of electronic waste per year. Only 1.5 % of the total e-waste gets recycled.
Suggest a method to manage e-waste .

Ans.
1. Buy environmentally friendly electronics
2. Donate used electronics to social programs
3. Reuse, refurbish electronics Recycling e-waste
Q14. Receiving irrelevant and unwanted emails repeatedly is an example of ______________.
Ans. Spam or spamming
Q15. A _______ protects Literacy and Artistic works such as books, novels, compositions, etc.
from getting copied or utilized without permission.
a) Patient
b) IPR
c) Copyright
d) Trademark
Ans. c) Copyright
Q16. Siddhant received an email from an unknown source claiming he has won a reward of
Rs. Five lakh. He need to click on a link and provides some information to claim award, he is
a victim of :
a) Cyber Bullying
b) Virus attack
c) Trojan Attack
d) Phishing
Ans. d) Phishing
Q17. Anita has installed a strong anti-virus on her laptop. She is sure that now she cannot be
a victim of any cybercrime. Anita is
a) 100% correct in her thinking
b) Correct, if she keep updating her antivirus regularly
c) Correct, till she is using websites hosted from Indian Servers.
d) Not correct, as antivirus protects only from virus.
Ans. b) Correct, if she keep updating her antivirus regularly
Q18. .What is the name of the IT law that India is having in the Indian legislature?
a) India's Technology IT Act 2000
b) India's Digital information technology DIT Act, 2000
c) India's Information Technology IT Act, 2000

d) The technology act, 2008.


Ans. c) India's Information Technology IT Act, 2000
Q19. Which of the following would be a creative work protected by copyright?
a) A list of all Indian President names
b) A Portrait of your family
c) A song you wrote
d) The name of your pet dog
Ans. c) A song you wrote
Q20. Which of the following is a disadvantage of proprietary software?
a) You need to be an expert to edit code.
b) You have to pay for this type of software.
c) It’s licensed.
d) It is launched after proper testing.
Ans. b) You have to pay for this type of software.
Q21. The ________ are the permissions given to use a product or someone's creator by the
copyright holder.

a) Source code
b) License
c) Software authority
d) Digital rights
Ans. b) License

Q22. Any work / information that exist in digital form idea on internet or on an electronic
device, is known as________________ property.

a) Licence property
b) digital property
c) source code property
d) software property
Ans. b) digital property

Q23. OSS stands for


a) Open system security
b) Open system source
c) Open software and security
d) Open source software
Ans. d) Open source software
Q24. Legal term to describe the rights of a creator of original creative or artistic work is called
_____.
a) Copyright
b) Copyleft
c) GPL
d) None of these
Ans. a) Copyright
Q25. What we have to ensures to maintain good health of a computer system?

a) Wipe monitor’s screen often using the regular microfiber soft cloth.
b) Keep it away from direct heat, sunlight and put it in a room with enough ventilation
for air circulation.
c) Do not eat food or drink over the keyboard
d) All of the above
Ans. d) All of the above
Q26. The process of re-selling old electronic goods at lower prices is called ____

a) refurbishing
b) recycle
c) reuse
d) reduce
Ans. a) refurbishing

Q27. ________ is a kind of cyber crime in which attacker blackmails the victim to pay for
getting access to the data.

a) Phishing
b) Identity theft
c) Ransomware
d) None of the above
Ans c) Ransomware

Q28. ______________ is an activity where fake websites or emails that look original or
authentic are presented to the user.
a) Phishing
b) Hacking
c) Spamming
d) Identity theft
Ans a) Phishing
Q29. ____________ is the act of unauthorized access to a computer, computer network or
any digital system.
a) Sign in
b) Hacking
c) Tracking
d) None of the above
Ans. b) Hacking
Q30. Which of the following is cybercrime?
a) Hacking
b) Phishing
c) Spamming
d) All of the above
Ans. d) All of the above
2Marks type Questions
Q1. List any four benefits of e-waste management.

Ans1. The e-waste management:


i. Saves the environment and natural resources
ii. Allows for recovery of precious metals
iii. Protects public health and water quality
iv. Saves landfill space

Q2. Mention any four net etiquettes.


Ans2. Four net etiquettes
i. No copyright violation
ii. Share the expertise with others on the internet
iii. Avoid cyber bullying
iv. Respect other’s privacy and diversity
Q3. What is Open Source Software ? Write the names of any two software which can be
categorized as Open Source.
Ans. Open source software is code that is designed to be publicly accessible—anyone can see,
modify, and distribute the code as they see fit.
Firefox web browser and Linux operating system
Q4. What is cyber bullying? What are the two actions you would take if you feel that you are
a victim of cyber bullying?
Ans. Cyberbullying is bullying with the use of digital technologies. It can take place on social
media, messaging platforms, gaming platforms and mobile phones. It is repeated behaviour,
aimed at scaring, angering or shaming those who are targeted. Examples include:
1. Spreading lies about or posting embarrassing photos or videos of someone on social
media
2. Sending hurtful, abusive or threatening messages, images or videos via messaging
platforms
3. Impersonating someone and sending mean messages to others on their behalf or
through fake accounts.
Two actions you would take if you feel that you are a victim of cyber bullying:

Your parents, a favorite teacher, school administrators, counselors, and even police
officers can help you deal with cyberbullying.

Q5. What is Phishing? Write any two precautions that you would take to avoid being victim
of phishing.
Ans. Phishing:The fraudulent practice of sending emails purporting to be from reputable
companies in order to induce individuals to reveal personal information, such as passwords
and credit card numbers.

Two precautions:
1. Don’t give your information to an unsecured site
2. Change password regularly

3 Marks type answers

Q1. Nadar has recently shifted to a new city and school. She does not know many people in
her new city and school. But all of a sudden, someone is posting negative, demeaning
comments on her social networking profile etc. She is also getting repeated mails from
unknown people. Every time she goes online, she finds someone chasing her online.
i. What is this happening to Nadar?
ii. What immediate action should she take to handle it?
iii. Is there any law in India to handle such issues? Discuss briefly.
Ans.
i. Nadar has become a victim of cyber bullying and cyber stalking.
ii. She must immediately bring it into the notice of her parents and school
authorities. And she must report this cyber crime to local police with the help of
her parents.
iii. Yes. The Information Technology Act, 2000 (also known as ITA-2000, or the IT Act)
is the primary law in India dealing with cybercrime and electronic commerce.
Q2. What do you understand by plagiarism? Why is it a punishable offence? Mention any two
ways to avoid plagiarism.
Ans. Plagiarism is the act of using or stealing someone else’s intellectual work, ideas etc. and
passing it as your own work. In other words, plagiarism is a failure in giving credit to its source.
Plagiarism is a fraud and violation of Intellectual Property Rights. Since IPR holds a legal entity
status, violating its owners right is a legally punishable offence.
Any two ways to avoid plagiarism:
∙ Be original
∙ Cite/acknowledge the source

Q3. What do you mean by Identity theft? Explain with the help of an example.
Ans. Identity theft is the crime of obtaining the personal or financial information of another
person for the sole purpose of assuming that person's name or identity to make transactions
or use it to post inappropriate remarks, comments etc.

Alex likes to do his homework late at night. He uses the Internet a lot and also sends useful
data through email to many of his friends. One Day he forgot to sign out from his email
account. In the morning, his twin brother, Flex started using the computer. He used Flex’s
email account to send inappropriate messages to his contacts.
Q4. What do you understand by Net Ettiquetes? Explain any two such ettiquetes.

Ans. Net Ettiquets refers to the proper manners and behaviour we need to exhibit while being
online. These include :
1. No copyright violation: we should not use copyrighted materials without the permission
of the creator or owner. We should give proper credit to owners/creators of open source
content when using them.

2. Avoid cyber bullying: Avoid any insulting, degrading or intimidating online behaviour like
repeated posting of rumours, giving threats online, posting the victim’s personal information,
or comments aimed to publicly ridicule a victim.

5 Marks type Questions


Q1. Smridh has recently changed his school so he is not aware of the people, but someone is
posting negative, demeaning comments on his social media profile. He is also getting
repeated mails from unknown people. Every time he goes online, he finds someone chasing
him online.
i. Smridh is a victim of …………. :
a. Eavesdropping
b. Stolen identity
c. Phishing

d. Cyber stalking
Answer(d)
ii. The action that Smridh should take :
a. He should ONLY share with his friends
b. He should NOT share with anyone as it can cause serious problem
c. He should immediately report to the police
d. He should bring to the notice of his parents and school authorities.

Answer : (d)
iii. …………………….. is a set of moral principles that governs the behaviour of a group or
individual and regulates the use of computers.
a. Copyright
b. Computer ethics
c. Property rights

d. Privacy law
Answer: (b)
iv. Smridh needs to protect his personal information or data from unintentional and
intentional attacks and disclosure which is termed as ………...
a. Digital right
b. Copyright
c. Privacy

d. Intellectual property
Answer : (c)
v. The act of fraudulently acquiring someone’s personal and private information, such as
online account names, login information and passwords is called as ……………
a. Phishing
b. Fraud
c. Scam

d. Plagiarism
Answer : (a)
Q2. The school offers Wi-Fi to the students of Class XII. For communication, the network
security-staff of the school is having a registered URL "schoolwifi.edu". On 17th September
2017, emails were received by all the students regarding expiry of their passwords.
Instructions were also given renew their password within 24 hours by clicking on particular
URL provided. On the bases of the above case study, answer the questions given below:
i. Specify which type of cybercrime is it.
a) Spamming
b) Phishing
c) Identity Theft
d) Hacking
Answer: (b) Phishing

ii. URL stands for____________


a) Universal Resource Loader
b) Uniform Resource Locator
c) United Research Loader
d) Uniform Resource Loader

Answer: (b) Uniform Resource Locator


iii. Unsolicited commercial email is known as:
a) Malware
b) Virus
c) Spam

d) Spyware
Answer: (c) Spam
iv. WiFi stands for ___________
a) Wireless Internet Frequent Interface
b) Wireless Functioning

c) Wireless Fidelity
d) Wire Free Internet
Answer: c Wireless Fidelity
v. Ideally, what characters should be used in a password to make it strong?
a) Letters and numbers only

b) Mixed Case (Upper and Lower)


c) Special characters
d) All of above
Answer: (d) All of the above
Q3. Sumit has to prepare a project on “Swachh Bharat Shreshth Bharat”. He decides to get
information from the Internet. He downloads three web pages (webpage1, webpage 2,
webpage 3) containing information on the given topic.
1. He read a paragraph on from webpage 1 and rephrased it in his own words. He finally
pasted the rephrased paragraph in his project.
2. He downloaded three images of from webpage 2. He made a collage for his project using
these images.
3. He also downloaded an icon from web page 3 and pasted it on the front page of his project
report.
i. Step1 An Example of __________
a. Plagiarism
b. Paraphrasing

c. copyright infringement
d. Intellectual Property right
Answer:(b) :Paraphrasing
ii. Step 2 An act of __________
a. plagiarism

b. copyright infringement
c. Intellectual Property right
d. Digital Footprints
Answer: (a) Plagiarism
iii. Step 3 An act of _________

a. Plagiarism
b. Paraphrasing
c. copyright infringement
d. Intellectual Property right
Answer: (c) Copyright Infringement

iv. A website is a collection of ___________


a. Web Servers
b. Web pages
c. Browsers
d. Hyperlinks

Answer: (b)
v. The process of getting web pages, images and files from a web server to local computer is
called
a. FTP
b. Uploading
c. Downloading
d. Remote access

Answer: (c) Downloading


CLASS XII
INFORMATICS PRACTICES(065)
UNIT IV SOCIETAL IMPACTS
MASTER CARD
SAMPLE QUESTION PAPER
CLASS XII
INFORMATICS PRACTICES (065)
TIME: 03 HOURS M.M.: 70
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A has 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 02 questions carrying 04 marks each.
7. Section E has 03 questions carrying 05 marks each.
8. All programming questions are to be answered using Python Language only.
SECTION A

1. A ____________is a device that connects the organisation’s network with the 1


outside world of the Internet.
i. Hub
ii. Modem
iii. Gateway
iv. Repeater

2. When e-waste such as electronic circuit boards are burnt for disposal, the 1
elements contained in them create a harmful chemical called ________which
causes skin diseases, allergies and an increased risk of lung cancer.
i. Hydrogen
ii. Beryllium
iii. Chlorine
iv. Oxygen

3. Copyright, Patent and Trademark comes under: 1


i. Intellectual Property Right
ii. Individual Property Right
iii. Industrial Property Right
iv. International Property Right

4. Predict the output of the following query: 1


SELECT MOD (9,0);
i. 0
ii. NULL
iii. NaN
iv. 9
5. Which of the following SQL functions does not belong to the Math functions 1
category?
i. POWER()
ii. ROUND()
iii. LENGTH()
iv. MOD()

6. ________ is not a FOSS tool. 1


i. Libre Office
ii. Mozilla Firefox
iii. Google Chrome
iv. Python

7. CSV stands for: 1


i. Column Separated Value
ii. Class Separated Value
iii. Comma Separated Value
iv. Comma Segregated Value

8. Raj, a Database Administrator, needs to display the average pay of workers 1


from those departments which have more than five employees. He is
experiencing a problem while running the following query:

SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5


GROUP BY DEPT;

Which of the following is a correct query to perform the given task?

i. SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5


GROUP BY DEPT;
ii. SELECT DEPT, AVG(SAL) FROM EMP HAVING COUNT(*) >
5 GROUP BY DEPT;
iii. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT
WHERE COUNT(*) > 5;
iv. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT
HAVING COUNT(*) > 5;

9. Predict the output of the following query: 1


SELECT LCASE (MONTHNAME ('2023-03-05'));
i. May
ii. March
iii. may
iv. march
10. Which of the following command will show the last 3 rows from a Pandas 1
Series named NP?
i. NP.Tail( )
ii. NP.tail(3)
iii. NP.TAIL(3)
iv. All of the above

11. With reference to SQL, identify the invalid data type. 1


i. Date
ii. Integer
iii. Varchar
iv. Month

12. In Python Pandas, while performing mathematical operations on series, index 1


matching is implemented and all missing values are filled in with _____by
default.
i. Null
ii. Blank
iii. NaN
iv. Zero

13. By restricting the server and encrypting the data, a software company's 1
server is unethically accessed in order to obtain sensitive information. The
attacker blackmails the company to pay money for getting access to the data,
and threatens to publish sensitive information unless price is paid. This kind
of attack is known as:
i. Phishing
ii. Identity Theft
iii. Plagiarism
iv. Ransomware

14. In SQL, the equivalent of UCASE() is: 1


i. UPPERCASE ()
ii. CAPITALCASE()
iii. UPPER()
iv. TITLE ()

15. Collection of hyper linked documents available on the internet is known 1


as_______________.
i. Website
ii. Webpage
iii. Web Server
iv. Web Hosting
16. _______________is a non-profit organization that aims to build a publicly 1
accessible global platform where a range of creative and academic work is
shared freely.
i. Creative Cost
ii. Critical Commons
iii. Creative Commons
iv. Creative Common

17. Assertion (A):- MODEM stands for modulator-demodulator. 1


Reasoning (R): - It is a computer hardware device that converts data from a
digital format to analog and vice versa.
i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true and R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True

18. Assertion (A):- To use the Pandas library in a Python program, one must 1
import it.
Reasoning (R): - The only alias name that can be used with the Pandas library
is pd.
i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true and R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True

SECTION B

19. Briefly explain the basic concepts of a web server and web hosting. 2
OR
Rati is doing a course in networking. She is unable to understand the concept of
URL. Help her by explaining it with the help of suitable example.

20. The python code written below has syntactical errors. Rewrite the correct code 2
and underline the corrections made.
Import pandas as pd
df ={"Technology":["Programming","Robotics","3D
Printing"],"Time(in months)":[4,4,3]}
df= Pd.dataframe(df)
Print(df)

21. Consider the given SQL string: 2


“12#All the Best!”
Write suitable SQL queries for the following:
i. Returns the position of the first occurrence of the substring “the” in
the given string.
ii. To extract last five characters from the string.
22. Predict the output of the given Python code: 2
import pandas as pd
list1=[-10,-20,-30]
ser = pd.Series(list1*2)
print(ser)

23. Differentiate between the active digital footprint and passive digital footprints. 2

24. Complete the given Python code to get the required output as: Rajasthan 2
import _________ as pd
di = {'Corbett': 'Uttarakhand', 'Sariska':
'Rajasthan', 'Kanha': 'Madhya Pradesh’,
'Gir':'Gujarat'}
NP = ___________. Series( _____ )
print(NP[ ___________ ])

25. What are aggregate functions in SQL? Name any two. 2

SECTION C

26. Based on the SQL table CAR_SALES, write suitable queries for the following: 3
+--------+-------------------+--------+-------+-------+
| NUMBER | SEGMENT | FUEL | QT1 | QT2 |
+--------+-------------------+--------+-------+-------+
| 1 | Compact HatchBack | Petrol | 56000 | 70000 |
| 2 | Compact HatchBack | Diesel | 34000 | 40000 |
| 3 | MUV | Petrol | 33000 | 35000 |
| 4 | MUV | Diesel | 14000 | 15000 |
| 5 | SUV | Petrol | 27000 | 54000 |
| 6 | SUV | Diesel | 18000 | 30000 |
| 7 | Sedan | Petrol | 8000 | 10000 |
| 8 | Sedan | Diesel | 1000 | 5000 |
+--------+-------------------+--------+-------+-------+
i. Display fuel wise average sales in the first quarter.
ii. Display segment wise highest sales in the second quarter.
iii. Display the records in the descending order of sales in the second
quarter.
OR
Predict the output of the following queries based on the table CAR_SALES
given above:
i. SELECT LEFT(SEGMENT,2) FROM CAR_SALES WHERE FUEL=
"PETROL";
ii.SELECT (QT2-QT1)/2 "AVG SALE" FROM CAR_SALES WHERE
SEGMENT= "SUV";
iii. SELECT SUM(QT1) "TOT SALE" FROM CAR_SALES WHERE
FUEL= "DIESEL";
27. Create a DataFrame in Python from the given list: 3
[[‘Divya’,’HR’,95000],[‘Mamta’,’Marketing’,97000],[‘Payal’,’IT’,980000],
[‘Deepak’,’Sales’,79000]]
Also give appropriate column headings as shown below:

28. Write MySQL statements for the following: 3


i. To create a database named FOOD.
ii. To create a table named Nutrients based on the following specification:
Column Name Data Type Constraints
Food_Item Varchar(20) Primary Key
Calorie Integer

29. Richa, recently started using her social media account. Within a few days, she 3
befriends many people she knows and some that she does not know. After
some time, she starts getting negative comments on her posts. She also finds
that her pictures are being shared online without her permission.
Based on the given information, answer the questions given below.
i. Identify the type of cybercrime she is a victim of.
ii. Under which act, she can lodge a complaint to the relevant authorities?
iii. Suggest her any two precautionary measures which she should take in
future while being online to avoid any such situations.
OR
Mention any three health hazards associated with inappropriate and excessive
use of gadgets.

30. Consider the given DataFrame ‘Genre’: 3


Type Code
0 Fiction F
1 Non Fiction NF
2 Drama D
3 Poetry P

Write suitable Python statements for the following:


i. Add a column called Num_Copies with the following data:
[300,290,450,760].
ii. Add a new genre of type ‘Folk Tale' having code as “FT” and 600
number of copies.
iii. Rename the column ‘Code’ to ‘Book_Code’.
SECTION D

31. Preeti manages database in a blockchain start-up. For business purposes, she 4
created a table named BLOCKCHAIN. Assist her by writing the following
queries:
TABLE: BLOCKCHAIN

i. Write a query to display the year of oldest transaction.


ii. Write a query to display the month of most recent transaction.
iii. Write a query to display all the transactions done in the month of May.
iv. Write a query to count total number of transactions in the year 2022.

32. Ekam, a Data Analyst with a multinational brand has designed the DataFrame 4
df that contains the four quarter’s sales data of different stores as shown below:
Store Qtr1 Qtr2 Qtr3 Qtr4
0 Store1 300 240 450 230
1 Store2 350 340 403 210
2 Store3 250 180 145 160
Answer the following questions:
i. Predict the output of the following python statement:
a. print(df.size)
b. print(df[1:3])
ii. Delete the last row from the DataFrame.
iii. Write Python statement to add a new column Total_Sales which is the
addition of all the 4 quarter sales.
OR
(Option for part iii only)
Write Python statement to export the DataFrame to a CSV file named data.csv
stored at D: drive.

SECTION E

33. Write suitable SQL queries for the following: 5


i. To calculate the exponent for 3 raised to the power of 4.
ii. To display current date and time.
iii. To round off the value -34.4567 to 2 decimal place.
iv. To remove all the probable leading and trailing spaces from the
column userid of the table named user.
v. To display the length of the string ‘FIFA World Cup’.
OR
Kabir has created following table named exam:
+-------+---------+------------------+-------+
| RegNo | Name | Subject | Marks |
+-------+---------+------------------+-------+
| 1 | Sanya | Computer Science | 98 |
| 2 | Sanchay | IP | 100 |
| 3 | Vinesh | CS | 90 |
| 4 | Sneha | IP | 99 |
| 5 | Akshita | IP | 100 |
+-------+---------+------------------+-------+
Help him in writing SQL queries to the perform the following task:
i. Insert a new record in the table having following values:
[6,'Khushi','CS',85]
ii. To change the value “IP” to “Informatics Practices” in subject
column.
iii. To remove the records of those students whose marks are less than
30 .
iv. To add a new column Grade of suitable datatype.
v. To display records of “Informatics Practices” subject.

34. XYZ Media house campus is in Delhi and has 4 blocks named Z1, Z2, Z3 and 5
Z4. The tables given below show the distance between different blocks and the
number of computers in each block.
The company is planning to form a network by joining these blocks.
i. Out of the four blocks on campus, suggest the location of the server that
will provide the best connectivity. Explain your response.
ii. For very fast and efficient connections between various blocks within the
campus, suggest a suitable topology and draw the same.
iii. Suggest the placement of the following devices with justification
(a) Repeater
(b) Hub/Switch
iv. VoIP technology is to be used which allows one to make voice calls
using a broadband internet connection. Expand the term VoIP.
v. The XYZ Media House intends to link its Mumbai and Delhi centers.
Out of LAN, MAN, or WAN, what kind of network will be created?
Justify your answer.

35. The heights of 10 students of eighth grade are given below: 5

Height_cms=[145,141,142,142,143,144,141,140,143,144]

Write suitable Python code to generate a histogram based on the given data,
along with an appropriate chart title and both axis labels.
Also give suitable python statement to save this chart.
OR
Write suitable Python code to create 'Favourite Hobby' Bar Chart as
shown below:

Also give suitable python statement to save this chart.


MARKING SCHEME
SAMPLE QUESTION PAPER
CLASS XII
INFORMATICS PRACTICES (065)
TIME: 03 HOURS M.M.: 70
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A has 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 02 questions carrying 04 marks each.
7. Section E has 03 questions carrying 05 marks each.
8. All programming questions are to be answered using Python Language only.
SECTION A

1. iii. Gateway 1
(1 mark for correct answer)

2. ii. Beryllium 1
(1 mark for correct answer)

3. i. Intellectual Property Right 1


(1 mark for correct answer)

4. iv. NULL 1
(1 mark for correct answer)

5. iii. LENGTH () 1
(1 mark for correct answer)

6. iii. Google Chrome 1


(1 mark for correct answer)

7. iii. Comma Separated Value 1


(1 mark for correct answer)

8. iv. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING 1


COUNT(*) > 5;
(1 mark for correct answer)

9. iv. march 1
(1 mark for correct answer)

10. ii. NP.tail(3) 1


(1 mark for correct answer)
11. iv. Month 1
(1 mark for correct answer)

12. iii. NaN 1


(1 mark for correct answer)

13. iv. Ransomware 1


(1 mark for correct answer)

14. iii. UPPER( ) 1


(1 mark for correct answer)

15. i. Website 1
(1 mark for correct answer)

16. iii. Creative Commons 1


(1 mark for correct answer)

17. i. Both A and R are true and R is the correct explanation for A 1
(1 mark for correct answer)

18. iii. A is True but R is False 1


(1 mark for correct answer)

SECTION B

19. Web server: A web server is used to store and deliver the contents of a website 2
to clients such as a browser that request it. A web server can be software or
hardware.
Web hosting: It is a service that allows to put a website or a web page onto
the Internet, and make it a part of the World Wide Web.
(1 mark each for each correct explanation)
OR
URL: It stands for Uniform Resource Locator. It provides the location and
mechanism (protocol) to access the resources over the internet.

URL is sometimes also called a web address. It not only contains the domain
name, but other information as well that completes a web address.

Examples:
https://www.cbse.nic.in, https://www.mhrd.gov.in, http://www.ncert.nic.in,
http://www.airindia.in, etc.
(1 mark for correct explanation)
(1 mark for correct example)
20. import pandas as pd 2
df ={"Technology":["Programming","Robotics","3D
Printing"],"Time(in months)":[4,4,3]}
df= pd.DataFrame(df)
print(df)
(1/2 mark for each correction)

21. i. SELECT INSTR("12#All the Best!","the"); 2


ii. SELECT RIGHT("12#All the Best!",5);
(1 mark for each correct query)

22. 0 -10 2
1 -20
2 -30
3 -10
4 -20
5 -30
(2 marks for correct output)

23. Active Digital Footprints: Active digital footprints include data that we 2
intentionally submit online. This would include emails we write, or responses or
posts we make on different websites or mobile Apps, etc.
Passive Digital Footprints: The digital data trail we leave online
unintentionally is called passive digital footprints. This includes the data
generated when we visit a website, use a mobile App, browse Internet, etc.
(2 marks for correct differentiation)

24. import pandas as pd 2


di = {'Corbett': 'Uttarakhand', 'Sariska':'Rajasthan', 'Kanha': 'Madhya
Pradesh','Gir':'Gujarat'}
NP = pd.Series( di)
print(NP[ 'Sariska'])
(1/2 mark for each correct fill-up)

25. Aggregate functions: These are also called multiple row functions. These 2
functions work on a set of records as a whole, and return a single value for each
column of the records on which the function is applied.

Max(), Min(), Avg(), Sum(), Count() and Count(*) are few examples of multiple
row functions.
(1 mark for correct explanation)
(½ mark each for two correct names)
SECTION C
26. i. SELECT FUEL, AVG(QT1) FROM CAR_SALES GROUP BY FUEL; 3
ii. SELECT SEGMENT, MAX(QT2) FROM CAR_SALES GROUP BY
SEGMENT;
iii. SELECT * FROM CAR_SALES ORDER BY QT2 DESC;
(1 mark for each correct query)
OR
i.
+-----------------+
| LEFT(SEGMENT,2) |
+-----------------+
| Co |
| MU |
| SU |
| Se |
+-----------------+
ii.
+------------+
| AVG SALE |
+------------+
| 13500.0000 |
| 6000.0000 |
+------------+
iii.
+----------+
| TOT SALE |
+----------+
| 67000 |
+----------+
(1 mark each correct output)

27. import pandas as pd #Statement 1 3


df=[["Divya","HR",95000],["Mamta","Marketing",97000
],["Payal","IT",980000], ["Deepak","Sales",79000]]
#Statement 2
df=pd.DataFrame(df,columns=["Name","Department",
"Salary"])#Statement 3
print(df) #Statement 4
(#Statement 1 & 4 – ½ mark each)
(#Statement 2 & 3 – 1 mark each)
28. i. CREATE DATABASE FOOD; 3
(1 mark for correct answer)
ii. CREATE TABLE NUTRIENTS(NAME VARCHAR(20) PRIMARY
KEY,CALORIES INTEGER);

(½ mark for CREATE TABLE NUTRIENTS


½ mark each for correctly specifying each column
½ mark for correctly specifying primary key)

29. i. She is a victim of Cyber Bullying. 3


ii. Information Technology Act, 2000 (also known as IT Act).
iii. a. Need to be careful while befriending unknown people on the
internet.
b. Never share personal credentials like username and password with
others.
(1 mark for each correct answer)
OR
Simran needs to be made aware of the following consequences:
i) Eye strain ii) Painful muscles and joints iii) Poor memory
iv) Lack of sleep v) Back pain and neck pain
(1 mark each for writing any 3 correct health hazards)

30. i. Genre["Num_Copies"]=[300,290,450,760] 3
ii. Genre.loc[4]=["Folk Tale","FT",600]
iii.Genre=Genre.rename({"Code":"Book_Code"},
axis=1)
OR
Genre=Genre.rename({"Code":"Book_Code"},
axis="columns")
(1 mark for each correct statement)

SECTION D

31. i. SELECT YEAR(MIN(TRANSACTION_DATE)) FROM 4


BLOCKCHAIN;
ii. SELECT MONTH(MAX(TRANSACTION_DATE)) FROM
BLOCKCHAIN;
iii. SELECT * FROM BLOCKCHAIN WHERE MONTHNAME
(TRANSACTION_DATE)='MAY';
iv. SELECT COUNT(ID) FROM BLOCKCHAIN WHERE
YEAR(TRANSACTION_DATE)=2022;
(1 mark for each correct query)
32. i. a. 15 4
b. Store Qtr1 Qtr2 Qtr3 Qtr4
1 Store2 350 340 403 210
2 Store3 250 180 145 160
( ½ mark for each correct output/statement)
ii. df=df.drop(2)
OR
df.drop(2,axis=0)
(1 mark for correct statement)
iii.
df["total"]=df["Qtr1"]+df["Qtr2"]+df["Qtr3"]+df["Qtr
4"]
OR
df.to_csv(“D:\data.csv”)
(2 mark for correct statement)

SECTION E

33. i. SELECT POWER(3,4); 5


ii. SELECT NOW();
iii.SELECT ROUND(-34.4567,2);
iv. SELECT TRIM(USERID) FROM USER;
v. SELECT LENGTH("FIFA World Cup");
(1 mark for each correct query)
OR
Ans:
i. INSERT INTO EXAM VALUES(6,'Khushi','CS',85);
ii. UPDATE EXAM SET subject= "Informatics
Practices" where subject = "IP";
iii. DELETE FROM EXAM WHERE marks<30;
iv. ALTER TABLE EXAM ADD COLUMN grade varchar(2);
v. Select * from exam where subject="Informatics
Practices";
(1 mark for each correct query)

34. i. Z2 as it has maximum number of computers. 5


ii. For very fast and efficient connections between various blocks within
the campus suitable topology: Star Topology
iii. Repeater: To be placed between Block Z2 to Z4 as distance between
them is more than 100 metres.
Hub/Switch: To be placed in each block as each block has many
computers that needs to be included to form a network.
iv. Voice Over Internet Protocol
v. WAN as distance between Delhi and Mumbai is more than 40kms.
(1 mark for each correct answer)

35. import matplotlib.pyplot as plt #Statement 1 5


Height_cms=[145,141,142,142,143,143,141,140,143,144]
#Statement 2
plt.hist(Height_cms) #Statement 3
plt.title("Height Chart") #Statement 4
plt.xlabel("Height in cms") #Statement 5
plt.ylabel("Number of people") #Statement 6
plt.show() #Statement 7
(½ mark each for each correct statement 1,2,4,5,6,7)
(1 mark for correct statement 3)

plt.savefig("heights.jpg")

(1 mark for the correct statement)


OR
import matplotlib.pyplot as plt #Statement 1
hobby = ('Dance', 'Music', 'Painting', 'Playing
Sports') #Statement 2
users = [300,400,100,500] #Statement 3
plt.bar(hobby, users) #Statement 4
plt.title("Favourite Hobby") #Statement 5
plt.ylabel("Number of people") #Statement 6
plt.xlabel("Hobbies") #Statement 7
plt.show() #Statement 8
(½ mark for each correct statement)
plt.savefig("hobbies.jpg")
(1 mark for the correct statement)
Subject: Informatics Practices Class XII
Max Marks: 70 Time: 3 Hours

General Instructions:
This question paper contains five sections, Section A to E.
All questions are compulsory.
Section A have 18 questions carrying 01 mark each.
Section B has 07 Very Short Answer type questions carrying 02 marks each.
Section C has 05 Short Answer type questions carrying 03 marks each.
Section D has 03 Long Answer type questions carrying 05 marks each.
Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against
part c only.
All programming questions are to be answered using Python Language
only.

PART A
1. Fill in the blanks :
The command used to show legends is
a. display()
b. show()
c. legend()
d. legends()
2. Write the output of the following SQL command.
select round(15.857,-1);
a. 15.8
b. 15.9
c. 15.0
d. 20
3. Given a Pandas series called Sample, the command which will display the
last 3 rows is .
a. print(Sample.tail(3))
b. print(Sample.Tail(3))
c. print(Sample.tails(3)
d. print(Sample.Tails(3))
4. Which of the following is not a valid chart type?
a. Lineplot
b. Bargraph
c. Histogram
d. Statistical
5 Which amongst the following is the first page we normally view on a Website?
a. Home Page
b. Master Page
c. First Page
d. Banner Page
6. The now()function in MySql is an example of .
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
7. A website store the browsing activity through __________
a. chat
b. cookies
c. scam
d. antivirus
8. Gaining unauthorized access to a network or computer with malicious
intensions is an example of ________
a. Hacking
b. Evasdropping
c. Snooping
d. Bullying
9. The command that will display the time and date at which the
command got executed.
a. DateTime()
b. sysdate()
c. systemdate()
d. timenow()
10. Consider name of table is employee(empid, firstname, lastname, doj, department,
salary)
What should be sql query to get average salary of employee department wise.
a. select avg(salary) from employee order by department;
b. select average(salary) from employee group by department;
c. select avg(salary) from employee group by department;
d. None of above

11. In a network HTTP resource are located by:


a. Uniform Resource Identifier
b. Uniform Resource Log
c. Unique Resource Locator
d. Uniform Resource Locator
12. Identify single row functions from the following:
a. count
b. sum
c. mod
d. having
13. Online posting of rumours, giving threats online, posting the victim’s personal
information, comments aimed to publicly ridicule a victim is termed as
a) Cyber Bullying
b) Cyber Crime
c) Cyber Insult
d) All of the Above
14. Which out of the following, will you use to have an audio-visual chat with an expert
sitting in a far away place to fix uo a technical issue?
a. VoIP
b. Email
c. Htp
d. FTP
15. The mid() function in MySql is an example of .
a. Math function
b. Text function
c. Date Function
d. Aggregate Function
16. Write the output of the following SQL command.
select round(15.872,1);

a. 15.87
b. 15.9
c. 15.8
d. 16
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true and R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True
17 Assertion (A): - To make a Histogram with Matplotlib, we can use the plt.hist()
function.
Reason (R) :- The bin parameter is compulsory to create histogram.
18 Assertion (A): Someone has created a fake social media profile in the name of Saket.
Saket is a victim of cyberstalking.
Reason (R): Cyberstalking is a form of cybercrime.
Reason (R) :-
SECTION B
19 Mr. Amit Mishra is using his internet connection for checking the online account 2
of the company's admin without his knowledge. What do we call this type of
activity? What are the ways by which we can avoid such type of
activities?
20 Mr. Sharma writes the following commands with respect to a table 2
department having fields, deptno, dept_name, head_of_department,
manager.
Command1 : Select count(*) from department;
Command2: Select count(manager) from department;
He gets the output as 8 for the first command but gets an
output 6 for the second command. Explain the output
with justification.
21 What is the difference between the where and having clause when used 2
along with the select statement? Explain with an example.
22 Consider a given Series, Subject:
INDEX MARKS
ENGLISH 75
HINDI 78
MATHS 82
SCIENCE 86

Write a program in Python Pandas to create this series.


23 2
Expand the following terms related to Computer Networks:

a. PPP
b. HTTPS

c. VoIP

d. PAN
24 What will be the output of following code-

import pandas as pd
s1=pd.Series([1, 2, 2, 7, ’Sachin’, 77.5])
print(s1.head(3))

25 Consider the following DataFrame, sports

SECTION C
26. Write the output of queries(a) to (d) based on the table, PERIPHERALS given below 3

Table: EMPLOYEE
.

(a) Select DEPT,MAX(SALARY) from EMPLOYEE group by DEPT


(b) SELECT FNAME,SALARY*12 ANN_SAL from EMPLOYEE WHERE PID LIKE ‘%N%’; (c)
SELECT FNAME,DEPT from EMPLOYEE where SALARY>=12000 order by HIRE_DATE
desc;
27. Write a Python code to create a DataFrame with appropriate column headings from 3
the list given below:
[[1011,'Sanjay’,58],[1012,'Srivani',67],[1013,'Vikrant' ,91],[1014,'Prathvi',78]]
28. Consider the following DataFrame, df 3

Write commands to :
i. Add a new column ‘Course’ to the Dataframe with values which are any
computer science related field.
ii. Add a new row with values (Sam,456,Chennai,Data Science)
iii. Display the average of TMarks column
29. What do you mean by Identity theft? Explain with the help of an example. 3

OR
What do you understand by plagiarism? Why is it a punishable offence? Mention any
two ways to avoid plagiarism.

30. Consider the table Garment and write the query: 3

i. Display the Minimum price of the Garment.


ii. Count and display the number of GARMENT from each SIZE where number of
GARMENTS are more than 1
iii. Display the sum of price of each color garment
SECTION D
31. Write suitable SQL query for the following: 5
i. Display 6 characters extracted from the 4th left character onwards from the string
‘MAKE IN INDIA’.
ii. Display the position of the occurrence of string ‘ING’ in the string ‘HELLO I AM
COMING’.
iii. Round off the value 67.27 to one decimal place.
iv. Display the remainder of 47 divided by 6.
v. Remove all the expected leading and trailing spaces from a column student_name
of the table ‘STUDENT’

32. 5
33. 5
SECTION E
34 A relationToys is given below:

T_no Name Company Price Qty


T001 Doll Barbie 1200 10
T002 Car Seedo_wheels 550 12
T003 MiniHouse Barbie 1800 15
T004 tiles Seedo_wheels 450 20
T005 Ludo Seedo_wheels 200 24
WriteSQLcommandsto:
a. Display the average price of each type of company having
quantitymorethan15.
b. Count the type of toys manufactured by each company.
c. Display the total price of all toys.
OR (Option for part iii only)
Write a query to display the total qty of toys available in relation Toys.
35. Consider the following DataFrame name df

Name Age Marks

0 Amit 15 90.0

1 Bhavdeep 16 NaN

2 Reema 17 87.0

Write the output of the given command:

a. print(df.marks/2)

b. print(df.loc[:0,’Age’])

c. Write Python statement to display the data of marks who secured marks >85

OR (Option for part iii only)

Write Python statement to compute and display the data of students by filling value as 0 in
place of NaN in the given DataFrame.

You might also like