0% found this document useful (0 votes)
3 views54 pages

Informatics Practices Book 12 Answer Key

The document provides an answer key for Chapter 1 of a book on Informatics Practices, focusing on Python Pandas. It includes short and long answer questions covering topics such as Series, DataFrames, and basic operations in Pandas, along with example codes and outputs. Additionally, it explains key concepts like vectorization, data manipulation, and the significance of the Pandas library.

Uploaded by

nidhiganatra3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views54 pages

Informatics Practices Book 12 Answer Key

The document provides an answer key for Chapter 1 of a book on Informatics Practices, focusing on Python Pandas. It includes short and long answer questions covering topics such as Series, DataFrames, and basic operations in Pandas, along with example codes and outputs. Additionally, it explains key concepts like vectorization, data manipulation, and the significance of the Pandas library.

Uploaded by

nidhiganatra3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

Informatics Practices

Book 12
Answer Key
Chapter-1 Python Pandas

Section B: Unsolved Questions


A. Short answer type questions.
1. What do you mean by Series in Python?

Ans. Series is a one-dimensional array that contains a succession of values of any data type (int,
float, list, string, etc.) that have numeric data labels (called index) that start at zero by default. The
following is an example of a series including city names:
a. Delhi
b. Mumbai
c. Bangalore
d. Jaipur

2. Write the code in Python to create an empty Series.


Ans.
import pandas as pd
import numpy as np
es=pd.Series()
print(es)

3. Name a method which is used to create Series in Python.


Ans. Series() is a Pandas function that can be used to create Series objects.

4. Name any two attributes of Series in Python.


Ans. Two attributes of Panda Series are:
Size: It returns the number of values in the Series Object. It is size immutable.
Values: It returns the list of the values in the series. Series value is mutable.

5. How is Series different from ndarray?


Ans. Series are different from ndarrays as elements in NumPy arrays are accessed by their integer
index position, starting from 0 for the first element. A Pandas Series object is more flexible and can
have any type of index.
Secondly, aligning data from different Series and matching labels with Series objects is more efficient
than using ndarrays, for example dealing with missing values. If there are no matching labels during
alignment, Pandas returns NaN(not any number) so the operation doesn't fail.
For example:
import numpy as np
import pandas as pd
a=np.array([1,2,3,4])
print(a[0]) #index is from 0 to 3
b=pd.Series([1,2,3,4], index=[10,20,30,40])
print(a[20]) #index is custom and can be anything
c=pd.Series([1,np.nan,3]) #NaN can be used
6. How is Series similar to ndarray?
Ans. Similarity is that both work as an array.
7. What is the significance of Pandas library?
Ans. Pandas is a software library written for the Python programming language for data
manipulation and analysis. In particular, it offers data structures and operations for manipulating
numerical tables and time series.

8. Carefully read the following code and answer the questions:


import pandas as pd
class11 = {'A': 23,'B': 25 , 'C': 30,'D':26}
class12={'Sc':35,'Com': 20, 'Hum':30}
tot={1:class11 , 2: class12}
df1 = pd.DataFrame(tot)
a. List the index labels of the DataFrame df1.
b. List the column name of DataFrame df1.
Ans.
a. Index(['A', 'B', 'C', 'D', 'Sc', 'Com', 'Hum'], dtype='object')
b. [1, 2]

9. Write a Python code to drop a row from DataFrame labeled as 0.


Ans. df.drop([0],axis=0)

10. Zehra got a code to extract first five rows of a DataFrame.


x.loc[0:5]
While retrieving, she has received 6 rows. Why? How can she get only first five rows?
Ans. She received only 6 rows because the upper index is included in retrieval. To get only the first
five rows, the command is:
x.loc[0:4]

11. Write the output of the following:


import numpy as num
import pandas as pd
arr=num.array([8,16,24])
S1 = pd.Series(arr)
print(S1)

Ans.
Output:
0 8
1 16
2 24
dtype: int64

12. What will happen with the following code?


import numpy as num
import pandas as pd
arr=num.array([8,16,24])
S1 = pd.Series(arr, index = (8,88))
print(S1)

Ans.
ValueError: Length of values (3) does not match length of index (2)
13. Fill in the blanks in the given code:
import pandas as pd
____________ = ____________. Series([5,10,15,20])
print(S1)

Ans.
S1 = pd.Series([5,10,15,20])

14. Complete the code to get the required output.


import ______ as pd
________ = pd.Series([31, 28, 31], index = ["Jan", "Feb", "Mar"] )
print(S1["_______"])
Output:
28

Ans.
import pandas as pd
S1 = pd.Series([31, 28, 31], index = ["Jan", "Feb", "Mar"] )
print(S1["Feb"])

15. Write a program to display only those values, which are greater than 200 in the given Series
"S1".
0 150
1 100
2 1000
3 1500

Ans.
import pandas as pd
a=[150,100,1000,1500]
S1 = pd.Series(a)
for i in range(0,len(S1)):
if S1[i] > 200:
print(S1[i])

16. Write a program to perform basic mathematical operations on two Series.


Ans.
import pandas as pd
series1 = pd.Series([0,2,4,6])
series2 = pd.Series([1,2,1,3])
series3 = series1+series2 #addition
print(series3)
series4 = series1-series2 #subtraction
print(series4)

17. What is the purpose of the following statement?


df.drop(["Total", "Marks"], axis=1)
Ans. It will drop or remove columns "Total" and "Marks".
18. Write the differences between Series and DataFrames.
Ans. Series can only contain single list with index, whereas dataframes can be made of more than
one series or we can say that a dataframe is a collection of series that can be used to analyse the
data.

19. Write any four characteristics/features of the Pandas module.


Ans. The following are the advantages of using Pandas over other libraries:
• Pandas's components, DataFrame, and Series represent the data in a format that is suitable
for data analysis.
• Pandas's strong Application Programming Interface (API) helps user to concentrate on the
most important parts of the code. As a result, the user receives a clean and simple code.
• Datasets can be reshaped and pivoted using Pandas.
• Pandas can also be used for aggregations and transformations.

20. What will be the output of the following?


import pandas as pd
student_dict = {'Name': ['Ritu', 'Nia', 'Huzaif','Tina','Jay','Jenny','Rose'],
'Age': [20, 21, 19,17,18,19,17],
'Marks': [85.10, 77.80, 91.54,72,87.9,90,72]}
student_df = pd.DataFrame(student_dict)
topRows = student_df.head()
print(topRows)

Ans.
Output:
Name Age Marks
0 Ritu 20 85.10
1 Nia 21 77.80
2 Huzaif 19 91.54
3 Tina 17 72.00
4 Jay 18 87.90

B. Long answer type questions.


1. Write a program to store employees' salary data for one year. Write functions to do the
following:
a. Display salary data for every 5th month.
b. Display salary of any one month.
c. Apply increment of 15% to salary for all values.
d. Give 2500 arrear to employees in April month.
Ans.
import pandas as pd
d={'Jan':45000,'Feb':44808,'Mar':44302,'Apr':45000,'May':44808,'June':43521,
'July':44785,'Aug':44856,'Sept':46325,'Oct':45878,'Nov':45368,'Dec':45778}
s=pd.Series(d)
#Salary of data for every 5th month
print("\nSalary of every 5th month:")
print(s[::5])
#Display the salary of a specific month
m=input("\nEnter month to display salary:")
if m in s.index:
print("\nMonth:",m,"Salary:",s[m])
else:
print("\nEnter valid month")
#Increment 15% for all months
s=s+(s*0.15)
print(s)
#Add arrears for April
s['Apr']=s['Apr']+2500
print("\nSalary with Arrears",s['Apr'])

Input:
Aug
Output:
Salary of every 5th month:
Jan 45000
June 43521
Nov 45368
dtype: int64
Enter month to display salary:
Month: Aug Salary: 44856
Jan 51750.00
Feb 51529.20
Mar 50947.30
Apr 51750.00
May 51529.20
June 50049.15
July 51502.75
Aug 51584.40
Sept 53273.75
Oct 52759.70
Nov 52173.20
Dec 52644.70
dtype: float64

Salary with Arrears 54250.0

2. Explain head( ) and tail( ) functions in Pandas Series with an example.


Ans.
The head() method is used to retrieve and display the elements from the top of the Series. By
default, it gives first five elements.
Syntax: <pandas object>.head([n])
Here, n is the number of rows that that are to be returned. If no value is provided to 'n', then it
returns top five rows. For example:
import pandas as pd
a = [10,9,9,9.5,10,10,9.5,8.5,8,7]
x = pd.Series(a, index = ["r1", "r2", "r3","r4","r5","r6","r7","r8","r9","r10"])
print(x.head(3)) #x.head(3) will retrieve top 3 rows of the Series.

Output:
r1 10.0
r2 9.0
r3 9.0
dtype: float64

The tail() method returns the Series' elements from the bottom of the Series object.
Syntax: <pandas object>.tail([n])
Here, n is the number of rows that are required to be returned. If no value is provided to 'n', then it
returns bottom five rows. For example:
import pandas as pd
a = [10,9,9,9.5,10,10,9.5,8.5,8,7]
x = pd.Series(a, index = ["r1", "r2", "r3", "r4","r5","r6","r7","r8","r9","r10"])
print(x.tail(3)) #x.tail(3) will retrieve bottom three rows of the Series.

Output:
r8 8.5
r9 8.0
r10 7.0
dtype: float64

3. What is Pandas NumPy?


Ans. NumPy is the fundamental package for scientific computing in Python. It is a Python library that
provides a multidimensional array object, various derived objects (such as masked arrays and
matrices), and an assortment of routines for fast operations on arrays, including mathematical,
logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra,
basic statistical operations, random simulation and much more.

4. What is vectorisation in Python Pandas? Explain with an example.


Ans. When a function or expression is applied to an object, it is applied individually to each item of
the object. This process is called vectorisation in Python.
Consider the following example:
import pandas as pd
a = [5,2,1,3.5,3]
x = pd.Series(a, index = ["a", "b", "c", "d", "e"])
x=x*3 #Here, x*3 increases the value of each and every element of the Series object x by 3 times,
and displays the final value using the print() statement.
print(x)

Output:
a 15.0
b 6.0
c 3.0
d 10.5
e 9.0
dtype: float64

5. Explain data operations in Pandas DataFrames.


