0% found this document useful (0 votes)
139 views143 pages

IP Notes Class 12th 2024-25

Uploaded by

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

IP Notes Class 12th 2024-25

Uploaded by

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

KENDRIYA VIDYALAYA SANGATHAN,BHOPAL REGION

HST- 2024-2025

BHOPAL
OFFICE
REGIONAL

VIENOSNGATNK

ANDO
AC
BRAR
Date

CLASS XII -STUDY MATERIAL

INFORMTICS PRACTICES
212HD Patrons

Dr. R.
Senthil Kumar, Deputy Commissioner
KVS Regional Office, Bhopal

oftaci Noft sia

ftacft foraen asfàren


Content Coordinator
ShriRajesh Sahu, Principal
PMSHRI Kendriya Vidyalaya Narmadapur

Mr. Sandeep Jain Mr. Jitesh Thorat


PGT Computer Science PGT Computer Science
PMSHRIKendriya Vidyalaya PMSHRI Kendriya Vidyalaya
Narmadapuram Raisen

CONTENT TEAM
BAIRAGARH HEMANT SONI
BARWANI Abha Jain
BETUL YASHDEV HADA
BHOPAL No.2 Shikha Chourasia
BHOPAL No.3 Sabra Khan
BINA Mr Rajesh Babu Kushwaha
SEONI MALWA Mrs. Kirti Asrekar
UJJAIN RAHUL NAMDEO

GUNA Mrs SNEHLATA PAWAR

GWALIOR No.4 Sh.Vikas Saxena


BURHANPUR ARVIND GUPTA
KHARGONE SMT KALPANA CHOUHAN

Mandsaur MANISH JAISWAL


TEKANPUR HIMANSHUKHARE
Mhow MANISHA DUBEY
SEHORE Smt. BHARTI ARYA
SHEOPUR SACHIN PATEL

Final Design & Conpile


Lakhan Lal Bagwan
Malam Singh Kirar
INDEX
S Topic
No.

1 Curriculum for the Academic Year 2024-25

2 Data Handling using Pandas -I Introduction to Python librariesPandas,


Matplotib. Datastructures, Introduction to Python librariesPandas, Matplotlib,
Datastructures in Pandas Series and Data Frames.
3 Creation of Series from - ndarray, dictionary, scalar value; mathematical
operationsi Head and Tail functions:Selection, Indexing and Slicing.
-
4 Data Frames: creation from dictionary of Series, list of dictionaries, Text/CSV
files:display: iteration:
5 Operations on rows and columns: add, select, delete, rename; Head and Tail
functionsi Indexing using Labecls, Boolean Indexing
6 Importing/Exporting Data between CSV files and Data Frames.
7 Data Visualization Purpose of plotting;drawing and saving following types of plots
using Matplotlib - line plot, bar graph, histogram Customizing plotsi adding label,
title, and legend in plots.
8 Revision of database concepts and SQL commands covered in class XI
9 Database Query using SQL Math functions: POWER 0, ROUND 0, MOD 0. Text
functions: UCASE OUPPER 0, LCASE O/LOWER 0, MID 0/SUBSTRING
O/sUBSTR0, LENGTH 0,LEFT 0, RIGHT 0, INSTR 0, LTRIM 0, RTRIM 0,
TRIM 0.
10 Date Functions: NOW ), DATE ), MONTH 0, MONTHNAME 0, YEAR0, DAY 0,
DAYNAME 0.
Aggregate Functions: MAX 0, MIN 0, AVG 0, SUMO,COUNT 0; using COUNT ().
Querying and
manipulating data using Group by, Having, Order by.
Introduction to networks, Network Devices: modem, hub, switch, repeater, router,
11
gateway
12 Network Topologies: Star, Bus, Tree, Mesh
13 Introduction to Internet, URL, WWW, and its applications- Web, email, Chat.
VolP. Website:
Website: Introduction, difference between a ofwebsite and webpage, static vs
14 a website.
dynamic web page, web server and hosting
15 Web Browsers: Introduction, commonly used browsers, browser settings, addons
and plug-ins,cookies
16 Data protection, intellectual property rights(IPR), plagiarism,licensing and
copyright, free and open source software (FOSS). Cybercrime and cyber laws
hacking, phishing, cyber bullying, overview of Indian ITAct E-waste: hazards and
management. usage of technology
17 Awareness about health concerns related to the
10 Question Papers
1. Prerequisite: Informatics Practices -Class XI
2. Learning Outcomes
At the end of thiscourse, students will be able to:
Create Series, Data frames and apply various operations
Visualize data using relevant graphs.
Design SQL queries using aggregate functions.
Import/Export data between SQL database and Pandas.
Learn terminology related to networking and internet.
Identify internet security issues and configure browser settings.
Understand the impact of technology on society including gender and
disability issues.

3. Distribution of Marks and Periods


Unit Unit Name Marks Periods Periods Total
No Theory Practical Period
1 Data Handling using Pandas and 25 25 25 50
Data Visualization
2 Database Query using SQL 25 20 17 37

3 Introduction to Computer 10 12 12
Networks
4 Societal Impacts 10 14 14
Project 7 7

Practical 30

Total 100 71 49 120

4. Unit Wise syllabus


-
Unit 1: Data Handling using Pandas
Introduction to Python libraries Pandas, Matplotlib. Data structures in Pandas
Series and Data Frames.
Series: Creation of Series from - ndarray, dictionary, scalar value: mathematical
operations; Head and Tail functions; Selection, Indexing and Slicing.
Data Frames: creation - from dictionary of Series, list of dictionaries, Text/CSV files:
display: iteration; Operations on rows and columns: add, select, delete, rename: Head
and Tail functions, Indexing using Labels, Boolean Indexing:
Importing/Exporting Data between CSV files and Data Frames.

Data Visualization

