Informatics Practices Book 12 Answer Key
Informatics Practices Book 12 Answer Key
Book 12
Answer Key
Chapter-1 Python Pandas
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
Ans.
Output:
0 8
1 16
2 24
dtype: int64
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])
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])
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
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
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
Output:
a 15.0
b 6.0
c 3.0
d 10.5
e 9.0
dtype: float64
Output:
a Atharva
b Seema
c Yashica
d NaN
Name: name, dtype: object
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
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
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
Output:
Original Data Series:
0 100
1 200
2 python
3 300.12
4 400
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)
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
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
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)
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)
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
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
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)
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
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:
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
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")
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.
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.
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:
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;
e. Select Name
from Hospital
where Sex='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
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'.
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
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.
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.
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.
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.
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.
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.
• 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.