Ans. A DataFrame is a two-dimensional data structure in which information is organised in rows and
columns in a tabular format. Simple operations, like selecting, deleting, adding, and renaming on the
rows and columns of a DataFrame can be executed.
Selecting a Column: To access a column in a DataFrame
import pandas as pd
d = {'name' : pd.Series(['Atharva','Seema','Yashica'], index=['a', 'b', 'c']),
'marks' : pd.Series([10, 9, 8, 9], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print (df['name'])

Output:
a Atharva
b Seema
c Yashica
d NaN
Name: name, dtype: object

6. Create a Pandas Series from a dictionary of values and a ndarray.


Ans. A Series is defined as a one-dimensional array that can store various data types. We can create
a Pandas Series from Dictionary by using the following method:
If the dictionary object is being passed as an input and the index is not specified, then the dictionary
keys are taken in a sorted order to construct the index.
If index is passed, then values corresponding to a particular label in the index will be extracted from
the dictionary. Consider the following code:

import pandas as pd
import numpy as np
info = {'x': 0., 'y' : 1., 'z' : 2.}
a = pd.Series(info)
print (a)

Output:
x 0.0
y 1.0
z 2.0
dtype: float64

7. Write a program to perform arithmetic operations on two Pandas Series.


Ans.
import pandas as pd
series1 = pd.Series([0,2,4,6])
series2 = pd.Series([1,2,1,3])
series3 = series1+series2 #addition
print("Addition")
print(series3)
print("Subtraction")
series4 = series1-series2 #subtraction
print(series4)
print("Multiplication")
series5 = series1*series2 #multiplication
print(series5)
print("Division")
series6 = series1/series2 #division
print(series6)

Output:
Addition
0 1
1 4
2 5
3 9
dtype: int64
Subtraction
0 -1
1 0
2 3
3 3
dtype: int64
Multiplication
0 0
1 4
2 4
3 18
dtype: int64
Division
0 0.0
1 1.0
2 4.0
3 2.0
dtype: float64

8. How to add an Index, row, or column to a Pandas DataFrame?


Ans.
#Adding a Column to a DataFrame:
import pandas as pd
info = {'I' : pd.Series([1, 11, 111, 1111], index=['a', 'b', 'c', 'd']), 'II' : pd.Series([2, 22, 222, 2222,
22222], index=['a', 'b', 'c', 'd', 'e'])}
df = pd.DataFrame(info)
print("Original data frame")
print(df)
print ("Adding new column by passing values")
df['III']=pd.Series([3, 33, 333],index=['a', 'b', 'c'])
print (df)

Output:
Original data frame
I II
a 1.0 2
b 11.0 22
c 111.0 222
d 1111.0 2222
e NaN 22222
Adding new column by passing values
I II III
a 1.0 2 3.0
b 11.0 22 33.0
c 111.0 222 333.0
d 1111.0 2222 NaN
e NaN 22222 NaN

9. How to delete indices, rows, or columns from a Pandas DataFrame?


Ans. The drop() method removes a row or column from a DataFrame object. This method eliminates
the selected column by specifying the column axis (axis='columns') and the given row by specifying
the row axis (axis='index').
import pandas as pd
data = {"name": ["Mukta", "Rohini", "Reyansh"],"age": [45, 40, 30],"qualified": [True, False, False]}
df = pd.DataFrame(data)
newdf = df.drop("age", axis='columns')
print(newdf)
newdf = df.drop(['age', 'qualified', ], axis = 1) #The statement df.drop("age", axis='columns') removes
whole column from 2D array.

# Drop rows with label 0


df = df.drop(0)
print(df)

10. Write a Pandas program to add some data to an existing Series.


Ans.
import pandas as pd
s = pd.Series(['100', '200', 'python', '300.12', '400'])
print("Original Data Series:")
print(s)
print("\nData Series after adding some data:")
new_s = s.append(pd.Series(['500', 'php']))
print(new_s)

Output:
Original Data Series:
0 100
1 200
2 python
3 300.12
4 400
dtype: object

Data Series after adding some data:


0 100
1 200
2 python
3 300.12
4 400
0 500
1 php
dtype: object

11. Write a Pandas program to select the rows where the percentage is greater than 90.
Ans.
import pandas as pd
record = {
'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ],
'Age': [21, 19, 20, 18, 17, 21],
'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'],
'Percentage': [88, 92, 95, 70, 65, 78] }

# create a dataframe
dataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage'])
print("Given Dataframe :\n", dataframe)

# selecting rows based on condition


rslt_df = dataframe[dataframe['Percentage'] > 90]
print('\nResult dataframe :\n', rslt_df)

Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Science 95
3 Priyanka 18 Math 70
4 Priya 17 Math 65
5 Shaurya 21 Science 78

Result dataframe :
Name Age Stream Percentage
1 Amit 19 Commerce 92
2 Aishwarya 20 Science 95

12. Write a Pandas program to select the rows in which the percentage is between 70 and 90
(inclusive).
Ans.
import pandas as pd
import numpy as np
exam_data = {'name': ['Aman', 'Kamal', 'Amjad', 'Rohan', 'Amit', 'Sumit', 'Matthew', 'Kartik', 'Kavita',
'Pooja'],
'perc': [79.5, 29, 90.5, np.nan, 32, 65, 56, np.nan, 29, 89],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['A', 'B', 'C', 'B', 'E', 'F', 'G', 'H', 'I', 'J']
df = pd.DataFrame(exam_data , index=labels)
print("Number of students whose percentage is between 70 and 90:")
print(df[df['perc'].between(70,90)])

Output:
Number of students whose percentage is between 70 and 90:
name perc qualify
A Aman 79.5 yes
J Pooja 89.0 yes

13. Write a Pandas program to change the percentage in a given row by the user.
Ans.
import pandas as pd
import numpy as np
exam_dic = {'name': ['Aman', 'Kamal', 'Amjad', 'Rohan', 'Amit', 'Sumit', 'Matthew', 'Kartik', 'Kavita',
'Pooja'],
'perc': [79.5, 29, 90.5, np.nan, 32, 65, 56, np.nan, 29, 89],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['A', 'B', 'C', 'B', 'E', 'F', 'G', 'H', 'I', 'J']
df = pd.DataFrame(exam_dic , index=labels)
print("\nOriginal data frame:")
print(df)
ch = input("Enter the index of row : ")
per = float(input("Enter percentage to be changed: "))
print('\nChange the percentage in row '+ch+ ' to',per)
df.loc[ch, 'perc'] = per
print(df)

Input:
B
99

Output:
Original data frame:
name perc qualify
A Aman 79.5 yes
B Kamal 29.0 no
C Amjad 90.5 yes
B Rohan NaN no
E Amit 32.0 no
F Sumit 65.0 yes
G Matthew 56.0 yes
H Kartik NaN no
I Kavita 29.0 no
J Pooja 89.0 yes
Enter the index of row : Enter percentage to be changed:
Change the percentage in row B to 99.0
name perc qualify
A Aman 79.5 yes
B Kamal 99.0 no
C Amjad 90.5 yes
B Rohan 99.0 no
E Amit 32.0 no
F Sumit 65.0 yes
G Matthew 56.0 yes
H Kartik NaN no
I Kavita 29.0 no
J Pooja 89.0 yes

14. Write a Pandas program to join the two given DataFrames along with rows and assign all data.
Ans.
import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
student_data2 = pd.DataFrame({
'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'],
'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha
Preston'],
'marks': [201, 200, 198, 219, 201]})
print("Original DataFrames:")
print(student_data1)
print("-------------------------------------")
print(student_data2)
print("\nJoin the said two dataframes along rows:")
result_data = pd.concat([student_data1, student_data2])
print(result_data)

Output:
Original DataFrames:
student_id name marks
0 S1 Danniella Fenton 200
1 S2 Ryder Storey 210
2 S3 Bryce Jensen 190
3 S4 Ed Bernal 222
4 S5 Kwame Morin 199
-------------------------------------
student_id name marks
0 S4 Scarlette Fisher 201
1 S5 Carla Williamson 200
2 S6 Dante Morse 198
3 S7 Kaiser William 219
4 S8 Madeeha Preston 201

Join the said two dataframes along rows:


student_id name marks
0 S1 Danniella Fenton 200
1 S2 Ryder Storey 210
2 S3 Bryce Jensen 190
3 S4 Ed Bernal 222
4 S5 Kwame Morin 199
0 S4 Scarlette Fisher 201
1 S5 Carla Williamson 200
2 S6 Dante Morse 198
3 S7 Kaiser William 219
4 S8 Madeeha Preston 201

15. Write a Pandas program to join the two given DataFrames along with columns and assign all
data.
Ans.
import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
student_data2 = pd.DataFrame({
'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'],
'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha
Preston'],
'marks': [201, 200, 198, 219, 201]})
print("Original DataFrames:")
print(student_data1)
print("-------------------------------------")
print(student_data2)
print("\nJoin the said two dataframes along columns:")
result_data = pd.concat([student_data1, student_data2], axis = 1)
print(result_data)

Output:
Original DataFrames:
student_id name marks
0 S1 Danniella Fenton 200
1 S2 Ryder Storey 210
2 S3 Bryce Jensen 190
3 S4 Ed Bernal 222
4 S5 Kwame Morin 199
-------------------------------------
student_id name marks
0 S4 Scarlette Fisher 201
1 S5 Carla Williamson 200
2 S6 Dante Morse 198
3 S7 Kaiser William 219
4 S8 Madeeha Preston 201

Join the said two dataframes along columns:


student_id name marks student_id name marks
0 S1 Danniella Fenton 200 S4 Scarlette Fisher 201
1 S2 Ryder Storey 210 S5 Carla Williamson 200
2 S3 Bryce Jensen 190 S6 Dante Morse 198
3 S4 Ed Bernal 222 S7 Kaiser William 219
4 S5 Kwame Morin 199 S8 Madeeha Preston 201

16. Write a Pandas program to append a list of dictionaries or Series to an existing DataFrame and
display the combined data.
Ans.
import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'marks': [200, 210, 190, 222, 199]})
s6 = pd.Series(['S6', 'Scarlette Fisher', 205], index=['student_id', 'name', 'marks'])
dicts = [{'student_id': 'S6', 'name': 'Scarlette Fisher', 'marks': 203},
{'student_id': 'S7', 'name': 'Bryce Jensen', 'marks': 207}]
print("Original DataFrames:")
print(student_data1)
print("\nDictionary:")
print(s6)
combined_data = student_data1.append(dicts, ignore_index=True, sort=False)
print("\nCombined Data:")
print(combined_data)

Output:
Original DataFrames:
student_id name marks
0 S1 Danniella Fenton 200
1 S2 Ryder Storey 210
2 S3 Bryce Jensen 190
3 S4 Ed Bernal 222
4 S5 Kwame Morin 199

Dictionary:
student_id S6
name Scarlette Fisher
marks 205
dtype: object

Combined Data:
student_id name marks
0 S1 Danniella Fenton 200
1 S2 Ryder Storey 210
2 S3 Bryce Jensen 190
3 S4 Ed Bernal 222
4 S5 Kwame Morin 199
5 S6 Scarlette Fisher 203
6 S7 Bryce Jensen 207

17. Write a program to select or filter rows from a DataFrame based on values in columns in
Pandas.
Ans.
import pandas as pd
record = {
'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ],
'Age': [21, 19, 20, 18, 17, 21],
'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'],
'Percentage': [88, 92, 95, 70, 65, 78] }

# create a dataframe
dataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage'])
print("Given Dataframe :\n", dataframe)

# selecting rows based on condition


rslt_df = dataframe[dataframe['Percentage'] > 80]
print('\nResult dataframe :\n', rslt_df)

Output:
Given Dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Science 95
3 Priyanka 18 Math 70
4 Priya 17 Math 65
5 Shaurya 21 Science 78

Result dataframe :
Name Age Stream Percentage
0 Ankit 21 Math 88
1 Amit 19 Commerce 92
2 Aishwarya 20 Science 95

18. Write a program to create a DataFrame salesman using the Series sales_person, which stores
the salesman names and quantity of sales in August.
Ans.
import pandas as pd
sales_person = [["Ram",55],["Ajay",22],["Vijay",67],["Sachin",44]]
salesman = pd.DataFrame(sales_person,columns=["Name","Sales(August)"])
print(salesman)