Purpose of plotting, drawing and saving following types of plots using Matplotlib -line plot,
bar graph, histogram Customizing plots: adding label, title, and legend in plots.
Unit 2: Database Query using SQL
Revision of database concepts and SQL
XIMath functions: POWER (0.
commands covered in class
ROUND (). MOD (0.
Text functions UCASE (0/UPPER (). LCASE
()/LOWER 0. MID ()/SUBSTRING
(0/SUBSTR ),LENGTH 0, LEFT (). RIGHT (),
Date Functions: NOW (), DATE (). MONTH INSTR 0, LTRIM 0, RTRIM (), TRIM )
DAYNAME ().
MONTHNAME ), 0. YEAR 0. DAY ().
Aggregate Functions: MAX (). MIN (), AVG ().
SUM(). COUNT (). using COUNT (*)
Querying and manipulating data using
Group by, Having,Order by
Working with two tables
using equi-join
Unit 3:
Introduction to Computer
Networks
introduction to networks, Types of network: PAN, LAN, MAN,
WAN. Network Devices:
modem, hub, switch, repeater, router, gateway Network
Introduction to Internet, URL, WWW,
Topologies: Star, Bus, Tree, Mesh.
and its applications- Web, email, Chat, VolP.
Website: Introduction, difference between a website
page, web server and hosting a and webpage, static vs dynamic web
of website.
Web Browsers: Introduction, commonly used browsers,
and plug-ins, browser settings, add-ons
cookies.

Unit 4: Societal Impacts


Digital footprint, net
and communication
property rights (PR), plagiarism, licensing etiquettes, data protection, intellectual
software (FOSS). cybercrime and cyber and copyright, free and open source
laws, hacking, phishing. cyber bullying,
Overview of Indian IT Act.
E-waste: hazards and management.
Awareness about health concerns related to the usage of
technology.
Project Work
The aim of
the class project is to create tangible and
identify a useful IT application. The learner may
real-world problem by exploring the environment. e.g. Students can visit
shops/business places, communities or other organizations in
about the functioning of the organization, their localities and enguire
and how data are generated, stored,
managed.The learner can take data stored in cSv or and
database file and analyze using Python
iibraries and generate appropriate charts to visualize

Practical Marks Distribution


S. No. Unít Name
Marks
1
Programs using Pandas and Matplotlib
lco
8
2 SOL QUeries
7
3 Pracical file (minimumof 15 programs based on Pandas, 4
Matplotlib and 15 SQL queries must be included)
based on 5
4 Project VWork(using concepts learned in
class XI and XIl)
5
5 Viva-Voce
5
TOTAL 30

5. Suggested Practical List


5.1 Data Handling
1. Create a panda's series from a dictionary of values
and a ndarray
2. Given a Series, print all the elements that are above the 75th percentile
3. Create a Data Frame quarterly
sales where each row contains the item category, item
name, and expenditure. Group the rows by the category and print
the total
expenditure per category
4. Create a data frame for examination result and display row labels, column labels data
types of each column and the dimensions
5. Filter out rows based on different criteria such as
duplicate rows.
6. Importing and exporting data between pandas and CSV file

5.2 Visualization

1.Given the school result data, analyses the performance of the students on
different parameters, e.g subject wise or class wise.
2. For the Data frames created above, analyze, and plot appropriate charts with title
and
legend.
3. Take data of your interest from an open source (e.g. data.gov.in),
aggregate
and summarize it. Then plot it using different plotting functions of the Matplotlib library.
5.3 Data Management

1. Create a student table with the student id, name, and marks as attributes where
the student id is the primary key.
2. Insert the details of a new student in the above table.
3. Delete the details of a student in the above table.
4. Use the select command to get the details of the students with marks more than 80.
5. Find the min, max, sum, and average of the marks in a student marks table.
6. Find the total number of customers from each country in the table (customer
ID, customer Name, country) using group by.
7. Write a SQL query to order the (student ID, marks) table in descending order of
the marks.
STUDY MATERIAL
Pandas Series
like one-dimensional array capable of holding data of any type (integer, string, Tioat, Python
tis
objects, etc.). Series can be created using constructor.
Syntax pandas.Series( data, index, dtype, copy)
Creation of Series is also possible from -ndarray, dictionary, scalar value.
Series can be created using
1. Array
2. Dict
3. Scalar value or constant
Create an Empty Series
e.g.
import pandas as pseries
S=pseries. Series()
print(s)
Output
Series([),dtype: float64)
a
Create Series from ndarray without index
e.g.
import pandas as pd1
import numpy as np1
=
data np1.array(['a','b','c, d'])
S= pdl.Series(data)
print(s)
Output
1a
2 b
3c
4d
dtype: object
:
Note default index is starting from 0 with index position
e.g.
import pandas as p1
import numpy as np1
data = np1.array(['a','b', 'c','d')
s= p1.Series(data, index=[100,101,102, 103))
print(s)
Output
100 a
101 b
102 c
103d dtype:
object
Note :index is starting from 100
Create a Series from dict
Eg. 1(without index)
import pandas as pdl
import numpy as np1
data = (a' :0., 'b' :1,, 'c' :2.)
s= pd1.Series(data)
print(s)
Output
a 0.0
b1.0
c2.0
dtype: float64

Eg.2 (with index)


import pandas as pd1
import numpy as np1
data = ('a':0.,'b': 1., 'c:2.}
S= pd1.Series(data, index=('b','c, d',a])
print(s)
Output
b1.0
c2.0
d NaN
a 0.0
dtype: float64

Create a Series from Scalar


e.g
import pandas as pd1
import numpy as np1
s= pd1.Series(5, index=(0, 1, 2, 31)
print(s)
Output
05
15
25
35
dtype: int64
Note :- here 5 is repeated for 4 times (as per no of index)
Maths operations with Series
e.g.
import pandas as pd1
s= pd1.Series([1,2,3])
t= pd1.Series([1,2,4])
u=stt #addition operation print (u)
u=s*t #multiplication operation
print (u)
output
02
14
27
dtype: int64
01
14
2 12
dtype: int64
Head function
e.g
import pandas as pd1
s= pd1.Series([1,2,3,4,5], index = ['a','b','c'd','e'])
print (s.head(3)
Output
a 1

b. 2
c. 3
dtype: int64
Return first 3 elements
tail function
e.g
import pandas as pdl
S= pd1.Series([1,2,3,4,5], index =
['a',b';c,'d',' e'])
print (s.tail(3)
Output
c3
d. 4
e. 5
dtype: int64
Return last 3 elements

Accessing Data from Series with indexing and slicing


e.g.
import pandas as pd1
s= pd1.Series([1,2,3,4,5], index= ['a','b,'c','d'' e'])
print (s[O])# for 0 index position
print (s[:3]) #for first 3 index values
print (s[-3:]) # slicing for last 3 index values
Output
1
a. 1
b. 2
C. 3

dtype: int64 c3
d. 4
e. 5
dtype: int64
Retrieve Data Using Label as (Index)
e.g.
import pandas as pd1
=
s= pd1.Series([1,2,3,4,5], index ('a', 'b',' c',' d',' e'])
print (s['c,' d'])
Output c
3
d4
dtype: int64
Retrieve Data from selection
There are three methods for data selection:
*
loc gets rows (or columns) with particular labels from
the index.
iloc gets rows (or columns) at particular positions in
the index (so it only takes integers).
ix usually tries to behave like loc but falls back to

behaving like iloc if a label is not present in the index.


IX
deprecated and the use of loc and iloc is encouraged instead Pandas Series Retrieve Data from
is
selection
e.g.
>>>s= pd.Series(np.nan, index-[49,48,47,46,45, 1, 2, 3, 4, 5])
>>> s.iloc[:3] #slice
the first three rows
49 NaN
48 NaN
47 NaN
>>> s.loc:3] # slice up to and including label 3
49 NaN
48NaN
47 NaN
46 NaN
45 NaN
1 NaN
2 NaN
3 NaN
>>> s.ix[:3] # the integer is in the index so s.ixl:3] works like loc
49 NaN
48 NaN
47 NaN
46 NaN
45 NaN
1
NaN
2 NaN
3 NaN

QUESTIONS MLL
1. **What is a Series in Python's pandas library?**
-
Answer: A Series is a one-dimensional array-like object in pandas that can hold any data type
(integers, strings, floating-point numbers, etc.). It is similar to a column in an Excel sheet.
2. **How do you import the pandas library in Python?**
Answer: import pandas as pd
3. **Write a code snippet to create a Series from a list [10, 20, 30, 40, 50].**
-Answer:
'import pandas as pd; s = pd.Series([10, 20, 30, 40, 50))
4. **How can you create a Series with custom indices ['a', 'b','c, 'd', 'e'] from the list [10, 20, 30, 40,
50]?**
Answer: 's = pd.Series([10, 20, 30, 40, 50), index=['a', 'b', 'c, 'd', 'e'])
5.**What function is used to create a Series froma dictionary ('a': 1, 'b': 2, 'c': 3)2**
Answer: pd.Series(f'a': 1, "b': 2, 'c': 3)'
-

6. **How can you access the value at index 'b' in the Series created from the dictionary (a': 1, 'b': 2,
'c': 3)2**
Answer: 's= pd.Series([l'a': 1, 'b': 2, 'c': 3}); value = s[b']
-

7. **Write a code to create a Series from a NumPy array 'np.array([1, 2, 3, 4, 5]) .**
-
Answer: import numpy as np; import pandas as pd; arr = np.array([1, 2, 3, 4, 5); s =
pd.Serieslarr)"
8. **What attribute of a Series object can be used to view the index labels of the Series?**
-
Answer: s.index
9. **How do you change the index of a Series to ['w', 'x, 'y', 'z] fora Series with 4 elements2**
-Answer:
's.index = ['w, '*,'y', z]
10. **What is the output of 's[1]' if = pd.Series([5, 10, 15, 20, 25))' ?**
's
Answer: 10
11 "How can you check if the index 'a' exists in the Series 's *

Answera' in s
12. **Write a code to create a Series with default indices from a tuple (10, 20, 30, 40),**
Answer:'s= pd Series((10, 20, 30, 4O))
13**what is
the method to retrieve the first 3 elements of a Series s
?,
Answer: s.head(3)
14 *Write a code to create an empty Series
and assipgn it to the variable s.
Answer:'s= pd.Series)
15.**Explain how to convert a Series to a list.
Answer: Use the tolist() method. Example:
's.tolist()

These questions should help Class 12th CBSE students get a good grasp of
the basics of creating and
manipulating Series in Python using the pandas library.
Assertion reasoning
Topic: Creation of Series from ndarray, dictionary,
1. ""Assertion:* A
scalar value
Pandas Series can be created from a Num Py ndarray.
Reasoning:** Because a Series is essentially a one-dimensional labeled array capable of holding
any data type.
(A) Both assertion and reasoning are true, and the reasoning is
the correct explanation far the
assertion.
(B)Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer: A**
2
Assertion: When creating a Series from a dictionary, the keys become the index.
Reasoning:** This is because a Series can automatically use the keys of a dictionary as index labels
for the corresponding values.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation far the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer: A
3. Assertion: A Series created from a scalar value will have the same value for all elements
Reasoning: Because when a scalar value is used, Pandas creates a Series of the specified length
where each elermnent is the scalar value.
(A)Both assertion and reasoning are true,and the reasoning is the correct explanation for the
assertion.
(B)Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer: A

4. Assertion: If no index is provided, Pandas will generate a default integer index starting from 1

Reasoning: Because Pandas uses integers as defauit index values.


(A)Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer:C
5. Assertion:You cannot create a Pandas Series from a dictionary with mixed data types.
Reasoning: Because a Series can only hold data of a single type.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer: D
Topic: Mathematical Operations
1. Assertion: Mathematical operations on a Pandas Series are element-wise.
Reasoning: Because Pandas is designed to perform vectorized operations to enhance performance
and efficiency.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer: A
2. Assertion:Adding a scalar to a Pandas Series adds the scalar value to each element in the Series.
Reasoning:This operation is called broadcasting, where the scalar is broadcasted to all elements in
the Series.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer: A
3. Assertion: When performing element-wise operations between two Series, their indices must
match.
Reasoning: Because Pandas aligns Series based on their indices before performing element-wise
operations.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, butthe reasoning is notthe correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
Answer: A
4. Assertion: Multiplying a Series by another Series with different indices results in NaN values.
Reasoning: Pandas aligns the indices of the two Series, and any index without a match result in
NaN.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.
*Answer: A**
S.Assertion:** The operation 'Series1 + Series2' will result in a Series of the same lengtn ds
Series1.
Reasoning:** Because the length of the resulting Series is determined by the length of the
longer Series.
(A) Both assertion and reasoning are true, and the reasoning is thecorrect explanation tor the
assertion.
(b) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
-
(C) The assertion is true,
- but the reasoning is false.
(D) Both assertion
and reasoning are false.

**Answer: D**

### Topic: Head and Tail Functions

1. **Assertion:** The head()' function in Pandas returns


the first n rows of a Series.
**Reasoning:** This is useful for quickly inspecting
- the beginning of a Series.
(A) Both assertion and reasoning are true,
and the reasoning is the correct explanation for
assertion. the
- (B)
Both assertion and reasoning are true, but the reasoning is not
the correct explanation for the
assertion.
- (C)
The assertion is true, but the reasoning is false.
-
(D) Both assertion and reasoning are false.

**Answer: A**

2. **Assertion:** By default, the tail() function returns


the last 10 rows of a Series.
**Reasoning:** This helps in quickly inspecting the end of a Series.
-
(A) Both assertion and reasoning are true, and the reasoning is the correct
explanation for the
assertion.
-
(B) Both assertion and reasoning are true,
but the reasoning is not the correct explanation for the
assertion.
-(C) The assertion is true, but the reasoning is false.
- (D)
Both assertion and reasoning are false.

**Answer: D**

3.**Assertion:** 'head()' and 'tail()' functions can only be used with Series and not with
DataFrames.
**Reasoning:** Because these functions are designed to work with one-dimensional data
structures.
-(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for
the
assertion.
-(B)Both assertion and reasoning are true, but the reasoning is not the correct explanation for
the
assertion.
-
(C) The assertion is true, but the reasoning is false.
-
(D) Both assertion and reasoning are false.

**Answer: D**
4.*Assertion** The head(n=3) function cal returns the first three elements of a Series.
*Reasoning** Because the n' parameter specifies the number of rows to return from the start.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B)Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
(C) The assertion is true, but the reasoning is false.
(D) Both assertion and reasoning are false.

**Answer: A**

S.**Assertion:** The tail(n=S)' function call returns the last five elements of a Series.
**Reasoning:** This function call is useful for inspecting the last few elements of a Series.
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
-(C) The assertion is true, but the reasoning is false.
-
(D) Both assertion and reasoning are false.

**Answer: A**

### Topic: Selection, Indexing, and Slicing

1. **Assertion:** You can select a single element from a Series using its index label.
** Reasoning:** Because a Series is indexed and elements can be accessed using
these labels.
-(A) Both assertion and reasoning are true, and the reasoning is
the correct explanation for the
assertion.
-(B)
Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
- (C)
The assertion is true, but the reasoning is false.
-
(D) Both assertion and reasoning are false.

**Answer: A**

2. **Assertion:** Slicing a Series using 'Series[start:stop]' includes the element at the stop
position.
**Reasoning:** This follows the standard Python slicing convention where the stop index is
inclusive.
-
(A)Both assertion and reasoning are true, and the reasoning is the correct explanation for the
assertion.
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
-
(C) The assertion is true, but the reasoning is false.
-
(D)Both assertion and reasoning are false.

**Answer: C**

3.*Assertion:** Indexing a Series with a list of indices returns a Series containing only the specifed
indices.
*Reasoning:** This allows for selecting multiple elements at once.
-

(A)Both assertion and reasoning are true, and the reasoning is


the correct explanatoto ce
assertion.
(B) Both assertion and reasoning are true, but
the reasonine is not the correct explanation ror tie
assertion.
-(C)
The assertion is true, but the reasoning is
- (D) false.
Both assertion and reasoning are false.

**Answer: A**

4. **Assertion:** Series cannot A


be indexed by boolean arrays.
**Reasoning:** Boolean indexing is not
supported in Pandas Series.
-(A) Both assertion and reasoning are true, and the reasoning is the correct explanation
for the
assertion.
-
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for the
assertion.
- (C)
The assertion is true, but the reasoning is false.
-
(D) Both assertion and reasoning are
false.

**Answer: D**

5. **Assertion:*** The method `iloc is used for integer-location based indexing in a Series.
** Reasoning:** iloc allows selecting elements based on their integer index
positions, not the
index labels.
-
(A) Both assertion and reasoning are true, and the reasoning is the correct explanation
for the
assertion.
-
(B) Both assertion and reasoning are true, but the reasoning is not the correct explanation for
the
assertion.
-
(C)The assertion is true, but the reasoning is false.
-
(D)Both assertion and reasoning are false.

**Answer: A**

These questions should help in understanding various aspects of creating and manipulating Pandas
Series.

MCQs

### Topic: Creation of Series from ndarray, dictionary, scalar value

1, **Which of the following is a correct way to create a Series froma NumPy ndarray?**
-
(A)`pd.Series(ndarray)"
-
(B) 'pd.Series(array)'
-(C) `pd.Series(ndarray, index=ndarray)'
-
(D) `pd.Series(index=ndarray)

**Answer: A**

dictionary?**
a
2. **What becomes the index when a Series is created from
(A) The values of the dictionary
(B) The keys of the dictionary
-

(C) Sequential integers starting from 0


(D) The length of the dictionary
**Answer: B**

3. **Creating a Series from a scalar value requires specifying which additional parameter?**
-(A) dtype
-(B)
index
-(C) name
-(D)
`columns

**Answer: B**

4. **What will be the output of 'pd.Series(5, index=['a', 'b',


-(A) A
'c]) ?**
Series with values 5, 5, 5 and index 'a', 'b', 'c'
-
(B) A Series with values 5, 5, 5 and default integer index
-(C) A Series withvalues 1, 2, 3 and index 'a', 'b', 'c'
- (D) error
An

**Answer: A**

5. **if no index is provided, what index will a Series created from a list have ?**
- (A) The values of listthe
- (B)
The length of the list
- (C)
Sequential integers starting from 0
- (D) Sequential integers starting from 1

**Answer: C**

### Topic: Mathematical Operations

1. **What is the result of adding a scalar to a Pandas Series?**


- (A)
Adds the scalar to each element of the Series
-
(B) Multiplies each element of the Series by the scalar
-
(C) Raises each element of the Series to the power of the scalar
-
(D) Divides each element of the Series by the scalar

**Answver: A**

2. **What happens when you add two Series of different lengths?**


-
(A) The operation fails
(B) The shorter Series is extended with NaN values
(C) The operation aligns by index and fills missing values with NaN
(D) Only elements up to the length of the shorter Series are added

**Answer: C**

3. **Which of the following operations is performed element-wise on a Series?**


(A)Addition with another Series
(B) Scalar multiplication
(C) Boolean comparison
(D) Allof the above

**Answer: D**
indices2**
result of series1 series2 if seriesl" and series2 have the same
4.
What will
be the
(A)Elemnent-wise multiplication of
the Series
(B) Seriesl values replaced by
Series2 values
(C)Series with the sum of corresponding
values
(D) Series with the product
of the indices

**Answer: A**

5.*1fyou have series pd.Series([1, 2, 3, 4]), what will series


-(A)O6 172 839 dtype: int64 +5' returnt
-(B)O 1122334 dtype:int64
(C)
'06172839 dtype:object
(D) An error

Answer:A*

#HR Topic: Head and Tail Functions

1. **What does the head(0 function do by default in Pandas?**


-(A) Returns the first 3 rows
-(B) Returns the last 5 rows
-(C) Returns the first 5 rows
(D) Returns all rows

**Answer:C**

2. **How can you get the last 7 rows ofa Series?*


-
(A)series.head[7)
-(B) 'series.tail(7)
(C) 'series.iloc[-7:]
-(D) series[-7:]

**Answer: B**

3. **What does 'series.head(3) return if 'series has 10 elements?**


-(A) The first elements
3

-(B) The last 3 elements


-(C) All elements
-(D) An error

Answer: A**

4. 1f series = pd.Series([10, 20, 30, 40, 50]), what does 'series.tail(2) return?**
-(A) 340 4 50 dtype: int64
-(B) O 10 1 20 dtype: int64
-(C)
- (D) 1
4 50 dtype: int64
20 2 30 dtype: int64

*Answer: A**

5.*What does 'series.head(0) return?*


(A) The first element
(B) An empty Series
(C) The entire Series
(D) An error

**Answer: B*

Hn# Topic: Selection, Indexing, and Slicing

1. **How can you access the element at index '2 in a Series 'series ?*

-(A) 'series[2]
(B) 'series.loc[2]'
-(C)'series.iloc[2]
-
(D) Allof the above

**Answer: D**

2. **What does `series['a':'c]' return if 'series' has string indices?**


-
(A) Elements between 'a' and 'c' inclusive
- (B)
Elements between'a' and 'c' exclusive
- (C)
Only the element at 'c'
(D) An error

**Answer: A**

3.**Which method would you use for integer-location based indexing?**


(A) loc
-
(B) iloc'
-
(C)'index
-
(D) position

**Answer: B**
a
4. **How can you select multiple non-contiguous elements in Series?**
-(A) Using a list of indices
-
(B) Using a slice
- (C) Using a boolean array
-
(D) Both A and C

**Answer: D**

5. **What will 'series.iloc[-3:]' return?**


-
(A) The last 3 elements of the Series
- (B)
The first 3 elements of the Series
-
(C) An error
-
(D) The elements excluding the last 3

**Answer: A**

CBT

### Topic: Creation of Series from ndarray, dictionary, scalar value


1.*Task:** Create a Pandas Series from the NumPy ndarray
**Question:** Write the code to create
'array=np.arrayl[1, 2, 3, ,1)
the Series and print it.
python
import numpy as np
import pandas as pd

array = np.array([1, 2, 3, 4, 5])


series = pd.Series(array)
print(series)

2. **Task:** Create a Pandas Series from


the dictionary 'data = ('a': 10, 'b': 20, 'c': 30)
**Question:** Write the code to create
the Series and print it.
python
data = (a': 10, 'b': 20, 'c': 30)
series = pd.Series(data)
print(series)

3.**Task:** Create a Pandas Series from the scalar value 5 with


the index ['x', 'y', 'z'].
**Question:** Write the code to create the Series and print it.

python
series = pd.Series(5, index=['x, 'y, 'z])
print(series)

4, **Task:** Create a Series from the list


[1, 2, 3, 4, 5] without specifying an index.
*Ouestion:** Write the code tocreate the Series and print it. What will be the default
indey?
python
series = pd.Series([1, 2, 3, 4, 5)
print(series)

**Defauit index:** The default index will be integers starting from 0.

5*Task* Create a Series from the dictionary data = ('a': 1, 'b: 2} and assign it to a variable
series. Then, print the data type of the values in the Series.
**Question;** Write the code to create the Series and print the data type.

python
data = (a': 1, 'b': 2}
series = pd.Series(data)
print(series.dtype)

## Topic: Mathematical Operations


,
seriesl pd Series([1,2, 3)) and 'series2 a
pd.Series([4, 5, 6]) perform
1*TaskGlven
elementwise addition.
Question ** Write the code to add'series1 and 'series2 and print the result.

python
seriesl a pd. Series([L. 2, 3)
series2 pd. Series(l4.5, 6)
result = series1 + series2
print(result)

2. **Task** Multiply the Series 'series = pd.Series([10, 20, 30]) by 2.


**Question:** Write the code to multiply the Series by 2 and print the result.

python
series = pd Series([10, 20, 30))
=
result series 2
print(result)

3. **Task:** Given 'series1 =


pd.Series([1, 2, 31)' and 'series2 = pd.Series([1, 2). perform element
wise subtraction.
**Question:** Write the code to subtract 'series2' from 'series1' and print the result.

python
seriesl = pd.Series([1, 2, 3])
series2 = pd.Series([1, 2])
-
result = series1 series2
print(result)

4. **Task:**Create a Series 'series = pd.Series([1, 2, 3, 4]). Calculate the square of each element.
Question:** Write the code to square each element and print the result.

python
series pd.Series([1, 2, 3, 4))
result series **2
print(result)

= = pd.
5. **Task:** Given 'series1 pd.Series([10, 20, 30])' and 'series2 Series([1, 2, 3). perform
element-wise division.
**Question:** Write the code to divide 'seriesl' by 'series2 and print the result.

'python
series1 = pd.Series([10, 20, 30))
series2 = pd.Series([1, 2, 3)
result series1 / series2
print(result)

WHH Topic: Head and Tail Functions


1.Task:** Create a Series `series = po Seriesirangel10o): Use the head function to get the nst a
elements
*Question:** Write the code to get and print the first 3 elements.

python
series = pd Series(range(10)
result = series.head(3)
print(result)

.
Create a Series 'series = pd.Seriesrange(20)) Use the tail function to get the last 5
2.lask:
elements.
**Question:** Write the code to get and print the last 5 elements.

python
series = pd.Series(range(20))
result = series.tail(5)
print(result)

3.**Task:** Create a Series 'series = pd.Series([100, 200, 300, 400, 500)). Use the 'head' function
without any parameters.
**Question:** Write the code and print the result. How many elements are returned?

python
series = pd.Series([100, 200, 300, 400, 500)
result = series.head()
print(result)

**Number of elements returned:** 5 (default value).

4, **Task:** Create a Series 'series = pd.Series(range(1, 11))'. Use the 'tail function with parameter
0

**Question:** Write the code and print the result. What is returned?

'python
series = pd.Series(range(1, 11)

result = series.tail(0)
print(result)

**Returned:** An empty Series.

s *Task:** Create a Series 'series pd.Series(range(5, 15)). Use both 'head' and 'tail' functione to
get the first 2 and last 2 elements.
w*Question:** Write the code to get and print both results.

python
= pd.Series(range(5, 15))
series
head result = series.head{2)
tail result = series.tail(2)
print("Head:", head_result)
print("Tail:", tail_result)

### Topic: Selection, Indexing, and Slicing

1. *Task:** Create a Series 'series = pd.Series([10, 20, 30, 40, 50), index=['a', 'b', 'c', 'd', 'e'])'. Select
the element at index'c'.
**Question:** Write the code to select and print the element.

'python
series = pd.Series([10, 20, 30, 40, 50], index=['a', 'b', 'c, 'd', 'e'])
result = series['c']
print(result)

2. **Task:** Create a Series 'series = pd.Series(range(10))' . Use slicing to get the elements from
index 2 to 5.
**Question:** Write the code to slice and print the result.

'python
series = pd.Series(range(10))
result = series[2:6)
print(resuit)

3. **Task:** Create a Series 'series =pd.Series([1, 2, 3, 4, 5, 6,7, 8, 9, 10) . Select the elements at
positions 1, 3, and 5 using integer indexing.
**Question:** Write the code to select and print the elements.

python
series = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
result = series.iloc[1, 3, 5]]
print(result)

4. **Task:** Create a Series 'series = pd.Series([100, 200, 300, 400, 500], index=['a', 'b', 'c, 'd', 'e'|).
Use boolean indexing to select elements greater than 300.
**Question:** Write the code to select and print the elements.

'python
series = pd.Series([100, 200, 300, 400, 500), index=['a', 'b', 'c, 'd', 'e'])
result = series[series > 300]
print(result)

5. **Task:** Create a Series'series =pd.Series(range(1, 6), index=['a', 'b', 'c', 'd', 'e'])'. Select
elements at indices 'b' and 'd' using label-based indexing.
**Question:** Write the code to select and print the elements.

python
=
series pd.Series(range(1, 6), index=['a', 'b', 'C, 'd','e'])
=
result series.loc[['b,'d']]
print(result)

Case Based

# Topic: Creation of Series from


ndarray, dictionary, scalar value

1Case
of
Study:* A
data scientist is working on a machine learning project and has a NumPy array
feature values for a dataset.
**Question:** How canthe data scientist convert the following
NumPy array features
np.array([0.1, 0.2, 0.3, 0.4, 0.5])' intoa Pandas Series? Write the code
and explain why this step
useful.

python
import numpy as np
import pandas as pd

features=np.array([0.1, 0.2, 0.3, 0.4, 0.5])


series = pd.Series(features)
print(series)

**Explanation:** Converting to a Pandas Series allows for easier


manipulation and integration with
other data processing tasks in Pandas.

2. **Case Study:** A financial analyst has data about stock


prices stored in a dictionary with dates as
keys and prices as values.
**Question:** How can the analyst create a Series from the following
dictionary 'stock_prices =
(2024-01-01': 150, 2024-01-02': 152, '2024-01-03': 148)? Write the code
and explain how the
resulting Series can be used.

'python
stock prices = (2024-01-01': 150, '2024-01-02': 152, '2024-01-03': 148)
series = pd.Series(stock_prices)
print(series)

**Explanation:** The resulting Series can be used for time


series analysis, plotting, and further
statistical computations.

3. **Case Study:** An engineer needs to initialize a Series with a constant value to represent a
baseline measurement for multiple sensors.
**Ouestion:** How can the engineer create a Series with a
scalar value baseline = 10` sensors
indexed as f'sensor1, 'sensor2', 'sensor3'] ? WNrite the code and discuss the significance for
of
initializing with a scalar value.

'python
baseline = 10
series = pd.Series(baseline, index=('sensor1', 'sensor2','sensor3')
print(series)

**Explanation:** Initializing with a


scalar value is useful for setting default or baseline
values for
comparison or further calculations.
stores them in a list. They
4. *Case Study:* A researcher collects daily temperature readings and
need to convert this list into a Series for further analysis. termperatures = (22, 21, 23, 22,
**Question:** How can the researcher create a Series from the list
20]? Write the code and explain howthe index willbe assigned.

python
temperatures = [22, 21, 23, 22, 20]
series = pd.Series(temperatures)
print(series)

**Explanation:** The index will be automatically assigned as sequential integers starting from 0.

narnes as keys and


5. **Case Study:** A teacher records scores for a test in a dictionary with student
scores as values. They need to analyze these scores using Pandas.
=
**Question:** How can the teacher create a Series from the dictionary 'scores (Alice': 85, 'Bob':
90, 'Charlie': 78)? Write the code and explain how this Series can be utilized.

'python
scores = ('Alice': 85, 'Bob': 90, 'Charlie': 78)
series = pd.Series(scores)
print(series)

**Explanation:** This Series can be used to calculate statistics like mean, median, and standard
deviation of the scores.

### Topic: Mathematical Operations

1. **Case Study:** A data analyst has two Series representing sales data for two quarters. They need
to calculate the total sales.
**Question;** How can the analyst add the Series 'sales_q1 = pd.Series([200, 250, 300])' and
'sales q2 = pd.Series([220, 270, 320])'? Write the code and explain the result.

python
sales_q1 = pd.Series([200, 250, 300])
sales_q2 = pd.Series([220, 270, 320])
=
total_sales sales_q1+ sales_q2
print(total_sales)

**Explanation:** The result is the element-wise addition of the two Series, giving total sales for
each corresponding period.

2, **Case Study:** A scientist has a Series representing experimental data. They need to normalize
this data by subtracting the mean.
**Question: ** How can the scientist normalize the Series 'data = pd.Series([10, 20, 30, 40, 50])| ?
Write the code and explain the steps.

python
data = pd.Series([10, 20, 30, 40, 50])
-
normalized data = data data.mean()
print(normalized _data)
txplanation:* Subtracting the mean centers thedata aeosnd 0.
which is useful Tor Turnet
statistical analysis.

3.**Case Study:* A mathematician


needs to calculate the Square of each element in a Series for a
certain calculation.
Question:** How can the mathematician calculate
the souare of the Series numbers
pd.Series([1, 2, 3, 4])? Write the code and explain
the significance of element-wise operatons.
python
numbers = pd.Series([1, 2, 3, 4])
Squared_numbers = numbers
**2
print(squared_numbers)

Explanation:* Element-wise operations allow for efficient


and concise calculations across all
elements in the Series.

4.Case Study:** An economist needs to adjust prices in a Series by multiplying them with a factor
of 1.05 to account for inflation.
**Question:** How can the economist adjust the Series
'prices = pd.Series([100, 200, 300]) ?
Write the code and explain the importance
of such adjustments.
python
prices = pd.Series([100, 200, 300])
adjusted_prices = prices* 1.05
print(adjusted_prices)

**Explanation:** Adjusting for inflation helps in


understanding the real value changes over time.
5. **Case Study:** A teacher wants to apply a curve to
test scores by adding 5 points to each score.
**Question:** How can the teacher curve the Series scores =
pd.Series([70, 80, 90])'? Write the
code and discuss the potential impacts of curving scores.

python
scores = pd.Series([70, 80, 90])
curved scores = SCores +5
print(curved_scores)

**Explanation:** Curving scores can improve overall grades


and may be used to adjust for test
difficulty.

### Topic: Head and Tail Functions


1. **Case Study:** A researcher hasa large Series of experimental
data and wants to quicklv inspect
the first few entries.
**Ouestion:** How can the researcher use the head function on the Series
data
pd.Series(range(100)) to get the first 5 elements? Write the code and explain why
this is useful.
python
data = pd.Series(range(100))
first five = data.head()
print(first_five)
a
**Explanation;4* The head function is useful for quickly inspecting the beginning of Series to
understand its structure and content.
2. **Case Study ** An analyst is working with a time series dataset and wants to see the most recent
entries.
**Question;** How can the analyst use the tail' function on the Series time_series =
pd.Series(range(50)) to get the last 3 elements? Write the code and explain its significance.

python
time_series = pd.Series(range(50))
last_three = time series.tail(3)
print(last_three)

**Explanation:** The tail' function allows for quick inspection of the most recent data, which is
often critical in time series analysis.

3.**Case Study:** A data scientist needs to verify the initial values in a Series to ensure data
integrity before further processing.
**Question:** How can the data scientist use the head' function on data = pd.Series([5, 10, 15,
20,25, 30])' to check the first 2 elements? Write the code and explain the benefits.

'python
data = pd.Series([5, 10, 15, 20, 25, 30])
first_two = data.head(2)
print(first_two)

**Explanation:* * Checking initial values helps in validating data before applying any
transformations or analysis.

4. **Case Study:** A teacher has a Series of student scores and wants to see how the last few
students performed.
**Question;** How can the teacher use the 'tail' function on 'scores = pd.Series([80, 85, 90, 75,
95, 88]) toget the last 4 scores? Write the code and discuss the importance.

python
Scores =pd.Series( [80, 85, 90, 75, 95, 88])
last_four = scores.tail(4)
print(last_four)

**Explanation:** This allows the teacher to focus on the recent performance of students, which
can be helpful for identifying trends or

issues.

5. **Case Study:** An inventory manager needs to check the most recent additions to the stock.
**Question;** How can the manager use the tail function on inventory = pd.Series(range(100,
110)) to get the last element? Write the code and explain its usefulness.

python
inventory = pd.Series(range(100, 1 10))
last item inventory.tail( 1)
=

print(last_iten)
*Explanation:** Checking the most recent
addition helps in verifving the latest stock upaates
ensuring accurate inventory management. ae
### Topic: Selection, Indexing,
and Slicing
1. "*Case Study:** A data analyst has a Series with sales data indexed
access the sales by months and wants to
data for March.
Question:** Howcan the analyst
select the element at index 'March' in
pd.Series([200, 250, 300, 400], index-[January', the Series sales
explain the importance. 'February', 'March', 'April']) ? Write the code ana

python
sales = pd.Series([200, 250, 300, 400), index=('lanuary',
march sales = sales['March'] 'February', 'March, 'April])
print(march _sales)

Explanation:** Accessing specific elements by


label is crucial for analyzing and making decisions
based on particular time periods or
categories.

2. **Case Study:** A researcher has a Series of


dailymeasurements and needs to extract data from
the 3rd to the Sth day.
**Question:** How can the researcher use slicing on
get the values from the 3rd to5th positions? Write 'measurements = pd.Series(range(10, 20)) to
the code and explain the slicing technique.

python
measurements = pd.Series(range(10, 20)
sliced data = measurements[2:5]
print(sliced_data)

**Explanation:** Slicing helps in extracting a subset of data for focused


analysis or visualization.

3. **Case Study:** An economist has a Series with quarterly GDP


data and wants to compare the
first and last quarter.
**Question:** How canthe economist use both integer and label-based indexing on
'gdp =
pd.Series([1000, 1500, 2000, 2500], index=('Q1, 'Q2', Q3', 'Q4|) to get the first and last values?
Write the code and discuss the difference between these indexing methods.

python
gdp = pd.Series([1000, 1500, 2000, 2500], index=['Q1, 'Q2', 'Q3, 'Q4])
first_quarter =gdp.iloc[0]
last_quarter = gdp.loc['Q4']
print(first_quarter, last_quarter)

**Explanation:** Integer indexing ('iloc) is used for positional access, while label-based indeying
('loc) is used for accessing data by label.

4 **Case Study:** A teacher has a Series of student names and scores. They need to get scores for
students whose names are 'Alice' and 'Charlie'.
**Question:** How can the teacher use label-based indexing on 'scores = pd.Series(90. R5 QgI
index=[Alice','Bob', 'Charlie'])' to get the scores for 'Alice' and 'Charlie'? Write the code and
the process.
python
scores = pd Series([90, 85, 95], index=['Alice', 'Bob, 'Charlie'])
selected scores = scores. loc[[|'Alice', 'Charlie'])
print(selected_scores)

**Explanation:** Label-based indexing allows for precise selection of data based on the index
labels, useful in named datasets.

5.Case Study:** A project manager has a Series of task durations and needs to find the tasks that
took more than 5 days
*Question:** How can the manager use boolean indexing on durations = pd.Series([2, 5, 8, 6, 3).
index=[Task1', Task2', Task3', Taska', Task5'])' to get tasks taking more than 5 days? Write the code
and discuss the benefits.

python
durations = pd.Series([2,5, 8, 6, 3], index=['Task1', "Task2, Task3, Task4', TaskS'])
long_tasks = durations(duratians > 5]
print(long_tasks)

**Explanation:** Boolean indexing filters data based on conditions, enabling easy identification of
specific data points that meet certain criteria.

Series, DataFrame, CSV

M.LL. :QUESTIONS
1. What is series?
2. Write a program to create a series to print scalar value "5" four times

3. Which attribute is used to get total number of elements in a Series?

4. Define DataFrame?
5. What are the different ways Data Frame is created?

6. Write a Python code to create a DataFrame stock with appropriate column headings from
the list given below:
[[101,'Geeta',98], [102, 'Raju',95], [103, 'Seema',96], (104, Yash',88]]
7. How are Dataframe related to series?

8. What do you understand by the size of (1) Series, (ii) Dataframe

9. How can we fill missing values in DAtaFrame?


10. Which is the standard data missing marker used in Pandas?

11. What difference do we see in deleting with del and pop methods?

12. Which attribute is used to check if the series object contains NaN values?
13. What is a CSV files?

14. Which Pandas method is used to send content to a dataframe to CSV file?

15. Which Pandas method is used to read CSV Files?


M.LL ANSWERS
1. Series is a one dimensional structure with
elements of homogeneous oato.
2. import pandas as pd
S=pd.Series(5, index=[1,2,3,4,5])
3 Size
4 Itis a two dimensional data structure, iust like any table.
it is similar to spreadsheets or Sq
tables. Columns can be of deifferent types. Its size and values are
mutable.
5. Data Frame can be create
with the following construct:
List, Series, Dictionary, Numpy
ndarrays
6. import pandas as pd
d=[[101,'Geeta',98],(102, 'Raju',95],[103, Seema' ,96), [104, Ya sh',88])
c=['sno','Name','Score']
stock=pd. Data Frame(d,columns=c)
print(stock)
: Dataframe and series both are datastructures in pandas library. The individual columns of a
dataframe can be considered as a Series object.
8. Size attribute gives the number of elements present in Series or Dataframe.
9. For filling missing values, we can is fillna() method, for example
Df = fd1.fillna(0)
10. NaN
11. del method does not display the content of the column deleted where as pop() method
deletes and
existing column as well as displays the content of the deleted column.
12 hasnans attribute is used.
.
13 CSV files is a type of plain text file It stands for Comma Seperated Value. This is the simplest
way to
store tabular data. It must be save with the.CSV extension. It can store text as well as
number.
14. to csv()method
15. read_csv() method

TOPIC: .Assertion & Reason

Directions: In the following questions, a statement of Assertion (A) is followed by a statement of


Reason (R). Mark the correct choice as:
(A)Both Assertion (A) and Reason (R) are true, and Reason (R) is the correct explanation of Assertion
(A).
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of
Assertion (A).

(C) Assertion (A) is true, but Reason (R) is false.

(D) Assertion (A) is false, but Reason (R) is true.

QUESTIONS:

1. Assertion(A): DataFrame is a two-dimensional labelled array.

Its columns types can be heterogeneous i.e., of varying types.


Reason(R): We need a Data Frame with a Boolean index to use the Boolean indexing.
2. Assertion (A): Iteration is a general term for taking each item of something one after

another.
Reason (R): itertuples () returns the iterator yielding each index value along with a series
containing the data in each row.
3. Assertion (A): Indexing can also be known as sub selection.

Reason (R): Pandas DataFrame. loc attribute access group of rows and columns by label(s) or
a boolean array in the given DataFrame.

4. Assertion (A): To delete a column from Panda Data Frame,drop() method is used.

Reason (R): Columns are deleted by dropping columns with index label.
5. Assertion (A): Rows can also be selected by passing integer location.

Reason (R): Integer location can be pass to the iloc[] method


6. Assertion (A): head() function returns first n rows from the object based on position.

Reason (R): n is the selected number of rows whose default value is 3.


7. Assertion (A): List of dictionary can be passed to form a DataFrame.
Reason (R): Keys of dictionary are taken as row names by default.
8. Assertion (A): Indexing can also be known as sub selection.
Reason (R): Pandas DataFrame.loc attribute access group of rows and columns by label(s)or
a
Boolean array in the given DataFrame.
9. Assertion (A): CSV files are available to open in any spreadsheet program, including Google

Sheets, Open Office, and Microsoft Excel.


Reason (R): Using a spreadsheet program can serve a user's needs better since it has cells
where data sorted in rows and columns.
10. Assertion (A):- While creating a DataFrame with a
nested or 2D dictionary, Python interprets
the outer dict keys as the columns and the inner keys as the row indices.
Reasoning (R):- A column can be deleted using remove command
TOPIC: Assertion & Reason

Answers
1. Option (C) is correct.

2. Option (C) is correct.


Explanation: Iteration is the repetition of a process in order to generate an outcome. The
sequence willapproach some end point or end value. Each repetition of the process is a

single iteration, and the outcome of each iteration is then the starting point of the next

iteration.
iterrows() returns the iterator yielding each index value along with a series containing the
data in each row.
3. Option (D) is correct.
Explanation: Indexing can also
be known as subse selection.
Ioc takes two single/ist/range operator separated by7. The first one
indicates the row at
the second one indicates columns.
4. Option (C) is correct.
Explanation: To delete a column from Pandas DataFrame, drop() method is used. Columns
are deleted by dropping
columns with column names.
5. Option (B) is correct.
Explanation: To retrieve rows from a DataFrame, a specialmethod is used named
DataFrame.loc[). Rows can also be selected by passing integer location to iloc[] method.
6. Option (C) is correct.
Explanation: head() function returns first n rows from the object based on position. It IS
useful for quickly verifying data. for example,after sorting Syntax, Data Frame.head(n = 5)
Here, n is the selected number of rows whose default value is 5.
7. Option (C) is correct.
Explanation: List of dictionary can be passed to form a DataFrame. Keys of dictionary are
taken
8. Option (D) is correct.
Explanation: Indexing can also be known as subse selection.loc takes two single/list/range
operator separated by 7. The first one indicates the row and the second one indicates
columns.
9. Option (A) is correct.
Explanation: A CSV file stores data, both numbers and text in a plain text. All fields are
separated by commas while allrecords are separated by an elaborate line of characters. A

spreadsheet program sorts the data in a CSV file systematicaly via columns. This helps to
filter all the contents in the file.
10. Option (C) is correct.
Mulitple Choice Questions

1. Which attribute is used to get total number of elements in a Series?


a. size b. itemsize
C. shape d. ndim
2 To display last five rows of a series object 'S1', you may write:

S1.Head() b. S1Tail(5)

C. S1.Head(5) d. S1.tail()
3. Todisplay top five rows of a series object 'S', you may write:
S.head) b. S.Tail(5)

C. S.Head(5) d. S.tail()
4. Which method in Pandas can be used to change the index of rows and columns of a Series or

DataFrame:
rename() (ü) reindex() (i) reframe() (iv) none of the above
5. In a Dataframe, axis = 0 is for:
a. Columns b. Rows

C Rows and Column d. None of these

6. Pandas Series is:


a. 2-Dimensional b. 3-Dimensional c. 1 Dimensional d. Multidimensional
7. Python pandas was developed by:

a. Guido van Rossum b. Travis Oliphant


c. Wes McKinney d. Brendan Eich

8. The command to install the pandas is:


a. install pip pandas b. install pandas

C. pip pandas d. pip installpandas

9. The name "Pandas" is derived from the term:


a. Panel Data b. Panel Series
c. Python Document d. Panel Data Frame

10. We can analyse the data in pandas with


a. Series b. Data Frame
c. Both of the above d. None of the above

11. Pandas is a:
a. Package b. Language
c. Library d. Software

12. Which of the following import statement is not correct?


a. import pandas as CLASS12 b. import pandas as 1pd
c. import pandas as pd1 d. import pandas as pd
13. Which of the following is not an attribute of pandas data frame?
a. length
b. T
C. Size
d. shape
14. Find the correct
option as output of following :
as code
import pandas pd
s=pd.Series([1,2,3,4,5), index=['aman',' Atul','charu',
'Soumya','Sumera'])
print(s['charu'])
a. 1 b. 2 c. 3 d. 4
15. Assuming the given series,named stud, which command willbe used to print 5 as outputr
Sumit 90
Rajesh 100
Mahesh 50
Adnan 67
Zeenat 89
Name: Student, dtype: int64
a. stud.index b. stud.length
C. stud.values
d. stud.size
16. A social science teacher wants to use a pandas
series to teach about Indian historical
monuments and its states. The series should have the monument names as
values and state
names as indexes which are stored in the given lists, as
shown in the code. Choose the
statement which will create the series:
import pandas as pd
Monument=['Qutub Minar', Gatewayof India',' Red Fort', Taj Mahal']

State-['Delhi, Maharashtra',' Delhi',' Utar Pradesh']


a. S=df.Series(Monument, index=State)

b. S=pd.Series(State, Monument)
c. S=pd.Series(Monument, index=State)
d. S=pd.series(Mon ument, index=State)
17. Difference between loc() and iloc().:
a. Both are Label indexed based functions.
b. Both are Integer position-based functions.
c. loc() is label-based function and iloc() integer position-based function.
d. loc() is integer position-based function and iloc() index position-based function.

18. Which attribute of dataframe is used to retrieve its shape


a. T b. Ndim
c. Empty d. Shape

19. Which attribute of dataframe is used to retrieve its axes


a. T b. Ndim
c. Empty d. Shape

20. Which attribute of dataframe is used to perform transpost operation on a dataframe


a. T b. Ndim
c. Empty d. Shape
ANSWERS
Sie
stail)
shead)
reindex)
Rows
1. Dimensional
Wes Mckinney
pip install pandas
Panel Data
10 Both of the above
11 Library
12 impoart pandas as pd
13. length
14 3
15 stud.size
l6. s=pdSeries(Monument, index=State)
17. loc() is label based function and iloc() integer position based function.
18. shape
19. Ndim
20 T

PRACTICE PROGRAMS

1. Create a pandas series from a dictionary of values and an ndarray.

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


3. Write a Pandas program to add some data to an existing Series.
4. Write a Pandas program to select the rows where the percentage greater than 70.
5. Writea Pandas program to select the rows the percentage is between 70 and 90 (inclusive)

6. Writea Pandas program to change the percentage in given row by user.


7. Replace all negative values in a data frame with a 0

8. Read the Student_result.csv' to create data frame and do the fallowing operation:

To display Adm_No, Gender and Percentage from 'Student_result.csv file.

To display first 5 and last 5 records from 'student_result.csv file.

9. Read the Student_result.csv to create data frame and do the following operation:

To display Student_ result file with new column names.

To modify the Percentage of student below 40 with NaN value in dataframe.

10. Read the 'Student_result.csv to create data frame and do the following
operation:
To createa duplicate file for 'student_result.csv containing Adm No, Name and
Percentage.
Write the statenent in Pandas to find the highest percentage and also pr

student's name and percentage.

SOLUTIONS OF PROGRAMS

1# Create a panda's series from a dictionary


of values and a ndarrayY
import pandas as pd
import numpy as np
s=pd.Series(np.array([1,3,4,7,8,8,9]))
print(s)

#
create a dictionary
dictionary = ('X 10, "Y':20,:
'Z' :30) # create a series
series = pd.Series(dictionary)
print(series)

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


import pandas as pd
=
ds1 pd. Series([3, 6, 9, 12, 15))
=
ds2 pd.Series([2, 4, 6, 8, 10])
= +
ds ds1 ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
= -
ds ds1 ds2
print(ds)
print("Multiply two Series:")
= ds1 * ds2
ds
print(ds)
print("Divide Series1 by Series2:")
=
ds dsl1/ ds2
print(ds)
an existing Series.
3# Write a Pandas program to add some data to
import pandas as pd
s= pd.Series(['S 101', 'Amjad', 'C.Sc.', "XIl - A1, '450'])

print("Original Data Series:")


print(s)
print("\n Data Series after adding some data:")
new_s = s.append(pd.Series(['90.0', "PASS'])
print(new_s)

4# Write a Pandas program to select the rows where the percentage greater than 70.
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, ", "]
,
df = pd.Data Frame(exam_data index=labels)
print("Number of student whoes percentage more than 70:")
print(df[df['perc'] > 70])

5# Write a Pandas program to select the rows the percentage is between 70 and 90
(inclusive)
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, '', "]
,
df pd.Data Frame(exam_data index=labels)
=

print("Number of student whoes percentage more than 70:")


print(df[df['perc']. between(70,90)])

6# Write a Pandas program to change the percentage in given row by user.


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, ", '")
df pd.DataFrame(exam_dic, indexelabels)
print(" \nOriginaldata frame:")
print(df)
ch =
input("Enter the index of row :")
per = float(input("Enter percentage
to be changed: ")
print(\n Change the percentage in row
'+ch+'to',per)
df.loc[ch, 'perc'] = per
printid)

7# Replace all negative values in a data


frame with a 0.
import pandas as pd
data = (sales1':[10,20,-4,5,-1,15],
'sales2':[20,15, 10,-1,12,-2])
df= pd.Data Frame(data)
print("Data Frame")
print(df)
print('Display Data Frame after replacing every negative value with 0')
df[df<0]=0
print(df)

8# Importing and exporting data between pandas and CSV file.


#
To create and open a data frame using 'Student_result.csv' file using Pandas.
# To display row labels, column labels data types of each column and the dimensions
# Todisplay the shape (number of rows and columns) of the CSV file.

import pandas as pd
import cSV
#Reading the Data
= pd.read_csv("student_result.csv")
df
# Display Name of Columns
print(df.columns)
#
Display no of rows and column
print(df.shape)
# Display Column Names and their types
print(df.info()
a following operation:
9# Read the 'Student_ result.csv' to create data frame and do the
B To display Adm No, Gender and Percentage from 'student_result.csv
file.

# To display the first 5 and last S records from 'student result.csv file.

import pandas as pd
import csv
RTodisplay Adm_ No,
Gender and Percentage from 'student_result.csv file.
= ['ADM NO, GENDER', PERCENTAGE|)
df = pd.read_csv("student_result.csv",usecols
print(" To display Adm_No, Gender and Percentage from 'student_result.csv file.")
print(df)
#To display first 5 and last 5 records from 'student_result.csv' file.

dfl = pd.read_csv("student_result.csv")
print(dfl.head()
print[df1.tail()

10# Read the 'Student_result.csv' to create a data frame and do the following operation:
#To display Student_result file with new column names.
#To modify the Percentage of student below 40 with NaN value in dataframe.

import pandas as pd
import numpy as np
import csv
df = pd.read_csv("student_result.csv")
print(df)
names.
#To display Student_resuit file with new column
1,
dfi = pd. read_csv("student_result.csv",skiprows
names ('Adno', 'Sex','Name''Eng', 'Hin',
Maths','Sc.'SSt', San', IT,' Perc'])
print("To display Student result file with new column names")
print(df1)
# Tomdify the Percentage of student below 40 with NaN value.
= pd.read_csv("student_result.csv")
df2
print(df2)
print("To modify the Percentage of student below 40 with NaN value.")
df2.loc[(df2('PERCENTAGE'] <40, 'PERCENTAGE')}) = np.nan
print(df2)
IMPORTING/EXPORTING DATA BETWEEN DATAFRAME
AND CSV FILE
1. The dataof any CSV file can be shown in which of
the following software
(a) MS Word (b) Notepad (c) Spreadsheet
(d) All of the above
2. Tabular data that saved as plain text where datavalues are
separated by comte
a. Dataframe b. CSV c MySQL d. All of the above
3. Look at this image and identify the file type

Rollno. Name, Class


Sanjay 12
2. Ram an, 12

a. MySQL
b. Dataframe
C. CSV
d. Excel

4. Select the INCORRECT statement


a. CSV files occupies less memory space
b. CSV files are easy to read and write manually
c. CSV files are compatible only with spreadsheet
d. Data value of CSV files can be separated by any delimiter like
comma/semicolon/space/tab.
5. All individual rows of CSV files are called
a. Tuple b. Data c. Record d. Cardinality
6. CSV files are text files
a. True
b. False
7. CSV file can also be considered as Binary files
a. True b. False c. Sometimes d. Not sure
8. Look at the anatomy of CSV file and select correct abbreviation for1and 2
Rolino, Name, Class
1, 12
Sanjay,
2. Raman, 12

a. Attributes, 2. Rows
b. Columns, 2. Data
c. Degree, 2. Record

d. Header, 2. Record

9. Which of the following isnot relavent to CSV files?


a. Smaller in size

b. Human readable
c. Easyto parse
d Test and numeric data are distinct
10. Defauit delimeter in CSV is

a. ;

b.:
c. I

d.,
11. A CSV ile can take as delimeter
a. ;

b. |

c.
\t
d. @
e. All of the above
12. To read data from CSV file in pandas dataframe method is used.

a. read_csv() b. to_csv() c. reader() d. writer()

13. method saves data of dataframe to CSV file.

a. read csv()
b. to_csv()
C. reader()
d. writer()

14. Rama want to make a dataframe 'saledata' based on data of sale.csv which is stored in folder
'Python' in C: drive. What code she should write for it?

a. Saledata = pd.read_csv("'sale.csv") |
b.Saledata = pd.read_csv("C:/Python/sa le. csv")
c. Saledata = pd.to_csv("C:/ Python/sale.csv")
d. All of the above

15. If you want to read top 20 rows of data from CSV file, which argument would you give to
read_csv()?

a. Rows
b. NrowS
c. Header
d. Head

QUESTIONS ASSERTION AND REASONONG

ASSERTION AND REASONING based questions. Mark the correct choice as


1. Both A and are
R true and R is the correct explanation for A
ii. Both A and R are true and R is not the correct explanation for A
ii. A is True but R is False
A is false but R is True

1. Assertion (A): - The acronym CSV is a short form for Comma Separated Values, which refers
to a tabular data saved as plain text where data values are separated by commas. Data can
be imported to a Dataframe from csv file.
ReasoninB (R):- If we have the data in a CSv file. we can import the data. But, Pytnon 3
Pandas library must be imported to the program.

2. Assertion(A) :Only database can support import/export to CSV


format.
Reasoning (R) : CSV file can be created and edited using any text
editor

Assertion(A) :All the columns of CSV file can be separated by comma,or other
3.
Reasoning (R) : CSV is a short form for Comma Separated Values, which reters to a
oee
teuua
data saved as plain text where data values are separated by commas oniy.

4. Assertion(A) Python Panda library offers function ality to interact


with a CsV file.
Reasoning (R) : Panda's read_csv() and to csv) functions can
read
from and write-to CSV files.

5. Assertion. The read csv() function of Python Pandas can read data of a csv file
into any of
pandas data structures.

Reasoning(R). Data Frame is a compatible data structure


for
read_csv() function.
6. Assertion(A) The read csv() function reads a csv file's
data into a Data Frame.
Reasoning( R):The to csv()function writes a DataFrame on to a csv

file.

7. Assertion(A):By default, read_csv() uses the values of


first row as column headers in
DataFrames.

Reasoningg( R) : header argument is given to ensure


that the top/first row's data is used as
data and not as column headers.
8. Assertion(A):The nrows argument can
be used to read only the top 10 rows of
CSV file using the read csv() data from a
function in pandas. Reasoning( R) : The nrows argument
specifies the number of rows of the file to read.

9. Assertion(A): CSV is a short form for Comma Separated


Values files, occupies less memon
space.
Reasoning( R) : CSV files which refers to a
tabular data saved as plain text.

10. Assertion (A): CSV (Comma Separated Values) is a file format for
data
storage which looks like a text file.
Reason (R): The information is organized with one record on each line
and each field is separated by comnma.
11. Assertion(A) :We can read specific rows from the csv files.
Reasoning( R):The nrows attribute is used to
read specitic rowws from the Csy Fos
12. Assertion(A) :Pandas is a library of python.
Reasoning(R) We import pandas and import and export data between dataframe and csv
:

files.
13. Assertion (A):- CSV (Comma Separated Values) is a file format for data

storage which looks like a text file.


Reasoning (R):- A csv file is a two-dimensional labelled data structure like a table of MySQL.
14. Assertion(A) : There are two functions we would use to read data and write data to and
from a CSV file into a Data Frame.
Reasoning(R) The function used to read data from a CSv file into a Dataframe
:

is read_csv().The function used to fetch data from an SQL table into a DataFrame
is read_sql().
15. Assertion(A) : CSV stands for comma separated value file.

Reasoning( R) : A CSV file can not take other delimiter.

MCO

1. A CSV file can take character as separator.


(a), (b) - (c) I (d) \t (e) only (a) (f) all of these

2. The correct statement to read from a CSV file in a dataframeis


(a) <DF>. read _csv(<file>)
(b)<File>, read csv( )(<DF>)
(c) <DF> = pandas.read(<file>)
(d) <DF> = pandas.read_csv(<files>)

3. Which argument do you specify with read_csv( ) to specify a separator character ?


(a) character
(b) char
(c) separator
(d) sep

4. Tosuppress first row as header, which of the following arguments is to be given in


read csv( )?
(a) noheader = True
(b) header = None
(c) skipheader = True
-
(d) header Null

5. To read specific number of rows from a CSV file, which argument is to be given in
read csv( )?
rows = <n>
(a)
(b) nrows = <n>
(c)n_rows <n> -

(d) number rows = <n>


6.To skip first 5 rows of CSV
file, which argument will you give in read_csvt )
(a) skip rows = 5
(b) skiprows =5
(c)skip-5
(d) noread - 5

7. Toskip 1st, 3rd and 5th rows of CSV file, which areument
will you give in read_csVI )
(a) skiprows = 11315
(b) skiprows - (1, 3, 5]
(c) skiprows = [1, 5, 1]
(d)Any of these

8. While reading from a CSV file, to use a column's values as index labels, argumnent
given in read_CSV() is :
(a) index
(b) index_col
(c) index_ values
(d) index label

9. Nowadays for developing Machine learning projects programmers


rely on
CSV files rather than databases.
Why?
(a) csv can be used with proprietary softwares only.
(b) cSv files can be downloaded from open source websites free of cost.
(c) csv files need not be imnported while creating the projects
(d) csv is a simple and well formatted mode for data storage

10. Which of the following is not a parameter (argument) of read_csv() method?


a. sep b. names c.
header d. sort

11. Raju want to make a dataframe 'saledata' based on data of sale.csv which is stored in folder
'Python' in C: drive. What code he should write for it?

a. Saledata =
pd.read_csv("sale.csv") |
b. Saledata = pd.read csv("C:/Python/sale.csv")
c. Saledata = pd.to_csv("C:/Python/sale.csv")

d. Allof the above

12. (i) attribute used with read_csv() to import selective records/rows in dataframe
(i) attribute used with read_csv() to specify the number of row whose values are to
be used as column names.

a. (i) nrows, (ii) names


b. (i) rows, (ii) pos
c. (i) nrows, (ii) header
d. (i) head, (ii) nrows

13. Attribute used to specify the separator character for values being imported in dataframe
using read_csv()

a. Sepatator
b. Sep
c. Sepies
d. Space

.
14. Write code to read data from CSV file student.cSV stored in C: in dataframe 'std' including
exculsive columns rollno, name, percent where all values are separated by semicolon

a. Std = pd.read_csv("C:\student.csv", sep = %, names = ['rollno',name''percent])


b. Std = pd.read_csv("C:\student.csv'", sepies = ', names = (rollno,' name'' percent')
c. Std = pd.read_csv("C:\student.csv'", sep =', header = [rollno', name' percent])
d. Std = pd.read_csv("C:\student.csv", sepies = %, columns = [rollno', name',' percent'])
15. Which of the following attribute should be taken to import first 10 rows in a dataframe from
CSV?

a. Nrows = 10
b. Rows= 10
c. Skiprows = 10

d. Head= 10

16. You need to import CSV package in order to store a Data Frame in a CSV file.
a) True b) False

17. Write command to store data of DataFrame mdf into a CSV file Mydata.csv, with separator
character as'@

18. A CSV file is also known as a


a) Flat File b)3D File c) String File d) Random File

19. The data of any CSV file can be shown in which of the following software?
(a) MS Word (b) Notepad (c) Spreadsheet (d) All of the above

20. Nowadays for developing Machine learning projects programmers rely on


CSV files rather than databases. Why?
(a) csv can be used with proprietary softwares only.
(b) cSv files can be downloaded from open source websites free of cost.
(c) csv files need not be imported while creating the projects
(d) csv is a simple and well formatted mode for data storage
CSVFILES CSV
(Comma-separated values)
CSV FILES CSV (Comma-separated values) files are the comma
be viewN as an excel file and separated by commas. CSV file is
separated values. This type o
a simple text file.
e
nothing more than
However, it is the most common, simple and easiest method to store tabular data. This particular
format arranges tables by a specificstructure divided into rows and columns.

Once we have the DataFrame, we can persist it in CSV on the local disk.

Lets first create CSV file using data that is currently present in the DataFrame, we Can store Ce
of this DataFrame in CSV format using API called
to_CSV (..) of Pandas.

Importing/Exporting Data between CSV files and DataFrames

Pandas read csv()function is used to import a CSV file to Data Frame format.

Syntax: df.read_csv('file_name.CSV', header=None)

Here,
header allows you to specify which row will be used as column names for your DataFrame. Expected
int value or a list of int values.

If your file does not have a header, then simply set header=None.

To export a Pandas Data Frame to a CSV file, use to_csv function. This saves a DataFrame as a CSV

file.

Syntax: to_csv(parameters)

1. Write python code to write DataFrame data into "a.csv file.


Ans.
import pandas as pd
Dic={ 'empno': (101,102,103, 104),'name':('a',b','C,d),
'salary': (3000,5000,8000,9000)}
df=pd.Data Frame(Dic)
df.to_csv("a.csv")
Note: csv can be opened in excel, notepad, etc.

2. Modify the above code and write the data in d:\software folder.
Ans.
import pandas aspd
Dic=('empno':(101, 102, 103,104),'name':('a','b',c', d'),

'salary':(3000,5000,8000,9000)}
df=pd.Data Frame(Dic)
df.to csv(r"D:\software\a.csv") #t or df.to_csv("D:\\software\\a.csv")

Read CSV File as Pandas Using the read_csv() function from the pandas
package, youcan import tabular data from CSV files into pandas Dataframe:

3. Write python code to read a csv file "test.csv" from D:\


Ans.
import pandas as pd
df = pd.read csv('d:\test.csv') #read the csv file
print(df)

How to Create CSV File in Excel


Step 1: Open excel and write data in worksheet
...
Step 2: Select file option from menu and click on save as

A a Seve As
Excel Macro-Enabled Termplate
1 Ths PC Lecal Disk (D)
sktop Excel 97-2003 Template
roll name marks Tet (Tab delimited)
Curnents
2 1
aleeza 55 New folder
|Uricode Text
wnloads XML Spresdsheet 2003
3 2 ananya 34 Muc Nae Microsoft Excel SD/95 Werkbook
Pctures SVGoma delumited)
4 3 rajesh 90 2
tures Fomatted Tet (Space delimited)
Videos
backup Text (Mscintosh)
5 4 amar 23 Local Disk () efrbackup-HCB Seos Text (MS-DOS)

HP Lasedet cal Disk (cCsV (Macintosh)


5 rohit 42 Local Disk O) Prn CSV (hMS-D05)
sOXC(E Local Drsk cal Disk (DDIF (Data lnterchange Fomat)
6 pahul 53
project sYLK Symbolic Link
24 File pame Ecel Add-tn
7jyoti sottware ces 97-2003 Add-in
Nrtwork
9 8 divya 99 ve as ype PDF
XPS Document
10 9 harshit 24 File name est.cv Athors strict Open XML Spreadsheet
10 himanshi 66 OpenDecument Spreadsheet
1 Sve at type bel Wertbook

Step 3: Select drive and folder name where you want to save csv file
Step 4: Click on save as type option and select csv option from list.
Step 5: Click on save button

Other attributes used with csvfile:

Here is the Pandas read syntax with its parameters.


CS\V

Syntax: pd. read_csv(filepath, sep=,, header='infer, index_col=None, usecols=None,


skiprows=None, nrows=None)
header:
Bydefault, read csv() uses the values of first row as colums hezders in datafrarnes.
Header argument is used to ensure that the top/first roW's data is used as data and not a5
headers
cou
=
df pd.read_csv "File Path",header =
None)
nrows:
To read top n rows of data 'nrows' argument is used.

df = pd.read csv( "File Path", header None, nrows =n)


=

sep:
It stands for separator, default is ,
df = pd.read_csv('sanple.csv', sep=':)

skiprows: Skips passed rows in the new data frame.


df = pd.read_csv("people.csv', skiprows = [1,5])

names: We can exclusively specify column names using the parameter names while creating the
DataFrame using the read_csv() function.

import pandas as pd
m = pd.read_csv("data.csv", sep=",", header=0, narnes-('Rno', 'S_Name', 's_Class', 'Section '])
print(m)

usecols
Retrieves only selected columns from the CSV file.
df = pd.read_csv('people.csv',
header=0,
usecols=("First Name", "Sex", "Email"])

index col
This is to allow you to set which columns to be used as the index of the dataframe. If None, there
are no index numbers displayed along with records.
df = pd.read csv("'people.csv',
header=0, index col=["Id", "Job Title"),
usecols=["Id", "Job Title", "Email"], nrows=3)

10 QUESTIONS CBT

1. To create dataframe T from following csv file temp.csv stored in c drive, which of the following
code is correct?
state matemp mintemp
mp 26 2

up 24
jk 12 -4
a. T= pd.read csv("c:\temp.csv")
b. T= pd.read csv("c:\temp.csv",sep ="")
c.T= pd.read csv("c:\temp.csv", sep=\n")
d. T= pd.read csv("c:\temp.csv', sep =Mt")

2. Select appropriate code toexport all data of dataframe df to csv file temp.csv located in c drive
excluding row labels.

a. df.to_csv("C:\temp.csv")
b. df.to_csv("C:\temp.csv", index = False)
C. df.to_csv("C:\temp.csv",
header = False)
d. None of the above

3. In order to work with CSV files from panda, you need to import ,other than
pandas.

1. .csV

2. pandas.io
3. neWCsV
4. no extra package required

4. The correct statement to read from a CSV file in a Data Frame is:

1. <DF>.read_csv(<file>)
2. <File>. read_csv( )(<DF>)
3. <DF>= pandas.read(<file>)
=
4. <DE> pandas.read csv(<files>)

5. To suppress first row as header, which of the following arguments is to be given in read csv() ?

= True
1. noheader
2.. = None
header
3. skipheader = True
= Null
4. header

6. Identify the function which can save dataframe df into csv file.
(i) dfwrite_csv() (ii)df.store_csv() (i) df.to_csv() (iv) df.create_csv()

7. To skip first 5 rows of CsV file, which argument will you give in read_csv() ?

1. skiprows = 5
2. skip_rows =5
3. skip=5
4, noread = 5
8. To skip 1st, 3rd and 5th row of CSV file, which argument will you
give in read_
1. skiprows =1| 13|5
2. skiprows =
[1, 5, 1]
3. skiprows = [1, 3, 5]
4. any of these

9. The data of CSV files can be shown in which of the following


software?
a Spreadsheet software only
b Spreadsheet Software and Text Editor
c Text Editors
only
d Any software
10. Which of the following advantage motivates to use CSV files over database transfer
a CSV a common format for
data interchange
b Nearly all spreadsheets and databases support import/export to CSV format
c No need to learn or remember any
database command or any other tools
d A simple, common, and ubiquitous for data storage

CASE STUDY BASED

1. Write a programto read allcontent of "student.csv" in a dataframe and display records of only
those students who scored more than 80 marks. Records stored in students is in format : Rollno,
Name, Marks

2. For given sale.CSV located in C:\invetory


ID, Name, Jan, Feb, Mar
1, Ram kumar, 45, 78, 89
2, Suraj singh, 76, 45, 81
3, Jai Shankar, 45, 80, 66
4, sulekha rani, 67, 43, 56
5,jeevan, 66,77, 88,99

Shivangi want to create dataframe 'Sales' as given below

0 1 2 3 4
0 1 Ram kumar 45 78 89
1 3 Jai Shankar 45 80 66
2 4 Sulekha rani 67 43 56

Help her to write correct code to do so.


3. Write a program to read from CSV file "c:python\data.csv' where the delimeter is @with
following conditions
(i) Give exclusivecolumn names as col1, col2, col3
(i) First row should be taken as data and not as column headers

4.For given dataframe book

Bcode Bname Author Price

B1 C++ Ravichanran 200

1 B2 C Kanitkar 180

2 B3 ETC Kennedy 230

Write a program to create csv file lib.csv with columns bname and price.

5. Ms Priya is working on an application made in python. She wrote the command tp customize the
column header but getting an error. Provide her the solution for the same and also give the
explanation.

Df = pd.read_Csv("'adm.csv', columns=("AdmNo"" FirstNAme"" LAstNAme"" Class"])

6.Mr Prakash has created a csv file to store the students details with header rows. While reading
data from csv file into the dataframe he wants to hide the header from the csv file. He has written
the following code but getting an error.:

Df- pd.read_csv("d://adm.csv",header="no")

Provide him the solution for the same and also give the explanation.

7. Ms Smita wants to write the following data in similar pattern in csv file (separated each by * and
ignore default index). Help her to do the same.

SNO Name Score Rank


1 1
Sachin 345

2 Manish 300 3

3 Saurabh 250 4

8. Write a program toread data from a CSV file where separator character is '@'. Make sure that:

the top row is used as data, not as column headers.


only 10 rows are read into Data Frame.
Let the contents of the file bike.csv be the following:
Let the contents of the file bike.csv be the following:
Honda@2500
Yamaha@2800
Suzuki@2100
Kawasaki@3200
Ducati@3500
BMW@4500
Harley-Davidson @5500
KTM@4000
Triumph@5300
Aprilia@4800
Indian@5700
Royal Enfield @3000

9. Ms. Payal wants to create a CSV file from another CSV file. The file contains 5 columns EmpName,
Empld, Salary, Designation, DOB. Payal wants to read first three rows from the file. She has found
the code to do the task she wants, but one line of code is missing. Help her to complete the code.

import pandas as pd
df = pd.read_csv("E:|\Data\\Employee.csv")
df.to_csv("E:\\Data\\Emp.csv",

10. Write a program that reads from aCSV files where the separator character is '#.Read only first
5 rows in your dataframe.
i.Give column headings as EmpName, Designation, Salary.
ii. Make sure to read first row as data and not as column headers.

11.Write a program to show the detail of the student who scored the highest marks. Rama stored
in "Data.csv" in given below
:

the students details


Rollno, Name, Marks
1, Aman, 35
2, Kanak, 1
3, Anuj, 33
4, suman, 25
a
Help her to show the detail of the student who scored the highest marks by importing this data in
dataframe.

student of class 12th is trying to write program to search the record from "data.csy!
a
12. Amit, a
is
according to the admission number input from the user. Structure of record saved "data.csy"
in
Marks.
Adm_no, Name, Class, Section,

Help him to show the detail


13. Rohit, a student of class 12th, is learning CSV File Module in Python.
of the student who are class by importing this
XI data in a dataframe.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XI,A
3,ARVIND,XII,A
4,RAVI,XI,A
5,ASHISH,XI,A
14. Write a program to read data from a CSV file where separator character
is';'. Make sure that:
the top row is used as data, not as column headers.
only 5 rows are read into Data Frame.
Let the contents of the file std.csv be the following:

1, AKSHAY, XII,A
2, ABHISHEK, XII,A
3, ARVIND, XII, A

4, RAVI, XIl, A
5, ASHISH, XIl, A

15.Consider the following dataframe :


df1
mark1 mark2
0 10 15
1 40 45
2 15 30
3 40 70

Write the code to export this dataframe into the csv file Marks.csv.
MLL

1.
Pip installmatplotlib is a command to
install Matplotlib in your system.
2. In order to be able to use Python's Data Visualisation library, we
need to import the pyplot
module from Matplotlib library
3. mp.show) is used to display the figure, if matplotlib.pyplot as mp
is imported.
4. Write the function name to draw
line chart of two variables.plt.plot(X,y)
5. plt.savefig) function is
used to save the plot.

Q1:

import pandas as pd
data={'city':('Delhi', Bangalaru',' Chennai, Mumbai']),' MaxTemp': (40,31,35,29),
MinTemp':|32,25,2
7,21],'Rainfall':(24.1,36.2,40.8,35.2])
df=pd.Data Frame(data)
print(df) Temperature Analysis
Max
df['difference' ]=df['MaxTemp') 40.0
Min
Rain
37.5
df('MinTemp']
35.0
#print(df)
32.5
df.loc[4]=[('Gujrat',30,27, 25.8,5]
30.0
##print(df)
27.5
#print(df.head(3))
25.0

df.to_csv('climate.csv')
22.5

#print(df.drop(1)
Delhi Bangalaru Chennal Mumbat Gujrat
#print(df) Cities

import matplotlib.pyplot as plt


plt.plot(df[lcity'], df('MaxTemp'],'r', Jabel='Max')

plt.plot(df['city'], df['MinTemp'],'g',label='Min')
plt.plot(df['city'], d f['Rainfall],'b',label='Rain')

plt.legend()
plt.title('Temperature Analysis')
plt.xlabel('Cities')
plt.ylabel('Temp')
plt.show()

Q2:

import pandas as pd
data=('BookiD':['B001, B002', BO03','BO04'],'Subject':('CS,'CS,'CA', IP), BookTitle':[NCERT
CS,'Move with IP','Sample papers, NCERT IP])
df=pd.DataFrame(data)
print(df)
print(df.drop(3))
Books published yearwise
df.to_csv('Book.csv')
200

print(dfT)
175

print(df.head (3)
150

2 125

import matplotlib.pyplot as plt


100
nob=[160,170,185,150,200]
75

year=[2019,2020,2021,2022,2023]
50

plt.title('Books published yearwise')


25
pit.xlabel('Year')
2019 2020 2021 2022 2023
plt.ylabel('No. of books') ear
plt.bar(year,nob,color=[r, b,'g.'y, m'])
plt.show()

Q3

import pandas as pd
data=('Name':('Ritesh' Mana' Harshal, Parth', 'Srishti'],' English':(67,78,89, 99,88],'Hindi':(76,87,9
8,99,70], Maths':[54,56,57,67,66], 'Science':[78,88,77,99,89])
df-pd.Data Frame(data)
print(df) Result Analysis
100
Eng
df['Grade']=('A1', A2', 'A1,'B1',' A2'] Hn
Math
print(df) 90 SC

df.to_csv('studentinfo.csv')

print("No. of records", df.count() 80

print(df.T)
70

import matplotlib.pyplot as plt 60

Ritesh Mana Harshal Parth Srsht


Student Name

plt.plot(df['Name'],df['English'], r,label='Eng')
plt.plot(df('Name'),df[|Hindi']).'g'abel'Hin')
plt.plot(df['Name'],df[fMaths'],"'b',label-'Math)
plt.plot(df['Name'],df('Science'],'m',label'Sci')
plt.legend)
plt.title(Result Analysis')
plt.xlabel('Student Name')
plt.ylabel('Marks')
plt.show()

Q4

import pandas as pd
data=('Name':['Anand', 'Manish', 'Rohit', 'Suresh",'Mahesh'], Year':(2020,2020,202 1,2021,2020), To
tal Score':[410,350, 150,380,400],'Result':["'Pass',' Pass', Fail',
'Pass', Pass'])
df=pd.Data Frame(data)
print(df)

print(df.loc[df['Name']=='Anand') Student Analysis


print(df.loc[df['Result']=='Pass'])
400

df.to_csv('student. csv') 350

print(df['Year']) 300

print(df.shape) 250

200

import matplotlib.pyplot as plt 150

plt.bar(df['Name'], df[('Total 100

Score'],color=['b', 'y', 'r,'g,'m'])


50

plt.title('Student Analysis')
Anand Manish Pohit Suresh Mahesh
plt.xlabel('Name of Students') Name of Students

plt.ylabel('Total Score')

plt.show()
Assertion Reasoning based
Assertion (A):
information and data using visual
Data visualization refers to the graphical representation of
elements like charts, graphs and maps etc.
Reason (R):

Toinstall matplotlib library we can use the command


pip installmatplotlib.
A

the correct explanation


of

A. BothA and R are true and R is

8. Both A and R are true but R is not the correct explanation of A

C.Ais true but R is false


D. A is false but Ris true
E. Both A and R are false

Assertion (A): Two sequences being plotted using plot function of matplotlib library do not produce
any result and gives error.
Reasoning(R) Two sequences being plotted do not match in their shape.
:

A. Both A and R are true and R is the correct explanation of A


B. Both A and R are true but R is not the correct explanation of A

CAis true but Ris false

D. A is false but R is true


E. Both
A
and R are false

Assertion : Line chart displayed as scatter chart.


Reasoning : linestyle argument is not specified with linecolor& markerstyle
BothA and R are true and the correct explanation
A
R of
A. is

B. Both A and R are true but R is not the correct explanation of A


C.A is true butRis false
D. A is false but Ris true
E. Both A
and Rare false

Assertion :While plotting chart using matplotlib, the coordinate postion of x axis andy axis is always
set to 0,0 and any data beyond this cannot be displayed
Reasoning :by using function pf pyplot we can limits for x-axís and y-axis.

A.
Both A and R are true and R is the correct explanation of A
B. Both A
and R are true but R is not the correct explanation of A
C.A is true but R s fase
D. A
is false but R is true
E. Both A
and R are false

1. Consider a given Series, M1:

Marks
Term1 45
index
Term2 65
Term3 24
Term4 89

Write a program in Python Pandas to create the series similar to creating a Datafrarme.
2. Consider the Dataframe
Humanoid

H1
H_2

H_3
i.
Write a command to display the records of the dataframe which have amount greater

than equal to5000.

i. How will you change the index from H_1,H_2,H_3 to101,102, 103

SName Amount

Alexa 7000

Cortana 5000

MCO 20 Siri 4000


1. How do you set a title for a plot using
matplotlib library?
A. plt.set.title("Title'")

B. plt.Title("Title")

C. plt.title("Title")
D. plt.set title("Title")

2. What is the function for creating a horizontal bar plot?


A. plt.bar hor(x, y)
B. plt.hbar(x, y)
C. plt.barh(x. y)

D. plt.bar(x. y)
3. What is the standard way to import matplotlib's pyplot library in python
A. import matplot as plt
B. import matplotlib,pyplot as plt
C. from matplotlib inport pyplot as plt
D. import matplotlib pyplot as plt

4. Given a Pandas series called p_series, the command which will display the last 4 rows is

A. print(p_series.Tail(4))
B. print (p_series.Tails(4))
C. print (p_series.tail(4))
D. print(p_series.Tails(4))

5. Using Python Matplotlib histograms can be used to count how many values fall into each

interval. Each interval is known as


A. hist
B. class
C. bin
D. label

6. Which of the following type of chart is not valid


A. Line
B. Pie
C. Curve
D. Bar
7. We can display more than one data series in
A. Line chart
B. Bar chart

C. Histogram
D. Both A and B
E. Allof the above
8. In histogram it describes the no. of that fall within a given value of data range
A. bins
B. bins

C. range
D. range)
Data Visualization with Pandasis the presentation of data a
in oranhicalformat. It heips peope
understand the significance ofdata bysummarizing and prosenting a huge amount of data in a
simple and easy to-understand format and helps communicate information clearly and
erectuvey
Datavisualization is a general term that describes any
effort to help people understanu t
Significance of data by placing it ina visual context. In simple words., Data
visualization 5 the
process of displaying data/information
ingraphical charts,figures and bars.
SIgniticance :- Patterns, trends and correlations that might oo undected in text based data can be
exposed and recognized easier with data visualization techniaues or tools such as line chart, bar
cart,histogram etc, Thus the data visualization tools, information can be
processed in eiciemt
manner and hence better decisions can
be made.
Python Supports data visualizations by providing some useful
libraries for visualization. IMMost

commonly used data visualization library is matplotlib.


The matplotlib libraryoffers very extensive range of 2D plot types and output formats. It offers
complete 2D support along with limited 3D graphic support. It is useful in producing publication
quality figures in interactive environment across platforms. It can also be used for animation as
well.

Types of chart
1. Line chart - A line chart or line graph is a type of chart which displays information as a series
of data points called markers connected by straight line segments. The pyplot interace offers
plot() function for creating a line graph.
2. Bar chart - It is a graphical display of data using bars of different heights. A bar chart can be
drawn vertically or horizontally. Pyplot offers bar function to create a bar chart.
3. Histogram - A histogram is a statistical tool used to summarize discrete or continuous data. It

provides a visual representation of numerical data by showing the number of data points that
fallwithin a specified range of values called bins.

LINE CHART

1. Plotting a single line


2. Plotting more than one line

Various settings/attributes of line chart


1. Changing line color and style and Iinewidth
plt.plot(x,a, 'b',linewidth=4,linestyle=' dashed')
other linestyle aref linestyle-['solid".'dashed', ' dashdot,' dotted'}
2. Changing marker type, size and color
plt.plot(a.b, 'k'.marker=d'.markersize=5.,markeredge color='red')

BAR CHART

1. Creating bar graph


Command - plt.bar(info.Australia)
2. Creating multiple bar graph

3. Creating horizontal bar chart


plt.barh(info,australia)
Various setting of bars in bar chart
1. Changing width of bar

Default width-0.8 units


plt.bar(in fo, Australia, width=0.5)l all bars of equal width
plt.bar(info, Australia, width-[0.5,0.6.0.7.0.8] l all bars of different width
2. Changing colors of the bars in a bar chart

plt.bar(info,Australia,color=r) I/ all bars of same color


plt.bar(info,Australia,color-['r,' g,"b', 'k']) ll all bars of different color

Customizing the plot


1. plt.figure(figsize-(width, length)
2. plt.title(*"A Bar Chart")
3. Setting x and y limits- plt.xlim(-2.0,4.0)
4. Setting ticks for axes- plt.xticks([0,1,2,3])
5. Adding legends
import matplotl ib. pyplot as plt
import numpy as np
ob-('Python 'C++, '3ava ', ' Perl','scala','Lisp)
y_pos=np.arange(len(ob) )
performance-[10, 8,6,4,2,1]
plt.bar(y_pos, performance, align=' center',color='r)
plt.xticks (y_pos, ob)
plt.xlabel("Usage")
plt.title('P.L.Usage)
plt.show()

P.LUsage
10

Python Pert Scala Lisp


Usage

yel[140, 16,140, 180,10|, |130, 209, 180, 150, 160},[128, 130,150, 208,130), |190, 200, 178, 129,
1||
X=np.arange(5)
plt.bar (x+0.00,y[0], color-'b' ,width-0.30,label='1AN')
plt.bar(x+8.28,y[1], color='r',width-8.30, label='FEB')
plt.bar (x+6.48,y[2], color-'k',width-8.30,label-'MAR')
plt.bar(x+8.68,y[3], color='g',width-8.30,label= 'APR')
plt.ylabel('Rainfall in mn')
plt.xlabel('Directions')
plt.title("'Data of rainfall for 4 months')
plt.xticks (x, a)
plt. legend(1oc='upper right')
plt. show)
Data of rainfall for 4 months
200 JAN
FEB
175 MAR
150 APR

125

100

75

50

25

north sOuth east Vest Central


Directions
inport -matplotl ib.pyplot as plt
x-[1,4,5,6,7]
y-[2,6,3,6, 3]
plt.plot (x,y, color-'red' , linestyle-' dashdot', linewidth=3,
marker='o', markerfacecolor='blue' ,markersize-12)
plt.ylim(1, 8)
plt.xlim(1, 8)
plt.xlabel('x -axis')
plt.ylabel('y-axis')
plt.title('Displaymarker')
plt.show()

Displaymarker
8

y-axis
54

1
1 2 4 5 6 7 8
X-axis

o:Write a Python program to plot a bar chart, showing the No. of Books published in respective year using
the following data.
No. of Books = [160,170,185, 150,200]

Year = (2019, 2020, 2021, 2022, 2023)


Colour of al
bar should be different and the No of books and year labels should be displayed in the desired
Yearwise".
location and also the title of plot should be "Books published

Explain Matplotlib.
Write the names of various types of plots offered by matplotlib library.
Write the name of the attribute to specify the style of the line as dashed in line chart.
Section B-2 Marks each
What is the purpose of a legend?
Name any 4 methods used in pyplot.
Differentiate between bar chart and histogram.
What types of graphs can be plotted using matplotlib?
How to change the thickness of line, line style, line color, and marker properties of a
chart?
Define histogram.

2. Plot a histogram for marks of 10 students obtained in atest out of 100. Adjust bins as per
suitability. What is the affect on histogram on changing value of bins. Draw the histograrn so produced.
Also display title, xlabel, ylabel.
2. Give output forthe following program:

import matplotlib.pyplot as plt


india_score=[7,8,4,6,9]
australia_score=(6,5,9,9,7]
over=[1,2,3,4,5]
plt.plot(over,india_score, label="India")
plt.plot(over,Australia_score,label="Australia")
plt.xlabel("Name of Country")
plt.ylabel("'Scoring rate in 5 overs")

plt.legend()
plt.show()
3. Ramesh is an IP student. He is working on Data Visualization. His teacher has assigned hirrn a task
to create a line chart to show rainfallin Jaipur from 2001 to 2005. His code produced the following
output:
Rainfall in Jaipur

350

300
mm

in
Rainfall
250

200

150

2001 2002 2003 2004 2005


Year

Write code to produce this output.

CBT QUestions
1. Consider the following graph (Figure 26). ldentify
the code to plot it.
a. import matplotlib.pyplot as plt plt.plot
(2,7],[1,6]) !6). ldentify the code to plot it.
plt.show()
a. import matplotlib.pyplot as plt plt.plot([1,6],(2,7)

plt.show( )

b. import matplotlib.pyplot as plt plt.plot([2,3]. [5, 1


1)

plt.show( )
d. import matplotlib.pyplot as plt plt.plot([1,3], [4,1])
Figure for Questlon 26
)
plt.show(
2. For the given histogram number of bins are

Chem
2

60 BO 100
3. In the following line chart, the command to plot is

Open
782
High
Low
780 Cose

778

776

774

772

rinketplutprry
770

O3 O4 O6

2016
trin ket_plot. png
A. plt.plot(x,y, color='g, label= low')
, )
plt.plot(x,y, color='r' label=close
plt.plot(x,y,color="b', label='open')
,
plt.plot(x.y, color='y' label='high)
plt.legend(0
B. plt.plot(x.y, colour='g, label='low')
plt.plot(x,y,colour='r, label= close')
plt.plot(x.y,colour-'b', label='open' )
plt.plot(x.y,colour-'y' ,label='high')
plt.legend0
C. plt.plot(x,y,linecolorr'g,label=low')
plt.plot(x,y. linecolor-'r label=' close')
plt.plot(x,y,lineco lor-b',label='open')
plt.plot(x,y, linecolor='y', label="high')

plt.legend(0

4. For the following code the line chart printed will be of which shape
x=np.array([-5,-4,-3,-2,-1,0, 1,2,3,4,5])
y-x**2+16
plt.plot(x,y)
plt.show()
A. B
5. pltlegend() is not printing legend in the the graph, the reason could be
A. Label attribute is not set
while plotting.
B. Legend is not plotted.
C. Legend color is not set.
D. Legend is not positioned properly.

6. While ploting multiple graph, the bars gets overlapped and some data is not shown, the way
to print multiple bar is
A. Setting thickness of bar
B. Setting starting position of bars on x axis for multiple data ranges.
C. Choosing different colors for different bars
D. Seting x label
7. What type of chart is this figure

A. Multiple bar chart

B. Bar chart
C. Histogram

D. Frequency polygon

Case Base Study


on number of
Q Mrs. Namrata is a coordinator in the senior section school. She represented data
students who passed the exam on line chart as follows:

Boys
Girls
30

25
Students

20
of
No.
2 15

10

XA XIl A XIIB
XB XI A XIB
Classes

She has written the following code but not getting the desired output. Help her by correcting her
code.

import matplotlib.pyplot as plt


classes=-("X A", "X B","XI A", "XIB", "XI| A", "XI1 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 Stduents") #Statement 3


plt.ytitle("Classes") #Statement 4

plt.show()
i) What will be the correct code for Statement 1
and Statement 2?

ii) What is the correct function name for Statement 3 and Statement 4?

iü) Write a method and parameter required to display legends?

tl Name the parameter and values used to apply the marker as given in the output.

vÌ Name the parameter and values Used to apply line style as given in the utet
vi)How to apply the line colours as given in the figure?

vi) Write to save the figure as image.


Q1:

Consider the Data Frame below and answerthe questions that follow.

Name Weight Height

A_1 Pawan 50 153

A_2 Piyush 60 165

A_3 Prem 40 150

A_ 4
Prakash 70 145

A_S Prateek 55 160

a. Which command willproduce the following output to extract only a part of

dataframe?

Piyush 60

Prem 40

Prakash 70

b. What is the correct syntax to display the record of Piyush?


i. df_data(df_data['Name']='Piyush']

i. df_data[df_data['Name']=='Piyush']
ii. df _data [df_data.Name=='Piyush']
iv. df_data['Name']==Piyush'
c.
What output of the command
>>> df_data.max()

d. How do you display only the index of the dataframe df_data?

e. What is the shape of the dataframe df_data?


Attendance of students in class as shown in the figure
2. Write a code to plot the Monthly
name xlabel and ylabel. 3Marks
given below: Display title of graph and

Monthly Attenda nce

AN FEB MAR APR MAY JUN

3. Draw a bar chart as below representing the number of students in each class. Display title of

graph and name xlabel and ylabel.

Student Strength

30

20

10

4. 3 Marks

5. Mr. Vijay is working in the mobile app development industry and he was comparing the given
chart on the basis of the rating of the various apps available on the play store.

App Rating

3
Rating

Arogya Setu WPS Office Cam Scanner WhatsApo Telegram


Apps
He is trying to write a code to plot the graph. Helo Mr Viiay to fl in the blanks of the code and get
the desired output.

import as plt #Statement 1

apps=["Arogya Setu", "WPS Office", "Cam Scanner" "WhatsApp", "Telegram"]


ps_rating-[3.9,4.5,4.6,4.2,4.3]
plt. (apps,ps_rating,color='m',label= #Statement 2 Statement 3

plt.xlabel("Apps")
plt.. ("Rating") #Statement 4
plt. #Statement 5

plt.
#Statement 6
i)Write the appropriate statement for #state ment 1 to import the module.
i) Write the function name and label name as displayed in the output for #statement 2 and

#statement 3 respectively.
iii) Which word should be used for #statement 4?
iv) Write appropriate method names for #Statement 5 to display legends and #Statement 6 to
open the figure.

v) Mr. Vijay wants to change the chart type to a line chart. Which statement should be updated

and which method or function is used?


Database Concepts:

Introduction to Database
a
The of interrelated data is called database, and database system is fundamentally
colle ction
one particular
Computer based record keeping System. Database, contains information about
enterprise, especially for decision-making in management of the organization.

common and control approach is adopted for adding., modifying and retrieving data from database.
A

as
The importance of database is that the same collection of data serves as many applications possible.
Database is repository of information and it answers to the queries for planning purposes.

REQUISITES OF DATABASE (Need)

A database should be repository of all types of data. Data should be accurate, private and protected
from damage. Database should be well-organized so that data may be used in diverse applications.
Different application programmers and end users should have different views of data, as per their
need and use. Database should be valuable in the sense that it may be utilized in constantly and rapidly
changing conditions and in new conditions. Database should not have duplicate data. Database should
contain standardized data.
DATABASE MANAGEMENT SYSTEM (DBMS) DBMS is a software that controls the organization, storage,
retrieval, security and integrity of data in a database. DBMS accepts request from application and
instructs the operating system to transfer the appropriate data. DBMS makes use of traditional
programming languages such as COBL, C, C++ etc, or it may include its own programming language for
application development.
ADVANTAGED/CHARACTERISTICS OF GOOD DBMS

DBMS Reduced Data Redundancy


Duplication of data is known as data redundancy. Data redundancy leads to inconsistency,
wastage of storage space and human-time.
In DBMS, all the data are kept at one place and all the applications that require data refer to
centrally maintained database. If any change is made to data, it will be made just at one place and
the same changed application will be available to all the applications referring to it. Thus,
redundancy gets controlled and so the problems associated with it also gets controlled.

DBMS Controls Data Consistency When the redundancy is not controlled, there may be
occasions on which the two entries about the same data do not agree. This situation called
inconsistency. Inconsistence results in incorrect and conflicting information.DBMS controlled this
inconsistency by controll ing redundancy or by propagation updates (retaining redundancy due to
some technical reasons, without inconsistency is called propagation update).
DBMS Facilitates Data Sharing Accessing the same piece of data to different user for different uses
iscalled sharing of data. DBMS ensures this facility.
DBMS Enforces Standards DBMS enforces standards which are set by the company or
organization. This is done so that desired data may be interchanged or migrated between
different systems.

DBMS Ensures Data Security The information stored insidesthe database is of great value
and organization or corporation. Therefore DBMS ensures data security and privacy of data
ensuring that access to database can be made through proper channel.
DBMS Maintains Integrated Database Unification of severaldistinct data with any redundancy
eliminated is called integrated database DBMS ensures integrated database against hardware
failures and various types of accidents occurring occasionally, through updating and se
procedure defined by DBMS.

TYPES OF USERS ON DBMS

End UserAn end user isa person who is not a computer trained person but used the databa5e to
retrieve some information. E.g. In a railway /airways reservation system, a Customer retneves
details of train/flight details.
Application System Analyst A person who is concerned about the database at logical level, without
considering the physical implementation details is called application system analyst.
Physical Storage System Analyst Physical storage system analyst is a person who is concerned witn
the physical implementation details of the database.
DATABASE ABSTRACTION A database system provides the users only that much information that is
required by them. The complexities and details are hidden form users. This is called database
abstraction.
VARIOUS LEVESL OF DATABASE ABSTRACTION/IMPLEMENTATION
It
or
Internal Level Physical Level This is the lowest level of abstraction. It describes how the data are
actually stored on the storage media. At this level, complex, low level data structures are described
in details.

Conceptual Level It describes about the actual storage in database and relationship among existing
data. Data-structure is very important at this level.

External Level or View Level This is closest to the users. It is concerned with the way
and style
of display of data for users. The interrelationship of the three levels has been given in the following
figure:

EXTERNAL LEVEL
View1 View-2 View-3

CONCEPTUAL LEVEL

CONCEPTUAL LEVEL

DATA INDEPENDENCE The ability to modify a scheme definition in one level without affecting a
scheme definition in the higher level is called data independence.
THE RELATIONAL DATA MODEL This data model was propounded by E., F, Codd of lBM, and accepted
in DBMS technology. This model is also used in CAD and other environment.

TERMINOLOGY USEDIN RELATIONAL DATA MODEL

Entity An entity is an object which can be distinctly identified. E.g. a car with no. MP-136667.
student's
Roll No. 47 are entities.
Relation A relation is a table consisting of rows and columns. The programmer views a relation
as file in database. The column's name is called attribute. A structure of
relation name Procuct hae
been shown below:
Produc Headin
t
Attribut
PID Name Company Price (in Rs.)
NO01 -POD JXD 15000.00
NO02 LAPTOP LG 28000.00
Data

Domain The domain is a set of possible values that an attribute can have.
Tuple A row in a relation is called a tuple. A tuple having a set of n numbers of attributes is
termed as n-typle. The number of tuples in a relation may vary with time because on demand of users
of some tuples can be added or deleted.
Attributes The columns of relation are generally called attributes.
Degree A relation having n attributes is said to be a relation of degree n.

Degree of Relation Relation referred as


1 Unary relation
2 Binary relation
3 Tertiary relation
5 N-ary relation
Cardinality The number of tuples in a relation is called the cardinality of relation.
KEYS Keys are a special type of attributes which provides uniqueness to tuples. There four types of
keys -
1. Primary key :A primary key is a set of one or more attributes that can uniquely identify tuples
within the relation. For example, PID is a primary key in the relation Product.
2. Candidate key: The attribute which can serve as a primary key are called candidate keys as they
are eligible for primary keys.
3. Alternate key : A candidate key that is not the primary key is called alternate key.
4. Foreign key: A non-key attribute whose values are derived from the primary key of some other
table is known as foreign key to the current table.
The table in which the foreign key attribute exists, is called a foreign table or detail table and the table
that defines the primary key, form which the foreign key of detail table is derived is called primary
table or master table.
Structured Query Language
sOL is a non procedural language that is used to create, manipulate and process the relations.
Characteristics SQL of

1. lt is very easy to learn and use.


2. Large volume of databases can be handled quite easily.
3. It is non procedural language. It means that we do not need to specify the procedures to
accomplish a task but just to give a command to perform the activity.
4. SQL can be linked to most of other high level languages that makes it first choice for the
database programmers.
Processing Capabilities of SQL
The following are the processing capabilities of SQL
Data Definition Language (DDL) :
DDL contains commands that are used to create the tables, databases, indexes, views, sequences
and synonyms etc.
e.g: Create table, create view, create index, alter table etc.
Data Manipulation Language (DML)
DML contains command that can be used to manipulate the data base objects and to query the
databases for information retrieval.
e.g Select, Insert, Delete, Update etc.
DataControl Language
This language is used for controlling the access to the data, Various cornmands like GRANT,
REVOKE etcare available in DCL.
Transaction Control Language (TCL)
TCL include commands to control the transactions in a data base systerm. The cornmonly used
commands in TCL are COMMIT, ROLLBACK etc.

Data types of SQL

Just like any other programming language, the facility of defining data of various types is available in
SQL also. Following are the most common data types of SQL.
1) NUMBER
2) CHAR
3) VARCHAR / VARCHAR2
4) DATE
5) LONG
6) RAW/LONG RAW

1. NUMBER/DECIMAL
Used to store a numeric value in a field/column. It may be decimal, integer or a real value.
General syntax is Number(n,d)
Where n specifies the number of digits and d specifies the number of digits to the right of the
decimal point.
e.g marks number(3) declares marks to be of type number with maximum value 999.
pct number(5,2) declares pct to be of type number of 5 digits with two digits to the right
of decimal point.
2. CHAR
Used to store character type data in a column. General syntax is
Char (size)
where size represents the maximum number of characters ina column. The CHAR type data can hold
at most 255 characters.
e.g name char(25) declares a data item name of type character of upto 25 size long.

3 VARCHAR/VARCHAR2
This data type is used to store variable length alphanumeric data. General syntax is
varchar(size) /varchar2(size)
where size represents the maximum number of characters in a column. The maximum allowed size
in this data type is 2000 characters.
e.g address varchar(50); address is of type varchar of upto 50 characters long.

4 DATE
Date data type is used to store dates in columns. SQL supports the various date formats other that
the standard DD-MON-YYYY.
e.g dob date; declares dob to be of type date.

5 LONG
This data type is used to store variable length strings of upto 2
GB size.

e.g description long,


6 RAW/LONG RAW
RAW or LONG RAW data type is used A
lo store binary data (images/pictures/animation/clips etc)
column LONG RAWtype can hold upto 2 GB of binary data.
eg image raw(2 000):

SQL Commands
CREATE TABLE Command:
Create table command is used to create a table in SQL It is a DDL type of command. The general
syntax of creating a table is
Creating Tables
The syntax for creating a table is
create table <table> (
<column 1> <data type> [not nul] [unique) [<column constraint>]

<column n> <data type> [not nul] [unique] [<column constraint>l


<table constraint(s)>]

For each column, a name and a data type must be specified and the column name must be unique
within the table definition. Column definitions are separated by comma. Uppercase and lowercase
letters makes no difference in column names, the only place where upper and lower case letters
matter are strings comparisons. A not null Constraint means that the column cannot have null value
that is a value needs to be supplied for that column. The keyword unique specifies that no two tuples
can have the same attribute value for this column.
Operators in SQL:
The following are the commonly used operators in SQL
1. Arithmetic Operators
2.. Relational Operators
3. Logical Operators OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations.
Relational Operators are used when two values are to be compared and
Logical operators are used to connect search conditions in the WHERE Clause in SQL
Constraints:
Constraints are the conditions that can be enforced on the attributes of a relation. The constraints
come in play when ever we try to insert, delete or update a record in a relation.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY

4. FOREIGN KEY
5. CHECK
6. DEFAULT
Not null ensures that we cannot leave a column as null. That is a value has to
be supplied for that
column.
e.g name varchar(25) not null:
Uniaue constraint means that the values under that column are always unique.
e.g Roll_no number(3) unique;
Primarv key constraint means that a column can not have duplicate
values and not even a null value.
Roll no number(3)
e.g. primary key;
The main difference between unique and primary key
constraint is that a column specified as unique
may have nullvalue but primary key
constraint does not allow null values in the column.
Coreign key is used to enforce referential integrity
and is declared as a primary key in some other
table.
e.g cust id varchar(5) references master(cust id):
it declarescust_id column as a foreign key that refers to cCust id feld of table master. nat mea
cannot insert that value in cust_id filed whose corresponding value is not present in cust_id neld o
master table.
Check constraint limits the values that can be inserted into a column of a table.
e.g marks number(3) check(marks>=0);
The above statement declares marks to be of type number and while inserting or updating the vaiue
in marks it is ensured that its value is always greater
than or equal to zero.
Default constraint is used to specify a default value to a column of a table automatically. This default
value will be used when user does not enter any value for that column.
e.g balance number(5) default = 0;
CREATE TABLE student
Roll_no number(3) primary key,
Name varchar(25) not null,
Class varchar(10),
Marks number(3) check(marks>0),
City varchar(25) );
Data Modifications in SQL
After a table has been created using the create table command, tuples can be inserted into the table,
or tuples can be deleted or modified.
INSERT Statement
The simplest way to insert a tuple into a table is to use the insert statement
insert into <table> [(<column i,
. . . ,
column j>)] values (<value i,
... , value j>);
INSERT INTO student VALUES(101, Rohan', XI'400,'Jammu');
While inserting the record it should be checked that the values passed are of same data types as the
one which is specified for that particular column.
For inserting a row interactively (from keyboard) & operator can be used.
e.g INSERT INTO student VALUES(&Roll_no,&Name, &Class''&Marks'' City' ): &

In the above command the values for all the columns are read from keyboard and inserted into the
table student.
NOTE:- In SQL we can repeat or re-execute the last command typed at SQL prompt by typing "/" key
and pressing enter.
Roll_no Name Class Marks City

101 Rohan XI 400 Jammu


102 Aneeta Chopra XII 390 Udhampur
Pawan Kumar IX 298 Amritsar
103
Rohan IX 376
104 Jammu
105 Sanjay VII 240 Gurdaspur
113 Anju Mahajan VIlI 432 Pathankot
Queries:
To retrieve information from a database we can query the databases. SQL SELECT statement is used
to select rows and columns from a database/relation.
SELECT Command
This command can perform selection as well as projection.
Selection: This capability of SQL can return you the tuples form a relation with all the attributes
Projection: This is the capability of SQL to return only specific attributes in the relation.
SELECT* FROM student; command will display all the tuples in the relation
student
SELECT * FROM student WHERE Roll no <=102;
The above command display only those records whose Roll_no less than or equal to 102.
Select command can also display specific attributes from a relation.
SELECT name, class FROM student;
The above command displays only name and class attributes from student table.
SELECT count(*) AS "Total Number of Records" FROM student;
Display the total number of records with title as "Total Number of Records" i.e an alias
We can also use arithmetic operators in select statement, like
SELECT Roll _no, name, marks+20 FROM student;
SELECT name, (marks/500)* 100 FROM student WHERE Roll_no> 103;
Eliminating Duplicate/ Redundant data

DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT statement.
e.g. SELECT DISTINCT name FROM student;
The above command returns
Name
Rohan
Aneeta Chopra
Pawan Kumar

Conditions based on a range


SQL provides a BETWEEN operator that defines a range of values that the column value must fall for
the condition to become true.
e.g. SELECT Roll_no, name FROM student WHERE Roll no BETWENN 100 AND 103;
The above command displays Roll_no and name of those students whose Roll_no lies in the range 100
to 103 (both 100 and 103 are included in the range).

Conditions based on a list


To specify a list of values, IN operator is used. This operator select values that match any value in the
given list.
e.g. student WHERE city IN ('Jammu'; Amritsar;Gurdaspur);
SELECT * FROM
The above command displays all those records whose city is either Jammu or Amritsar or Gurdaspur.

Conditions based on Pattern


SQL provides two wild card characters that are used while comparing the strings with LIKE operator.
a. percent(%) Matches any string
b. Underscore() Matches any one character
e.g SELECT Roll _no, name, city FROM student WHERE Roll_no LIKE "%3";
displays those records where last digit of Roll_no is 3 and may have any number of characters in front.
e.g SELECT Roll no, name, city FROM student WHERE Roll no LIKE "1
3";
displavs those records whose Roll_no starts with 1 and second letter may be any
letter but ends with
3.
digit
DELETE Command
To delete the record fro a table SQL provides a delete statement. General syntax is:
DELETE FROM <table_name> [WHERE <condition>];
e.g. DELETE FROM student WHERE city = (Bhopal';
Thiscommand deletes allthose records whose city is Bhopal.
UPDATE Command
To update the data stored in the data base, UOPDATE COmmand is used.
UPDATE student SET marks =
e. g. marks + 100; (|ncrease marks of all the students by 100.)
UPDATE student SET City = 'Indore' WHERE city =
e.g. Ujain':
changes the city of those students to Indore whose city is Uijain.
We can also update multiple columns with update command, like
e.g. UPDATE student set marks = marks + 20, city = 'Jalandhar
WHERE City NOT IN ('Jammu'"'Udhampur');

ALTER TABLE Command


In SQL if we ever need to change the structure of the data base then ALTER TABLE COmmand is Useu
By using this command we can add a column in the existing table, delete a column from a tzbie
modify columns in a table.

Adding a column
The syntax to add a column is:
ALTER TABLE
table name
ADD column name datatype;
e.g ALTER TABLE student ADD(Address
varchar(30);
The above command adda column Address to the table atudent.
If we give command
SELECT * FROM student;

The following data gets displayed on screen:


Roll_no Narme Class Marks City Address
101 Rohan X1 400 Jammu
102 Aneeta Chopra XI1 390 Udhampu

103 Pawan Kumar 1X


298 Amritsar
104 Rohan IX 376 Jammu
105 Sanjay VIl 240 Gurdaspu
r
113 Anju MAhajan Vill 432 Pathanko
t

Note that we have just added a column and there will be no data under this attribute. UPDATE
command can be used to supply values / data to this column.
Rernoving a column
ALTER TABLE table_name
DROP COLUMN column_name;
e.g ALTER TABLE Student
DROP COLUMN Address;
The column Address will be removed from the table student.

DROP TABLE Command


use. DROP TABLE COmmand is usodto
Sometimes you may need to drop a table which is not in
we can not drop a table if it
Delete/ drop a table permanently. It should be kept in mind that
contains
can be
records, That is first all the rows of the table have to be deleted and only then the table
dropped. The general syntax of this command
is:

DROP TABLE <table_name>;


e.g DROP TABLE student;
This command will remove the table student
MLL
1. A large collection of related data, which models the relationship between various entities
is called
(a) Database
(b) File
(c) Record
(d) None of these
2. Duplication of data is known as data
(a) Redundancy
(b) Inconsistency
(c) Security
(d) Dependency
3. column in a table that uniquely identifies the rows in the table is called
A

(a) Primary Key


(b) Foreign Key
(c) Candidate Key
(d) Super Key
4. Which of the following is not DML Command
(a) Select
(b) Insert
(c) Update
(d) Create
5. Total Number of a column is called
(a) Cardinality
(b) Degree
(c) Key
(d) None of above
6. By using this command we can add a column in the existing table
(a) Create
(b) Insert
(c) Drop
(d) Alter
7. A
is a property of the entire relation, which ensures through its value
that each tuple is
unique in a relation.
(a) Rows
(b) Key
(c) Attributes
(d) Fields
8. Special value that is stored when actual data value is unknown for an
attributes.
(a) Key
(b) Null Value
(c) Duplicate Value
(d) None

9. The operator which is used for pattern matching


along with Select command
(a) Between
(b) In
(c) Like
(d) Case
10 Consider the table with structure as
Student(ID, name, dept name, tot cred)
In the above table, which attribute will form the primary key?
(a) namne
(b) dept name
(c) Total credits
(d) ID
11. Which of the following is a DDL command?
(a) SELECT
(b) CREATE
(c) INSERT
(d) UPDATE
12. Which operator can take wild card characters for query condition?

(a) BETWEN
(b) LIKE
(c) IN
(d) NOT
?
13. In SQL, which command(s) is/are used to change table's structure/characteristics
a

(a) ALTER TABLE


(b) MODIFY TABLE
(c) CHANGE TABLE
(d)All of these
14. Which of the following statements will delete all rows in a table namely

mytable without deleting the table's structure.


(a) DELETE FROM mytable;'
(b) DELETE TABLE mytable;
(c) DROP TABLE mytable;
(d) None of these.

in DECIMAL(5,2)?
15. What is the maximum value that can be stored
(a) 9999.99
(b) 99.9999
(c) 99.99
(d) 9.99

12-b, 13-d, 14-a, 15-a


Answer: 1-a,2-a,3-a,4-d,5-b,6-d,7-b,8-b,9-c, 10-d,11-b,

MCQ
an error ?
1. Which of the following queries contains
(a) Select from emp where empid=10003;
empid=10006;
(b) Select empid from emp where
(c) Select empid from emp;
lastname= 'GUPTA;
(d) Select empid where empid=10009 and
2. A Table can have
(a) Many primary keys and many unique keys.
(b) One primary key and one unique key
(c) One primary key and many unique keys.
(d) Many primary keys and one unique key.

3. An attribute in a relation is termed as a foreign key when it reference the of another


relation.
(a) Foreign Key
(b) Primary Key
(c) Unique Key
(d) Check Constraint
4. What should be the data type for the column Item_ Price storing values less than
Rs. 1000
e.g.200.21
(a) VARCHAR(50)
(b) NUMBER
(c) DECIMAL(5,2)
(d) NUMBER(6)
5. ldentify the most correct INSERT queries from the following:
(a) INSERT INTO Persons('xx1', 'yy1');
(b) INSERT INTO Persons('Surname', 'Name')Values ('xxx, 'yyy):
(c) INSERT INTO Persons Values('xx1', 'yy1');
(d) INSERT INTO Persons Value('xx1', 'yyl')
6. To increase the size ofa column in an existing table, use commond
(a) Alter
(b) Select
(c) Modify
(d) Modify Size
7. What is the meaning of Remark LIKE
"%7%7%";
(a) Column Remark begin with two 7s
(b) Column Remark ends with two 7s
(c) Column Renark has more than two 7s
(d) Column Remark has two 7s in it, at any position.
8. Consider the following table namely Employee:
Employee_id Name Salary
1001 Rahul 6000
1009 Rohit 4500
1018 Ravi 7000
9. Consider the following SQL Statement. What type of statement is this
INSERT INTO COACHVALUES (10211, 'RAHUL', 'CS',
69000);
(a) Procedure
(b) DCL
(c) DML
(d) DDL
10. Which of the following will be the correct SQL a new column FEES
command to add
in a table TEACHER ?
(a) ALTER TABLE TEACHER ADD FEES FLOAT:
(b) ADD COLUMN FEES FLOAT INTO TEACHER;
(c) UPDATE TEACHER ADD COLUMN FEES FLOAT:
(d) INSERT INTO TEACHER ADD COLUMN FESS FLOAT:
11. Which of the following will display a list of tables in a database ?
(a) DISPLAY TABLES;
(b) SHOW TABLES;
(c) SELECT TABLES;
(d) VIEW TABLES;
from employee
12. Which of the following will display information about all the employees
table, whose names contains second letter as "A" ?
(a) SELECT FROM EMPLOYEE WHERE NAME LIKE "_A%";
(b) SELECT FROM EMPLOYEE WHERE NAME LIKE "%A_"
(c) SELECT * FROM EMPLOYEE WHERE NAME LIKE" A%";
SELECT WHERE NAME =
(d) FROM EMPLOYEE " A%";
13. Which of the following SQL command will help in decremanting values of
column in STUDENT table by 5%?
(a) UPDATE STUDENT ASSIGN FEES = FEES * 1.5%;
(b) UPDATE STUDENT SET FEES = FEES- FEES * 1.05;
(c) UPDATE STUDENT SET FEES = FEES * 5%;
(d) UPDATE STUDENT SET FEES- 5%;
14. Which of the following clause is used with SELECT Command in MySQL to avoid
duplication of output rows.
(a) NO DUPLICATE
(b) UNIOQUE
(c) DISTINCT
(d) NO REPEAT
a
15, Which SQL keyword is used to remove a table from database?
(a) DROP
(b) DELETE
(c) REMOVE
(d) ALTER
16. To add a column named "Email" of type VARCHAR to an existing table named
"Users," which SQL statement is correct?
(a) ALTER TABLE Users ADD COLUMN Email VARCHAR
(b) ALTER TABLE Users ADD Email VARCHAR
(c) UPDATETABLE Users ADD Email VARCHAR
(d) INSERT INTO Users (Email) VALUES ('VARCHAR')

17. What is the correct SQLstatement to create a foreign key in the "MYOrders" table that
references the "Customers" table's primary key?
la) CREATE FOREIGN KEY (CustomerlD) REFERENCES Customers(CustomerlD);
(b) ALTER TABLE MYOrders ADD CONSTRAINT fk customer FOREIGN KEY
(CustomeriD) REFERENCES Customers(CustomerlD);
(c) ALTER TABLE MYOrders ADD FOREIGN KEY (CustomeriD) REFERENCES Customers;
(d) CREATE TABLE MYOrders ADD FOREIGN KEY CustomerlD REFERENCES Customers;
18. What does the term 'cardinality' refer to in the context of databa ses?
a
(a) The uniqueness of data in column
(b) The number of rows in a table
(c) The number of tables in a database
(d) The relationships between tables
19. What is the correct SQL syntax to return only distinct (different) values from the
"Name" column in the "Employees" table?
(a) SELECT DISTINCT Name FROM Employees;
(b) SELECT UNIQUE Name FROM Employees;
(c) SELECT DIFFERENT Name FROM Employees;
(d) SELECT Name FROM Emnployees DISTINCT;
20. To update the "Salary" column in the "Employees" table by increasing all salaries by
10%, which SQL statement is correct?
(a) UPDATE Employees SET Salary = Salary " 1.1
(b) UPDATE Employees INCREASE Salary BY 10%
(c) ALTER TABLE Employees MODIFY Salary = Salary * 1.1
(d) CHANGE Employees SET Salary = Salary + (Salary * 0.1)

Answer:
1-d 2-c, 3-b, 4-c, 5-b, 6-a, 7-d, 8-c, 9-c,10-a, 11-b, 12- a, 13- b,
14-c 15- a,
16-b, 17-b,, 18-b, 19- a, 20-a

ASSERTION and REASONING

Question No. 1 to 15 are ASSERTION and REASONING based questions. Mark


choice as
the correct
(a) Both A and R are true and R is the correct explanation for A
(b) Both and R are true and R is not the correct explanation for A
A

(c) A is True but R is False


(d) A is False but R is True

1. Assertion(A): A database constraint can be added or removed any time from


database tables.
Reasoning(R): Alter table command is used to change the structure
(a) Both and R are true and R is the correct explanation
A of table.
(b) Both and R are true and R is not the correct
A
for A
explanation for A
(c) A is True but R is False
(d) A is False butR is True

2. Assertion(A): SQL has efficient mechanisms to retrieve


data stored in multiple
in a MySQL
tables database.
Reasoning(R): The SQL statements CREATE is used to retrieve
data from the
tables in a database and is also called query statement.
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct
explanation for A
(c) A is True but R is False
(d) A is False but R is True

3. Assertion (A): RDBMS stands for Relational Database Management


System.
Reasoning (R): RDBMS does not allow relating or associating two
tables in a
database.
(a) Both and R are true and R is the correct explanation
A

for A
(b) Both and R are true and R is not the correct explanation
A

for A
(c) A is True but R is False
(d)A is False but R is True

4. Assertion (A): The number of attributes or


columns in a relation is called the degree
of the relation.
Reasoning (R):The number of tuples or records in a
relation is called the
cardinality of the relation.
(a) Both A and R are true and R is the correct explanation
forA
(b) Both and R are true and R is not the correct
A

explanation for A
(c) A is True but R is False
(d) A is False but R is True
fromn the primary
foreign key is an attribute whose value is derived
S.Assertion (A): A
key of another relation. relationship between tables
or
key is used to represent the
Reasoning (R): foreign
A
relations. (a)
explarnation for A
(a) Both A and R are true and is the correct
R

(b) BothA and R are true and is not the


R correct explanation for A
(c) A is True but R is False
(d) A is False but R is True
6.
Assertion (A): A database can have only one table.
Reason (R): If a piece of data is stored in
two places in the database, then storage
space is wasted.
A
(a)Both A and R are true and R is the correct explanation for
tor A
(b) 8oth A and R are true and R is not the correct explanation
(c)A is True but R is False
(d)A is False but Ris True
is derived from
7. Assertion (A): Foreign key is a non-key attribute whose value
primary key of another table. a
Reason (R): Each foreign key refers a candidate key in relation.
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d)A is False but R is True
8. Assertion (A): Select command is DML Command
Reason (R): Update is alsoa DML Command to update the table
(a) BothA and are true and R is the correct explanation for A
R

(b) Both and R are true and R is not the correct explanation for A
A

(c) A is True but R is False


(d) A is False butR is True

9. Assertion (A): CHAR and VARCHAR2 is used for character datatype


Reason (R): VARCHAR2 is used for variable length character strings whereas CHAR is used
for fixed length strings
(a) Both and R are true and R is the correct explanation for
A A

ib) Both A and R are true and is not the correct explanation for A (b)
R

(c) A is True but R is False


(d) A is False but R is True
10. Assertion (A): It is possible to remove the tuple from the table.
Reason (R): DROP command is used to delete the tuple.
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A (b)
(c) A is True but R is False ©
(d) is False butR is True
A

11. Assertion (A): Update Command is used to modify the constraints


Reason (R): Alter Command is used to add the constraints.

(a) Both A and Rare true and R is thecorrect explanation for A

(b) Both A and R are true and R is not the correct explanation for A (b)
(c) A is True but R is False
(d) A is False but R is True

12. Assertion (A): Where clause can also be included with Select Command
Reason (R): Where clause is used to filter the data based on given condition.
(a) Both A and R are true and R is the correct explana tion for A
(b)BothA and R are true and R is not the correct explanation for (b) A

(c) Ais True but R is False


(d) is False but Ris True
A

13. Assertion (A): Prirmary key and Alternate Keys are subset of Candidate Keys
Reason (R): Primary Key should be unique and not null.
(a) Both A and R are true and R is the correct explanation forA
(b) Both and R are true and R is not the correct explanation for A b)
A

(c) A is True but Ris False


(d)A is False but Ris True

14. Assertion (A): Candidate key can be any attribute or combination of attributes
that can qualify as unique key in the database
Reason (R): There can be multiple candidate keys in a table
(a) Both A and R are true and R is the correct explanation
for A
(b) Both A and R are true and R is not the correct explanation for A (b)
(c) A is True but R is False
(d) A is False but R is True

15. Assertion (A): Data redundancy is the duplicate


data exist in database.
Reason (R): Data Consistency improves by controling Data Redundancy.
a) Both A and R are true and R is the correct explanation
for A
(b) Both A and R are true and R is not the correct
explanation for A (b)
(c) A is True but Ris False
(d) A is False but R is True
Answers
1. 8 2. C3.C4. B5. A
6. D 7. B
&. B9B 10 11D 12
C
B 13 B 14 B 15 A

Case Based Questions


Consider the Table ACCOUNT and solve the question from 1 to 15
TABLE: ACCOUNT

ANO ANAME ADDRESs AMOUNT


101 Nirja Singh Bangalore 15000
102 Rohan Gupta Chennai 20000
103 AliReza
Hyderabad 50000
104 Rishabh Jain Chennai 56000
105 Simran Kaur Chandigarh 25000
1. List the Account number and account
holder name who are not living in Chennai.
2. Display the Account number who are belongs to Hederabad Address.
3. Display the Account holder names whose name
is begin with letterR.
4 Increase the Amount number by 5000.
5. Display ANAME where ANO ranges
from 101 to 105
6. insert the values in above
table with 106, Ram Singh' Munmbai 10000.
7
Remnove all the records whose ADDRESS is
Chennai but not ANO 104.
8. Display the Account holder's Names,Amount
having amount is less than 1000 or address
is chandigrah.
9. Write the Degree and Cardinality of the table Account.
10. Add the column company of Character type.
11.Add the ANO as Primary Key constraint.
12. Delete all the records whose Amount is less than 50000.
13 List all those records whose AMOUNT is more
than 20000 and less than 50000
Give the output of following sql statement based on
table ACCOUNT
14. Select distinct{Address) from ACCOUNT Where ACNO in (101,103)
15. Increase the value of amount of all account holders who are from Chennai.
Answers:
1. Select ANO,ANAME from ACCOUNT where ADDRESS not in ("Chennar" );
2. Select ANO from ACCOUNT where ADDRESS in ("Hyderabad"):
3. Select ANAMEfrom ACCOUNT where ANAME like "R%";
4. Update ACCOUNT set AMOUNT=AMOUNT+5000;
S. Select ANAME FROM ACCOUNT where ANO between 101 and 105;
6. Insert into ACCOUNT values(106,'Ram
Singh'' Mumbai.10000)
7. Delete from ACCOUNT
Where ADDRESS='Chennai' and ANO<>104,
8. Select ANAME,AMOUNT from ACCOUNT AMOUNT<1000 OR
where
ADDRESS='Chandigarh';
9. Degree= 4, Cardinality=5
10. ALTER table ACCOUNT add Company
varchar2(10) :
11. Alter table Account add primary key (ANO);
12. Delete from ACCOUNT where AMOUNT<50000;
13. Select * From ACCOUNT Where AMOUNT>20000 AND AMOUNT<50000.
14. Chennai
15. UPDATE ACCOUNT set AMOUNT=AMOUNT+0.5*AMOUNT where ADDRESS=' Chennai';

MySQL Date and Aggregate Functions

Objectives:
1. Understand the purpose and usage of MySQL Date Functions.
2. Learn how to use Aggregate Functions in MysQL.
3. Master the use of COUNT("), Group by, Having, and Order by for querying and
manipulating data.
4. Develop problem-solving skills by answering MCQ, Level Learning, Assertion and Reasoning,
and
Case Study-based questions.

Lesson Structure:
1.
Introduction to Date Functions in MySQL - Brief overview of Date Functions and their significance.
Detailed explanation of NOw (), DATE (), MONTH (), MONTHNAME (), YEAR ), DAY (), DAYNAME (). -

Practical examples to understand the concepts.


I1. Understanding Aggregate
Functions in MySQL -Definition and importance of Aggregate
Functions in database queries. - Explanation of MAX (), MIN (), AVG (), SUM (), COUNT (), and COUNT
(").
- -
Querying and Manipulating Data Introduction to Group by, Having, and Order by clauses.
IlI.
-
Step-by-step guide on how to use Group by togroup similar data. Practical exercises on applving
Having to filter grouped data.

Name of the Explanation and use MySQL Example with


Function of the Function Output Assignment Questions
Date These functions work with dates and date-time values. They help extract
Functions specific parts of a date, format dates, and perform comparisons.
* Write a query
Returns the current SELECT NOW): to
*
NOW) display the current date
date and time Output: 2024-05-12
only (YYYY-MM-DD
(including seconds) 12:30:00
format).
Write a query to
Extracts the date part extract the date part
SELECT DATE(NOW)}:
DATE) (YYYY MM-DD)from a from a specific date-time
Output: 2024-05-12
datetime expression. value (e.g., 2023-11-19
10:20:30')
Write a query to
Extracts the month SELECT display all records from
MONTH) value (1-12) from a MONTH(NOW)): an 'Orders' table with an
date. Output: 5 'OrderDate' in the
Current month.

*
Write a query to display
all employees' names and
MONTHNAME) Returns the full SELECT their date of joining
month name (e.g., MONTHNAME(NOW()): (month name only) from an
"May') for a date. Output: May 'Employees' table.
* Write a query to find
the
Extracts the year total number of customers
*YEAR) added each year in the
(YYYY) from a date. SELECT YEAR(NOWO): 'Customers' table (use
Output: 2024 YEAR and COUNT).
* Write a query to display
Extracts the day of allupcoming birthday
* DAY) the month (1-31) records (month and day
from a date. SELECT DAY(NOW));
only) from a 'Students'
Output: 12 table.
Returns the full *Write a query to display
DAYNAME)
weekday name SELECT all ongoing courses with
(e.g., 'Sunday') for DAYNAME(NOW): their start date (day name)
a date. Output: Sunday from a 'Courses' table.

Name of
the Explanation and use MysQL Example with
Function of the Function Output Assignment Questions

Aggregate These functions perform calculations on groups of data. They provide


Functions summarized information like maximum, minimum, average, sum, and count.
SELECT MAX(salary) FROM
Returns the employees; Output
MAX() maximum value in a (assuming salary column Write a query to find the
column. exists): Maximum salary highest order amount from
value an 'Orders' table.,
SELECT MIN(price) FROM
*Write a query to find the
Returns the products; Output department with the
*MIN) minimum value in a (assuming price column lowest average salary in an
column. exists): Minimum product 'Employees' table (use MIN
price and AVG).
Write a query to find the
*

Calculates the SELECT AVG(marks) FROM average order value per


*AVG) average value in a students; Output customer in an 'Orders'
numeric column. (assuming marks column table (use AVG and GROUP
exists): Average marks BY).
SELECT SUM(quantity)

Calculates the sum of


FROM order_ items; *Write a query to find the
* SUM() values in a numeric Output (assuming quantity total number of employees
column exists): Total in each department from
column.
quantity of all items an 'Employees' table (use
ordered SUM and GROUP BY).
Counts the number
of rows in a table or Write a query to count
*

cOUNT(*) the number of non SELECT COUNT(*) FROM the number of orders
nullvalues in a customers; Output: placed in each month (use
specific column. Total number of customers COUNT and MONTH).

Name of Explanation and Assignment


the Topic Gist of the Topic MySQL Example with Output
Questions

Group By, * GROUP BY


GROUP BY
Example 1. Write a query to
Having & Groups data based SELECT department, COUNT(") display the number
Order By on one or more FROM employees GROUP BY of employees in each
columns. department; department and
Output: Groups employees by filter for
department and displays the departments with
count for each. more than 10
employees.
* HAVING - Filters HAVING Example
groups after SELECT department, COUNT() 2. Write a query to
BY
applying GROUP FROM employees GROUP BY display employee
(used with department HAVING COUNT() > details sorted by
aggregate 5; (This wilI name in ascending
functions). show departments with more order.
than 5 employees)

* ORDER BY- Sorts ORDER BY Example 3. Write a query to


data in ascending orSELECT * FROM employees find the department
descending order ORDER BY salary DESC; with the highest
(based on one or (This will order employees by average salary.
more columns). salary in descending order)

Serial Question Answer MySQL Example


No
*Question:** Retrieve the total
*cOUNT(")**; Counts number of employees and the
all rows in a table, number of employees with a
including rows with NULL department assigned (assuming a
values in the specified DeptName column).
Explain COUNT(") Vs.
COUNT(<col name>) column. * COUNT(<col
**Answer:** sQL:
name>): Counts only rows SELECT COUNT(") AS
where the specified Total_Employees,
column has a value (not COUNT(DeptName) AS
NULL). EmployeesWith Dept
FROM Emp;
**Question:** Find the number
of employees in each department.
**SQL:**
GROUP Used to group
BY: SELECT DeptName, COUNT(") AS
rows based on one or Employee Count
Where to use GROUP more columns and then FROM Emp
BY? perform aggregate GROUP DeptName;
BY

functions (like COUNT,


*
**Answer:** Thisquery groups
sUM, AVG) on each group. employees by their department
(DeptName) and then counts the
number of employees in each
department. |

**Question:** Find departments


with more than 5 employees.
**SOL:**
HAVING: Used with
SELECTDeptName, COUNT() AS
GROUP BY to filter the
Employee Count
grouped data based on a
FROM Emp
Where to use GROUP condition applied to the
GROUP BY DeptName
3 BY along with aggregate function's
HAVING COUNT(*) > 5;
HAVING? result. Note: HAVING is ***
**Answer:** This query groups
applied after the groups
are formed using GROUP employees by department and
BY.
then countsthem. Finally, it uses
"HAVING to filter and display only
departments with more than5
employees. |
1. Multiple Choice Questions(MCOs)

1. Which function returns the current date and time?


o a) DATE()
o
b) NOW() (Correct Answer)
c) YEAR()
d) DAY()
2. What function extracts the month number (1-12) from a date value?
o
a) MONTHNAME()
o b) DAYNAME()
o c) MONTH() (Correct Answer)
o d) YEAR()
3. Which function retrieves the full month name (e.g., 'January')?
a) MONTH)
b) YEAR()
) DAY()
d)MONTHNAME)(Correct Answer)
4. What function returns the year as a four-digit number?
a) DAY()

b) YEAR() (Correct Answer)


c) MONTHNAME)
e
d)NOW)
5. Which function extracts the day of the month as a
number (1-31)?
e
a) DAYNAME()
b) DAY() (Correct Answer)
c) MONTH)

d) YEAR()
6. What function retrieves the fullweekday name (e.g., 'Monday')?
a) MONTH)
b)DAY()
c) DAYNAME) (Correct Answer)
d) YEAR()
7. Which aggregate function returns the highest value in a column?
o a) AVG()
b) MIN()
o c) MAX() (Correct Answer)
o d) SUM)
8. What aggregate function calculates the average of a numeric column?
a) SUM()
o b) COUNT()
c) AVG() (Correct Answer)
d) MIN)
9. Which aggregate function computes the total sum of a numeric column?
a) MIN()
b) MAX()
c) COUNT()
d) sUM) (Correct Answer)
10. What aggregate function determines the number of rows (including NULL values)?
a) AVG()
b) SUM()
o c) CUNT) (Correct Answer) (can use COUNT(*))

d) MAX()
11. The GROUP BY clause is used to:
a) Sort data in ascending or descending order
o b) Filter rows based on specific criteria
c) Group rows with matching values in one or more columns (Correct Answer)
od) Combine results from multiple tables
12. The HAVING clause is used with GROUP BY to:
a) Apply additional filtering conditions after grouping (Correct Answer)
b) Define the order in which results are retrieved
c)Specify columns to be included in the result set
d) Rename columns in the output
13. The ORDER BY clause is used to:
a) Group rows based on shared values
b) Filter rows based on specific criteria
Answer)
c) Sort data in ascending or descending order (Correct
o
d) Combine results from multiple tables
14. Which of the following is NOT a valid order in the ORDER BY clause?
o a) column_name ASC
o b)column name DESC
o c) column_name
-
o d) column_name Order by expressions are not allowed
+5(Correct Answer)
15. How can you count the number of employees in each department using GROUP BY?
o a) SELECT
COUNT() FROM employees GROUP BY department; (Correct Answer)
o b) SELECT COUNT(department) FROM employees;
c) SELECT department, COUNT(*)FROM employees;
d) SELECT * FROM employees GROUP BY department;

