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

LMRS Ip 2020 21

The document provides revision material for the Informatics Practices class for Class XII. It covers key concepts in Python including variables and identifiers, data types, operators, flow of control, functions, and an introduction to NumPy and Pandas libraries. It also includes comparison questions on lists, NumPy arrays, and Pandas Series as well as examples of creating and manipulating Series and performing math operations on Series in Pandas.
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)
80 views

LMRS Ip 2020 21

The document provides revision material for the Informatics Practices class for Class XII. It covers key concepts in Python including variables and identifiers, data types, operators, flow of control, functions, and an introduction to NumPy and Pandas libraries. It also includes comparison questions on lists, NumPy arrays, and Pandas Series as well as examples of creating and manipulating Series and performing math operations on Series in Pandas.
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/ 21

LAST MINUTES REVISION MATERIAL

Session: 2020-21

Class-XII
INFORMATICS PRACTICES
LAST MINUTES REVISION MATERIAL

Session: 2020-21

CHIEF PATRON
Sh. B L Morodia, Deputy Commissioner, KVS (RO), Jaipur

PATRON(S)
Shri D R Meena, Assistant Commissioner, KVS(RO), Jaipur

Sh. Mukesh Kumar, Assistant Commissioner, KVS(RO), Jaipur

CONTENT COORDINATOR/LEADER

Sh. Manoj Kumar Pandey, Principal K V Itarana Alwar

CONTENT TEAM
Sh. Sandeep Arora, PGT(CS) KV 1 Udaipur
Sh. Prem Prakash Meena, PGT(CS) KV Alwar
Sh. Navneet Sadh, PGT(CS) KV Churu
Python Revision
Intro:
• Python is a high level (close to English) and interpreted (read and executed line by line) programming
language developed by Guido Van Rossum in the 90s.
• It can be operated via shell (interactive) or script mode.
Identifier: A variable/name of the function can be any combination of letters, digits and underscore
characters. The first character cannot be a digit. Variables in Python are case sensitive.
abc (all chars) 1abc (starts with a digit)
valid _val1 (underscore, char and digits) for (it is a reserved keyword) invalid
first_name (underscore as a first&name (use of special character)
connector)
Keywords: Reserved for special use. Can’t be used as variable names. Ex. if, any, in while, else etc
Operators: Just like regular mathematics has operators so does the python, most are borrowed from
math
a, b=15,4
✓ Arithmetic: +, -,*,/,//,%,** Ex. print(a+b,a%b,a//b,a*b) O/P 19 3 3 60
✓ Comparison: <,==,>=; Ex. print(a>b, a<b, a==15) O/P True False True
✓ Logical: and, or, not; Ex. print(a>b and b<a-b) O/P True
✓ Membership: in, not in Ex. print (a in [3,41,50]) O/P False
Data Types:
✓ Number (Immutable)
✓ Integer- 52, -9
✓ Float- 23,7,-0.0003,
✓ Boolean- True, False, 2>3, 5%2==1
✓ Collection
❖ String- Ordered and immutable collection of characters, digits and special symbols. Methods: count (),
find (), isupper (), isdigit (), tolower (), etc. Ex. s1,s2 = 'अजगर', ''Sita sings the blues''
❖ List - Ordered, Heterogenous and mutable collection. Methods: count (), insert (), append (), remove (),
pop (), sort () etc. Ex. l1,l2= [1,2,3], [1109,'R Rajkumar','XII','89.25%']
❖ Tuple - Ordered, Heterogenous and immutable collection. Methods: count(), index() etc.
Ex.t1,t2= (1,2,3), (1109,'R Rajkumar','XII','89.25%')
● Common Operations:
○ * and + operator will behave same on all three.
Ex. print(s1*3) # O/P: अजगरअजगरअजगर
Ex. print(l1+l2) # O/P: [1,2,3,1,2,3]

○ Iteration works exactly the same.


Ex. for i in t1:
print(i,end=' ') # O/P: 1 2 3

○ Slicing and element access is also the same.


Ex. print(s2[0:10]) # O/P: ''Sita sings''

● Uncommon: t1[2]=4 or s2[3]='e' will result in error(as they are immutable).


- Mapping Dictionary- Unordered, Heterogenous and has custom names for index called key.
Methods: get(), keys(), items(), update() etc.
d1= {'rno':1109,'name':'R Rajkumar','class':'XII','marks':'89.25%'}

KVS Regional Office Jaipur| Session 2020-21 Page 1 of 19


FLOW OF CONTROL: High resolution version of flowchart image:

i=0 #initialisation Flow chart


while(i<=5): # execute statement inside, until i<=5
i=i+1
if(i==2): # skip rest of the code and go to back to loop
continue
elif(i==4):
break # come out of the loop
else:
print(i,end=',')
else:
print('came out successfully')
print('break was applied') # will print it if break is executed

for i in range(1,6): # i will have values from 1 to 5


if(i==2):
continue
elif(i==4):
break
else:
print(i,end=',')
else:
print('came out successfully')
print('break was applied')
output: 1, 3, break was applied
# increment was done with help of range function

Some Common Functions/properties: use with example


- Inbuilt: len(), type(),id(), print(), input(), int(), float(),eval()
- math: log(),sqrt(),pow() etc
Numpy Library: Ordered, Homogenous collection of numbers (generally).
Import via=> import numpy as np

Comparison Question from list, NumPy, and pandas series (3 Marks)


List vs numpy array vs series
- Size - Numpy data structures take up less space than list and series
- Performance - they are faster than lists and series
- Indexing - Both list and NumPy have a numeric index (0,1,2…) whereas Series supports custom index.
- List does not support vectorised operation ex. print(np.array([2,4])*2) ⇒ [4,8]

import numpy as np O/P Note: Even though lst (list object), arr (array object)
import pandas as pd [2, 1, 1, 2, 2, 1, 1, 2] and sr (series object) have the same data. I.e. 2, 1, 1
lst=[2,1,1,2] [4 2 2 4] and 2.
arr=np.array(lst) [2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2]
When + or * operators are applied to them list behaves
sr=pd.Series(lst) 0 6
differently from both NumPy and series.
print(lst+lst) 1 3
print(arr+arr) 2 3 lst*3 prints the list elements three times, whereas sr*3
print(lst*3) 3 6 multiplies 3 to the individual elements 2,1,1 and 2.
print(sr*3) dtype: int64