Output:
Name Sales(August)
0 Ram 55
1 Ajay 22
2 Vijay 67
3 Sachin 44
19. Write a Pandas program to select the specified columns and rows from a given DataFrame.
Select 'name' and 'score' columns in rows 1, 3, 5, 6 from the following DataFrame.
Sample DataFrame:
exam_data = {'name': ['Anna', 'Daina', 'Katrina', 'John', 'Emily', 'Meera', 'Mohan', 'Lalit', 'Kavya',
'Jaynil'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f ', 'g', 'h', 'i', 'j']
Ans.
import pandas as pd
import numpy as np
exam_data = {'name': ['Anna', 'Daina', 'Katrina', 'John', 'Emily', 'Meera', 'Mohan', 'Lalit', 'Kavya',
'Jaynil'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f ', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data, index=labels)
print("\nOriginal data frame:")
print(df)

print('\nSelect name and score columns in rows 1, 3, 5, 6')


print(df.iloc[[1,3,5,6], 0 : 2])

Output:
Original data frame:
name score attempts qualify
a Anna 12.5 1 yes
b Daina 9.0 3 no
c Katrina 16.5 2 yes
d John NaN 3 no
e Emily 9.0 2 no
f Meera 20.0 3 yes
g Mohan 14.5 1 yes
h Lalit NaN 1 no
i Kavya 8.0 2 no
j Jaynil 19.0 1 yes

Select name and score columns in rows 1, 3, 5, 6


name score
b Daina 9.0
d John NaN
f Meera 20.0
g Mohan 14.5

Chapter-2 Importing/Exporting Data between CSV Files and DataFrames


Section B: Unsolved Questions
A. Short answer type questions.
1. What is the purpose of the read_csv() Pandas function?
Ans. The read_csv( ) function is used to load a CSV file as a Pandas DataFrame.
For example:
import pandas as pd
df=pd.read_csv('Student.csv', names = ["Student_ID", "Name", "Marks"], index_col =
"Student_ID")
print(df)

2. Explain the purpose of to_csv() function with a suitable Python example.


Ans. The to_csv() function is used to write object to a comma-separated values (csv) file.
For example:
import numpy as np
import pandas as pd
df = pd.DataFrame({'name': ['Leonardo', 'Michelangelo'],
'mask': ['blue', 'orange'],
'weapon': ['katana', 'nunchaku']})
df.to_csv(index=False)

3. How are the arguments skiprows and nrows different? Support your answer by giving a suitable
Python example.
Ans. Using skiprows, line numbers to skip (0-indexed) or the number of lines to skip (int) at the start
of the file are mentioned. Whereas with nrows, the number of rows to read from the file are
mentioned.
Example:
import pandas as pd
df = pd.read_csv('departments.csv')
print("Original file")
print(df)
df1 = pd.read_csv('departments.csv',skiprows = [1,3])
print("Skipping row 1 & 3")
print(df1)
df2 = pd.read_csv('departments.csv',nrows = 3)
print("Reading top 3 rows using nrows")
print(df2)

Output:
Original file
department_id department_name manager_id location_id
0 10 Administration 200 1700
1 20 Marketing 201 1800
2 30 Purchasing 114 1700
3 40 Human Resources 203 2400
4 50 Shipping 121 1500
5 60 IT 103 1400
6 70 Public Relations 204 2700
7 80 Sales 145 2500
Skipping row 1 & 3
department_id department_name manager_id location_id
0 20 Marketing 201 1800
1 40 Human Resources 203 2400
2 50 Shipping 121 1500
3 60 IT 103 1400
4 70 Public Relations 204 2700
5 80 Sales 145 2500
Reading top 3 rows using nrows
department_id department_name manager_id location_id
0 10 Administration 200 1700
1 20 Marketing 201 1800
2 30 Purchasing 114 1700

4. What do you mean by the index column?


Ans. A first column added by default in the DataFrame. It is known as the index column.

5. What is the default separator in CSV? How can you change the separator to '+'? Explain with a
suitable example.
Ans. The default separator in a CSV file is a comma symbol. It can be changed using the 'sep'
argument.
For example:
import pandas as pd
df = pd.read_csv('sample.csv',sep="+")
print(df)

B. Long answer type questions.


1. Write a program to import a CSV file in a DataFrame and print the data.
Ans.
import pandas as pd
df = pd.read_csv('departments.csv')
print(df)

Output:
department_id department_name manager_id location_id
0 10 Administration 200 1700
1 20 Marketing 201 1800
2 30 Purchasing 114 1700
3 40 Human Resources 203 2400
4 50 Shipping 121 1500
5 60 IT 103 1400
6 70 Public Relations 204 2700
7 80 Sales 145 2500

2. Ms Neena is an English teacher who has maintained a record of 5 test marks for 10 students.
Write a Python program to import her CSV file and display the data using Pandas.
Ans.
import pandas as pd
print("******************Marksheet****************")
df=pd.read_csv("result.csv")
print(df)

Output:
******************Marksheet****************
Unnamed: 0 Test1 Test2 Test3 Test4 Test5
0 Surbhi 67 55 66 45 54
1 Anu 89 67 78 56 65
2 Shreya 90 45 89 67 76
3 Ruhin 55 56 90 65 87
4 Tisha 66 65 88 55 84
5 Swati 78 78 97 84 76
6 Neerja 95 66 81 77 61
7 Ravi 92 88 75 52 92
8 Vishal 80 90 94 90 83
9 Kanav 75 95 95 61 91

3. Rewrite the program in question 2 and display the records using '|' separator.
Ans.
import pandas as pd
marks = {"Test1" :[67,89,90,55,66,78,95,92,80,75],
"Test2":[55,67,45,56,65,78,66,88,90,95],
"Test3":[66,78,89,90,88,97,81,75,94,95],
"Test4" :[45,56,67,65,55,84,77,52,90,61],
"Test5":[54,65,76,87,84,76,61,92,83,91]}
label=["Surbhi","Anu","Shreya","Ruhin","Tisha","Swati","Neerja","Ravi","Vishal","Kanav"]
result = pd.DataFrame(marks, index=label)
print("******************Marksheet****************")
re=result.to_csv(sep="|")
print("\nreading the data")
print(re)

Output:
******************Marksheet****************
reading the data
|Test1|Test2|Test3|Test4|Test5
Surbhi|67|55|66|45|54
Anu|89|67|78|56|65
Shreya|90|45|89|67|76
Ruhin|55|56|90|65|87
Tisha|66|65|88|55|84
Swati|78|78|97|84|76
Neerja|95|66|81|77|61
Ravi|92|88|75|52|92
Vishal|80|90|94|90|83
Kanav|75|95|95|61|91

4. Write a program to save 10 records in three columns and display the first and the fifth rows
using Pandas.
Ans.
import pandas as pd
technologies = {
'Courses':["C","C++","Java","HTML","Python","JavaScript","Hadoop","R","SQL",".NET"],
'Fee' :[15000,21000,25000,12000,25000, 23000, 23000, 24000,18000,25000],
'Duration':['15 days','30 days', '30 days', '15 days', '30 days', '55 days', '15 days', '15 days', '10 days',
'15 days'],
}
course = pd.DataFrame(technologies)
course.to_csv("course.csv")
print("Original Data")
print(course)
print("\nDisplaying the first and the fifth rows")
df=pd.read_csv("course.csv",skiprows=[2,3,4,6,7,8,9,10])
print(df)

Output:
Original Data
Courses Fee Duration
0 C 15000 15 days
1 C++ 21000 30 days
2 Java 25000 30 days
3 HTML 12000 15 days
4 Python 25000 30 days
5 JavaScript 23000 55 days
6 Hadoop 23000 15 days
7 R 24000 15 days
8 SQL 18000 10 days
9 .NET 25000 15 days

Displaying the first and the fifth rows


Unnamed: 0 Courses Fee Duration
0 0 C 15000 15 days
1 4 Python 25000 30 days

5. Fill in the blanks to complete the following code snippet:


import ____________ as pd
_______= pd._________('users.csv', skiprows=2)
_______('Contents of the Dataframe created by skipping top 2 lines from the csv file.')

Ans.
import pandas as pd
MyDF=pd.read_csv('users.csv', skiprows=2)
print(MyDF)

6. Write a program to import a CSV file and display only the top 5 rows using DataFrame.
Ans.
import pandas as pd
print("Displaying Top 5 rows")
df=pd.read_csv("co.csv",nrows=5)
print(df)

Output:
Displaying Top 5 rows
Unnamed: 0 Courses Fee Duration
0 0 C 15000 15 days
1 1 C++ 21000 30 days
2 2 Java 25000 30 days
3 3 HTML 12000 15 days
4 4 Python 25000 30 days

7. Write a program to create a CSV and write the following data to it.

Ans.
import pandas as pd
bloodbank = {
'Name':["Riya","Suhani","Tarun","Shahid","Raghu","Raman"],
'Blood Group' :['O+','B+','AB+','O+','O-','AB-'],
'Contact Code':['110', '112', '121', '111', '001','002'],
}
bb = pd.DataFrame(bloodbank)
bb.to_csv("blood.csv")

8. Write a program to import and export data between Pandas and CSV file.
a. To create and open a DataFrame using 'student_marks.csv' file using Pandas
b. To display top 5 rows and columns
c. To skip the second and fourth rows and display the remaining
Ans.
import pandas as pd
marks = {"English" :[67,89,90,55,66,78,95,92,80,75],
"Maths":[55,67,45,56,65,78,66,88,90,95],
"Accounts":[66,78,89,90,88,97,81,75,94,95],
"BST" :[45,56,67,65,55,84,77,52,90,61],
"IP":[54,65,76,87,84,76,61,92,83,91]}
label=["Surbhi","Anu","Shreya","Ruhin","Tisha","Swati","Neerja","Ravi","Vishal","Kanav"]
result = pd.DataFrame(marks,index=label)
result.to_csv("student_marks.csv")
print("\nreading the file")
df=pd.read_csv("student_marks.csv")
print(df)
print("\ndisplaying top 5 rows and columns")
df1=pd.read_csv("student_marks.csv",nrows=5)
print(df1)
print("\nSkipping the second and fourth rows and displaying the remaining")
df2=pd.read_csv("student_marks.csv",skiprows=[2,4])
print(df2)

Output:

reading the file


Unnamed: 0 English Maths Accounts BST IP
0 Surbhi 67 55 66 45 54
1 Anu 89 67 78 56 65
2 Shreya 90 45 89 67 76
3 Ruhin 55 56 90 65 87
4 Tisha 66 65 88 55 84
5 Swati 78 78 97 84 76
6 Neerja 95 66 81 77 61
7 Ravi 92 88 75 52 92
8 Vishal 80 90 94 90 83
9 Kanav 75 95 95 61 91

displaying top 5 rows and columns


Unnamed: 0 English Maths Accounts BST IP
0 Surbhi 67 55 66 45 54
1 Anu 89 67 78 56 65
2 Shreya 90 45 89 67 76
3 Ruhin 55 56 90 65 87
4 Tisha 66 65 88 55 84

Skipping the second and fourth rows and displaying the remaining
Unnamed: 0 English Maths Accounts BST IP
0 Surbhi 67 55 66 45 54
1 Shreya 90 45 89 67 76
2 Tisha 66 65 88 55 84
3 Swati 78 78 97 84 76
4 Neerja 95 66 81 77 61
5 Ravi 92 88 75 52 92
6 Vishal 80 90 94 90 83
7 Kanav 75 95 95 61 91

Chapter-3 Data Visualisation


Section B: Unsolved Questions
A. Short answer type questions.
1. What is data visualisation?
Ans. Data visualisation refers to a graphical representation of data or information. Some of the data
visualisation tools are visual elements, such as charts, graphs, and maps. These tools help the users
to understand the presented information in a better way.

2. What are the major components of a chart?


Ans. The basic components of a chart plotted by PyPlot are:
• Chart Title: Chart title is the title given to the chart, which is used to identify it.
• Figure: It is the main plot, which contains all the components of the chart.
• Legend: It contains the labels of each plot.
• Axes: Every two-dimensional chart has two axes, i.e., X axis and Y axis.
• Ticks: Every coordinate axis has the values used to show specific points.

3. Name the functions to create the following chart:


a. Line b. Bar c. Histogram d. Pie
Ans.
a. plot() function
b. bar() function
c. hist() function
d. pie() method

4. What is the significance of PyPlot in matplotlib?


Ans. Pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function
makes some changes to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some
lines in a plotting area, decorates the plot with labels, etc. Matplotlib is a library for data
visualization, typically in the form of plots, graphs and charts.

5. Write the statement to import PyPlot.


Ans. import matplotlib.pyplot as plt

6. What is histogram? How is it useful?


Ans. The histogram is a popular graphing tool. It is used to summarize discrete or continuous data
that are measured on an interval scale. It is often used to illustrate the major features of the
distribution of the data in a convenient form.
Histograms are particularly helpful to analyse the frequency distribution of sample data. In a
statistical experiment, frequency distribution is the number of observations that belong to a
particular category (or “bin” in histogram terminology).

7. Name a function to add ticks on axes.


Ans. xticks() and yticks()

8. What is the purpose to add ticks to axes?


Ans. Ticks are the markers denoting data points on the axes and tick labels are the name given to
ticks. By default, matplotlib itself marks the data points on the axes but it has also provided us with
setting their own axes having ticks and tick labels of their choice.

9. What is the significance of legends in a chart?


Ans. A legend is an area describing the elements of the graph. In the matplotlib library, there is a
function called legend(), which is used to place a legend on the axes.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 5, 8, 9, 12]
plt.plot(x, y)
plt.legend(['single line'])
plt.show()

Output:
10. Which attribute or argument is used to change the normal line to dotted line in plot()
function? Write the statement for the same.
Ans. Linestyle attribute can be used to change the normal line to dotted line in plot() function.
Statement:
plt.plot(ypoints, linestyle = 'dotted')

11. Which function is used to add title in the graph? Write the appropriate Python statement for
the same.
Ans. title() function is used to add title in the graph.
Statement to add a title in a graph:
plt.title("This is the title of the graph")

12. What is the purpose of figure in the graph?


Ans. Figure is the main plot, which contains all the components of the graph.

13. What are the different types of chart in PyPlot module?


Ans. The different types of charts that can be drawn using PyPlot module are:
• Line chart
• Bar chart
• Histogram
• Scatter chart
• BoxPlot
• Pie Chart

14. What is bin in histogram? Explain by giving an example in Python.


Ans. In histogram, bins are the number of intervals into which all data is divided, such that it can be
displayed as bars on a histogram.
For example:
import matplotlib.pyplot as plt
n = [112,144,157,195,121,131,151,189,113,155,123,117,184,177,166,134,156,144,159,123]
plt.hist(n, edgecolor="black",bins=5)
plt.show()

Output:
B. Long answer type questions.
1. What is histogram? Which function in Python is used to create histogram? Write all its
parameters and explain with the help of a suitable Python example.
Ans. The histogram is a popular graphing tool. It is used to summarize discrete or continuous data
that are measured on an interval scale. It is often used to illustrate the major features of the
distribution of the data in a convenient form.
A histogram is plotted using the matplotlib.pyplot.hist() function. It offers a number of attributes
that can be used to modify a histogram.

The following table lists down the various attributes of a histogram:

x Array or sequence of arrays


bins It is an optional parameter. It can have integer, sequence, or auto values.
Optional Parameters
range The lower and upper range of the bins
density If true, the counts adjusted to create a probability density will be the first
element of the return tuple.
cumulative If the result is true, a histogram with count for each bin and all bins for
smaller values is computed.
histtype This parameter creates a histogram. By default, the shape of the histogram
is that of bar chart.
• "bar" refers to a standard bar-type histogram. The bars are arranged
side by side if multiple data are provided.
• A bar-type histogram called "barstacked" has numerous data layers
layered on top of one another.
• The "step" command creates a lineplot that is empty by default.
• When a lineplot is generated, it is filled by default.

For example:
from matplotlib import pyplot as plt
import numpy as np
a=np.array([10,30,5,42,55,76,55,54,11,20,51,15,75,37,25])
plt.hist(a,edgecolor="black", bins=[0,25,50,75,100])
plt.title("Marks Obtained by Students in a Class")
plt.xticks([0,25,50,75,100])
plt.xlabel("Marks")
plt.ylabel('No. of Students')
plt.show()
Output:

2. Write a Python program to plot a bar graph for the following data:
Month = ['Jan', 'March', 'May', 'July']
No. of working days = [24, 21, 22, 25]
Ans.
import matplotlib.pyplot as plt
x=['Jan', 'March', 'May', 'July']
y=[24, 21, 22, 25]
plt.bar(x,y)
plt.bar(x,y,color="green")
plt.xlabel("Month")
plt.ylabel("No. of working Days")
plt.title("Working Days per Month")
plt.show()

Output:

3. Akshay is studying in class 11 and wants to create a graph to check his progress in English
subject in periodic tests. To help him, write a Python program to analyse his progress.
Ans.
import matplotlib.pyplot as plt
x= ["PT1", "PT2", "PT3", "PT4"]
y=[24,16,18,20]
plt.bar(x,y)
plt.bar(x,y,color="pink")
plt.xlabel("Periodic Tests")
plt.ylabel("Marks Obtained")
plt.title("Akshay's Progress in English subject")
plt.show()

Output:

4. Mrs. Smita Dabas is a coordinator in a senior section school. She represented data on number of
students who passed the exam using line chart.
import matplotlib.pyplot as plt
classes=["X A","X B","XI A","XI B","XII A","XII B"]
no_of_boys=[23,22,20,26,33,30]
no_of_girls=[17,10,20,12,5,8]
plt.line(classes, no_of_boys) #Statement 1
plt.line(classes, no_of_girls) #Statement 2
plt.xtitle("No of Students") #Statement 3
plt.ytitle("Classes") #Statement 4
plt.show()
a. What will be the correct code for Statement 1 and Statement 2?
b. What is the correct function name for Statement 3 and Statement 4?
c. Write a method and parameter required to display legends.
d. Name the parameter and values used to apply a line style.

Ans.
import matplotlib.pyplot as plt
classes=["X A","X B","XI A","XI B","XII A","XII B"]
no_of_boys=[23,22,20,26,33,30]
no_of_girls=[17,10,20,12,5,8]
plt.plot(classes,no_of_boys, label="No. of Boys") #Statement 1
plt.plot(classes,no_of_girls, label="No. of Girls") #Statement 2
plt.ylabel("No of Students") #Statement 3
plt.xlabel("Classes") #Statement 4
plt.legend()
plt.show()
Output:

Linestyle attribute can be used to change the normal line to dotted line in plot() function.
Statement:
plt.plot(ypoints, linestyle = 'dotted')

5. Draw a histogram with the following frequency of scores 11, 10, 11, 9, 9, 10, 11, 11, 10, 10, 11, 9,
10, 9 with range (bins) starting from 9 to 11.
Ans.
import matplotlib.pyplot as plt
n = [11, 10, 11, 9, 9, 10, 11, 11, 10, 10, 11, 9, 10, 9]
plt.hist(n,edgecolor="black",bins=[9,10,11])
plt.xticks([9,10,11])
plt.show()

Output:

6. Science teacher, Ms Ranjana, gave a project to her class student Bhanu to find the interest of
students to have junk food in lunch or dinner for next 5 days and asked to store data with the
following columns:
Days Lunch Dinner
Monday 20 10
Tuesday 25 15
Wednesday 15 15
Thursday 10 20
Friday 24 6

Write a program to represent the data using line graph and add appropriate legends, labels and
line style or colour to make your chart self-explanatory.
Ans.
import matplotlib.pyplot as plt
#create data
bx=['Monday','Tuesday','Wednesday','Thursday','Friday']
sy=[20,25,15,10,24]
by=[10,15,15,20,6]
#plot lines
plt.plot(bx,sy, label ="Lunch")
plt.xlabel("Days")
plt.plot(bx,by, label ="Dinner")
plt.ylabel("Interest of students to have junk food")
plt.legend()
plt.show()

Output:

7. Tanya is working in an online cab service company and wants to create a chart to show the
number of cabs booked from Monday to Friday. She has stored the data in a CSV. Help tanya to
create a bar graph by taking her data from her CSV.
Ans.
import pandas as pd
import matplotlib.pyplot as plt
data= {'Days':['Monday','Tuesday','Wednesday','Thursday','Friday'],
'Cabs':[298,461,520,635,928]
}
bb = pd.DataFrame(data)
bb.to_csv("cab.csv")
df = pd.read_csv("cab.csv")
x=df['Days'].tolist()
y=df['Cabs'].tolist()
plt.bar(x,y)
plt.bar(x,y,color="violet")
plt.xlabel("Days")
plt.ylabel("Cabs booked")
plt.title("Number of cabs booked in the week")
plt.show()

Output:

8. Manasvi has opened a tiffin service and provide meals to employees of a company. She has
stored the number of employees opting for different menu in a dictionary. Now she wants to
create a chart to understand and analyse the data in a better way. Write a Python code to help her
to create a chart for the below mentioned data.
meals = {'Breakfast':23, 'Lunch':17, 'Snacks':35,'Dinner':29, 'Tea/Coffee' : 12}
Ans.
import matplotlib.pyplot as plt
meals = {'Breakfast':23, 'Lunch':17, 'Snacks':35,'Dinner':29, 'Tea/Coffee' : 12}
meal= list(meals.keys())
count = list(meals.values())
plt.bar(meal, count, color ='green', width = 0.5)
plt.xlabel("Meals Offered")
plt.ylabel("No. of Employees Opted")
plt.title("Employees opting for tiffin service")
plt.show()

Output:
9. On every Wednesday, class 5A, 5B, 5C and 5D watch an educational movie. The class teacher
has shown almost 5 movies till now and she has rolled out a form to know which movie their
children liked the most.

She has the following data:

Movies Liked by Number of Students


1 35
2 40
3 55
4 62
5 38

Now, write a Python program that create a horizontal bar graph to show the mentioned data.

Ans.
import matplotlib.pyplot as plt
x= [1,2,3,4,5]
y=[35,40,55,62,38]
plt.barh(y,x,color="cyan")
plt.xlabel("Movies")
plt.ylabel("Liked by Number of Students")
plt.title("Movies Liked by Students")
plt.show()

Output:
10. Write the Python code to plot the given histogram with the following data set:
Score=[40, 45, 41, 43, 42, 55, 53, 52, 46, 43, 40, 45, 44, 42, 46, 47, 51, 52, 54]
Ans.
import matplotlib.pyplot as plt
n = [40, 45, 41, 43, 42, 55, 53, 52, 46, 43, 40, 45, 44, 42, 46, 47, 51, 52, 54]
plt.hist(n, edgecolor="red", bins=5)
plt.show()

Output:

Chapter-4: Revision of Database Concepts


Section B: Unsolved Questions
A. Short answer type questions.
1. What is the difference between primary key and foreign key?
Ans. A primary key uniquely identifies each record in a table. It cannot contain NULL values.
A foreign key is a field or set of fields that is used to establish a relation between two tables. Each
value in a column or columns in a foreign key must match the primary key of the referential table.
Foreign keys assist in the maintenance of data and referential integrity.

2. Describe the relational data model.


Ans. The relational data model is easy to understand and contains all the traits and capabilities
needed to process data efficiently. The data is organised into tables called relations, with each row
representing a record and the data or attributes are stored in table's columns.

3. What is the difference between primary key and candidate key?


Ans. A primary key is a non-null key that uniquely identifies a record in a table. There can only be
one primary key in a table. A candidate key is similar to a primary key and is used to identify a record
in a table. However, a table can have multiple candidate keys. Out of a number of candidate keys,
one key is identified to be the primary key.

4. Define relational database.


Ans. The relational database is easy to understand and contains all the traits and capabilities needed
to process data efficiently. The data is organised into tables called relation, with each row
representing a record and the data or attributes are stored in the table's columns.

5. Differentiate between ALTER and UPDATE statements.


Ans. The ALTER statement is used to add, delete, and modify the attributes of the database's
relations (tables). The UPDATE statement is used to update existing database records. By default, the
ALTER statement sets all tuple values to NULL. The UPDATE statement updates the tuples with the
values supplied in the statement. The ALTER statement is a Data Definition Language (DDL)
command where as the UPDATE statement is a Data Manipulation Language (DML) command.

6. Write an SQL query to create the EMP table.


EMPID INTEGER(4)
DeptID INTEGER(2)
EmpName CHAR(10)
Job CHAR(10)
Manager INTEGER(4)
HireDate DATE
Salary INTEGER(7)
Commission INTEGER(7)
Ans.
CREATE TABLE EMP
(EMPID integer(4) NOT NULL PRIMARY KEY,
DeptID integer(2),
EmpName char(10) NOT NULL,
Job char(10),
Manager integer(4),
HireDate date,
Salary integer(7),
Commission integer(7));

B. Long answer type questions.

1. Consider the relation 'Hospital' and write the SQL query for questions from (a) to (g).
Ans.
a. Select *
from Hospital
where Department = 'Cardiology';

b. Select Name
from Hospital
where Department = 'Orthopedic' and Sex='F';
c. Select Name, Date_of_adm
from Hospital
order by Date_of_adm;

d. Select Name, Charges, Age


from Hospital
where Sex='M';

e. Select Name
from Hospital
where Sex='M';

f. Delete from Hospital


where No=10;

g. Alter table Hospital


add Status char(25);

2. Consider the relation 'Teacher'. Perform the following operations:


Ans.

a. Select * from Teacher Where Department='Computer';


b. Select Name from Teacher Where Department='History' and Sex='F';
c. Select Name from Teacher order by Dateofjoining;
d. Select Name, Department, Salary from Teacher Where Sex='F';
e. Insert into Teacher
Values (8, 'Mersa', 'Computer', '1/1/2000',12000, 'M');

3. Write the queries of the following on the basis of the given table 'Faculty'.
Ans.
a. Select *
from Faculty
where DOJ > '31.12.1990';

b. Select *
from Faculty
where Fsal > 20000;

c. Select Fname
from Faculty
where DOJ = '12.10.1980';

d. Select *
from Faculty
where Fname like 'A%';

e. Select *
from Faculty
where Fsal > 25000 and Fname like '%n';
Chapter-5: SQL Functions

Section B: Unsolved Questions


A. Short answer type questions.
1. What is the purpose of the following clauses in a select statement?
a. ORDER BY
b. GROUP BY
c. Where Clause
d. Like operator
Ans.
a. ORDER BY: An ORDER BY clause is used to display the result of a query in a specific order(sorted
order). The sorting can be done in ascending or in descending
order. It should be kept in mind that the actual data in the database is not sorted but only the results
of the query are displayed in sorted order. For example:
SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.

b. GROUP BY: The GROUP BY clause can be used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.
The syntax for the GROUP BY clause is:
SELECT column1, column2, ... column_n,
aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY column1, column2, ... column_n;

aggregate_function can be a function such as SUM, COUNT, MAX, MIN, AVG, etc. For example:
SELECT name, COUNT(*) as "Number of employees“ FROM student WHERE marks>350 GROUP BY
city;

c. Where Clause: The WHERE clause defines the conditions used to limit the contents of the result.
Where clause is optional. For example:
SELECT name
FROM student
WHERE class = 10;
The above query displays the names of students of class 10.

d. In a WHERE clause, the LIKE operator is used to look for a certain pattern in a column. There are
two wildcards that are frequently used with the LIKE operator:
• The percent sign (%) denotes zero, one, or more characters.
• The underscore symbol (_) denotes a single character.
For example:
SELECT name from Student WHERE name LIKE 'Ad%';
The above query will fetch the names of the students from the STUDENT table whose names start
with the letters 'AD'.

2. What is MySQL Function?


Ans. A function is a database object, which is a set of SQL statements that take input parameters,
process it, and then return the outcome. For example: ROUND, SUM, COUNT, MAX, MIN, AVG, etc.

3. Write the command for the following:


a. Display current date and time
b. Display only year from date
c. Convert text in lower case
d. Display the cube of a number
Ans.
a. select datetime();
b. select year(<date>);
c. select lower(<text>);
d. select power(<number>,3);

4. How many different types of functions available in MYSQL?


Ans. In MySQL there are two types of functions:
• Single Row Functions: Also known as scalar functions, these functions operate on each row
of the table and return the result for it. The functions like round (), power() , upper() are a
few examples of scalar functions.
• Multiple Row Functions: Functions that conduct operations on the set or group of values in a
column and return a single value are called multiple row functions or also aggregate
functions. For instance, count(), min(), max(), and avg() are a few examples of the multiple
row or aggregate functions.

5. Consider the following table products and write the output of the following queries:
a. Select lcase(pname) from products where pname='LED TV';
b. Select sqrt(price) from products where price>50000;
c. Select mod(qty, 3) from products;
d. Select substr(company, 1, 4) from products;
e. Select pname, truncate(mod(price, 10),3) from products where qty>100;
f. Select pcode, round(qty) from products where company in ('Sony', 'MI');
g. Select right(pname, 4) from products where qty = 10 or qty = 20;

Ans.
a.
lcase(pname)
led tv
led tv

b.
sqrt(price)
291.547594742265
308.2207001484488

c.

mod(qty, 3)
0
1
1
2
2
1
d.
substr(company, 1, 4)
Appl
Sony
Phil
Appl
MI
Ahuj
e.
pname truncate(mod(price, 10),3)
iPad 0

f.
pcode round(qty)
P1002 100
P1005 20

g.
right(pname, 4)
Mera
D TV

Chapter-6: Computer Networks


Section B: Unsolved Questions
A. Short answer type questions.
1. What is a computer network?
Ans. It is an interconnection of autonomous computers to share data and resources through
transmission media.

2. What is the internet?


Ans. The internet is a global network that connects millions of individuals all over the world. The
network of networks is called an internet.

3. Define a node?
Ans. An individual computer or device, which is connected to a network is called a node.

4. Define NSFNet.
Ans. NSFNET serves as a primary backbone communication service for the internet. The NSFNet
network was solely designed for academic research. Many commercial companies built their own
networks, later connected via NSFNet and ARPANET, which eventually became the internet.

5. What is data communication?


Ans. Data communication is the process of exchanging data between a sender and a receiver via a
transmission medium and protocols. It consists of five components: message, sender, receiver,
transmission medium, and protocols.

6. List the types of data communication.


Ans. There are three types of data communication:
• Simplex: In this mode, data is always transferred in only one direction.
• Half-duplex: In this mode, the data can be transferred in both directions but one at a time.
• Full-duplex: In this mode the data can be transferred in both directions simultaneously.

7. What is data transfer rate? List different measurement units of data transfer rate.
Ans. The data transfer rate (DTR) is the amount of digital data that is moved from one place to
another at a certain period of time. The data transfer rate can be viewed as the speed of travel of a
given amount of data from one place to another.
Kbps (Kilobits per second), Mbps (Megabits per second), Gbps (Gigabits per second), and Tbps
(Terabits per second) are different units of data transfer rates.
8. Explain the following terms:
Ans.
a. Channel: It is a communication medium that allows data or information to be transmitted from
one node to another. Communication channels are often used to connect computers over a
network.
b. Baud: It is a measuring unit for data transfer rate. 1 baud is equal to 1 bit per second. It represents
only one signal change per second.

9. Name all the components of data communication.


Ans. There are five components involved in data communication:
• Message: It is the information in any form of audio, text, picture, etc. which is to be
communicated.
• Sender: It refers to a device that sends information.
• Receiver: It refers to the device which receives the information.
• Transmission medium: It refers to the physical path that carries information in the form of
signals/bits and travels from one place to another.
• Protocols: A protocol is a set of rules that governs the data communication.

10. What is interspace?


Ans. The interspace is a global network that will facilitate knowledge manipulation through concept
navigation between community spaces.

11. Why is network device needed?


Ans. Network devices are hardware components that connect digital equipment (like computers,
printers, and other electronic devices) to the network. These devices transmit data quickly, securely,
and accurately over the same or different networks. Network devices are available for both inter-
network and intra-network use. The most common network devices are modems, RJ-45 connectors,
Ethernet cards, hubs, switches, routers, gateways, etc.

12. What is the purpose of a repeater?


Ans. A repeater is an electronic device that amplifies incoming signals. It regenerates the signals to a
higher level so that they can be transmitted over long distances. In transmission networks, repeaters
are used to regenerate distorted analog or digital signals caused by transmission loss.

13. What is the difference between a router and switch?


Ans. A router is a network device that connects multiple networks irrespective of their protocol. A
router forwards data packets from one connected network to another using their IP addresses.
A Switch is an intelligent device that connects several nodes to form a network and redirects the
received information only to the intended node(s).
14. What is a Wi-Fi card?
Ans. Wi-Fi cards (or wireless adapters) allow devices to connect to a wireless network.

15. What is the Network Interface Card (NIC)?


Ans. An NIC is a device that enables a computer to connect to a network and communicate. Any
computer which has to be a part of a computer network must have an NIC (Network Interface Card /
Unit) installed in it. Now a days, in most of the PCs and the laptops, NIC is an integral part of the
motherboard.

16. What is the difference between wireless NIC and Ethernet NIC?
Ans. Wireless NICs rely on an antenna to communicate through radio frequency waves on a Wi-Fi
connection. Wired NICs rely on an input jack and a wired LAN technology, such as the most popular
one, Ethernet. It may connect via USB.

B. Long answer type questions.


1. Write a short note on ARPANET.
Ans. ARPANET stands for Advanced Research Projects Agency NET. ARPANET was the first network
that consisted of distributed control. It was first to implement TCP/IP protocols. It was the beginning
of the internet with use of these technologies.

2. Explain the working of the internet.


Ans. The internet is a telecommunication and data transfer system that lets a group of autonomous
computers to communicate across a range of media. It works based on a packet routing network
that follows the TCP/IP. TCP/IP ensures the transmission across the internet is consistent and
reliable, regardless of the device or location.

3. What are the different types of transmission media?


Ans. Transmission media refers to the physical path that carries information in the form of
signals/bits and travels from one place to another. It can be divided into two categories:
Wired/Guided Media: It is a transmission medium that transmits the data using physical path from
one device to another.
Wireless/Unguided Media: It does not require the establishment of a physical link between two or
more devices interacting wirelessly.

4. Describe the role of IP address.


Ans. A device on the internet or a local network is identified by its IP address, which must be
unique. The internet protocol is a set of rules that governs the format of data sent over the internet
or a local network. It is a method of determining a user's unique identity.

5. What are the different types of switching techniques?


Ans. There are three types of switching techniques.
• Circuit switching: In this technique, a dedicated path is maintained between both ends until
the connection is terminated.
• Packet Switching: The routing of data in discrete quantities called packets, each with a
specified format and maximum size, is known as packet switching.
• Message Switching: It is also known as store and forward technique. A message is received
by an intermediary device in the switching office, which stores it until the next device is
ready to receive it.

6. Learn Together is an educational NGO. It is setting up its new campus at Jabalpur for its web-
based activities.
a. Suggest a cable layout of connections between the compounds.
b. Suggest the most suitable place (i.e., compound) to house the server for this NGO. Also, provide
a
suitable reason for your suggestion.
c. Suggest the placement of the following devices with justification:
i. Repeater ii. Hub/Switch
Ans .
a. Suggested cable layout is shown below.

b. The most suitable place to house the server is Training Compound as it has maximum
number of computers.
c. i. As per the suggested layout, the repeater needs to be placed between Training
Compound and the Finance Compound as distance between these compounds is 100m.
ii. Hub/Switch needs to be installed in all the compounds as it is required to form the
network.

7. The Institute of Distance Learning, Pune, is planning to go for networking of four wings for
better interaction.
a. Suggest the type of networking (LAN, MAN, WAN) for connecting Library Wing to Admin Wing.
Justify your answer.
b. Suggest the most suitable place (i.e., wing) to house the server with a suitable reason.
c. Suggest the placement of the following devices with reasons.
i. Repeater ii. Switch
d. The institute is planning to link its study center situated in Delhi. Suggest an economic way to
connect it with reasonably high speed. Justify your answer
Ans.

a. Since, the distance between Library Wing and Admin Wing is small. So, type of networking is
LAN.
b. Since, maximum number of computers are in Student Wing, so suitable place to house the
server is Student Wing.
c. i. Repeaters should be installed between Student Wing and Admin Wing and between
Student Wing and Admission Wing as the distances are <= 100 m.
ii. Switch should be installed in each wing to connect several computers.
d. Broadband connection as it is economical with high speed.

8. Explain the following:


a. Bus topology b. Star topology c. Tree topology
Ans.
a. Bus Topology: All the computers and network devices are connected by a single cable, called
the bus using interface connectors.
b. Star Topology: All the network devices and computers are separately connected to a central
device (hub, router, or switch).

c. Tree Topology: All the nodes are connected in a hierarchical manner. It is a typical network
topology that combines the benefits of both the bus and star topologies.

Chapter-7: Internet Technologies

Section B: Unsolved Questions


A. Short answer type questions.
1. What is the internet?
Ans. The internet is a global or international network of computer networks, which are
interconnected together to exchange data and information worldwide. It uses some set of rules and
procedures known as protocols, to control timing and data transfer format between the sender and
receiver.

2. What is the full form of WWW? Explain the term also.


Ans. WWW stands for World Wide Web, commonly known as the Web, is an information system
where documents and other web resources are identified by Uniform Resource Locators (URL),
which may be interlinked by hyperlinks, and are accessible over the internet.

3. Explain web hosting and its types.


Ans. Web hosting is the service that makes the website available to be viewed by others on the
internet. A web host provides space on its server, so that the other computers around the world can
access the website by means of an internet connection.

4. What is a web server?


Ans. A web server is a computer that accepts requests via HTTP to store, process, and deliver web
pages to the users.

5. What is an email?
Ans. Electronic mail (email) is a computer-based application for the exchange of messages between
users. A worldwide email network allows people to exchange email messages very quickly. Email is
the electronic equivalent of a letter, but with advantages in timeliness and flexibility.

6. What is a browser? Name any two browsers.


Ans. A web browser is an application software that acts as a bridge between the user and the
internet. For example: Internet Explorer, Google Chrome, Safari, etc.

7. Explain the following terms:


a. Home page b. Web page
Ans.
a. Home page: The home page of a website is its initial page. It is a web page that contains link to
other web pages. A homepage is a first page that is loaded into a browser when a website is opened.
b. Web page: A web page is typically a component of a website and may include text that is
organised into paragraphs, lists, tables, audio, video, and various forms of multimedia assets that are
displayed to the internet users in an attractive and easily accessible manner.

8. What is the difference between Cc and Bcc in email?


Ans. Cc stands for Carbon Copy and Bcc stands for Blind Carbon Copy. In Cc, all the email addresses
of the persons to whom a copy of the mail needs to be sent are specified. The e-mail addresses
mentioned in the Cc field are visible to all the recipients of the mail. Bcc field can also be used to
send a copy of the mail to several people, but the e-mail addresses mentioned in this field are not
visible to other recipients of the mail.

9. Name a few common domain names.


Ans. Some common domain names or extensions are as follows:
Domain Purpose
.com commercial
.in India
.org organisation
.net network
.int international organisations
.edu education
.gov national and state government agencies
.mil military

10. What are cookies?


Ans. A cookie is a piece of information from a website that is saved in a web browser for subsequent
retrieval by the website. Cookies are used to let a server know whether visitors have visited a
specific website again or not. A cookie gives information and enables the website to display
customised settings and tailored content when users return.

B. Long answer type questions.


1. Discuss the structure of an email message.
Ans. There is a standard structure for emails. Email contents are primarily classified as two, the
header and the body. The following contents come under the two subparts.
• Header: The email header gives us common details about the message such as the unique
identity of the message. The details of the users of the 'from' and 'to' ends are also stored
here. The email header consists of the following parts. However, the exact contents of the
header can vary according to the email systems that generate the email message.
a. Subject: The Subject field indicates the purpose of e-mail.
b. Sender (From:): This field describes the 'from' address of the email. This will specify the
sender's email address. Usually, it will be the “reply-to” address.
c. Date and time received (On): This is the date and time the message received.
d. Recipient email address
To: This field consists of the address to whom the message has to be sent. This is mandatory.
CC: Short for carbon copy. This is optional. The people who were mailed copies of the
message. The recipients of the message will know to whom all the copies have been sent.
BCC: Its stands for Blind Carbon Copy. It is used when we do not want one or more of the
recipients to know that someone else was copied on the message. This is optional.
e. Attachments: Attachment contains files that the sender is sending, linked documents,
pictures, etc. along with an e-mail. This is also optional.

• Body: The email body is the main part of an email message. It contains the message's text,
images, and other data (such as attachments). This field could also include signatures or text
generated automatically by the sender's email system.
The email's body is distinct from its header, which contains control information and data
about the message (such as its sender, the recipient and the path an email took to reach its
destination).
2. Discuss the advantages and disadvantages of an email.
Ans. Emails provide faster and easy means of communication. One can send messages to any person
or to multiple people at any part of the world by just clicking mouse and at the same time.
Advantages of E-mail:
• Various folders and sub-folders can be created within inbox of email, so it provides
management of messages.
• Emails are very easy to filter. A user according to his/her convenience can prioritise the
email by specifying a subject of an email.
• Email is not just only for textual messages. One can send any kind of multimedia with email.
• Email can be sent at any hour of the day, thus ensuring timeliness of message.
• It is a secure and reliable method to deliver messages.
• It also provides facility for editing and formatting of textual messages.
• There is also a facility of auto responders in an email, i.e., to send automated emails with
certain text.
• To write an e-mail there is no need of any kind of paper, thus it is environment friendly.
Disadvantages of E-mail:
• It is a source of viruses. Viruses can harm one's computer and read out user's email address
book and send themselves to a number of people around the world.
• It can be a source of various spams. These spam mails can fill up inbox and the deletion of
these mails consumes a lot of time.
• It is an informal method of communication. The documents those require signatures are not
managed by an email.
• To use the facility of an email, users must have access to the internet and there are many
parts of the world where people do not have access to the internet.
• Users have to check their inbox from time-to-time to keep themselves updated.

3. What is chatting?
Ans. Chatting is a text-based online conversation using an any app or IM (Instant Messaging)
software. It is a utility through which many people can connect with one another and talk about
their shared interests. Instant messaging is also possible between two people using the same chat
software. When a message is to be sent, the sender types it and transmits it; the recipient receives
it, reads it, and responds. It all takes place in real time as if the sender and receiver were seated
nearby. The chat participants must use the same chat application and be online at the same time in
order for immediate conversation. However, the sender can send the message and the receiver can
read it later as well. Message can comprise of pictures, documents, audio, and video files, etc.
depending on the chat software used. Communication via a video call or an audio call is also
possible. Additionally, group chats can also be conducted. Instant messengers include applications
like WhatsApp, Slack, Skype, Hangouts, Facebook Messenger, etc. Some of these applications enable
instant messaging in text, audio, and video formats.

4. Explain the difference between static website and dynamic website.


Ans.
Static website: A web page which displays same kind of information whenever a user visits it is
known as a static web page. A static web page generally has .htm or .html as extension. A static
website stores each page as a single HTML file, which is sent directly from the server to the static
webpage requested by the user in its entirety. This content effectively merges with the web page's
design and cannot be changed until the original HTML file is modified at the source code level. One
of the most important aspects of a static site is that every user receives and views exactly the same
content.

Dynamic website: An interactive web page is a dynamic web page. A dynamic web page uses
scripting languages to display changing content on the web page. Such a page generally has .php,
.asp, or .jsp as extension. In a dynamic website, the content can change depending on who is viewing
it. The web server does not just retrieve and send a dynamic web page when one is requested; it
may carry out some extra operations prior to providing the requested web page, such as retrieving
data from a database, changing the date and time, updating the weather information, etc. The
content of these web pages is regularly changed.

5. Seema and Rekha want to share some text messages, video, and images. They agreed to share
the content using an instant messaging service. Do they need to be online at the same time? Also,
suggest them some IM software and chatting applications.
Ans. They do not need to be online at the same time. Examples of some Instant messengers and
chatting applications are WhatsApp, Slack, Skype, Hangouts, Facebook Messenger, etc.

6. What is the purpose of cookies?


Ans. Cookies are used to let a server know whether visitors have visited a specific website again or
not. A cookie gives information and enables the website to display customised settings and tailored
content when users return.

7. Explain the different types of web hosting.


Ans. The different types of web hosting available are:
• Free Web Hosting: Free web hosting is best suited for personal websites which have short,
low-traffic. It is not suggested for use in high-traffic areas or in real-world situations. The
availability of technical support is frequently limited, and technological alternatives are
limited. Some internet service providers provide free web hosting.
• Shared Web Hosting: Shared hosting, also known as shared services or virtual hosting, is
when several websites share the same server, lowering costs for everyone. Most web
hosting firms offer shared hosting. Although shared hosting is a less expensive option for
businesses to establish a web presence, it is typically insufficient for high-traffic websites.
• Dedicated Hosting: Dedicated web hosting gives access to a whole server's resources and
capabilities, which are not shared with anybody else. With a dedicated server dedicated
solely to specific website(s), there is ample bandwidth and memory to manage massive
quantities of traffic as well as any type of multimedia or interactivity.
• Cloud Hosting: Cloud hosting is another type of hosting. The primary concept of cloud
hosting is "Divide and Rule," which means that the resources needed to
• operate a website are distributed among multiple web servers and rendered as needed. This
drastically lowers the risk of any downtime in the event of a server failure.

8. What is a web server? Explain some web services.


Ans. A Web Server is simply a computer with an Internet connection that runs software designed to
send out HTML, DHTML, XML or Java based pages and other file formats (such as multimedia files) as
per the user request. A web server is made up of a physical server, an operating system (OS), and
software that allows HTTP communication to take place. Numerous websites can be hosted on a
single web server, or a single website can be hosted on multiple linked or mirrored web servers.
Some of the web services are:
• E-Mail
• WWW
• GOPHER
• Usenet
• WAIS
• ARCHIE

9. What are plugins? Explain their purpose.


Ans. A plugin is a software add-on that is installed on a program, enhancing its capabilities. For
example, to watch a video on a website, a plugin is needed to play the same. If the plugin is not
installed, browser will not understand how to play the video. Firefox automatically downloads and
installs the OpenH264 plugin for video calls as well as the Google Widevine CDM for viewing content
protected by Digital Rights Management (DRM).

10. What is a URL? Explain the components of a URL.


Ans. Uniform Resource Locator is abbreviated as URL. The protocol identifier is the first part of the
URL, it determines the protocol to use, whereas the resource name is the second part, and it
identifies the IP address or domain name where the resource is located. The protocol, domain name,
and domain extension are all part of the URL.

11. What is VoIP? How is it useful?


Ans. VoIP stands for Voice over Internet Protocol. It allows user to make voice communication over
the internet. Instead of using traditional telephone lines, the data is transferred digitally in packets
across the Internet Protocol (IP). This allows users to communicate over great distances and across
the globe without incurring long distance or international phone expenses. The most common VoIP
protocols used are TCP, SIP, and H.323.

12. Explain the following terms:


a. Web Server b. Web Browser c. Website d. Web Page
Ans.

a. Web Server: A web server is a computer that accepts requests via HTTP to store, process, and
deliver web pages to the users.

b. Web Browser: A web browser is an application software that acts as a bridge between the user
and the internet. For example: Internet Explorer, Google Chrome, Safari, etc.
c. Website: A website is a collection of related web pages that may be viewed by going to the home
page in a browser. An individual, a company, or an organisation owns and manages each site. The
address of a company's or an individual's home page shows how to get to their website. All the other
pages are accessible from the home page. For example, the home page address of KIPS website is:
https://www.kips.in. The address for KIPS's home page links to many web pages.

d. Web page: A web page is typically a component of a website and may include text that is
organised into paragraphs, lists, tables, audio, video, and various forms of multimedia assets that are
displayed to the internet users in an attractive and easily accessible manner.

Chapter-8: Society, Law, and Ethics-I

Section B: Unsolved Questions


A. Short answer type questions.
1. Define digital footprint.
Ans. Digital footprints are the records and traces individuals leave behind as they use the Internet,
including posts, queries, photographs, emojis, likes, and the deleted posts. Digital footprints are
permanently stored.

2. What are netiquettes?


Ans. Netiquette is a combination of two words, “Net” + “Etiquette”. It refers to the polite and
respectful behaviour while using the internet. Email, social media, online chat, web forums, website
comments, multiplayer gaming, and other forms of online communication are all included in this
category. While there is no formal list of netiquette rules or principles, the overall concept is to treat
others with respect when using the internet.

3. Write a short note on the responsibilities of a digital citizen.


Ans. Responsibilities of a good digital citizen are:
• Follow the rules and act in a manner that is acceptable and appropriate while
communicating online.
• Treat others with civility and respect as would like to be treated.
• Communicate respectfully with target audience.
• Be considerate when posting something on a social networking platform.
• Follow cyber safety guidelines before publishing anything.

4. What is the difference between copyright and patent?


Ans. Copyright is a form of Intellectual Property Rights (IPR) concerned with protecting works of
human intellect. The domain of copyright is literary and artistic works, might that be writings,
musicals and works of fine arts, such as paintings and sculptures, as well as technology-based works
such as computer programs and electronic databases.
Patent is an exclusive right granted by law to an inventor or assignee to prevent others from
commercially benefiting from his/her patented invention without permission, for a limited period of
time in exchange for detailed public disclosure of patented invention.

5. What is IPR and its different types.


Ans. Intellectual property rights (IPR) are the rights of the owner of information to decide how much
information is to be exchanged, shared or distributed; and to decide the price for doing
(exchanging/sharing/distributing) so. The IPR exist to safeguard human's intellectual
accomplishments. These endeavours can be preserved both on a national and international level.
IPR provide a framework and policy for protecting creative works.
The different types of IPR are:
• Copyright: Copyright is a form of IPR concerned with protecting works of human intellect.
The domain of copyright is literary and artistic works, might that be writings, musicals and
works of fine arts, such as paintings and sculptures, as well as technology-based works such
as computer programs and electronic databases.
• Patent: Patent is an exclusive right granted by law to an inventor or assignee to prevent
others from commercially benefiting from his/her patented invention without permission,
for a limited period of time in exchange for detailed public disclosure of patented invention.
• Trademark: A trademark is a sign that individualizes the goods or services of a given
enterprise and distinguishes them from those of competitors. To fall under law protection, a
trademark must be distinctive, and not deceptive, illegal or immoral.

6. What is IPR Infringement?


Ans. Intellectual Property Infringement refers to the infringement of protected intellectual property
rights. If a work that is protected by IP laws is duplicated, used, or exploited without owner's
consent, IP rights may have been violated. There are three types of IPR violations:
• Plagiarism
• Trademark Infringement
• Copyright Infringement

7. What is ransomware?
Ans. Ransomware is a type of extortion virus that locks a user's computer and refuses access to
information unless a ransom is paid. It is a huge hazard to both individuals and businesses.
Ransomware encompasses virus and Trojan attacks that can wipe out files and the entire system.

8. What are Open Source Software?


Ans. OSS refers to open source software, which refers to software whose source code is available to
customers and it can be modified and redistributed without any limitation. An OSS may come free of
cost or with a payment of nominal charges that its developers may charge in the name of
development, support of software

9. Write a short note on Identity theft.


Ans. Identity theft is a type of fraud that involves using someone else's identity to steal money or
gain other benefits. Online identity theft refers to an act of
stealing someone's personal information such as name, login details etc. and then posing as that
person online.
Following are some common identity thefts:
• Criminal Identity Theft
• Medical Identity Theft
• Social Identity Theft
• Synthetic Identity Theft
• Financial Identity Theft
10. What is cybercrime?
Ans. Any criminal offense that is facilitated by, or involves the use of, electronic communications or
information systems, including any electronic device, computer,
or the Internet is referred to as Cybercrime. Some examples of cybercrime are cyber bullying, cyber
stalking, cyber terrorism, phishing, credit card frauds, illegal downloading, industrial espionage, child
pornography, creation and/or distribution of viruses, spam, etc.

B. Long answer type questions.


1. Explain cyberbullying by giving an example.
Ans. Harassing, demeaning, embarrassing, defaming or intimidating someone using modern
technologies like Internet, cell phones, instant messengers, social networks, etc., is called Cyber
Bullying. Cyberbullying is a crime, garnering such criminal charges as harassment, libel, assault, and
even terrorism. In addition to criminal charges, cyberbullies may be held responsible for the damage
they do in a civil lawsuit, where they may be ordered to pay for it. Cyber trolling, which means
posting of sarcastic-, demeaning- or insulting- comments about someone, is also considered form of
cyber bullying.

For example: Nandita has recently shifted to new city and new 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, school site's forum, etc. Nandita has become a victim of
cyber bullying.

Some more examples of cyberbullying behaviour are:


• Using inappropriate language and hurtful messages in emails, texts, or instant messaging.
• Sending harassing messages to a person.
• Spreading internet rumours or slander about someone.
• Making fun of someone in a group of people on a social media site.
• Threatening someone by text message or online.
• Taking and sharing an embarrassing photo or video without permission.

2. What is phishing? How is phishing different from spam emails?


Ans. It is the criminally fraudulent process of attempting to acquire sensitive information such as
usernames, passwords, credit card information, account data etc. In Phishing, an imposter uses an
authentic looking email or web-site to trick recipients into giving out sensitive personal information.
For instance, a user may receive an email from bank (which appears genuine) asking to update user's
information online by clicking at a specified link. Though it appears genuine, it may be taking the
user to a fraudulent site where all of user's sensitive information is obtained and later used for
cyber-crimes and frauds.

Spamming refers to the sending of bulk-mail by an identified or unidentified source. In non-malicious


form, bulk advertising mail is sent to many accounts. In malicious form (e.g., e-mail bombing), the
attacker keeps on sending bulk mail until the mail-server runs out of disk space.

Spam is unsolicited email, instant messages, or social media messages and are generally sent in bulk.
These messages are fairly easy to spot and can be damaging if opened or responded. Phishing is an
email sent from an Internet criminal disguised as an email from a legitimate, trustworthy source.

3. What is eavesdropping? What are the different types of eavesdropping?


Ans. Unauthorised monitoring of other people's communications is called Eavesdropping.
Eavesdropping is the most common attack in wireless communication. It is also known as a sniffer or
snooping attack. It happens when an electronic device steals information being carried over a
network. Hackers spy on online discussions. Malicious programmers take advantage of weak or
unprotected networks to steal data when transferring data between two devices over the internet.

There are two types of eavesdropping attacks:


• Active Attack: In this, an attacker tries to modify the content of the messages.
• Passive Attack: In this type of attack, an attacker observes the messages, copies it, and may
use it for malicious purposes.

4. Explain plagiarism. How you can protect yourself from plagiarism?


Ans. Plagiarism is stealing someone else's intellectual work and representing it as own work without
citing the source of information or obtaining permission from the original work's owner. It can be an
idea, literary work or academic work, etc.

To avoid plagiarism, one needs to be cautious and follow certain steps:


• Always give credits or quote the source or the person if their work is copied.
• Paraphrase or cite other's speech, written or spoken words, etc. in written or verbal work.
• If any image, poem, article or any published material is picked, then cite the origin of work
or media.

5. What are licenced software? Explain by giving suitable examples.


Ans. A software licence is a document that provides legally binding guidelines to the person who
holds it for the use and distribution of software. It typically provides end users with the right to
make one or more copies of the software without violating copyrights. It also defines the
responsibilities of the parties entering into the licence agreement and may impose restrictions on
how the software can be used. Software licencing terms and conditions usually include fair use of
the software, the limitations of liability, warranties, disclaimers, and protections.

Open Source Licence allows software to be freely used, modified, and shared. It has been approved
by Open Source Initiative (OSI). Some of the popular open source licences are:

• Apache Licence 2.0: The Apache Licence is a free and open source software (FOSS) licensing
agreement from the Apache Software Foundation (ASF). This licence explicitly grants rights
to the users that can be applied to both copyrights and patents.
• Creative Commons: Creative Commons is a non-profit organisation that provides a free,
straightforward, and standardised means for individuals and organisations to award
copyright permissions for creative and academic works.
• GPL: The GPL is one of the most widely used open source licences. It provides funds and
privileges to open source project creators. Owners of the programs may sell copies or
distribute them for free under the GPL terms. Digital resources can also be modified by the
owners.

Chapter-9: Society, Law, and Ethics-II

Section B: Unsolved Questions


A. Short answer type questions.
1. 1. Write the full form of VIRUS, ICT, and EEE.
Ans. VIRUS: Vital Resources Under Seize
ICT: Information and Communication Technology
EEE: Electrical and Electronic Equipment

2. Write the difference between Trojan horse, virus, and worms.


Ans. TROJAN HORSE: A Trojan horse is a computer program which carries out malicious operations
without the user's knowledge. Like a virus, a Trojan horse is a piece of harmful code placed within a
healthy program (like a false file-listing command, which destroys files instead of displaying the list).
VIRUS: Virus is a malicious program that damages data and files and causes harm to computer
system.
WORM: A worm is a self-replicating program which eats up the entire disk space or memory. A
worm keeps on creating its copies until all the disk space or memory is filled.

3. What is antivirus software? Give examples.


Ans. Antivirus software are utility software that work against not only viruses but also against almost
all kinds of malware. If the software is not able to remove the virus, it is neutralized. The antivirus
keeps a watch on the functioning of the computer system. If a virus is found it may alert the user,
flag the infected program or kill the virus. Some of the popular antivirus software are: Avast, AVG
Antivirus, Kaspersky, McAfee, Norton, etc.

4. Why was the Information Technology Act 2000 enacted?


Ans. The Information Technology Act of 2000, often known as the IT Act, was enacted in 2000. The
bill was approved during the 2000 budget session and signed by then-President K. R. Narayanan on
June 9, 2000, and it came into force on October 17, 2000. In India, it deals with cybercrime and e-
commerce. The major goal of this Act is to carry out legal and reliable electronic, digital, and online
transactions, as well as to limit or reduce cybercrime. This Information Technology Act is based on
the United Nations Model Law on Electronic Commerce (UNCITRAL Model) of 1996, which was
proposed by the United Nations General Assembly in a resolution dated January 30, 1997. It is India's
most important law dealing with cybercrime and electronic commerce. The Information Technology
Act of 2000 legitimises activities using electronic data transmission and other forms of electronic
communication, as well as electronic business transactions.

5. How can you ensure that a website address is secure?


Ans. Check for "https" at the beginning of the URL or the little lock icon in the web address bar to
see if a site is safe. These symbols indicate that the site is encrypted, which means that user visit will
not be intercepted by another computer. If these security signs are not there, then do not share
sensitive personal information, such as banking information on that site.

6. What is the importance of installing antivirus software on a computer?


Ans. Installing and regularly updating an antivirus software that includes internet security, provides
protection against threats such as viruses, Spyware, and PC intrusion, and is vital for proper
protection against the hackers, intruders, and other wrongdoers.

7. What do you mean by an identity theft?


Ans. Identity theft is a type of fraud that involves using someone else's identity to steal money or
gain other benefits. Online identity theft refers to an act of stealing someone's personal information
such as name, login details etc. and then posing as that person online.
Following are some common identity thefts:
• Criminal Identity Theft
• Medical Identity Theft
• Social Identity Theft
• Synthetic Identity Theft
• Financial Identity Theft

8. What do you know about the contribution of project Greene of the government of India in
handling e-waste?
Ans. The programme aims to create effective awareness in various levels (of society) to reduce the
adverse impact on environment and health arising out of the polluting technologies used in recycling
e-waste in the unorganized sector. During the project duration of 5 years, a city in each of the 10
identified states viz. Madhya Pradesh, Uttar Pradesh, Jharkhand, Orissa, Goa, Bihar, Pondicherry,
West Bengal, Assam and Manipur will be covered. The activities will include organising awareness
workshops for RWAs/Localities, Schools, Colleges, Bulk Consumers (including corporate & Govt.
sectors), Informal Sector, Dealers, Refurbishers, Manufacturers, etc. so as to build capacities of the
target groups to channelize e-waste in a manner that the rules are effectively implemented. Suitable
course curriculum would also be framed for schools/colleges. Effort would be made to prepare the
content in local language. This project will also stress on adopting best practices for e-waste
recycling available globally, so that the unorganised sector can generate jobs as well as viable
business prospects thereby mitigating the impact of improper recycling on the environment. The
project will also emphasize on the responsibilities of the producers and covey the message that they
must inculcate the principle of Extended Producer Responsibility (EPR) and follow the mechanism for
channelisation of e-waste from 'end of life' products to registered dismantlers or recyclers.

9. How can you report cybercrime in India?


Ans. The Indian government launched the cybercrime.gov.in service to make it easier for victims and
complainants to lodge cybercrime concerns online. One can also go to the crime cell in person and
file a report about cybercrime. In every city, cybercrime cells are located to register complaints and
gather evidence for future investigation.

10. What types of challenges are faced by people with impairments while using computers? Which
tools are used to assist them?
Ans. Types of challenges faced by people with impairments while using computers are:
1. Unavailability of Teaching Materials/Aids for students with different disabilities. For
instance, visually challenged students would want that there are screen readers that could
read the digital content to them; also programming lessons should not involve visual inputs
(e.g., in classes 9-10 there are two alternatives for programming concepts: Python for
visually impaired students and Scratch for others). Similarly, hearing impaired students
would want more of visual input than oratory, rather oratory instructions should be
available in sign language if possible. A lot of children, not all, with locomotor disabilities are
both keyboard disabled and mouse disabled; however, they can use virtual keyboards for
writing computer programs. For virtual keyboards supporting such students, special
hardware is required. For low-vison students, Braille keyboards, Braille monitors, and Braille
printers along with screen readers should be made available to facilitate their learning and
working on computers. Unavailability of such supportive programming aids and software are
a big issue that must be handled by schools and their managements.

2. Lack of Special Needs Teachers: For different types of special needs, if special needs teachers
are available, disabled students get their needs addressed in right manner e.g., for hearing
impaired students, a teacher who is able to converse in sign language would be able to
convey and explain the study material than traditional methods. There should be teachers
who know what types of hardware, software, tools etc. can be used for the differently able
students as per their specific needs, e.g., special types of specialized hardware such as Braille
keyboards, monitors, printers, synthetic speech generators, etc., software assistants such as
Google assistant, etc.

3. Lack of Supporting Curriculum: Curriculum should be designed while keeping focus on


inclusive education. There should be possible alternatives keeping in mind special needs of
the students. Software and programs should be so used so that the disabled students can
easily work on that. For example, office software-based curriculum can easily be
implemented for all types of students as nearly all office software provide accessibility
features. Similarly, a programming language that requires manual code typing, such as
Python, can also be used for teaching programming as long as specialized editors are also
available, but Scratch, the block-based programming language should not be used as it lacks
accessibility features. Further, the computer science contents and programming contests
should be so conducted so that all types of students can participate in them, inclusively.

B. Long answer type questions.

1. How will you report cybercrime in India?


Ans. Government of India launched the cybercrime.gov.in service to make it easier for victims and
complainants to lodge cybercrime concerns online. Women and children can use this portal to report
cybercrime or contact their local police. Law enforcement agencies/police deal with complaints
received on this portal based on the information provided in the complaints. It is critical to submit
complete and accurate information when making a complaint in order to receive rapid attention.
Victim(s) can also go to the crime cell in person and file a report about cybercrime. In every city,
cybercrime cells are located to register complaints and gather evidence for future investigation.
Under the Information Technology Act of 2000, they are solution providers for combating and
addressing cybercrime.
2. Write a short note on E-waste Management.
Ans. Electronic waste or e-Waste describes discarded electrical or electronic devices. “Electronic
waste” may also be defined as discarded computers, office electronic equipment, entertainment
device electronics, mobile phones, television sets and refrigerators. This includes used electronics
which are destined for reuse, resale, salvage, recycling, or disposal. Of all the different types of
waste, electronic waste has the characteristics of:
• the fastest growing segment of waste
• most valuable due to its basic composition
• very hazardous if not handled carefully

E-waste management process deals with proper disposal and recycling of various types of e-waste
such that it does not pose any health risks to people and saves the environment while also
producing useful products from trash. The environment, human health, and the accomplishment of
the Sustainable Development Goals (SDGs) set by the United Nations (UN) are all threatened by
exponentially growing quantities of e-waste and inappropriate disposal and deconstruction
methods. All around the world, people are devoting resources to achieve a sustainable future.
Global e-waste management and legislation might assist to mitigate the dangers of e-waste and are
the greatest way to achieve long-term development.

3. Write a short note on gender and disability issues faced while teaching and using computers.
Ans. The Gender issues while teaching /using computers are: under representation of girls, and not
girl-friendly work-culture.
Disability issues while teaching are: unavailability of teaching materials/aids, lack of special needs
teachers and lack of supporting curriculum.
People with impairments confront a number of challenges when it comes to using computers. These
barriers can be grouped into three functional categories:
• Barriers to providing computer input
• Interpreting output
• Reading supporting documentation
4. Why is it important to dispose electronic gadgets effectively?
Ans. The disposal of electronic gadgets or e-Waste and proper recycling is very much necessary and
important for the benefit of people, environment, and the nation. The major benefits are:
• Valuable precious metals can be recovered. Most consumer electronics contain valuable
materials like copper, gold, and zinc that can and should be recycled.
• Health benefit: E-waste contains a variety of toxic substances, which may include lead,
mercury and cadmium. When e-waste is disposed into landfills, these toxins can be released
into the atmosphere or leak in through the land and have negative health and
environmental effects.
• Generation of Jobs: Recycling e-waste domestically creates jobs for professional recyclers
and creates new markets for the valuable components that are dismantled. Save the
environment and assist the economy by establishing additional e-waste recycling facilities
and current agencies hiring more people for reprocessing.
• Reduce pollution: Mining produces toxic waste, which are linked with crop devastation and
human health crisis due to water contamination. Hence, pollution on land, water, and air
can be reduced by recycling e-waste.
• Reduce landfill: E-waste is a growing waste stream. Recycling these items will help conserve
landfill space.
• Save natural resources: By recovering and reusing items, e-waste management helps to
minimise pollution, save resources, and save energy.

5. What are the different ways to keep your data confidential?


Ans. There are number of ways through which confidentiality of data can be maintained:
• Encryption: Data can be encrypted and made unreadable for unauthorised users. The data is
changed using a secret key (an encryption key), and the modified data can only be read with
another secret key (decryption key). It encrypts and transforms sensitive data, such as credit
card information, into unreadable cipher text. It can be read only by decrypting the
encrypted data.
• Access Control: Restrict access to a system or to physical or virtual resources by
implementing some rules and regulations. It is the procedure through which users are
allowed access to systems, resources, or information, as well as specific rights. Users must
submit credentials such as a person's name or a computer's serial number before being
granted access in access control systems.
• Authentication: Validate a user's identity and position through an authentication procedure.
Authentication is a need for all businesses because it allows them to safeguard their
networks by allowing only authenticated users to access protected information. These
resources may include computer systems, networks, databases, webpages, and other
network-based applications or services.
• Authorisation: Authorisation is a security mechanism that carries out a certain operation.
Based on an access control policy, it determines whether a person or system has access to
resources such as computer programs, files, services, data, and application features. It is
usually followed by authentication, which verifies the user's identity. System administrators
are often granted permission levels that cover all system and user resources. During
authorisation, a system checks an authenticated user's access rules and either grants or
refuses resource access.
• Physical Security: Physically safeguarding IT assets such as premises, equipment, employees,
resources, and other things against unwanted access. It guards against physical dangers such
as theft, vandalism, fire, and natural disasters.

You might also like