16. Write a query to find the average salary for each department:

a) SELECT Department, AVG(Salary) FROM Employees; (Correct Answer)


b) SELECT Department, SUM(Salary) FROM Employees;
c) SELECT * FROM Employees WHERE Salary > AVG(Salary);
d) None of the above

17. What is the output of the following query: SELECT YEAR(CURDATE(): (Assuming today's date
is 2024-05-13)
a) 2024 (Correct Answer)
b) 12
c) Friday
d) An error

18. How can you find the number of employees in a department with a salary greater
than 50000?
a) SELECT COUNT(*) FROM employees WHERE department = 'IT'AND salary > 50000;
b) SELECT SUM(salary) FROM employees WHERE department = 'IT' AND salary > 50000;
c) SELECT MAX(salary) FROM employees WHERE department =|T' AND
salary > 50000;
d) SELECT AVG(salary) FROM employees WHERE department ='IT' AND salary > 50000;
Ans: a) SELECT COUNT(*) FROM employees WHERE department = 'IT'AND
salary > 50000;

19. Which function returns the number of distinct values in a column?


a) COUNT(DISTINCT column_name)
b) COUN TALL(Column_name)pen_spark
c) DISTINCTCOUNT(column_name)
d) None of the above
Answer: a)COUNT(DISTINCT column_name))