KVS Regional Office Jaipur| Session 2020-21 Page 2 of 19


Data Handling using Pandas-Python Unit-1(25 Marks)
Python Library – Pandas Basic Features of Pandas
• Python package for data • Keep track of our data.
1 or 2
science. • Use of different data types (float, int, string, date time, etc.) Marks
• Builds on packages like • Easy grouping and joins of data
NumPy and matplotlib • Good IO capabilities
• data analysis and • Python MYSQL Connectivity
visualization work. • Label-based slicing, indexing and subsetting of large data sets.
Data Structures in Pandas Two important data structures of pandas are– Series,DataFrame. 1 Mark
Series: It is like a one- Basic feature of series are: 1 Mark
dimensional array like • Homogeneous data
structure with homogeneous • Size Immutable
data. For example, the • Values of Data Mutable
following series is a collection Syntax: - pandas.Series (data, index, dtype, copy)
of integers. Creation of Series is possible from –darray, dictionary & scalar value
Create a Series from ndarray import pandas as p1 Output: 2
import numpy as np1 10 P Marks
data = np1.array(['P','R','E','M']) 11 R
s=p1.Series(data,index= [10,11,12,13]) 12 E
print(s) 13 M
Create a Series from import pandas as pd1 Output 2
dictionary import numpy as np1 b NaN Marks
data = {'P’: 0., 'R’: 1., 'E’: 2.,'M’: 2.} c NaN
s=pd1.Series(data,index=['b','c','d','a']) d NaN
print(s) a NaN
Create a Series from Scalar import pandas as pd1 Output 2
import numpy as np1 05 Marks
s = pd1.Series(5, index= 15
[0, 1, 2, 3]) 25
print(s) 35
Note: - here 5 is repeated for 4 times
Maths operations with Series import pandas as pd1 Output 2
s = pd1.Series([1, 2, 3]) 02 Marks
t = pd1.Series ([1, 2, 4]) 14
u=s+t #addition operation print (u) 27
u=s*t # multiplication operation
print (u) 01
14
2 12
head and tail function: head import pandas as pd1 Output 2
() returns the first n rows s = pd1.Series ([1, 2, 3, 4, 5], index = a1 Marks
(observe the index values) and ['a','b','c','d','e']) b. 2
tail() returns the last n rows print (s.head (3)) c. 3
(observe the index values). print (s.tail (3)) Return first 3 elements
The default number of -----------------------------
elements to display is five. c3
d. 4
e. 5
Return last 3 elements
Accessing Data from Series import pandas as pd1 Output: 2
with indexing and slicing s = pd1.Series ([1, 2, 3, 4, 5], 1 # for 0 index position Marks
index = ['p','r','e','m','e']) 1 #for first 3 index values
print (s[0]) 2
print (s[:3]) 3
print (s[-3:]) 3 # slicing for last 3 index values
4
5
KVS Regional Office Jaipur| Session 2020-21 Page 3 of 19
Retrieve Data from selection s = pd.Series (np.nan, index= s.iloc[:3] # slice the first 2
[49, 48,47,46,45, 1, 2, 3, 4, 5]) three rows Marks
49 NaN
48 NaN
47 NaN
DataFrame: It is like a two- Create DataFrame
dimensional array with It can be created with following:
1 or 2
heterogeneous data. • Lists Marks
features of DataFrame are: • Dict
• Heterogeneous data • Series
• Size Mutable • Numpy ndarrays
• Data Mutable • Another DataFrame
Create a DataFrame from import pandas as pd1 Output
Lists data1 = [['Freya',10],['Mohak',12], Name Age 2
Marks
['Dwivedi',13]] 1 Freya 10
df1 = pd1.DataFrame(data1,columns= 2 Mohak 12
['Name','Age']) 3 Dwivedi 13
print (df1)
Create a DataFrame from import pandas as pd1 Output 2
Dict of ndarrays / Lists data1 = {'Name’: ['Freya', Name Age Marks
'Mohak'],'Age':[9,10]} 1 Freya 9
df1 = pd1.DataFrame(data1) 2 Mohak 10
print (df1)
Create a DataFrame from import pandas as pd1 Output 2
List of Dicts data1 = [{'x': 1, 'y': 2}, {'x': 5, 'y': 4, 'z': 5}] x y z Marks
df1 = pd1.DataFrame(data1) 0 1 2 NaN
print (df1) 1 5 4 5.0
Create a DataFrame from import pandas as pd Output 2
Dict of Series d1 = {'one': pd1.Series([1, 2, 3], index= ['a', one two Marks
'b', 'c']), a 1.0 1
'two': pd1.Series([1, 2, 3, 4], index= ['a', 'b', b 2.0 2
'c', 'd'])} c 3.0 3
df1 = pd1.DataFrame(d1) d NaN 4
print (df1)
Column Selection print (df ['one']) 1
Marks
Column addition df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) 1
c = [7,8,9] Marks
df[‘C'] = c
Adding a new column using df['four’] =df1['one’] +df1['three'] 1
the existing columns values Marks
Column Deletion del df1['one'] # Deleting the first column using DEL function
df.pop('two') #Deleting another column using pop function 1
Marks
Rename columns df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) Output 2
>>> df.rename(columns= {"A": "a", "B": "c"}) ac Marks
014
125
236
#Selection by Label
import pandas as pd1 Output 2
Marks
d1 = {'one': pd1.Series([1, 2, 3], index= ['a', 'b', one 2.0
'c']), two 2.0
'two’: pd1.Series([1, 2, 3, 4], index= ['a', 'b', 'c', Name: b,
'd'])} df1= pd1.DataFrame(d1) dtype: float64
Row Selection print (df1.loc['b'])
#Selection by integer location 2
import pandas as pd1 Output Marks
d1 = {'one': pd1.Series([1, 2, 3], index= ['a', 'b', one 3.0
'c']), two 3.0
KVS Regional Office Jaipur| Session 2020-21 Page 4 of 19
'two': pd1.Series([1, 2, 3, 4], index= ['a', 'b', 'c',
'd'])}
df1 = pd1.DataFrame(d1)
print (df1.iloc[2])
Addition of Rows import pandas as pd1 Output 2
df1 = pd1.DataFrame([[1, 2], [3, 4]], columns = ['a', 'b']) a b Marks
df2 = pd1.DataFrame([[5, 6], [7, 8]], columns = ['a', 'b']) 0 1 2
df1 = df1.append(df2) 1 3 4
print (df1) 0 5 6
1 7 8
Deletion of Rows # Drop rows with label 0 1
df1 = df1.drop(0) Marks
Iterate over rows in a import pandas as pd1 2
DataFrame import numpy as np1 Marks
raw_data1 = {'name': ['freya', 'mohak'],'age': [10, 1],
'favorite_color': ['pink', 'blue'], 'grade': [88, 92]}
df1 = pd1.DataFrame(raw_data1, columns = ['name', 'age',
'favorite_color', 'grade'])
for index, row in df1.iterrows():
print (row["name"], row["age"])
Output
freya 10
mohak 1
Indexing a DataFrame using import pandas as pd Output 2
.loc[ ]: This function selects import numpy as np a -1.340477 Marks
data by the label of the rows df = pd.DataFrame(np.random.randn(8, 4), index b 0.669544
and columns. = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], columns = ['A', 'B', c -0.185628
'C', 'D']) d -0.658744
#select all rows for a specific column e 0.596576
print df.loc[: ,'A'] f -1.167927
g 0.404994
h -0.576133
Accessing a DataFrame with # importing pandas as pd 2
a Boolean index: In order to import pandas as pd Marks
access a dataframe with a # dictionary of lists
boolean index, we have to dict = {'name': [“Mohak", “Freya", “Roshni"],
create a dataframe in which 'degree': ["MBA", "BCA", "M.Tech"],
index of dataframe contains a 'score': [90, 40, 80]}
boolean value that is “True” or # creating a dataframe with boolean index
“False”. df = pd.DataFrame(dict, index = [True, False, True])
# accessing a dataframe using .loc[] function
print(df.loc [True])
Output:
#it will return rows of Mohak and Roshni only (matching true only)
Binary operation over x = pd.DataFrame({0: [1,2,3], Output 2
dataframe with series 1: [4,5,6], 2: [7,8,9] }) 0 1 2 Marks
y = pd.Series([1, 2, 3]) 0 2 5 8
new_x = x.add(y, axis=0) print(new_x) 1 4 7 10
2 6 9 12
Export Pandas DataFrame to import pandas as pd 1 or 2
a CSV File: cars = {'Brand': ['Honda Civic','Toyota Corolla', 'Ford Focus', Marks
'AudiA4'],
to_csv function 'Price': [22000,25000,27000,35000]}
df = pd.DataFrame(cars, columns= ['Brand', 'Price'])
df.to_csv (r'D:\export_dataframe.csv', index = False, header=True)
print (df) #csv file will be created in specified file location with
specified name.

KVS Regional Office Jaipur| Session 2020-21 Page 5 of 19


read_csv function: import pandas as pd Output: 1 or 2
data = pd.read_csv("D: Brand Price Marks
\export_ 0 Honda Civic 22000
dataframe.csv") 1 Toyota Corolla 25000
print(data) 2 Ford Focus 27000
3 Audi A4 35000
Aggregation/Descriptive import pandas as pd Output:
statistics – dataframe: import numpy as np Dataframe contents
2, 3
Aggregation is the process of #Create a Dictionary of series Name Age or 4
turning the values of a dataset d= {'Name': Score Marks
(or a subset of it) into one pd.Series(['Sachin','Dhoni','Virat','Ro 0 Sachin 26 87
single value. hit', 1 Dhoni 25 67
'Shikhar']), 2 Virat 25 89
'Age':pd.Series([26,25,25,24,31]), 3 Rohit 24 55
'Score':pd.Series([87,67,89,55,47])} 4 Shikhar 31
df = pd.DataFrame(d) 47
print("Dataframe contents") Name 5
print (df) Age 5
print(df.count()) Score 5
print("count age",df[['Age']].count()) dtype: int64
print ("sum of count age 5
score",df[['Score']].sum()) dtype: int64
print("minimum sum of score 345
age",df[['Age']].min()) dtype: int64
print("maximum minimum age 24
score",df[['Score']].max()) dtype: int64
print("mean age",df[['Age']].mean()) maximum score 89
print("mode of dtype: int64
age",df[['Age']].mode()) mean age 26.2
print("median of score”, df[['Score']]. dtype: float64
median()) mode of age 0 25
median of score: 67.0

Data Visualization- Python


Introduction to matplotlib matplotlib.pyplot is a collection of functions for 2D plotting. Some of 1
the types of plots: Line, Bar, Histogram, Pie and Boxplot. Marks
To import the library for - import matplotlib.pyplot as pl 1
plotting Basic steps to follow while plotting: Marks
➢ Choose appropriate plot type and then the function
• Line plot: plot ()
• Bar plot: bar () and barh()
• Histogram: hist ()
➢ Understand the data and assign the legend values
➢ assign the axis labels
➢ assign plot title
Line Plot: A line plot/chart is import matplotlib.pyplot as pl 3
a graph that shows the x = [1, 2, 3, 4, 5] Marks
frequency of data occurring y = [23, 41, 26, 10, 31]
along a number line pl.plot(x, y,'r', label = "Sales", linewidth = 4)
pl.title ("Test Plot", loc="right")
pl.xlabel ("X - AXIS")
pl.ylabel ("Y - AXIS")
pl.legend ()
pl.show ()

KVS Regional Office Jaipur| Session 2020-21 Page 6 of 19


Multiple line plots import numpy as np 3
import matplotlib.pyplot as plt Marks
year = [2014, 2015, 2016, 2017, 2018]
Jnvpasspercentage = [90, 92, 94, 95, 97]
Kvpasspercentage = [89, 91, 93, 95, 98]
plt.plot (year, jnvpasspercentage, color='g')
plt.plot (year, kvpasspercentage, color='orange')
plt.xlabel ('Year')
plt.ylabel ('Pass percentage')
plt.title ('JNV KV PASS % till 2018')
plt.show ()

Bar Plot: A graph drawn using import matplotlib.pyplot as pl 3


rectangular bars to show how x = ['English','Hindi','Maths','Science','SST'] Marks
large each value is. The bars y = [34, 54, 41, 44, 37]
can be horizontal or vertical pl.bar (x, y, width =0.8, label= "Marks", color="brown”,
edgecolor="black")
pl.title ("Marks of 5 subjects”, loc="right")
pl.xlabel ("Subject")
pl.ylabel ("Marks")
pl.legend ()
pl.show ()

KVS Regional Office Jaipur| Session 2020-21 Page 7 of 19


Multiple Bar Plots import matplotlib.pyplot as plt 3
from matplotlib.dates import date2num Marks
import datetime
x = [datetime.datetime (2011, 1, 4, 0, 0),
datetime.datetime (2011, 1, 5, 0, 0),
datetime.datetime (2011, 1, 6, 0, 0)]
x = date2num(x)
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]
ax = plt.subplot (111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()
plt.show()

Histogram: A histogram is a import matplotlib.pyplot as pl 3


graphical representation import numpy as np Marks
which organizes a group of math= [12,23,45,56,57,67,72,83,65,22,87,53,12,90,78,
data points into user-specified 83,45,75,37,28]
ranges. x = np.arange (len(math))
freq, bin, patches = pl.hist(math, bins=10, edgecolor = "black", label
= "Math marks")
# frequency give the list of number of events in each bin
# bin is the bin size taken for making 10 bins.
# Check the number of bins given in the exam and accordingly give
the bin size.
# patches are the individual rectangle object
pl.title ("Performance of students", loc="right")
pl.xlabel ("Mark in Maths")
pl.ylabel ("Number of students")
pl.legend ()
pl.show ()

Save Plot: plt.savefig ('line_plot.pdf') 1


To save any plot use function
plt.savefig ('line_plot.svg') Marks
pl.savefig("plot.png") plt.savefig ('line_plot.png')
Here plot.png is the name of
# Parameter for saving plots .e.g.
the file where plot is saved.
plt.savefig ('line_plot.jpg', dpi=300, quality=80, optimize=True,
progressive=True)
KVS Regional Office Jaipur| Session 2020-21 Page 8 of 19
DBMS: Data Base Management System [Unit II Total 25 Marks]
Data Models : is an abstract model that organizes elements of data and standardizes how they relate to
one another
• Relational Data • Network Data • Hierarchical Data • Object Oriented
Model Model Model Model
RDBMS : Relational Database Management System: e.g. MySQL, Oracle, Ms-Access, FoxPro
SQL: Structured Query Language : is a universal language to interact with a wide variety of RDBMS
Keys: [1 or 2 Marks Ques.]
Table 1 Table 2
RollNo Name Class LibNo. CourseID CourseID CName Duration
1001 Amit X L12 AS124 AS124 Streaming 2
1002 Booby X L13 AS135 AS135 Advance 3
1003 Anita XI L15 AJ147 AJ146 AI 3
1007 Ankit XII L18 AS124 AJ147 Programing 1
1009 Bipin XI L25 AS135
• Primary Key: A column or Group of Column, which uniquely identify a Tuple in a Table is called
Primary Key. A Primary key cannot have null or duplicate values. A table can have only ONE
primary key but a Combination of columns can also act as primary key. example Roll No., PNR
Number , Aadhaar etc.
• Candidate Key: All Columns or group of Column, that can act as a primary key are called
Candidate key. In Table 1 Roll No, LibNo, are possible candidate key.
• Alternate Key: All candidate key other than Primary key. In table 1 if we take RollNo as Primary
key, LibNo will become Alternate key.
• Foreign Key: is a non-key attribute, which helps to establish a relation with another table. It is
generally Primary Key of another table. In Table 1 CourseID if Foreign Key.

• Degree: Total No. of Columns in a table is called its Degree. In the above table degree is 4.
• Cardinality: Total No of Rows in a Table is Called its Cardinality. In the above table cardinality is
5. (Note, while calculating cardinality we do not count the header row.)
TIP: Degree →Column (DC : Direct Current ) ; Cardinality → Row (CR : Credit Ratio) Both C not
together
Q . A table has 4 rows and 6 column find its degree and cardinality. [1 or 2 Marks]
Ans. Degree 6 ; Cardinality 4
Q. A table has 6 rows and 5 columns. 2 insert operations are performed on it. Find the new degree and
cardinality of the table? [1 or 2 Marks]
Ans. Degree 5; Cardinality 8

SQL COMMANDS [1 or 2 Marks]


Data Definition Language (DDL)
1 CREATE DATABASE <DATABASENAME>;
To create a new database in the system. Create Database office;
2 SHOW DATABASES;
To view the names of all the databases in the database system. Show Databases;
3 USE <DATABASENAME>;
To open a database to work in it. use office;
4 DROP DATABASE <DATABASENAME>
To remove or delete a database.

KVS Regional Office Jaipur| Session 2020-21 Page 9 of 19


5 CREATE TABLE [2 Marks/ Query Based ]
To create a new table in the current database.
CREATE TABLE EMP
(
EMPID INT PRIMARY KEY,
ENAME CHAR(10) NOT NULL,
DOB DATE CHECK (DOB<=’01-01-2001’),
POST VARCHAR(30) DEFAULT “WORKER”,
TYPE VARCHAR(30) CHECK (TYPE IN (“REGULAR”,”CONTRACT”),
AADHAR INT(12) UNIQUE,
BASIC FLOAT CHECK(BASIC>0),
DEPT_NO VARCHAR(25) REFERENCES DEPT(DEPT_NO)
);
** DEPT_NO IS FOREIGN KEY WHICH REFERENCING PRIMARY KEY OF DEPT TABLE

6 ALTER TABLE
To modify the structure of the table. i.e. add a new attribute, delete an existing attribute, change
to size and data type of a new attribute, renaming an attribute
i. ALTER TABLE EMP ADD MOBILE INT(10) → Adding attribute
Ii ALTER TABLE EMP DROP MOBILE; → Deleting/removing attribute
Iii ALTER TABLE EMP MODIFY ENAME VARCHAR(25); → Changing data type and size of attribute
ALTER TABLE EMP MODIFY EMPID INT(4);
iv ALTER TABLE EMP CHANGE ENAME EMP_NAME VARCHAR(25); → renaming attribute
7 DROP TABLE <TABLENAME>
To Delete/remove a table from the database. Drop Table emp;
8 DESCRIBE / DESC
To view the structure of the table. Desc emp;
9 Show Tables
To view the names of the tables in the current database. Show Tables;

SQL COMMANDS
Data Manipulation Language (DML)
1 INSERT
To add new record or records into a table
INSERT INTO EMP VALUES(101,”RAKESH SHARMA”,’1995-05-10”, ”MANAGER”, ”REGULAR”,
12345678911, 50000, ”SALES”);
2 DELETE
To Remove tuples from a table.
DELETE FROM <tablename> WHERE <Condition>;
DELETE FROM emp WHERE Ename = ’Rakesh Sharma’;
3 UPDATE
To modify or change the data in the tables
UPDATE <tablename>
SET Attribute1=<new value>, Attribute2=<new value>,…
WHERE <Condition>
Update emp set sal = sal = 50 where deptno =30;
KVS Regional Office Jaipur| Session 2020-21 Page 10 of 19
4 SELECT [3+2 Marks/Query / Output ]
To view / show / fetch / extract rows or tuples from table(s) or relation(s)
SELECT Attribute list/*
FROM table name(s)
WHERE Condition
ORDER BY Attribute name
GROUP BY Attribute name
HAVING Condition
DISTINCT, AS, AND, OR, NOT, IN / NOT IN, BETWEEN / NOT BETWEEN, IS NULL / IS NOT NULL
5 SINGLE ROW FUNCTIONS
NUMERIC FUNCTIONS – [1 Mark / Output Based]
- POW(X,Y) - x raise to the power of y Select Pow(8,2); → 64
- MOD(X,Y) - Remainder of X/Y Select MOD(80/12) → 8
- ROUND(N,D) - Rounds number N upto given D Select Round(123.7898,2); → 123.79
no. of digits
- SIGN(N) - If N is position then output 1, Select SIGN(-165); → -1
negative then -1 and Zero then output is 0 Select SIGN(0) ; → 0
- SQRT(X) – Returns square root of X Select SQRT(144): → 12
SRING/CHARACTER FUNCTIONS [1 Mark / Output Based]
- LENGTH(STR) : Find Number of characters in Select LENGTH(‘APPLE’) → 5
given string.
- CONCAT(STR1,STR2,STR3….) : Joins the given select CONCAT('Ken', 'driya');
strings one after the other. → 'Kendriya'
- UPPER(STR)/UCASE(STR): Converts lower case Select UPPER('Kendriya') → 'KENDRIYA'
alphabets of given string alphabets to Upper Select UPPER('orange') → 'ORANGE'
case. Other charters remain as it is.
- LOWER(STR)/LCASE(STR) : Converts Upper Select LOWER('Kendriya') → 'kendriya'
case alphabets of given string alphabets to Select LOWER('ORANGE') → 'orange'
lower case. Other charters remain as it is.
- LTRIM(STR): Removes Spaces on left side of Select LTRIM(‘ APPLE IS RED ‘);
given string. → ‘APPLE IS RED ‘
- RTRIM(STR) : Removes Spaces on Right side Select RTRIM(‘ APPLE IS RED ‘);
of given string. → ‘ APPLE IS RED‘
- TRIM(STR) : Removes both leading (left) and Select TRIM(‘ APPLE IS RED ‘)
Trailing (right )Spaces from given string. → ‘APPLE IS RED ‘
- LEFT(STR,N) : extract N characters from left Select LEFT('Kendriya',4) → 'Kend'
side of given String
- RIGHT(STR,N) : extract N characters from Select RIGHT('Kendriya',4) → 'riya'
right side of given String
- INSTR(STR,SUBTRING) : returns the position Select INSTR("apple", "p"); →2
of the first occurrence of a string in another
string.
- SUBSTR(STR, position, no. of characters) or Select MID('Kendriya',4,2) → 'dr'
MID(STR, position, no. of characters)

DATE FUNCTIONS [1 Mark / Output Based]


KVS Regional Office Jaipur| Session 2020-21 Page 11 of 19
- CURDATE(): Display current date in YYYY- Select CURDATE ();
MM-DD format
- DATE(DateTime) : returns the date part of Select Date('2013-12-23');
date time value specified →2013-12-23
- DAYOFMONTH(DATE): returns the day of SELECT DAYOFMONTH('2021-03-04');
the month for a given date (a number → 04
from 1 to 31)
- DAYNAME(DATE) : returns the Day Name Select DAYNAME('2021-03-04');
corresponding to Date value supplied. → Thursday
- DAYOFWEEK(DATE): Returns the weekday Select dayofweek('2021-03-04');
index for a given date (a number from 1 to →5
7). 1=Sunday, 2=Monday, so on
- MONTH(DATE): returns the month part for Select month('2013-12-23')
a given date (a number from 1 to 12). → 12
- MONTHNAME(DATE) : returns the name Select MONTHNAME('2013-12-23')
of the month for a given date. → December
- YEAR(DATE): returns the year part for a Select YEAR('2013-12-23');
given date. → 2013
- NOW():returns the current date and time, Select Now();
- as "YYYY-MM-DD HH-MM-SS" (string)
6 AGGREGATE FUNCTIONS [1 Mark / Query Based]
- SUM() : the total sum of a numeric column
- COUNT(): the COUNT() function returns the number of rows that matches a specified
criterion. Count doesn’t count Null Values.
- AVG() : the average value of a numeric column.
- MAX() : The Maximum value of a column (Numeric/ Varchar/ Date)
- MIN() : The Maximum value of a column (Numeric/ Varchar/ Date)
Table : EMP Table : DEPT
Empid Ename Post Basic DEPT_NO DEPT_NO DEPT_NAME
17251 Pratham Clerk 1500 D101 D101 Accounts
17855 Vipn Manager 1800 D202 D202 HRM
17884 Nitin Clerk 1750 D103 D303 IT
17859 Jatin Manager 2000 D101 D404 Physics
17445 NULL Analyst 1900 D202 D505 AI
17499 Vikas Manager 2500 D202
EXAMPLES
COUNT(*) vs COUNT(<col name>)

Ques: Display the no of rows in the table EMP Count(*)


Query: SELECT COUNT(*) FROM EMP ; 6
Explanation: Count(*) is used to count no. of rows
Ques: Display the no of employees in the table EMP Count(*)
Query: SELECT COUNT(Ename) FROM EMP ; 5
Explanation: It will count no. of non null records of that column.
5 because NULL is present in the last row of Ename.
SUM,AVG, MAX and MIN

KVS Regional Office Jaipur| Session 2020-21 Page 12 of 19


Ques: Display maximum, total and average basic Max(Basic) SUM(Basic) AVG(Basic)
salary 2500 11450 1908.33
Query: SELECT
MAX(BASIC),SUM(BASIC),AVG(BASIC) FROM
EMP;
Where to use GROUP BY?
Ques: Display maximum basic income for each post POST MAX(Basic)
Query: SELECT MAX(BASIC) FROM EMP GROUP BY POST Analyst 1900
HINT: each time you find word ‘each’/ ‘wise’ in question go for Group Clerk 1750
by Manager 2500
Where to use GROUP BY along with HAVING?
Ques: Display the no of employee post wise having at least two POST Count(*)
employees. Clerk 2
Query: SELECT COUNT(*) FROM EMP GROUP BY POST HAVING Manager 3
COUNT(*) >=2;
HINT: use having when we have a condition involving a aggregate
function. Never use aggregate function in where Clause
7 JOINS – WORKING WITH MORE THAN ONE TABLES [2 Mark / Query Based]
- Cartesian Product : is formed by Horizontal joining each row of the first table with every other
row of the second table. i.e. table 1 has N rows and table 2 has M rows, Cartesian Product as N X
M rows.
- CROSS JOIN / CARTESIAN PRODUCT
SELECT * FROM CUSTOMER, ACCOUNT
- EQUI JOIN
SELECT * FROM CUSTOMER, ACCOUNT WHERE CUSTOMER.ANO=ACCOUNT.ANO
- NON-EQUI JOIN
SELECT * FROM CUSTOMER, ACCOUNT WHERE CUSTOMER.ANO>ACCOUNT.ANO
- NATURAL JOIN
SELECT * FROM CUSTOMER NATURAL JOIN ACCOUNT
Ques: Display Empid, Ename, Dept_Name and Basic of all Clerks.
Query: Select empid, Ename, Dept_name, basic
from emp as E, Dept as D
where E.Dept_No= D.Dept_No and
Post = ‘Clerk’;
Empid Ename Dept_Name Basic
17251 Pratham Accounts 1500
17884 Nitin IT 1750
TIP Format of a Join Condition : Table1. Common Colum = Table 2.CommonColumn
e.g. emp.deptno= dept.deptno
TIP Wherever, there is a query, in which data is extracted from more than one table, always add a join
condition.
Ques: Table 1 has 4 rows and 3 Columns. Table 2 has 5 rows and 4 Columns. Find the Degree and
cardinality of the Cartesian Product of Table1 and Table2. [1 Marks ]
Ans: Degree = Table 1 Cols + Table 2 Cols = 3 + 4 = 7
Cardinality = Table 1 Rows * Table 2 Rows = 4 * 5 = 20

KVS Regional Office Jaipur| Session 2020-21 Page 13 of 19


Introduction to Networks
Introduction to Networks: A computer network is a group of computers that are digitally interconnected, for
the purpose of sharing resources (Hardware/Software).
Advantages of Computer Network
• File sharing • Resource sharing
• Sharing a single internet connection • Increasing storage capacity
Types of Networks: [1 Mark / Theory]
Type Full Form Distance Media Used Devices Used
PAN Personal Area Network 30-40 ft Bluetooth, Infrared, Data Cable
(A Room ) etc.
LAN Local Area Network 0-1 Km Wifi, Twisted Wire Pair, Switch/Hub
Ethernet Cable
MAN Metropolitan Area Network 1-15Km Coaxial Cable, Microwaves Repeaters
WAN Wide Area Network ∞ Radio Waves, Optical Fiber, Gateways, Routers
Satellite Communication
Network Devices : [1 Mark / Theory]
• NIC : A network interface controller (also known as a network interface card, network adapter, LAN
adapter or physical network interface) is a computer hardware component that connects a computer
to a computer network.
• RJ-45 : RJ45 is a type of connector commonly used for Ethernet networking.
• Modem: Modulator–Demodulator : Convert Digital Signals to Analog Waves(Modulation) at Source
and Analog waves to Digital Signals at destination (Demodulation). It Connects Computer system to a
network through telephone line.
• Hub : Act as a Central Device in Star Topology. It is a passive device
• Switch: is networking hardware that connects devices on a computer network by using packet
switching to receive and forward data to the destination device. Also Known as Intelligent Hub.
• Repeater: A repeater is an electronic device in a communication channel that increases the power of
a received signal and retransmits them, allowing them to travel further.
• Router: A router is a networking device that forwards data packets between computer networks. i.e
a router connects networks. Routers are intelligent devices, and they store information about the
networks they’re connected.
• Gateway: are used to connect networks, which may be entirely different from each other.
• Bridge : A bridge is a network device that connects multiple LANs (local area networks) together to
form a larger LAN.
Network Topology: The physical way in which computers are connected to each other in a network is called
Network Topology. [1 Marks /Theory]
Bus: A bus topology is a topology for a Local Area Network (LAN) in which all the nodes are connected to a single
cable. The cable to which the nodes connect is called a "backbone". If the backbone is broken, the entire segment
fails.
Ring: A ring topology is a network configuration where device connections create a circular data path. Each
networked device is connected to two others, like points on a circle.
Star: A star topology is a topology for a Local Area Network (LAN) in which all nodes are individually connected to
a central connection point, like a hub or a switch.
Tree: A tree topology is a special type of structure where many connected elements are arranged like the branches
of a tree.
Mesh: A mesh topology is a network setup where each computer and network device is interconnected with one
another.
KVS Regional Office Jaipur| Session 2020-21 Page 14 of 19
BUS Topology Ring Star Tree Mesh
Topology Topology Topology Topology
Point to remember about Topologies:
1. Adding of nodes is the easiest in Bus Topology.
2. Ring Topology provides bi-directional flow of data.
3. Start Topology has central control.
4. Shortest cable length : Bus ; Maximum cable required : Mesh
5. Mesh topology provide multiple paths from source to destination.

Introduction to Internet: The Internet is a vast network that connects computers all over the world.
URL : Uniform Resource Locator : address of a given unique resource on the Web.
e.g. http://www.example.com/index.html
Domain Name: A domain name is the permanent address of a website on the Internet.
e.g. www.yahoo.com
WWW: World Wide Web : also known as a Web, is a collection of websites or web pages stored in web
servers and connected to local computers through the internet.
Web Site: a set of related web pages located under a single domain name, typically produced by a single
person or organization.

Web: is a collection of websites or web pages stored in web servers and connected to local computers
through the internet.
Email: is an Internet service that allows people who have an e-mail address (accounts) to send and receive
electronic letters. These letters may be plain text, hypertext or images. We can also send files with email
using attachments.
Chat : is a way of communication, in which a user sends text messages through Internet. The messages can
be send as one to one communication (one sender sending message to only one receiver) or as one to
many communication (one sender sending a message to a group of people)
VoIP: Voice over Internet Protocol: is a technology that allows you to make voice calls using an Internet
connection instead of a regular (or analog) phone line.
Difference between a Website and webpage
Webpage Website
Webpage is a single document on the Internet Website is a collection of multiple webpages with
information on a related topic
Each webpage has a unique URL. Each website has a unique Domain Name

Static Web Page: A static web page (sometimes called a flat page or a stationary page) is a web page that is
delivered to the user's web browser exactly as stored. i.e. static Web pages contain the same prebuilt content
each time the page is loaded
Dynamic web page: The contents of Dynamic web page are constructed with the help of a program. They may
change each time a user visit the page. Example a webpage showing score of a Live Cricket Match.
Web Server: Web server is a computer where the web content is stored. Basically web server is used to host
the web sites
KVS Regional Office Jaipur| Session 2020-21 Page 15 of 19
Hosting of a Website: When a hosting provider allocates space on a web server for a website to store its files,
they are hosting a website. Web hosting makes the files that comprise a website (code, images, etc.) available
for viewing online
Web Browser: A web browser (commonly referred to as a browser) is a software application for accessing
information on the World Wide Web. e.g. Internet Explorer, Google Chrome, Mozilla Firefox, and Apple Safari.
Add-ons/plug-ins : is a software component that adds a specific feature to an existing computer program.
Cookies: are combination of data and short codes, which help in viewing a webpage properly in an easy and fast
way. Cookies are downloaded into our system, when we first open a site using cookies and then they are stored
in our computer only. Next time when we visit the website, instead of downloading the cookies, locally stored
cookies are used. Though cookies are very helpful but they can be dangerous, if miss-utilized.
Protocols: Protocols are set of rules, which governs a Network communication. Or set of rules that determine
how data is transmitted between different devices in a network.
HTTP : Hyper Text Transfer Protocol : HTTP offers set of rules and standards which govern how any
information can be transmitted on the World Wide Web
HTTPs : Hypertext Transfer Protocol Secure: It is advanced and secure version of HTTP.
TCP/IP : Transmission Control Protocol / Internet Protocol : determine how a specific computer should be
connected to the internet and how data should be transmitted between them.
FTP : File Transfer Protocol : Transfer file(Upload/ Download) files to or from a remote server.
SMTP : Simple Mail Transfer Protocol : purpose is to send, receive, mail between email senders and
receivers.
POP3 : Post Office Protocol version 3 : standard protocol for receiving e-mail.
VoIP : Voice Over Internet Protocol :

HTTP HTTPs
HTTP is unsecured HTTPS is secured
HTTP sends data over port 80 HTTPS uses port 443

Hints to solve Case Study based Question: [5 Marks Generally last ques. in QP]
Question Type Hint Answer
Circuit Diagram Connects all the units in the question with a unit having
maximum no. of computers
Best Place to host Server Unit having Maximum no. of computers
Placing of Switch/Hub In each unit
Placing of Repeater Between units where distance is more than 100m
Most economical Communication Broadband
medium
Communication media for small Ethernet Cable
Distance < 100 m
Communication Media for Radio Waves,
Desert areas
Communication Media for Hilly Radio Waves/ Microwaves
Areas
Hardware/Software to prevent Firewall
unauthorized access

KVS Regional Office Jaipur| Session 2020-21 Page 16 of 19


Societal Impacts
Weightage: Part-A Section – I [5 Questions of 1 mark each (Fill in the blank/True False)] =5 Marks
Part-B Section – I [2 Questions of 2 Marks] and [Section – II 1 Question of 3 Marks]= 7 Marks
1. Digital Footprint is the trace you leave on the internet.
Ex. online purchase using your device, Check your insta feed and like a post.
Types: Active (A video uploaded on reels) & Passive (Window shopping on amazon).
How to reduce the footprint?
Logout after you’re done surfing a Keep comments/likes to a minimum
website

Think before posting on a public platform don’t post too much personal info online

2. Net and Communication etiquettes:


Net Etiquettes
Be Ethical Be Respectful Be Responsible

No copyright Share the Respect Respect Avoid cyber Don’t feed the
violation expertise privacy diversity bullying troll
Communication Etiquettes
Be Precise Be Polite Be Credible
Social Media Etiquettes
Be Secure Be Reliable
Choose a strong Know who beware of Think before you upload
password you befriend fake info

3. Intellectual property rights (IPR) allow its owners to exclude/include some third parties in order to
grant permission to access/modify his/her work through licensing while retaining ownership.
licensing of intellectual property: Technology Transfer, Trademark, Copyright and Patent

4. Plagiarism is the act of using or passing off someone else’s work as your own without giving proper
credit to the original creator.

crime or not: Under normal circumstances, it is considered a morally unethical issue but not a crime.
If a copyrighted work is copied without permission then it becomes a crime.

How to detect: Blockchain technology can be used to counter plagiarism. Services like Turnitin and
Grammarly are already used in academia to detect plagiarism.

5. Licence and copyright


Licence Copyright

One has to explicitly choose, or create, the license. It exists, without me doing anything to assert it,
It does not apply automatically. from the moment of creation.

KVS Regional Office Jaipur| Session 2020-21 Page 17 of 19


legal term to describe the terms under which Copyright is the legal term used to declare and
people are allowed to use the copyrighted material. prove who owns the intellectual property

Ex. When you are given a licence of the book from Ex. When you buy a book, you’re buying the
the copyright owner. You may republish or sell it printing copy of the book. You’re not buying the
under your name. copyright in the book.

Type of Open Source Licenses:


● MIT (shortest, most used. Its terms are loose and more open)
● BSD (much fewer restrictions in the distribution of free software)
● GPL (General Public License: more restrictive than MIT)
● Apache (Can be applied to both copyrights and patents)
● CC (Creative Commons: not necessarily open, common for design projects)
6. FOSS: Free and Open Source Software. It means that the source code of the software is open for all and
anyone is free to use, study and modify the code. Free as in free speech, not free as in free chocolate.
Ex. MySQL, Linux, Android, LibreOffice, VLC, Mozilla, WordPress etc.
7. Cyber Crime: Any criminal or illegal activity through an electric channel or through any computer
network is counted under cyber-crime.
- Crimes Against People Cyber harassment and stalking, distribution of child pornography, various
types of spoofing, credit card fraud, human trafficking, identity theft etc.
- Crimes Against Property These crimes include DDOS attacks, hacking, virus transmission, computer
vandalism, copyright infringement, and IPR violations.
- Crimes Against Government It includes hacking, accessing confidential information, cyber warfare,
cyber terrorism, and pirated software.
- Hacking: The act of unauthorised access to a computer, computer network or any digital system.
Two kinds: Ethical or White Hat and Unethical or Black Hat
- Phishing/scam calls/fraud emails: Generally, a URL that resembles the name of a famous website.
Ex. jio2021.com and with very lucrative offer like free internet for a year. When clicked a fake
website opens and steals the data or supplies free gift of the viruses to the user. This may lead to
identity theft.
- Identity theft: when someone uses our personal information—such as our name, license, or Unique
ID number without our permission to commit a crime or fraud.
Common ways how Identity Can Be Stolen: Data Breaches, Internet Hacking, Malware, Credit Card
Theft, Mail Theft, Phishing and Spam Attacks, Wi-Fi Hacking, Mobile Phone Theft, ATM Skimmers.
How to protect identity online: use up to-date security software, try to spot spam/scams, use strong
passwords, monitor credit scores, only use reputable websites when making purchases.
- Cyberbullying: is the use of technology to harass, threaten or humiliate a target. Examples of
cyberbullying is sending mean texts, posting false information about a person online, or sharing
embarrassing photos or videos. Different Types of Cyber Bullying: Doxing, Harassment,
Impersonation, Cyberstalking.

KVS Regional Office Jaipur| Session 2020-21 Page 18 of 19


Virus
Malware: program code that Worm: Self-replicating program Spyware: sits undetected by the OS
damages the system/network that hogs the resources or even by the antivirus software

Rootkit: Can’t be removed Trojan Horse: looks like useful Adware: unwanted software that
very easily from within the os software but contains malware bombards advertisements

8. Cyber Law: “law governing cyberspace”. It includes freedom of expression, access to and usage of the
internet, and online privacy. The issues addressed by cyber law include cybercrime, e-commerce, IPR,
Data Protection.
Indian IT Act, 2000 and amendment in 2008 is the cyber law of India.
● Guidelines on the processing, storage and transmission of sensitive information
● Cyber cells in police stations where one can report any cybercrime
● Penalties Compensation and Adjudication via cyber tribunals
9. E-waste: Various forms of electric and electronic equipment that have ceased to be of value to their
users or no longer satisfy their original purpose. Include TV, headphone, cell phone etc.
Hazards: It consists of a mixture of hazardous inorganic and organic materials.
● If mixed with water and soil creates a threat to the environment.
● Burning/Acid bath creates hazardous compounds in the air we breathe.
Management: Sell back, gift/donate, reuse the parts, giveaway to a certified e-waste recycler.
10. Technology and Health:
- Health apps and gadgets to monitor and alert. - Physical: Eye strain, Muscle Problems. Sleep
- Virtual Doctor issues, Depression etc
- VR games to improve fitness in a fun manner - Social: emotional issues, isolation, anti-social
- Online medical records.
behaviour etc

11. Network Security Attacks:


• Denial-of-Service (DoS) attack: It is an attack meant to shut down a machine or network,
making it inaccessible to its intended users. DoS attacks accomplish this by flooding the target
with traffic, or sending it information that triggers a crash.
• Network intrusion refers to any unauthorized activity on a digital network. Network intrusions
often involve stealing valuable network resources and almost always jeopardize the security of
networks and/or their data.
• Snooping, in a security context, is unauthorized access to another person's or company's data.
The practice is similar to eavesdropping but is not necessarily limited to gaining access to data
during its transmission.
• An eavesdropping attack, also known as a sniffing or snooping attack, is a theft of information as
it is transmitted over a network by a computer, smartphone, or another connected device. The
attack takes advantage of unsecured network communications to access data as it is being sent or
received by its user.

KVS Regional Office Jaipur| Session 2020-21 Page 19 of 19

You might also like