20. Write a query to find the month with the highest


number of sales (assuming a sales table with
sale date column).
(a)SELECT MONTH(sale_date), COUNT(*)FROM sales GROUP BY
MONTH(sale date)ORDER BY
COUNT(*) DESC LIMIT 1; (Correct Answer)
(b) SELECT MAX(COUNT(*)) FROM sales GROUP BY MONTH(sale
date):
(c) SELECT MONTHNAME(sale_date), COUNT(*) FROM sales;
(d) SELECT* FROM sales ORDER BY MONTH(sale_date) DESC:
2. Minimum Level Learning questions

Date Functions

1. Write a query to display the current date and time.


2. Write a query to display the date part only from a DATETIME column named 'order_date'.
3. Write a query to display the month number (1-12) from a DATETIME column named
'hire date'.
4. Write a query to display the full month name (e.g., January') from a DATETIME column
named 'birth date.
5. Write a query to display the year from a DATETIME column named 'registration_date'

Answers:
1. SELECTNOW():
2. SELECT DATE(order_date) FROM your_table;
3. SELECT MONTH(hire_date)FROM your_table;
4. SELECT MONTHNAME(birth date) FROM your table;
5. SELECT YEAR(registration _date) FROM your_table;

Aggregate Functions

6. Write a query to find the maximum value in a numeric column named 'salary'.
7. Write a query to find the minimum value in a numeric column named 'age!.
8. Write a query to calculate the average value in a numeric column named 'price'.
9. Write a query to calculate the total sum of a numeric column named 'quantity'.
10. Write a query to count the number of rows in a table named 'customers'.

Answers:

6. SELECT MAX(salary) FROM your_table;


7. SELECT MIN(age) FROM your_table;
8. SELECT AVG(price) FROM your_table;
9. SELECT SUM(quantity) FROM your_table;
10. SELECT COUNT(*) FROM customers;

Querying and Manipulating Data

11. Write a query to display the number of orders placed in each month (grouped by month).
12. Write a query to display the total number of orders with an order amount greater than Rs.
1000 (use HAVING clause).
13. Write a query to display the product names and their average price, ordered by price in
descending orde.
14. Write a query to calculate the average age of employees in the 'employees' table (assuming
the table has a 'dob' column).
15. Write aquery to select the top 10 highest-earning employees (based on salary) from a table
named 'employees'.

Answers:
BY
11. SELECT MONTHNAME(order date), COUNT(*)AS order count FROM orders GROUP
MONTH(order_date);
12. SELECT COUNT(") AS order count FROM orders HAVING order_amount > 1000;
3. SELECT product_name, AVG(price) AS average_price FROM products GROUP BY
name
product ORDER BY average price DESC;
14. SELECT AVG(YEAR(CURDATE))- YEAR(dob) AS average_age FROM employees;
15. SELECT FROM employees ORDER BY salary DESC LIMIT 10;

3. Assertion and Reasoning Questions

Instructions: Solve the following Assertion (A) and Reasoning (R) questions. Choose the most
appropriate option.

(a) Both A and R are true, and R is the correct explanation of A.


(b) Both A and R are true, but R is not the correct explanation of A.

1. Assertion (A): The DATE)function in MySQL returns the current date and time. Reasoning (R):
The NOW) function is used to retrieve the current date and
time.
Answer: (b) Both A
and R
are true, but R is not the correct explanation of A.

Explanation: The DATE) function extracts the date part from a datetime or timestamp value. The
NOW())function returns the current date and
time including timestamp.

2. Assertion (A): The MONTHNAME() function returns the abbreviated month name (e.g., Jan' for
January). Reasoning (R): The MONTH() function returns the numeric value of the month (1 for
January).

Answer: (a) Both A and R are true, and R is the correct explanation of A.

3. Assertion (A): The YEAR() function can be used to filter data for a specific year. Reasoning (R):
The
result of the YEAR() function can be used in a WHERE clause.

Answer: (a) Both A and Rare true, and R is the correct explanation of A.

4. Assertion (A): The DAYNAME() function returns the weekday name (e.g., 'Sunday'). Reasoning (R):
The DAY) function returns the numeric value of the day within the week (1 for Sunday).

Answer: (a) Both A and R are true, and R is the correct explanation of A.

5. Assertion (A): The MAX() function returns the highest value in a column.

Reasoning (R): Aggregate functions operate on entire columns or groups of rows.

Answer: (a) Both A and R are true, and R is the correct explanation of A.
E Assertion (A): The MIN) function can be used to find the minimum salary in an
emolovee table.
Reasoning (R): The MIN() function works with numeric data types.

Answer: (a) Both A and R are true, and R is the correct explanation of A
7. Assertion (A): The AVG) funchon calculates the average of a column's values. Reasoning (R):
Aggregate functhons are used for summarized data calculations.

Answer: a) Both A and R are true, and R is the correct explanation of A.

8. Assertion (A): The SUM) function adds all the values in a selected column. Reasoning (R): The
SUM)function can be used for various data types like integers and decimals.

Answer:(a) Both A and R are true, and R is the correct explanation of A.

9. Assertion (A): The CoUNT(") function returns the total number of rows in a table. Reasoning (R):
The asterisk () wildcard symbol represents all columns in the table.

Answer: (a) Both A and R are true, and R is the correct explanation of A.

1Assertion(A): The GROUP BY clause is used to categorize data before applying aggregate functions.
Reasoning (R): The HAVING clause filters grouped data based on aggregate function resuits.

Answer: (a) Both A and Rare true, and R is the correct explanation of A.

11. Assertion (A): The ORDER BY clause sorts the results of a query in ascending or descending
order. Reasoning (R): The ORDER BY clause can be used with multiple columns for sorting.

Answer: (a) Both A and R are true, and R is the correct explanation of A.

12. Assertion (A): You can use aggregate functions with the SELECT clause to retrieve summarized
data.Reasoning (R): Aggregate functions perform calculations on entire columns or groups of rows.

Answer: (a)Both A and R are true, and R is the correct explanation of A.

13. Assertion (A): The HAVING clause is used after the GROUP BY clause to filter grouped data.
Reasoning (R):The HAVING clause uses conditions based on aggregate function results.

Answer: (a) Both A and R are true, and R is the correct explanation of A.

14. Assertion (A): The GROUP BY clause is used to group rows based on one or more columns.
Reason (R): The HAVING clause is used to filter grouped data based on aggregate function results.

Answer: (a) Both A and R are true, and R is the correct explanation of A.
rows in a table.
15. Assertion (A): The COUNT() function returns the total number of

even some columns


Reasoning (R): The COUNT() function specifically counts the number of rows, if

are null.

Answer: (b) Both A and R are true, but R is the correct explanation of A.

4. Case Study Based Questions


-
Sr. No. -1 Case Base Study
Answer all the following questions based on the table custorners with the following schema:

CREATE TABLE CUstomers ( customer id INT PRIMARY KEY, name VARCHAR(SO), email
VARCHAR(100), registration_date DATE):

Scenario: This table stores information about customers, including their ID, name, email address,
and registration date.

Date Functions:

1.Write a query to display the current date and time.


2. Writea query to extract the year, month, and day from a customer's registration date (e.g.,
for customer ID 1).
3. Write a query to display the month name for all customer registrations.
4. Write a query to find the day of the week on which a customer registered (e.g., for customer
ID 1).

Aggregate Functions:

5. Write a query to find the total number of customers registered. (Use COUNT(")
6. Write a query to find the customer ID with the earliest registration date. (Use
MIN(registration date))
7. Write a query to find the average numberof days a customer has been registered (consider
today's date).
8. Write a query to find the total nufmbétof customers ragistered in each month (use
MONTH(registration_date))
iBRAR
ACC
N
Data Manipulation:
oat
9. Write a query to display the names of customørs registered in the last 30 days. 1 (Hint: Use
CURDATE() and DATE_SUB(CURDATE,. NPERVAL 30 DAY)
10. Write a query to display the customer details (ID, name, email) grouped by month of
registration.

HOTS:

11. Write a query to find the customer with the most recent registration.
12. Write a query to display the number of customers registered on each day of
the week. (Use
DAYNAME(registration_date)
13. Write a query to find the months with more than 10 customer registrations.
(Use HAVING)
14. Write a query to display the customer details sorted by registration
date (ascending).
15. Write a query to display the customer details sorted by registration
date (descending) and
then by name (ascending).

Answers:

(Replace customer_id with the actual ID for specific customer queries)

1. SELECT NOW):
2. SELECT YEAR(registration_date), MONTH(registration_date), DAY(registration
date) FROM
customers WHERE customer_id = customer_ id;
3 SELECT MONTHNAME(registration_date) AS
month_name FROM customers;
4. SELECT DAYNAME(registration_date) AS day of week FROM CUstomers WHERE CUstomer_id
=
customer id;
5. SELECT COUNT(") AS customers FROM customers;
total
6. SELECT customer id FROM customers WHERE registration date = (SELECT
MIN(registration date) FROM customers);
7. SELECT AVG(DATEDIFF(CURDATE(), registration date) AS avg_registration_days FROM
customers;
8. SELECTMONTH(registration date) AS month, COUNT()AS customer_count FROM
customers GROUP BY MONTH(registration_date);
9. SELECT name FROM customers WHERE registration date >= DATE SUB(CURDATE(), INTERVAL
30 DAY);
10. SELECT MONTHNAME(registration date) AS month, name, email FROM customers GROU DT
MONTH(registration_date);

HOTS Answers:

11. SELECT * FROM customers WHERE registration date = (SELECT MAX(registration_date) FROM
customers);
12. SELECT DAYNAME(registration_date) AS day, cOUNT(") AS customer_count FROM customers
GROUP BY DAYNAME(registration_date);
13. SELECT MONTHNAME(registration_date) AS month, COUNT(*) AS Customer_count FROM
customers GROUP BY MONTH(registration_date) HAVING cOUNT(") > 10;
14. SELECT* FROM customers ORDER BY registration _date ASC;
15. SELECT * FROM customers ORDER BY registration date DESC, name ASC;

-
Sr. No. -2 Case Base Study

Write commands in SQL for (i) to (ii) and output for (iv) and (v)

Storeld Name Location City NoOfEmp DateOpen SalesAmt

S101 Planet Bendra Mumbai 7 2015-10-16 40000


Fashion
S102 Vogue Karol Bagh Delhi 8 2015-07-14 120000
S103 Trends Powai Mumbai 10 2015-06-24 30000
S104 Super Thane Mumbai 11 2015-02-06 45000
Fashion
S105 Annabelle South Extn. Delhi 8 2015-04-09 60000
S106 Rage Defence Delhi 5 2015-03-01 20000
Colony
() To display names of stores along with Sales Amount of those stores that are located in Mumbai.

(i) To display the details of store in alphabetical order of name.


(i0)To display the City and the number of stores located in that City, only if number of stores is more
than 2.

(iv) SELECT MIN(Date Open) FROM Store;


(v) SELECT COUNT(Storeld), NoOfEmp FROM Store GROUP BY NoOfEmp HAVING

MAX(SalesAmt)<60000;
Ans. ) SELECT Name SalesAmt FROM Store WHERE City= Mumbai;

) SELECT FROM Store ORDER BY Name;


SELECT CIty,COUNT(") FROM Store GROUP BY Store HAVING COUNT(")>2,
(i)

Min(Date Open)

2015-02-06

()
Count(Storeid) NoOfEmp
1 10
11
1 5

-
Sr. No.-3 Case Base Study
Consider the following tables ACTIVITY and COACH and Write SQL commands for the statements (iO)
to (iv) and give the outputs for the SQL queries (v) to (vii)
Table - ACTIVITY

ACode ActivityName ParticipantsNum PrizeMoney Schedule Date


1001 Relay 10OX4 16 10000 23-Jan-2004
1002 High Jump 10 12000 12-Dec-2003
1003 Shot Put 12 8000 14-Feb-2004
1005 Long Jump 12 9000 01-Jan-2004
1008 Discuss Throw 10 15000 19-Mar-2004

Table: COACH
PCode Name ACode
1 Ahmed Hussain 1001
2 Ranvinder 1008
3 Janila 1001
Naaz 1003

() To display the name of all activities with their Acodes in descending order.
Ans. SELECT ActivityName, Acode FROM activity ORDER BY Acode DESC;

(ü) To display sum of prizemoney for each of the number of participants groupings (as shown in
column ParticipantsNum 10,12,16)
Ans.: SELECT SUM(PrizeMoney), ParticipantsNum FROM activity GROUP BY ParticipantsNum;

(i) To display the coach's name and ACodes in acending order of ACode from the table COACH.

Ans: SELECT Name,ACode FROM coach ORDER BY ACode;

(iv) To display the content of the Activity table whose ScheduleDate is earlier than 01/01/2004 in
ascending order of ParticipantsNum
Ans: SELECT * FROM activity WHERE ScheduleDate<{01/01/2004) ORDER BY ParticipantsNum;

(v) SELECT COUNT(DISTINCT ParticipantsNum) FROM Activity;


Ans-3

Points To Remember:

Date functions like NOW() return the current date and time, while DATE() extracts just the date part.
MONTH) gives the numeric month (1-12), MONTHNAME() spells it out (January).
YEAR) isolates the year, and DAY() and DAYNAME) handle day of month and its name.
Aggregate functions summarize data.
MAX() finds the highest value, MIN() the lowest, and AVG() calculates the average.

sUM)adds all values in a column, and COUNT() tells you how many rows exist.
COUNT() counts all rows, regardless of NULL values.
or more columns
GROUP BY: Groups rows based on shared values in one
HAVING: Filters grouped data based on a condition applied to aggregate results.
ORDER BY sorts data based on a chosen column, ascending or descending.

Introduction to Computer Networks:

Some key points to remember


A
network is a crucial part of modern computing, allowing devices to communicate and

share information. It can be a local network within a home or office or a global or world

wide network like the internet.


Networking media, also known as transmission media, provide the physical meansfor data
to travel from one device to another. These media come in various forms, each with its
own advantages and disadvantages.

>Ethernet cables, often categorized as twisted-pair cables, are commonly used in local area
networks (LANS). They offer reliability and high-speed data transnission over short

distances.
Optical fiber is an advanced networking medium that uses light signals to transmit data. It
provides high bandwidth and is immune to electromagnetic interference, making it
suitable for long-distan ce communication.
Microwave communication relies on radio waves in the microwave frequency range. It is
frequently used for point-to-point links, such as connecting two buildings in a city.
Radio wave communication utilizes radio frequency waves for wireless data transmission.
This is common in Wi-Finetworks and mobile communication.

Satellite communication involves the use of geostationary or low-earth-orbit satellites to


relay signals over vast distances. It's essential for global communication and broad casting.
Infrared communication uses infrared light to transmit data wirelessly, typicaly over short
distances. It's commonly found in remote controls and some short-range data transfer
applications.
notsagupd
Aoanpuler

nades er cangung dertms


th

ececd
As lydog
Charge dtn ad oos h ach uher A

canecn been hese deics can


ct
lagtca aanert ofnds and
meclons anebat. les una
due deics schsste
rs andso ihsh and

Nhot hubis a ode fet bradas


hby cospr ar Ehen
beaed deica comnddbL Ahb
lss sopheat han isth, he
Nct pciogy er d wtich ca
cte dua Netaot sulch comecds descesnaneoty

arsnisions bspicic deio bmct aher, tig then t


by

can be
ehargig data paclets Srlches
hadae deios ht monage phypicl
neots sotba-hased ita eices
ar

Introd.cton to
ComoLter hetwork
Anpociar is a nhot deice hat
etarsnis a caed sgnd wth

nbaot that s corfned lba o poNer ad to an eterded


gaogaphial ar ipobgal nelct

nad
baty
sal a tgreaty
bagengaohic asah
outay han a be tate
tng ah, scoc, or bióng

Nehcting hudan totes Neaot galeay isantacrt moe


a bot
Anetgon
conrnet s hat
(MWs
gr han
s8andesscounicaln and

comechly in anehoit Eack


ISd
comecs
n
lecomsiclons ta
age bing bd an nect ho ehots wih difeert

peclc ncionudenantot rison pcods bohe.


LAbt bad in a sige
gogzphi anes is amaler hama adisagerts Galeas sae saaty
ad et
ht patfor anblak

ois nlagr gogaçhic antas


odem conecs ja bte Ment. Tht
Routers gite and Grsct
netsk
Duicaad tarsocic abing damom as atasair h abs
solle splks y be und to med deicas lila comps, des, r
connucains, and
ti pe dí ghtíntbot. pdas b asb he ent by sincle
taerissors eweb racons
tptingsas fan an hlnt
Seiz Poir(SP
Definition of Network:

A group of two or more similar things or people interconnected with each other is called
network
A computer network is an
interconnection among two or more computers or computing
devices which allows computers to share data and resources among each other.
Apart from computers, networks include networking devices like switch, router, modem, etc.
Networking devices are used to connect multiple computers in different settings.
Advantages of Networks:
Enhancement of Communication and Information Availability
Convenient Sharing of Resources
Easy File/Data Sharing

Highly Flexible

Affordable
Increases Cost Efficiency
Networking Boosts Storage Capacity
Enhanced Security and Data Protection
Disadvantages of Networks:
Security vulnerabilities.
Potential for data breaches
Network congestion
Reliability issues.

Dependency on network infrastructure.


Components of a network:
The main components of a computer network are:
1
Nodes: These are the individual devices connected to the network, such as computers, printers,
servers (service provider), clients (service users), mobile devices etc.
2 Communication channels: These are the transmission media
that carry data between nodes,
such as cables (twisted -pair, coaxial, fibre optic), wireless signals, or satellite (inks.
3. Network devices: These are hardware components that enable communication and manage the
network, such as routers, switches, modems, and access points.
A
Network software: It includes protocols, services, and applications that facilitate communication
and dataexchange between nodes.

Types of Networks
Various types of computer networks ranging from network of handheld devices (like mobile phones
or tablets) connected through Wi-Fi or Bluetooth within a single room to the milions of computers

spread across the globe.


Computer networks are broadly cateqorised as (as per layout):

PAN (Personal Area Network)

LAN (LOcal Area Network)

MAN (Metropolitan Area Network)


WAN (Wide Area Network)

Personal Area Network (LAN):


A PAN is a network of local devices for personal network. It generally includes only one computer or
workstation connected in limited area with different devices. A computer fencoe
PERSONAL AREA NETWORK
connected with mobile Bluetooth, printer, speaker is a PAN.

A PAN can be set up using guided media (USB cable) or unguided


media (Bluetooth, Infrared).
For very small distance, almost 01 workstation with various communication devices connected

Private Communication
Example: Bluetooth, Infrared

Local Area Network (LAN):


It isa network that connects computers, mobile phones, tablet, mouse, printer, etc., placed at
a limited distance.

The geographicalarea covered by a LAN can range from a single room, a floor, an office having

one or more buildings in the same premise, laboratory,


a school, college, or university campus. WTOP

LLN CABLE

Connected with wires, Ethernet cables, Fibre Optics or LAKCAN PiNTO


LAN GA8LE

Wi-Fi
LAN CALLE LANCALE

LANS provide the short-range communication with the


high-speed data transfer rates
Can be extended up to 1 km
per Second)
Data transfer from 10 Mbps to 1000 Mbps (Mbps- Megabits

Metropolitan Area Network (MAN)


Metropolitan Area Network (MAN) is an extended form
of LAN which covers a larger geographical area like a
city or a town.

Data transfer rate is less than LAN

Cable TV Network, Cable based broadband internet are


some common examples.
Can be extended up to 30-40 Kms (normally covers a
city)
Many LANs are connected together to form MAN

Wide Area Network (WAN)

Connects computers and others and MANs, which are spread across different
LANS

geographical locations of a country or in different countries or


continents.
The Internet is the largest WAN that connects billions of computers,
smartphones and millions
of LANs from different continents.

Network Devices:
To communicate data through different transmission
media and to configure networks with different
functionality, we require different devices like Modem, Hub, Switch,
Repeater, Router, Gateway, etc.

Modem NIC Repeater Hub

Switch Router Bridge Gateway


Types of Network Devices

Modem:
Stands for 'MOdulator DEMolulator'
Device used for conversion between analog signals
and digital bits.
Modems connected to both the source and destination nodes
The modem at the sender's end acts as a modulator that converts the digital data into analog signals.
The modem at the receiver's end acts as a demodulator that converts the analog signals into digital
data for the destination node.

n
Modulate Demodulate
digital signals
wwe
analog signals

Telephone
Modem Network
Modem

Ethernet Card:
Also known as Network Interface Card (NIC) is a
network Gigabit Ethernet NiC
adaptor used to set up a wired network.
Interface between computer and the network
Circuit board mounted on the motherboard of a
PCI connectian
computer
Ethernet port
Ethernet cable connects the computer to the
Tachtorsm
network through NIC.
Data transfer between 10Mbps to 1 Gbps
Each NIChas a MACaddress, which helps in uniquely identifying
the computer on the network.

Repeater Repeater

Data are carried in the form of signals over


Weak Signal Amplfied
the cable Signal

Signals lose their strength beyond 100 m


limit and become weak.
The weakened signal appearing on the cable is
regenerated and put back on the cable by a
repeater

Hub
An Ethernet hub is a network device used to connect
different devicesthrough wires/cables.
Data arriving on any of the lines are sent out on all the others.
The limitation of hub is that if data from two devices come at the same time, they will collide.

Hub Data
[ETTEIIEL toall isforwarded
sentby connected
Data node nodes
one

Types of Hub:
Passive Hub: This type of does not amplify or boost the signal.It does not
manipulate or view the
traffic that crosses it.
Active Hub: It
amplifies the incoming signal before passing it to the other ports.

Switch
Like a hub, a network switch is used to connect multiple computers or communicating devices.
When data arrives, the switch extracts the destination address from the data packet and looks it up in
a table to see where to send the packet. Thus, it sends signals to only selected devices instead of

sending to all.
Can forward multiple packets at the same time.

Switch Data
onlyisforwarded
sentby destination
tothe
Data node
one node

Difference between Hub and Switch


The main difference between hub and switch is that hub replicates what it receives on one port onto

all the other ports whereas switch keeps a record of the MAC addresses of the devices attached to it
and forwards data packets onto the ports for which it is addressed across a network. Hence, switch is

an intelligent Hub.

Router
A
network device that can receive the data, analyse it and transmit it to other networks.
as it can analyse the data being
Compared to a hub or a switch, a router has advanced capabilities
it to another network of a different
carried over a network, decide or alter how it is packaged, and send
type.

• A
router can be wired or wireless.
access to
•A wireless router can provide Wi-Fi
ROUTER smartphones and other devices.
HUB SWITCH • Wi-Fi routers perform the dual task of
a router
Sitesb
and a modem/switch.
ISP
• connects to incoming broadband Iines, from
It
PCL
to
(Internet Service Provider) and converts them
digital data for computing devices to process.

Gateway
A
gateway is a device that connects dissimilar networks (Networks with different software and
hardware configurations and with different transmission protocol).
Gateway serves as the entry and exit point of a network, as all data coming in or going out of
a
network must first pass through the gateway in order to use routing paths.
Also maintain information about the host network's internal connection paths and the
identified paths of other remote networks.
It can be implemented as software, hardware, or a combination of both because network
gateway is placed at the edge of a network and the firewall is usually integrated with it.

What is Gateway
A Gateway is a device Sorver
that acts as an entry
point botween different
Swilch /Oafooy
networks. helps
facilitate communication
and data transfer
PC2
between networks with
differont protocols,

Network Topologies
The arrangement of computers and other peripherals in a network is called its topology. The topology
as
is normally be applied in localarea network. Some common topologies are follows:
1. Bus Topology
a transmission / communication medium, known as bus
tach communicating device connects to
backbone.
Bus Topology
Advantages:
Data transmitted in both directions

Simplicity in design and installation.

Cost-effective for small networks.


Easy to add or remove devices.

Data can be received by any of the nodes of network

Single backbone wire /bus used to connect computers


so cheaper and easy to maintain

Disadvantages:
Less secure

Less reliable

Susceptible to signal reflections and collisions, which can degrade performance.


Difficult to troubleshoot ifa fault occurs.

2. Star Topology
Each communicating device is connected to a central node, which is a networking device like a hub or
a switch.
Advantages:
Easy to install and manage.

Easy to troubleshoot
Very effective, efficient and fast HUB

• A single node failure does not affect the entire network.


Fault detection (if one connection fails, it doesn't affect

the entire network) and removal of faulty parts is easier.


. High reliability for individualconnections.

Disadvantaqes:
Difficult to expand. Longer cable is required.

The cost of the hub and the longer cables makes it expensive over others.
In case hub fails, the entire network stop working.
Dependent on the central hub; if it fails, the entire network can go down.
Requires more cabling compared to some other topologies.
3. Ring Topology

In a ring topology, devices are connected in a closed loop, where data circulates in one direction.
Advantages:
Each node is connected to two other devices, one
each on
either side
Ring Topology
The link in a ring topology is unidirectional.
Equal access to the network for all devices.

No collisions, as data travels in a predefined path.


Disadvantages:
Failure of one node breaks down the network.
If one
device or connection fails, it can disrupt the entire ring.
Adding or removing devices can be complex.

4. Mesh Topology

In this type of topology each and every computer or workstation is directly connected to each other
in the network, creating redundant paths.

Advantages:
Can handle large amounts of traffic since multiple nodes can MESH TOPOLOCY

transmit data simultaneously


If any node gets down doesn't affect other nodes
Secure than other topologies as each cable carries different data
High redundancy and fault tolerance.

No single point of failure.

Disadvantaqes:
Wiring / Cabling is complex and cabling cost is high in creating such networks

There are many redundant or un-utilised connections


High cabling and configuration complexity.

Cost-prohibitive for large networks due to the number of connections.

5. Tree or Hybrid Topology


are multiple branches and each branch can have one or
It is a hierarchical topology, in which there
more basic topoiogies like star, ring and bus.
Features of Tree Topology
tee Topog
ldeal if workstations are located in groups.
Used in Wide Area Network.
Advantages of Tree Topoloqy

Extension of bus and star topologies.


Expansion of nodes is possible and easy.
Easily managed and maintained.
a
It consists of multiple star-configured networks connected to central bus.

Points to remember: Network Devices and Topologies


over
A
modem is a device that modulates and demodulates digital data, allowing it to travel
analog communication lines like telephone or cable.
a
Hubsare basic devices that connect multiple network devices in LAN. They simply broadcast

data to all connected devices.


Switches are more intelligent than hubs. They operate at the data link layer and forward data
only to the device that needs it, reducing network traffic.
Repeaters are used to boost signal strength and extend the range of a network. They are
commonly employed in wireless networks and in situations where long cable runs are
necessary.
Routers connect different networks and determine the best path for data to travel between
them. They operate at the network layer of the OSI model.
Gateways are devices that connect networks using different communication protocols or
technologies, allowing them to communicate with each other.

15 Questions MLL

1. Expand the following: a) APRANET b) ISP

Ans. a) Advanced Research Projects Agency Network

b) Internet Service Provider

2. Write one advantage and one disadvantage of network?

Ans. Advantages:
1. Sharing of resources.
2. Data protection.
3. Improved speed of communication.
Disadvantages:
Security concerns, server dependence, high setup costs, maintenance needs.
3. What is server and client?
Ans. Server is a computer or repository which facilitates networking tasks such as sharing of files,
resources and communicating among hosts (clients) in a network.
Cient is a node or workstation that requests for a service from a server. It is just like a consumer in

that network.
4. Define Communication channel?

Ans. Communication channel is a medium by which hosts in a network interact with each other hosts
and server(s).
5. Write different types of Communication channels?
Ans: Wired: When host(s) and server(s) are connected with one another through guided media. Such
as: co-axial cables, twisted paired cables, fibre optic cables.

Wireless: When host(s) and server(s) are connected with one another through unguided media. Such
as: radio wave, micro wave, satellites, infrared, Bluetooth, laser etc.

6. Howa protocol is important in communication?


Ans:A protocol is required to share information among devices in a network. A protocol refers to a
pre-defined set of rules by which different parties of a network connect and interact with each

other.
7. Expand followings:a) TCP /1P b) OSI c) mbps d) Mbps

Ans: a) Transmission Control Protocol / Internet Protocol

b) Open System Interconnection


c) mega bits per second

d) Million bytes per second

8. Name the device for the following:


a) It stands for Modulator Demodulator Ans: MODEM

b) It regenerates the signals Ans: Repeater

9. Define Gateway?
Ans: Gateway is a key access point that acts as a "gate" between an organisation's network and the
outside world of the Internet. Gateway serves as the entry and exit point of a network, as alldata
coming in or going out of a
network must first pass through the gateway in order to use routing

paths.
10. Write about Router in brief?
Ans: A router is a network device that can receive the data, analyse it and transmit it to other

networks. A router connects a local area network to the internet. A router can be wired or
wireless. A wireless router can provide Wi-Fi access to smartphones and other devices.
11. Arjun, a student of Class XIl, is little confused about hub and switch. Help him stating any one
advantage of switch over hub?
Ans:A hub receives data from one node/ server and sends / forwards the data to all other connected
devicesthat network. On the other hand, a switch extracts the destination address from the
in

data packet and looks it up in a table to see where to send the packet.
Thus it sends signals to only selected devices instead of sending to all. It can also forward multiple
packets at the same time.
12. Name any 04 major components of a network?

Ans: Host, Server, Communication Channel, Network Services

13. Define any 01 difference between an active and a passive hub?

Ans: Active hub works as a repeater which amplifies signals and forward data, whereas passive sub
just forward the data without any amplification.
14. Comment the sentence as a network administrator: "By using resource sharing,
network cost
can be reduced."
Ans: In networking, resource sharing means sharing of costly resource (Hardware,
software or both)
can be implemented easily. Installation of these resources can
be in one node (server) and other
nodes (clients) can use these resources with some permissions without installation in
their
workstations.
15. Do you think, "Switch is an intelligent hub"?
Ans: Yes, a switch is an intelligent hub, because hub just
forward the data packets to all other
destinations / workstations. But switch checks IP address and sends
data to particular destination
only.

20 Questions MCQs
1. What is a stand-alone computer?
a)a computer that is not connected to a network
b) a computer that is being used as a server

c)a computer that does not have any peripherals attached to it


d) a computer that is used by only one person
Ans: a) a computer that is not connected to a network

2. Hub is a:

a) Broadcast device b) Unicast device

c) Multicast device d) None of these


Ans.: a) Broadcast device
3. The device that can operate in place ofa hub isa:
a) Switch b) Bridge c) Router d) Gateway
Ans: a) Switch

4. A repeater takes a weak and corrupted signal and it.

a) Amplifies b) Regenerates c) Resembles d) Reroutes


Ans: b) Regenerates

5. Component that is required to connect the computer to a network is:


a) Network Interface Card b) Hub c) Switch d) Wireless Access Point
Ans: a) Network Interface Card

6. A is a networking device that filters network data.


a) Switch b) Gateway c) Router d) Modem
Ans: a) Switch

7. computer in a network that cannot be accessed outside of the local network without giving
A

proper permission is called


a) Intranet b) Middleware c) Internet d) Modern

Ans: a) Intranet

8. A device is used to connect multiple nodes in a network.


a) Hub b) Repeater c) Router d) Modem

Ans: a) Hub
9. is a
device which seeks information on a network from server.
a) Client b) Networking c) Workstation d) Allof these
Ans: a) Client

10. Which one of the following network devices is the routing device?

a) Hub b) Router c) Both d) None

Ans: b) Router
11. Which one of the following network devices is used to connect different networks?

a) Hub b) Router c) Switch d) None

Ans: b) Router

12. Which one of the following network devices not provides security measures to protect the
network?
a) Hub b) Router c) Gateway d) Bridge

Ans: b) Hub

13. Which one of the following network devices is the broadcast device?

a) Hub b) Repeater c) Router d) Modem

Ans: a) Hub
14. Which one of the following network devices is used to create a network?
a) Hub b) Repeater c) Router d) Switch

Ans: d) Switch

15. Which one of the following network devices can work with similar networks?

a) Repeater b) Router c) Gateway d) All


Ans: b) Router

16. A network allows to


a) Resource sharing b) File Sharing c) Fast communication d) All
Ans: d) All

17. In a network, receiver end in known as


a) Client b) Server c) Workstation d) All of these
Ans: a) Client

18. Select odd one:

a) Client b) Server c) Communication Medium d) None


Ans: d) None

19. A Gateway can be implemented as:


a) Hardware b) Software c) Both a and b d) None
Ans: c) Both a and b

20. A passive hub


a) Broadcast signal b) Amplifies Signal c) Amplifies and broadcast d) All
Ans: c) Amplifies and broadcast

15 Questions Assertion and Reasoning


Given below are two statements. One labelled as Assertion (A)
and the other as Reason (R):
Choose the correct answer from the options given below:
a) Both (A) and (R)are true and (R) is the correct explanation
of (A)
b) Both (A) and (R) are true but (R) is not the correct explanation of (A)
c) (A) is true but (R) is false
d) (A) is false but (R) is true
1. Assertion (A): An Intranet is a private network for
sharing computing resources and information
within an organization
Reason (R): Intranet is a private version of the Internet.
Ans: b) Both (A) and (R) are true but (R) is not
the correct explanation of (A)

2 Assertion (A): On a computer network the users


work on network nodes only.
Reason (R): A server cannot act as a network node.

Ans: c) (A) is true but (R) is false


3. Assertion (A): There is a difference between a standalone computer and a computer as a network
node,
Reason (R): A standalone computer needs a specialhardware NIC to be a network node
Ans: a) Both (A) and (R) are true and (R) is the correct explanation of (A)
4. Assertion (A): server is a computer but not every computer is a server.
A

Reason (R): A computer having the capabilities to serve the requests of other network nodes is a
server.
Ans: a) Both (A) and (R) are true and (R) is the correct explanation of (A)
5. Assertion (A): A router is more powerful and intelligent than hub or switch.

Reason (R): It has advance capabilities as it can analyse the data and decide the data is packed and
send to other network.
Ans:a) Both (A) and (R) are true and (R) is the correct explanation of (A)
6. Assertion (A): A repeater is a device that amplifies the data.
Reason (R): A hub isa device which is used to connect more than one device in a network.
Ans: b) Both (A) and (R) are true but (R) is not the correct explanation of (A)
7. Assertion (A): A gateway connects dissimilar networks.
Reason (R): Gateway establishes a connection between local and external networks.
Ans: a) Both (A) and (R) are true and (R) is the correct explanation of (A)

8. Assertion (A): An access point is a device that connects dissimilar networks.


Reason (R): Access point broadcast wireless signals.
Ans: d) (A) is false but (R) is true

9 Assertion (A): A protocol means set of rules to transfer data in a network.


Reason (R): Local area network is an example of protocol.

Ans: c) (A) is true but (R) is false

10. Assertion (A): Router transmits data in more efficient way.


Reason (R): Router maintains a routing table.
Ans: a) Both (A) and (R) are true and (R) is the correct explanation of (A)
11. Assertion (A): In computer networking, a MODEM is considered as both input and output device
Reason (R): MODEM sends data and receives data at the same time.
Ans: a) Both (A) and (R) are true and (R) is the correct explanation of (A)
12. Assertion (A): Both Client and Server is required to establish a communication.
Reason (R): Server is more powerful than a client.
Ans: b)Both (A) and (R) are true but (R) is not the correct explanation of (A)
13. Assertion (A): A switch is a broadcasting device.
Reason (R): A hub is also a broadcasting device.
Ans: b) Both (A) and (R) are true but (R) is not the correct explanation of (A)
14. Assertion (A): A repeater accepts signals and amplifies and extend the network.
Reason (R): A repeater must always be installed when data has to transmit in long distance.
Ans: c) Both (A) and (R) are true and (R) is the correct explanation of (A)
15. Assertion (A): A hub is a broadcast device.
Reason (R): A switch in intelligent hub.
Ans: d) (A) is false but (R) is true.
Web Browsers: introduction, Commonly used browsers, Browsers settings,add -ons and plug
ins,Cookies
Multiple Choice Questions:
1. What is a web browser?

a) a program that can display a web page


b) a program used to view html documents
c) it enables user to access the resources of internet
d) all of the mentioned
2. An online activity that enables us to publish website or web application on the internet
a) Web server
b)Web Browser
c) Web Hosting
d) None
3. Small text files created by website on clients computer for storing the information of user is
called:
a) Web Page
b) Cookies
c) Text File
d) Server
4. which amongst the following is not an example of browser?
a) Chrome
b) Firefox
c) Avast
d) edge
5.Which of the following statements is true?
a)A web cookie is a smallpiece of data sent from a website and stored in user's web browser while a
user is browsinga website.
b)A web cookie isa small piece of data sent from user and stored in the server while a user is
browsing a website.
c)A web cookie is a small piece of data sent from root server to all servers.
d)None of these
6 cookies remain even after the web browser is closed.
a) Session
b)Third-party
c)Permanent
d)Second-party
7.Cookies are used to do which of the following?
a)Store your iD and password for subsequent logons to the site
b)Store contents of electronicshopping carts
c)To track web activity
d)All of the above
8.Which of the following is NOT a common web browser feature?
a)Tabbed browsing
b)Bookmarks
c)Home page
d)Desktop publishing
9. What is a "pop-up blocker" in a web browser used for?

a)To create pop-up advertisements


b)To allow all pop-up windows
c)To prevent unwanted pop-up windows from appearing
d)To display pop-up notifications
10.What does the term "incognito mode" or "private browsing" in web browsers mean:
a)A mode for conducting online shopping
b)A mode that blocks all websites
c)A mode that hides the user's browsing history
and cookies
d)A mode for sending anonymous emails

11.Which of the following is not a web browser?

a) Google Chorome
b) Mozilla FirefoxX
c) Opera
d) MS word

12.Which of the following is a web browser?

a) Adobe Photoshop
b) Corel Draw
c) Apple Safari
d) MS word

13.Which of the following was the first web browser developed by the National Centre for
Supercomputing Application (NCSA)?

a) Google Chrome
b) Mosaic
c) Mozilla Firefox
d) Opera

14.Which of the following button allows to move to the next page you visited by pressing back
button?

a) Forward
b) Next
c) Advanced
d) Ahead

15.The allows to save the web browser address for future use with just a click.

a) Bookmark
b) Sync
c) Privacy and Security
d) Search

16.A is acomplete program or software that help to extend and modify the
functionality of the browser.

a)plug-in

b)Add-on

c)Extension
d) Cookies

17.A adds only a particular functionality to the browser.

a)Add-on

b)Plug-in

c)Browser

d)Extension

18.Which of the following is peace of information stored in a form of a text file and that helps in
customizing the displayed information, login, showing data based on user's interests from the
web site?

a) Extension
b) Cookies
c) Login
d) Session

19.Which of the following information can be saved bythe auto-fill option?

a) Passwords
b) Payment methods
c) Addresses
d) All of these

20. 13. Which of the following is an Indian Web Browser ?


a) Google Chrome
b) Safari
c) Epic
d) IE
MLL
Q1. Define the termweb browser. Give some examples of it
Ans WEB BROWSER:- It is a software/application that is used to open website on a client/User
computer system. E.g Internet explorer, Google Chrome, Mozilla Firefox, opera, safari etc.
Q2. Explain the terms add-ons and plug-ins.
Ans:- ADD-ONS:- An add-on is a program utility or physical device that can be added to a system to
enhance its capabilities. PLUG-INS:- It is a smalladd-on software used to enhance the functionality
of a desktop program or a web application.
Q3. You are concerned about online privacy and security. Explain what cookies are, why they are
used, and how you can manage them in your web browser.
Ans Cookies are smalltext files that websites store on a user's device to track user preferences and
activities. They are used for personalization and tracking. To manage cookies, you can typically adjust
settings in your browser to block or delete them, thereby enhancing privacy and security

Q4.What is the difference between a web browser and a search engine?

Ans. A web browser is a software application used to retrieve data from webpages, whereas, Search
Engine is kind of a website where a user can search for information and the results based on the
same are displayed on the screen.

Q5. What the best web browser examples?

Ans. Given below are the examples of the most commonly used web browsers:

Google Chrome
Internet Explorer
Mozilla Firefox
Opera
There were web browsers like Netscape Navigator and WorldWideWeb, which were used before the
above-mentioned browsers.
Q6. When was the first web browser released?
Ans. The first web browser which gained public attention was the WorldWideWeb, which was
launched in 1990.
a7. Ruhaniwants to edit some privacy settings of her browser. How can she accomplish her task?
Ans. Steps to edit privacy settings of browser (Mozilla Fire fox)

1. Open Mozilla Firefox and click on menu button(right top corner of window)

2. Click on Options.

3. Click on Privacy and Security tab from left panel.

4. Make the changes and close the browser.

Steps to edit privacy settings of browser (Google Chrome)


1. Open browser and pres Alt + F from keyboard.

2. Click on Settings.

3. Click on Privacy and Security tab from left panel.

4. Make the changes and close the browser.


Q8. Shubham wants to play a video in his browser but he is not able to do so. A message on
the
Screen instructs him to install the Adobe Flash Player plugin. Help him to add it in his browser.
Ans.Steps to add Plugin in browser (Mozilla Firefox)

1. Open Mozilla Firefox and click on menu button(right top corner


of window)
2. Click on Settings.

3. Click on Extension and Themes from left panel.

4. Click on Plugins.

5. Make the desired selections to enable or disable the required plug-ins.


Q9. When Joe typed a URL in the address bar of his browser, Error 404 was displayed? Why did this
happen? What can be done to avoid it?
Ans. If the server is not able to locate the page, it sends a page containing the error message (Error
404- page not found) to the client's browser.
It can be avoided by typing correct address of page.

Web browser -A browser, short for web browser, is the software application that is used to search
for, reach and explore websites. The primary function of a web browser is to render HTML code (the
code used to design or "mark up" webpages). Each time a web browser loads a web page received
from web server, it processes the HTML, which may include text, links, and references to images and
other items, such as cascading style sheets and JavaScript functions. The browser processes these
items, then renders them in the browser window.
Commonly Used web browsers -
Google Chrome Google Inc. has developed google chrome web browser. It is an open and free
source. It runs on different operating systems, like Microsoft Windows, Mac OS X, Chrome OS, Linux,
Android and iOS. It was launched in 2008 and since then it has become the most popular web
browser in the world market. Google Chrome is very strong in its application performance and
JavaScript processing speeds. It allows users to create local desktop shortcuts which will open the
desired web page quickly and easily.
Mozilla Firefox This web browser is free and open, developed by the Mozilla Corporation and the
Mozilla Foundation in 2002. It works on Microsoft Windows, Mac OS and Linux operating systems.
Firefox features a pop-up blocker, antiphishing and anti-malware warnings, making it easy to validate
a website before we enter.
Apple Safari This web browser is free and closed source, developed by Apple Inc. It works on OS X,
iOS, and Microsoft Windows operating systems. Its market launch in 2003. Works on webkit to
render graphics and run javasript Safari is faster and more energy efficient than other browsers
Internet Explorer This web browser was developed by Microsoft Corporation, integrated into the
Microsoft Windows operating system in al its versions, It was launched in 1995 and was the most
poDular web browser until it was moved by Google Chrome in 2011.It supports ad ons, improved
security and power saving features.
Opera Opera is a web browser developed by the company Opera Software. It is compatibie Witn
Microsoft WindowS and Mac OS X operating systems mainly.
Although it also works, in oide
versions, on Linux. It was launched in 1995. It provide integrated adblocker,faster with opera
turbo,sidebar extension for multitask
Web Browser Settings
• Home Panel: This panel contains
options to set the home page of the browser, browser window
and tab settings.
• Search Panel: This panel contains
options to edit the settings of the search engine used by Firerox.
• Privacy and Security Panel: This panel
contains options to secure the browser and data. It includes
the following: enhanced tracking protection forms and passwords ) history and address bar
cookies and site data permission to view pop ups windows and
install addons
•Sync Panel: This panel contains options to set up and manage a Firefox account which is needed to
access allservices given by Mozilla. Make the desired
settings and close the browser settingS
window. The changes made in the browser settings will
be applied
Add-ons/Extensions :Add-ons are tools which integrate into our browser. They're similar to
regular
apps or programs, but only run when the browser runs. Addons can allow
the viewing of certain
types of Web content, such as Microsoft's Silverlight necessary for Netflix movies. How Add-ons Are
-
Installed There are two key ways in which add-ons become installed through an external installer
and through the browser's own add-on service. The add-on service is the most reliable way of
installing an add-on, with the browser service providing a relative "vetting" process for the general
safety of the add-on. Outside programs can also install add-ons in web browser as part of its
separate installation process. Microsoft Office, for example, may place an add-on which speeds up
the in browser opening of office documents.
There are two key ways in which add-ons become installed - through an external installer and
through the browser's own add-on service. The add-on service is the most reliable way of installing
an add-on, with the browser service providing a relative "vetting" process for
the general safety of
the addon. Outside programs can also install add-ons in wer browser as part of its separate
installation process. Microsoft Office, for example, may place an add-on which speeds up the in
browser opening of office documents.
Add-ons manager in
•Google chrome - /more tools,/extensions
• Mozilla firefox -/add-ons option or ctrl+shift+A
• Internet explorer - /tools/manage add-ons
• Opera - https://addons.opera.com/en/extensions/
A plugin is a piece of software that acts as an add-on to a web browser and gives the browser
additional functionality. Plugins can allow a web browser to display additional content it was not
originally designed to display. An example of a plugin is the free Macromedia Flash Player, a plugin
that allows the web browser to display animations using the Flash format. Most plugins are available
as free downloads. To install the plugin, we visit the website of the plugin's developer and click on a
link that willdownload the installer for the plugin we have selected. we can save the installer to an
easy to find location such as the Desktop or a specific folder we have created to organize all of our
downloads. Once we have downloaded the installer, we can open it and follow the prompts to install
the plugin on our system.
Difference between add ons and plugins: Plug-in is a complete program and add-on is not a program.
For example Flash is a plug-in made by adobe is required to play a video in flash player. Also Java is a
plug-in made by Sun Microsystem which is used to run programs based on Java. Plugin is not
bounded for browsers only. Flash can be installed in computers to play flash files. Similarly Java can
be installed to run Java files. On the other hand add-on is not a complete program. It is used to add a
particular functionality to a browser. If we suppose to install add-on on other work environment, say.
wer operating system, we can't do it. It means, add-ons are limited to a certain boundary.
Cookies - are small bits of data stored as text files ona browser. Websites use those small bits of data
to keep track of users and enable user-specific What's in a Cookie? Each cookie is effectively a small
Iookup table containing pairs of (key, data) values.
Once the cookie has been read by the code on
Server orclient computer, the data can be retrieved the
and used to customise the web page
appropriately. features. Suppose we want to have a counter
for a webpage to access it three times
Only,thisvalue can be stored over userscomputer at
first attempt it will be 1 then 2 and then 3 on
next time server willnot allow to access page.
that
When are Cookies Created? Writing data to a cookie is
usually done when a new webpage is loaded
with code to create cookies. Why are Cookies Used?
Cookies are a easiest way tocarry information
from one session on a website to another, or between
sessions on related websites, without having
to burden a server machine with massive amounts of
data storage. Storing the data on the server
without using cookies would also be problematic because it would
be difficult to retrieve a particular
user's information without requiring a login on
each visit to the website.
The time of expiry of a cookie can be set through
using server site scripting language ,when
Cookie is created. By default the cookie is destroye d the
when the current browser window isclosed, but
it can be made to persist for an arbitrary length
of time after that.
Cookies are not a threat to privacy, since they can only
be used to store information that the user
has volunteered or that the web server already
has.
Some commercial websites may include embedded advertising
material which is served from a third
party sites, and it is possible to store a cookie for that third-party
site, containing information fed to
it from the containing site- such information might include
the name of the site, particular products
being viewed etc.Then third party can advertise you in future with
the help of tracking cookies. Are
Cookies Enabled in my Browser? When a webpage with
cookies is opened a popup appears to
enable cookies ,if browser setting is disabled for cookies. We can also check it
through browsers
setting options

Assertion Reasoning
-
1.Assertion (A): Cookies are plain text files.
Reasoning (R): - Cookies are not automatically created.
2.Assertion(A): Incognito browsing opens up a versionof the browser that willtrack your activity
Reasoning(R): Incognito browsing is useful when entering sensitive data
3.Assertion (A): Cookies are a type of malicious software used to hack websites.
Doason (R):Cookies are small pieces of data stored on a user's computer by websites for
various
purposes.
5.Assertion(A)Cookies received from various websites are stored by web browser.
Reasoning(R)A web browser is the same thing as a search engine.
6. Assertion (A): Cookies are small text files, stored locally by the client's web browser to remember
the "name-value pair" that identifies the client.
Reason (R): Cookies are primarily used to track users' physical locations

7. Assertion (A): A web browser acts as an interface between a user and the World Wide Web.

Reason (R): A user can navigate files, folders, and websites using links on the web pages created
with HTML.

8.Assertion(A): A plugin is a piece of software that acts as an add-on to a web browser and gives the
browser additional functionality.
Reasoning(R): Plugin is not bounded for browsers only.
9.Assertion(A): add-on is not a complete program.
Reasoning(R) :It is used to add a particular functionality to a browser.
10.Assertion(A): Cookies are not a threat to privacy.
Reasoning(R): Cookies can only be used to store information that the user has volunteered or that
the web server already has.

DATA PROTECTION: Data protection is the process of protecting sensitive information from damage,

loss, or corruption. The terms Data protection and Data privacy are often used interchangeably, but

there is an important difference between the two. Data privacy defines who has access to data, while
data protection provides tools and policies to actually restrict access to the data.
Data protection principles help protect data and make it available under any circumstances. It covers
operationaldata backup and business continuity/disaster recovery (BCDR) and involves implementing
aspects of data management and data availability.
How can we protect our Data Online:
1) Create strong passwords
2) Don't overshare on social media
3) Use free wi-fi with caution
4) Watch out for links and attachments

5) Check to see if the site is secure


6) Keep your security software, internet browser, and operating system up to date.

7) Back up your data to protect it


8) Choose security questions only you know the answer to.

INTELLECTUAL PROPERTY RIGHTS:


Any piece of information is produced or created with a lot of efforts and it consumes a lot of time.

The cost factor is also involved with the creation or production of information. This type of
information is property of creator/producer or called intellectual property(1P).
The creator/producer of the information is the real owner of the information. And the owner has
every right to protect his/her intellectual property.
Intellectual property rights (IPR) are the rights of the owner of Information to decide how much
information is to be exchanged, shared or distributed. Also it gives the owner a right to decide the
price for doing (exchanging sharing/distributing) so.
Toprotect one's intellectual property rights one can get information copyrighted or patented or use
trademarks.
1) Copyright: A copyright is a collection of rights automatically inherit to someone who has

created an original work. The copyright owner has the authority to keep or to transfer the
rights to use/distribute, individually to one or more people, or to transfer them collectively to
one or more people.
When someone uses a copyrighted material without permission, it is called copyright infringement.
2) patent: A patent is a grant of exclusive right to the inventor by the government. Patents give
the holder a right to exclude others from making, selling, using or importing a particular
product or service.
3) Trademark: A trademark is a word,phrase, symbol, sound, colour and/or design that identifies

and distinguishes the products and goods of one party from those of others.

PLAGIARISM:

Plagiarism is stealing someone else's intellectual work (can be an idea, literary work or academic work
etc.) and representing it as your own work without giving credit to creator or without citing the source
of information.
Any of the following acts would be termed as Plagiarism:

Using some other author's work without giving credit to the author.

Using someone else's work in incorrect form than intended originally by the author/creator.

Modifying/lifting someone's production such as music-composition etc. without attributing it


to the creator of the work.
Giving incorrect or incorrect source of information i.e., wrongful citation.

Failure in giving credit or acknowledging the contribution of others in a collaborative effort,to


which youare also part of.
LICENSES

Licenses are the permissions given to use a product or someone's creation by the copyright holder.

cOPYRIGHT:

A copyright is a legal term to describe the rights of the creator of an original creative work such as a
literary work, an artistic work, a design, song, movie or software etc.

FREE AND OPEN-SOURCE SOFTWARE(FOSS):

It is a software that can be classified as both free software and open-source software .That is ,anyone is
treely licensed to use ,copy, study, and change the software in any way and the source code is openly
shared so that people are encouraged to voluntarily improve the design of the software.

CYBER CRIME:

Criminal activities or offences carried out in a digital environment can be considered as an cyber-crime.
In such crimes, either the computer/digital device itself is the target or the computer/digital device is

used as a tool to commit a crime.


Cyber-crimes are carried out against either an individual or a group or an organization or even against a

country, with the intent to directly or indirectly cause physical harm, financial loss or mental
harassment. A cyber-criminal attack a computer or a network to reach other computers in order to
disable or damage data or services.
a cybercriminal may spread viruses and other malwares in order to steal private and confidential data for

blackmailing and extortion.


Some cyber crimes common these days are:

HACKING: Hacking is the act of unauthorized access to a computer, computer network or any digital
system. Hackers usually have technical expertise of the hardware and software.

Hacking, when done with a positive intent is called ETHICAL HACKING. Such ethical hackers are known as
WHITE HAT HACKERS. They are specialists in exploring any vulnerability or loophole during testing of

the software. Thus, they help in improving the security of a software. An ethical hacker may exploit a

website in order to discover its security loopholes or vulnerabilities. He then reports his findings to
the website owner. Thus, ethical hacking is actually preparing the owner against any cyber-attack.
A NON-ETHICAL HACKER is the one who tries to gain unauthorized access to computers or networks
in order to steal sensitive data with the intent to damage or bring down systems. They are called BLACK

HAT HACKERS, OR CRACKERS. Their primary focus is on security cracking and data stealing.
or e-mails that
PHISHING AND FRAUD E-MAILS: Phishing is an unlawful activity where fake websites

look original or authentic are presented to the


user to fraudulently collect sensitive and personal
most common
details, particularly user names, passwords, banking and credit card details. The
or user
phishing method is through e-mail spoofing where fake forged e-mail address is used and the
a

presumes it to be from an authentic source. So you might get an e-mail from an address that looks
if you look carefully
similar to your bank or educational institution, asking for your information, but
you will see their URL address is fake. They will often use logos of the original website, making them

difficult to recognize ifit is real or fake. Fraud phone calls or text messages are also common these

days.
IDENTITY THEFT: ldentity thieves increasingly use personal information stolen from computers or
computer networks, to commit fraud by using the data gained unlawfuly. A user's identifiable
personal data like demographic details, e-mail ld, banking credentials, passport, PAN, Aadhaar number
and various such personal data are stolen and misused by the hacker on behalf of the victim.
FINANCIAL IDENTITY THEFT: When the stolen identity is used for financial gain.
CRIMINAL IDENTITY THEFT: Criminals use a victim's stolen identity to avoid detection of their true

identity.
MEDICAL IDENTITY THEFT: Criminals can seek medical drugs or treatment using a stolen identity.

RANSOMWARE: This is another kind of cybercrime where the attacker gains access to the computer
and blocks the user from_accessing, usually by encrypting the data. The attacker blackmails the victim
to pay for getting access to the data or sometimes threaten to publish personal and sensitive
information or photographs unless a ransom is paid.

Ransomware can get downloaded when the user visit any malicious or unsecure websites or download
software from doubtful repositories. Some ransomware are sent as an e-mail attachments in spam
mails. It can also reach our system when we click on a malicious advertisement on the Internet.
CYBER BULLYING: Cyberbullying or bullying
that takes place over digital devices like cell phones.
computers and tablets.Cyberbullying can occur through SMS, text and apps or online in social media.
forums or gaming where people can view, participate or share content.
Cyberbullying includes sending, posting or sharing negative, harmful, false or mean content
about
someone else. It can include sharing personal or private information someone about else causing
embarrassment or humiliation. Some cyberbullying crosses the line into unlawfulor criminal behavior.
Social media such as Facebook Instagram, Snapchat The most common
places where cyberbullying
OcCurS.
CYBER LAW: These are the laws that apply to the Internet and Internet related technologies.
Cyber
law is one of the newest areas_of the legal system. This is because Internet
technology develops at a
ranid pace.Cyber law provides legal protecthons to people using the Internet. This
includes both
businesses and everyday, citizens. Understanding cyber law is of the utmost importance to anyone
wha uses the Internet.Cyber law has also been referred to as the "law of the lnternet
Importance of Cyber law:
It covers all transactions over Internet.
It keeps eyes on all activities over Internet.
It touches every action and every reaction in cyberspace.

EVOLUTION OF CYBER LAW IN INDIA(INFORMATION TECHNOLOGY ACT)

With an increase in the dependency on the use of technologV. the need for cyber law was necessary.
Much like every coin has two sides, therefore, the dependency on technology has its pros and cons.
The rise of the 21" century marked the evolution of cyberlaw in India with the lnformation Technology
Act, 2000 (popularly known as IT Act).

With the growth of Internet, many cases of cybercrimes, frauds, cyber-attacks and cyber bullying are
reported. The nature of fraudulent activities and crimes keeps changing. To deal with such menace,
many countries have come up with legal measures for protection of sensitive personal data and to

safeguard the rights of Internet users.


The Parliament of India passed its first Cyber law the Information Technology (T) Act, 2000, on the
17th October2000, which provides the legal infrastructure for e-commerce in India.
Some of section under IT Act 2000 are given below:
Section Offence Penalty
67A Publishing images containing Imprisonment up to seven years,or'and with fine up to
sexual acts. L,000,000
67B Publishing child porn or Imprisonment up to five years, or/and with fine up to 1.000,000
predating children onlne. on first conviction. Imprisonment up to seven years,
orand with
fine up to 1,000,000 on second conviction.
67C Failure to maintain records. Imprisonment up to three years, or/an with fine.
68 Failure refusal to comply with Imprisonment up to three years, or/and with fine up to t 200,.000
orders.
69 Failure/refusal to decrypt data Imprisonment up to seven years and possible line.
70 Securing access or attempting Imprisonment up to ten years, oran with fine.
to secure access to a protected
System
71 Misrepresentation Inprisonment up to two years, or/an with fine up to 100.000

MLL QUESTION

Q.1 What is Data protection techniques?


Ans: Protecting yourself against viruses involves the following safeguards:

Active Protection
Use Anti-Virus and Anti-Spyware software.

Run frequent full-system scans.


Keep your system up-to-date.
Disable Cookies through settings.

Q.2 Compare Freeware and Shareware?


ANS: FREEWARE is a
computer software that is available for use at no cost or for an optional fee. Freeware
IS
generally proprietary software available at zero price and is not free software. The author usually

restricts one or more rights to copy, distribute and make derivative works of the software.
SHAREWARE is usually offered as a trial version with certain features only available after the license is
purchased, or as a full version, but for a trial period. Once the trial period has passed, the program
may stop running untila license is purchased. Shareware is often offered without support, updates,
or help menus, which only become available with the purchase of a license. The words "free trial" or

"trial version" are indicative of shareware.

Q.3. Differentiate between open source and open data.


ANS: The term 'OPEN SOURCE' is applicable to software,which means source code of a software is freely
available and user can make changes in it and reuse it.
The term 'OPEN DATA' is applicable to data that is freely available for everyone to use without any

licensing or copyright requirements.

Q.4 EXPEND: OSS, SDLC, FLOSS.


ANS: OSS. Open-Source Software.

SDLC. System Development Life Cycle.

FLOSS. Free Libre/Livre and Open-Source Software.

Q.5 What are intellectual property rights?


ANS: Intellectual property rights are the rights of the owner of information to decide how much
information is to be exchanged, shared or distributed. Also it gives the owner a right to decide
the
price for doing (exchanging/sharing/ distributing) so.

Q.6 Why should intellectual property rights protected?


ANS:The
intellectual property rights must be protected because protecting them
encourages individuals and businesses to create newsoftware and new
software applications, as wel
as improving existing applications, ensures new
ideas and technologies are widely distributed,
promotes investment in the national economy.
Q.7 What do youunderstand by plagiarism? Why is it a punishable offence?
ANS: Plagiarism is the act of using or stealing someone else's intellectual work, ideas etc. and passinB
it as your own work. In other words, plagiarism credit to its source.
is a failure in giving
a
Plagiarism is a fraud and violation of Intellectual property rights. Since intellectual property holds

legal entity status, violating its owner's right is a legally punishable offence.

Q.8What can be done to reduce the risk of identity theft? Write any two ways.

Ans: (i) Use unique ids to Protect your devices and accounts.
(ü) Using bio-metric protection

Q.9: Write names of any two common types of Intellectual Property Rights which are protected by the
law.

ANS

*Rights upon musical, literary, and artistic works.


* Rights upon discoveries and inventions.

* Words, phrases, symbols,and designs.

* Copyrights, trademarks, patents, industrial design rights and trade secrets.

Q.10: What is anti-virus software?


ANS: There are a number of malicious software ('malware") programs that can cause damage to
computers. These include viruses, worms, Trojan horses (Trojans), malware, spyware etc. Anti-virus
software is designed to detect and block attacks from malware. This software when loaded, resides in
memory and checks every operation if it is malicious or not. If it finds any suspicious activity, it blocks

that operation and saves our computer.

Q.11:Ican keep yousigned in.


Ican remember your site preferences.
Ican give you locally relevant content.

Who am 1?

ANS: Cookies.

Q.12: Define Digital Certificate?


ANS: Digital Certificates, specially formatted digital information issued to website, are used to verify
the identity of the message sender.
Q.13: DIGITAL SIGNATURES?

ANS: Digital signatures are


a way of authenticating the identity of creators or producers of digital

information.

Q.14: Describe the Pharming security issue and suggest


a way of protecting against it.
or on actual web server. Code
Ans: It is actually a code installed on the hard drive of user's computer
a

redirected user to a bogus/fake website without user knowing.


Method of protection:
Use filter to authenticate website.

* User should alert and look for pharming clues.

Q.15: Describe the Phishing security issue and suggest a way of protecting against it.
Ans: In phishing ,creator sends legitimate looking(fake) email in the hope of gaining personal
/financial

information fake email replicates a well known company e.g. a bank.

Method of protection:
ISPs can filter/block out phishing emails.
User should be aware of opening link of emails.

Topic: Awareness about health concerns related to the usage of technology.

Question MLL

Q:1 What is blue light, and how does it affect health?


high-energy visible light emitted by screens of electronic devices. Prolonged
A: Blue light is a

exposure to blue light can disrupt sleep patterns and cause eye strain.
Q:2 How does eXcessive screen time affect mental health?
A:Excessive screen time can contribute to anxiety, depression, and social isolation, especially in

children and adolescents.


Q: 3 What are some ergonomic tips to reduce the strain from using technology?
A: Adjust screen brightness, take regular breaks, use ergonomic furniture, and maintain good

posture to reduce strain from technology usage.


Q:4 Can technology addiction impact overall well-being?
A: Yes, excessive use of technology can lead to addiction, affecting sleep quality, productivity, and

mental health.
O:5 How does electromagnetic radiation from devices affect health?
A- While research is ongoing, some studies suggest that long-term exposure to electromagnetic
radiation from devices like cell phones may increase the risk of certain health issues, thougn more
evidence is needed.
Q:6 Can technology affect physical fitness?
A:Yes, excessive screen time can lead to a sedentary lifestyle, which is linked to various health
problems like obesity, cardiovascular issues, and muscle weakness.
Q:7 How can one mitigate the negative health effects of technology usage?
A:Setting limits on screen time, practicing digital detox, incorporating physical activity, and

maintaininga balanced lifestyle can help mitigate the negative health effects of technology usage.
Q:8 What is blue light?
A:High-energy visible light emitted by screens, which can disrupt sleep and cause eye strain.
Q:9 Can excessive screen time imnpact mental health?
A: Yes,
contributing to anxiety, depression, and social isolation.
Q:10 How can one reduce strain from technology usage?
A: Adjust brightness, take breaks, and maintain good posture.
Q:11 Does technology addiction affect well-being?
A: Yes, leading to sleep issues, productivity problems, and mental health challenges.
Q:12 Can electromagnetic radiation from devices pose health risks?
A: Studies suggest potential risks, but more research is needed.
Q:13 How does technology affect physical fitness?
A: Excessive screen time can lead to a sedentary lifestyle, impacting fitness negatively.
Q:14What can one do to minimize health risks from technology?
A:Set screen time limits, practice digital detox, and stay active.

0. 15 List any two health hazards related to excessive use of Technology.


Ans
(i) Impact on eyes: This is the most common form of health hazard as prolonged hours of screen
time can lead to extreme strain in the eyes.
(ii) Sleep problem: Bright light from computer devices block a hormone called melatonin which helps
us sleep. Thus we can experience sleep disorders leading to short sleep cycles.

Questions Assertion and Reasoning


ASSERTION (A) and REASONING (R) based questions.

Mark the correct choice as

() Both (A) and (R) are true and (R) is the correct explanation for (A).

() Both (A) and (R) are true and (R) is not the correct explanation for (A).
(1) (A)is true and (R) is false.

(iv) (A) is false but (R) is true.

Q. 1.
Act, 1980, anyone causing the pollution will
Assertion (A): According to Environmental Protection
pay for the damage caused.
(DIT) issued a comprehensive technical guide
Reason (R): The Department of Information Technology
on "Environmental Management for Information Technology Industry in India."

Ans. Option (iv) is correct.


anyone causing the pollution will pay
Explanation: According to Environmental Protection Act, 1986,

for the damage caused.


to
The DIT at the Indian Telephone Industries has set up demonstration projects showing how
recover copper from the Printed Circuit Boards.
Q2

Assertion:Excessive screen time can lead to digital eye strain.


Reasoning: Staring at screens for long periods can cause eye discomfort, dryness, blurred vision, and
headaches due to reduced blinking and increasedexposure to blue light.
Ans. Option (i) is correct.

Q.3
Assertion: Sedentary behavior associated with technology use contributes to obesity.
Reasoning: Engaging in prolonged sitting or lying down while using technology reduces physical
activity levels, which can lead to weight gain and an increased risk of obesity.
Ans. Option (i) is correct.

Q.4
Assertion: Excessive use of smartphones can cause sleep disturbances.
Reasoning: The blue light emitted by smartphone screens can interfere with the production of
melatonin, a hormone that regulates sleep, leading to difficulty falling asleep and disrupted sleep
patterns.
Ans. Option (i) is correct.

Q.5

Assertion: Text neck is a health issue caused by the use of mobile devices.
Reasoning: Holding mobile devices at a downward angle for extended periods puts strain on the

neck and upper spine, leading to pain, muscle imbalances, and postural issues.
Ans. Option (i) is correct.

Q.6
Assertion: The overuse of social media can't negatively impact nental health.
Reasoning: Constant exposure to curated and idealized represerntations of others' lives on social
media platforms can contribute to feelings of inadequacy, anxiety, depression, and social isolation.
Ans. Option (iv) is correct.

Q.7

Assertion: Technology addiction can have detrimental effects on overall well-being.


Reasoning: Excessive reliance on technology and the constant need for digital stirmulation can not
lead to neglect of personal relationships, poor academic or professional performance, and symptorns
resembling those of substance addiction.
Ans. Option (iii) is correct.

Q.8

Assertion: Prolonged use of handheld devices can lead to repetitive strain injuries.
Reasoning: The repetitive motions involved in typing, swiping, and scrolling on handheld devices can
strain the muscles, tendons, and nerves in the hands, wrists, and fingers, leading to conditions like
carpal tunnel syndrome.
Ans. Option (i) is correct.

Q.9

Assertion: Excessive gaming can contribute to physical health problems.


Reasoning: Engaging in long hours of gaming can lead to a sedentary lifestyle, resulting in
weight
gain, muscular imbalances, and an increased risk of cardiovascular dise ases.
Ans. Option (i) is correct.

Q.10

Assertion: The use of headphones or earphones at high volumes can't cause hearing loss.
Reasoning: Listening to music or other audio content at high volumes through
headphones or
earphones can damage the delicate structures in the ears, leading to permanent hearing loss or
tinnitus.
Ans. Option (iv) is correct.

Q.11
Assertion: Blue light emitted by screens can disrupt the circadian rhythm.

Reasoning:Exposure to blue light, especially in the evening and nighttime hours, can suppress
the
production of melatonin, disrupt the body's internal clock, and interfere with
sleep quality and
overall circadian rhythm.
Ans.Option (i) is correct.
Q.12

Assertion: Excessive use of social media can contribute to feelings of low self-esteem and body
image dissatisfaction.
Reasoning:The anonymous and pervasive nature of cyberbullying, facilitated by technology, can
result in emotional distress, anxiety, depression, and even suicidal thoughts or behaviors among the
victims.
Ans. Option (ii) is correct.

Q.13

Assertion: Cyberbullying has significant psychological consequences on its victims.


Reasoning:Constant exposure to carefully curated and filtered images on social media can lead to
unrealistic standards of beauty, comparison with others, and a negative impact on self-perce ption
and body image.
Ans. Option (ii) is correct.

Q.14
Assertion: Excessive use of smartphones can lead to decreased attention span.
Reasoning: Constant exposure to notifications, multitasking, and frequent switching between apps
and tasks on smartphones can contribute to a decrease in sustained attention and difficulty focusing
on one task for an extended period.
Ans. Option (i) is correct.

Q.15

Assertion: Technology use before bedtime can disrupt sleep patterns.


Reasoning:Spending excessive time playing video games can reduce opportunities for social
interaction and face-to-face communication, leading to a sense of isolation and difficulty in
developing and maintaining social relationships.
Ans. Option (i) is correct.

MCQs

1. When a person can't find a balance between their time online and their time offline is a
condition called as
A. Net Neutrality.
B. Internet Addiction Disorder
C. Hacking
D. Echo Chamber
2. Which of the following is not a health concern in usage of technology.

A. Internet can be addictive


B. Improper posture while using computer can cause backache.
C. Social
bonds can become strong.
D. Children tend to play online instead playing games outdoor.
3. Which of the following not a part of digital technologies?

a) Smartphones

b) Computers

c) Internet
d) FM Radio
4. With the outset of Covid-19 schools started Vonline classes but due to continuous online classes

students health issues also started. Health practitioner advised the parents to followa few health
tips. Which of the following health tips should not be suggested?
(A) The sitting posture should be correct.
(B) Breaks should be taken in between the online classes.
(C)To protect the eyes the gadgets be placed above eye level.
(D) Wash the eyes regularly
5. Which of the following health concerns is associated with excessive use of smartphones?
A) Digital eye strain
B) Increased attention span
c) Improved posture
D) Reduced risk of obesity
Answer:
A) Digital eye strain
Explanation:
Excessive use of smartphones, especially for prolonged periods, can lead to digital eye strain. Staring
at screens for extended periods can cause eye discomfort, dryness, blurred vision, and headaches
due to reduced blinking and increased exposure to blue light. Therefore, option A is the correct
answer.
It's important to note that while technology has numerous benefits, it is crucial to be aware of the

potential health concerns and take appropriate measures to mitigate them, such as practicing
healthy screen habits, ensuring ergonomic setups, and taking regular breaks from technology use.
6. Which of the following health concerns is commonly associated with excessive screen time?
a) Carpal tunnel syndrome

b) Sleep disturbances
c) Asthma

d) Vitamin D deficiency
7. Which of the following is a potential health concern associated with prolonged smartphone
usage?
a) Hearing loss
b) Migraine headaches
c) Osteoporosis
d) Hypertension
8. Which of the folowing is a potential risk of improper ergonomic setup while using computers?
a) Seasonal allergies
b)Skin rashes
c) Eye strain

d) Diabetes

9. Which of the following health concerns is associated with excessive use of headphones or
earphones?
a) Tinnitus
b) Cataracts

c) Gout
d) Allergic reactions

10. Which of the following is a potential health concern related to sedentary behavior associated
with technology use?
a) Iron deficiency anemia
b) Motion sickness
c) Varicose veins
d) Motion sensor synd rome
11.Which of the following health concerns is NOT commonly associated with excessive technology
use?
A. Eye strain
B. Neck and back pain
C. Anxiety and depression
D, Improved physical fitness
Answer:
D.
Improved physical fitness
12. Excessive use of smartphones and tablets can lead to which of the following health problems?
A) Improved posture
B) Reduced neck and shoulder pain
c) Decreased risk of carpal tunnel syndrome
D) Neck and shoulder pain
Answer: D) Neck and shoulder pain
13. Which of these mental health concerns has research linked to excessive social media use?
A) Increased self-esteem
B) Reduced anxiety
C) Improved mood
D) Depression
Answer: D) Depression
14. Which of the following is NOT a potential health benefit of using itness tracking devices?
A) Increased physical activity
B) Improved sleep quality
C) Better time management
D) Decreased motivation to exercise
Answer: D) Decreased motivation to exercise
15.Prolonged sitting while using technology can increase the risk of developing which of these
health conditions?
A) Improved cardiovascular health
B) Reduced risk of obesity
C) Decreased risk of type 2 diabetes
D)Sedentary behavior-related health issues
Answer: D) Sedentary behavior-related health issues
16. Which of the following isa common side effect of prolonged use of smartphones and tablets?
A) Improved hand-eye coordination
B) Reduced neck and shoulder strain
C) Decreased risk of headaches
D) Neck and shoulder pain
Answer: D) Neck and shoulder pain
17. Excessive use of social media has been linked to an increased risk of which mental health

condition?
A) Improved self-esteem
B) Reduced stress levels
c) Increased socialconnection
D) Anxiety and depression
Answer: D) Anxiety and depression
18 The blue lght emitted by digtal screens can have which efect on the body's natural sleep-wake
Cyclet
A) improves sleep quality
B)tncreases melatoninproduction
Disrupts the circadian rhythm
D)Enhances daytime alertness
Answer: ) Disrupts the circadian thythmn
19, Which of the following health benefits is NOT typically associated with
the use of fitness tracking
devices?
A) Increased physical activity
B) Improved sleep quality
) Better time management
D) Reduced motivation to exercise
Answer: D) Reduced motivation to exercise
20.Prolonged sitting and sedentary behavior due to technology use can
increase the risk of
developing which of these health conditions?
A) lmproved cardiovascular health
B) Reduced risk of type 2 diabetes
C) Decreased risk of obesity
D)Sedentary behavior-related health issues
Answer: D)Sedentary behavior-related health issues

Awareness about health concerns related to the usage of technology


As digital technologies have penetrated into
different fields, we are spending more time in front of
screens. be it mobile, laptop, desktop,
television, gaming console, music or sound device. But
interacting in an improper posture can be bad for us-both physically
and mentally. Besides, spending
too much time on the internet can be addictive
and can have a negative impact on our physical and
psychological well being.
Here are a few key considerations around technology use and how it
affects our health:
0) Eyes strain: When we gaze at a screen for long periods
of time, we often forget to blink. In fact,
research has shown that digital eye strain reduces our blink rate
by half, which means the tears that
protect our eyes evaporate without being replaced. Additionally,
reading the srnaller fonts on a
or
smartphone other portable device can intensify the strain.
i) Sleep Disorders: We love our devices so much that many us even
of sleep with them. One study
found that 72% of smartphone owners keep their
phone next to their bed at night to ensure they do
use can interfere with
not miss a thing. It might seem like a harmless habit but late night technology
your ability to sleep.
use with sleep conducive activities such
To avoid sleep disruption, try replacing late night technology
as taking a bath or reading in bed. Resisting the urge to keep your phone on your nightstand can also

help minimize nighttime interruptions


games or TVs, we generally
(0) Physical Inactivity:When we are using technology like computers, video
are not exercising. That's why there's an increasing body of research linking the overuse of digital
more time on watching TV or
devices to decreasing exercise and fitness levels Logically, spending
playing video games reduces the time you spend staying active.
over social media every
(iv)Mental Health: More than three billion people interact with each other
can impact our
day. While many of our exchanges are generally harmless, over-using these services
well being. Social media addiction is linked to a rise in mental health disorders like depression, suicidal

ideation, particularly teenagers. Researchers make that correlation by highlighting how platforms
in

like Facebook, Instagram and Twitter place higher social pressures on young people and adults that

can lead to instances of cyberbullying, increased need for approval and general feelings of discontent.

1. Posture-related issues: Prolonged use of technology devices, such as smartphones, tablets, or


laptops, can contribute to poor posture. Slouching or hunching over while using these devices can lead
to neck pain, shoulder pain, and back pain. It is recommended to maintain proper posture and take
regular breaks to stretch and move around.

2.Sleep disturbances : The use of technology before bedtime can disrupt sleep patterns. The blue light
emitted by screens can interfere with the production of melatonin, a hormone that regulates sleep.
This can result in difficulties falling asleep, reduced sleep quality, and daytime drowsiness. Establishing
a technology-free bedtime routine and limiting screen time before sleep can help promote better

sleep.

3. Sedentary lifestyle: Engaging in prolonged screen time often involves sitting or lying down for

extended periods, leading to a sedentary lifestyle. Lack of physical activity can increase the risk of
obesity, cardiovascular diseases, and other health problems. It is important to balance screen time
with regular physical activity, such as exercise or outdoor activities.

4. Digital eye strain: Staring at screens for long durations can cause digital eye strain, also known as
computer vision syndrome. Symptoms may include eye fatigue, dryness, irritation, blurred vision, and
neadaches. To reduce the risk, it is recommended to follow the 20-20-20 rule: every 20 minutes, look
away from the screen and focus on an object at least 20feet away for 20 seconds.

can have negative impacts on


5. Mentalhealth issues: Excessive use of technology and social media
mental health. Constant exposure to social media can contribute to feelings of inadequacy, anxiety,
depression, and social isolation. It is important to maintain healthy balance and prioritize real-world
a

relationships and activities.

6. Repetitive strain injuries: Repetitive motions associated with technology use, such as typing or using

a mouse, can lead to repetitive strain injuries (RSIs) like carpal tunnel syndrome. It is essential to
practice proper ergonomics, use ergonomic accessories, and take regular breaks to prevent these
injuries.

7. Hearing problems: Listening to music or audio content at high volumes through headphones or

earphones can lead to hearing loss or tinnitus. It is advisable to keep the volume at a safe level and
take breaks from using headphones or earphones to protect hearing health.
These health concerns highlight the importanc of maintaining a balanced approach to technology
usage and adopting healthy habits tomitigatè the potential risks associated with excessive screen time

and improper usage. ACCM

Here's some more information about health concerns réated to the usage of technology:
1. Blue light exposure: Screens emit blue lightwhich an affect sleep patterns and disrupt the body's

circadian rhythm. Exposure to blue light in the evening and nighttime hours can suppress the
production of melatonin, making it harder to fall asleep and negatively impacting sleep quality. Some
devices now offer features like night mode or blue light filters to reduce the amount of blue light
emitted.

2.Cyberbulying: The rise of technology and social media has also led to an increase in cyberbulying.
Cyberbulying involves the use of technology to harass, intimidate, or humiliate others. It can have
severe psychological consequences on victims, including anxiety, depression, and even suicidal
thoughts or behaviors. It is important to promote safe and respectful online behavior and educate
individuals about cyberbullying prevention and intervention.
3. Digital addiction: Excessive use of technology, especially smartphones and social media, can
lead to
digital addiction. People may experience a compulsive need to constantly check their devices,
leading
to neglect of personal relationships, reduced productivity, social isolation,
and anxiety. Developing
healthy digital habits, setting boundaries, and taking regular breaks from
technology can help prevent
digital addiction.
4. Electromagnetic radiation: Some individuals express concerns about the potential health effects ot

electromagnetic radiation emitted by devices such as smartphones and Wi-Fi routers. Hovwevet, the
scientific consensus is that the levels of electromagnetic radiation emitted by these devices are
generally considered safe and do not pose significant health risks. Regulatory bodies establish safety
guidelines and standards to ensure the safety of technology devices.
5. Gaming-related disorders: Excessive gaming can lead to gaming-related disorders, such as gamin8

addiction or Internet Gaming Disorder (IGD). Individuals with gaming disorders may experience
impaired control over gaming, prioritizing gaming over other activities or responsibilities, continued
gaming despite negative consequences, and withdrawal symptoms when not gaming. Treatment
options and interventions are available for individuals struggling with gaming-related disorders.
6. Privacy and data security: The use of technology often involves sharing personal information and
data online. Privacy breaches and data security issues can have signiicant consequences for
individuals, including identity theft and unauthorized access to personal information. t is crucial to be
vigilant about privacy settings, use strong passwords, and be cautious when sharing personal
information online.
These additional health concerns highlight the need for responsible technology usage, digital well
being, and maintaining a healthy balance between technology and other aspects of life. It is important
to stay informed, practice good digital habits, and seek support or professional help when needed.

You might also like