Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
799 views

Python Notes

Uploaded by

Shreya Pant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
799 views

Python Notes

Uploaded by

Shreya Pant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 260

CLASS XII

COMPUTER SCIENCE

REVISION OF THE BASICS OF PYTHON


DEVELOPED BY- MEETU SINGHAL PGT (COMPUTER SCIENCE)
KENDRIYA VIDYALAYA NO.3 AGRA
Easy to code and
Dynamically typed
language

Large Standard Free and open


libraries source

Python

Portable and Object Oriented


Integrated language

GUI Programming
Support

Developed By :Meetu Singhal, PGT (Computer Science)


KV NO 3 Agra
Tokens
smallest individual unit in a program

Literal Punctuator
Operator
Identifier triggers an action when applied to variables Keyword
name given to differnt parts of program
Reserved word with special
Numeric
meaning Boolean
literal
String literal eg.
literal {}
eg.
e.g []
True
"abc" @
Logical Floating False
Arithmetic Integer point :
operator
operator literal literal
eg. NOT Assignment #
eg. + , - , *, /, operator eg. 12 eg. 23.3
AND Relational ""
% etc. operator eg. eg. =
eg. variable, OR eg.
function > , < , <=, >=
break if else NOT
name, , ==
etc.
objects etc.

DEVELOPED BY – MEETU SINGHAL PGT (COMPUTER SCIENCE)


KENDRIYA VIDYALAYA NO 3 AGRA
Integers
to store any signed integer value eg. 50
Boolean
to store True or False values eg. 1 or 0
Floating point number
to store double precision decimal numbers eg. 26.3
Numbers Complex number
to store real part and imaginary part of a number eg. A+Bj

sequence of characters
String eg. - "abcd", "1234", "_xyz" , "A12"
Data Types
a group of comma seperated values of any datatype between square
Identify type of List brackets
data eg. - [ 1,'a',76.3]

a group of comma seperated values of any datatype between paranthesis


Tuple eg. - ( 1, 'a', 76.3 )

an unordered set of comma seperated key:value pairs within curly brackets


Dictionary eg. - { 'a': 1, 'e': 2, 'i': 3,'o': 4,'u': 5}

None
Empty value

Developed by: Meetu Singhal PGT (Computer Science)


Kendriya Vidyalaya No 3 Agra
Data Objects

Mutable Immutable
(modifiable types) (non - modifiable types)

List Integers

Dictionaries Boolean

Set Floating point

String

Tuple

Developed by : Meetu Singhal PGT (Computer Science)


Kendriya Vidyalaya No 3 Agra
if

if <condition> : if age >=18:


if- else statement print ("Eligible to vote")
condititon else: else:
statement print("Not eligible to vote")
Flow of control

while while <test expression>: while (count <=10):


loop statement print (count)

for for <variable> in <sequence>: for i in range (1,10):


loop statement print (i)

Developed by: Meetu Singhal PGT (Computer science)


Kendriya Vidyalaya no 3 Agra
Concatenation operator eg. - "my"+"class"
(+) output: myclass
eg. - "hi !" * 3
Replication operator (*)
output: hi ! hi ! hi!

String operators Membership operator eg. - "dia" in "India"


( in / not in) output : True

Comparison operator eg. - "A" == "a"


( <, <=, >, >= , == , != ) output : False

Strings String slices Strings are sliced using eg. - word = " myclass"
stored as individual (part of the string or range of indices print( word[ 2:]
characters in string [n:m] output : class
continguous sub string)
locations
1. string. capitalize()
2. string.find( str , start, end)
3. string.isalnum()
String Functions 4. string. isdigit()
<string object> . <method name> () 5. string.upper()
6. string.lower()
ord( char) – returns ASCII value of a character
7. string.lstrip()
eg. - ord (‘A’) output: 65 8. string .rstrip()
chr (int) – returns character corresponding to 9. string.split()
ASCII value of passed integer value
eg. - chr (97) output : a

len(string) – returns length of string


eg - len(“string’) output : 6 Developed by: Meetu Singhal PGT (Computer science)
Kendriya Vidyalaya No 3 Agra

eeg
seq = L [start:stop:step]
List Slicing eg. - lst [0:10:2]
* it is similar to string slicing

Lists are depicted by square 1. append - List.append(<item>)


brackets. Some examples of e.g. - lst=[25,58,17]
lists are:
lst.append(90)
[] # empty list output : [25,58,17,90]
[1,2,3] 2. Updation - List [index] = <new value>
['a' ,'b' ,'c'] List e.g - lst = [10,20,30]
List Manipulation
[ 1 , 'a' , 'one', 3.5] lst[2] = 25
output : [ 10,20,25]
(Mutable 2. Deletion - del List [index]
sequence ) e.g. - del lst[ 1]
output : [ 10,25,30]

1. list.index ( <item>)
2. list. append (<item>)
3. list.extend(<list>)
4. list.insert(<pos>, <item>)
List 5. list.pop(<index>)
Functions 6. list.remove( <value>)
7. list.clear()
8. list.count(<item>)
9. list.reverse()
Developed by - Meetu Singhal PGT (Computer Science)
Kendriya Vidyalaya No 3 Agra
10. list.sort()
Tuples are depicted by round seq= T [start:stop]
brackets. Some examples of eg. - tup = (10,12,15,20,30,32,50)
tuples are: Tuple Slicing
tup [3:4]
() # empty tuple output : (20, )
(7 ,) # tuple with one member
(1,2,3) Creating a tuple is known as packing
( 'a', 'b', 'c') eg. t= (1,2,'a','b')
('a', 1 , ' one', 3.8) Creating individual values from tuple
Tuples is known as unpacking.
Packing and
Immutable e.g. w,x,y,z=t
unpacking tuples
sequence print (w,x,y,z)
output : 1 2 a b

1. len(<tuple>)
2. max( <tuple>)
3. min (<tuple>)
Tuple Functions
4. <tuple>.index(<item>)
5. <tuple>.count(<item> )
6. tuple( <sequence>)

Developed by: Meetu Singhal PGT (Computer Science)


Kendriya Vidyalaya No 3 Agra
Traversing elements
eg. - d= { 1 : "red", 2: "green"}
for key in d:
print( key , d[key])
output : 1 red
2 green

Adding /updating elements


Dictionary <dictionary> [key] = <value>
Dictionary is mutable, Operations
eg. - dict [ 'marks'] = 99
unordered collection with
elements in the form of a Key output : { 'marks' : 99}
: Value pairs that associates
keys to values.
dict = { <key> : <value> } Deleting element
del <dictionary>[<key>]
<dictionary>.pop(<key>)
Dictionary eg. d.pop(2)
output : { 1: red}

1. len ( <dictionary>)
2. <dictionary>.clear()
3. <dictionary>.get( <key>)
Dictionary
4. <dictionary>.items()
Functions
5. <dictionary>. keys()
Developed by: Meetu Singhal PGT (Computer Science)
6. <dictionary>. values()
Kendriya Vidyalaya No 3 Agra
7. <dictionary>. update (<other-dictionary>)
Sorting is arranging elements in
specific order either in ascending or
Sorting
descending Techniques

There are multiple algorithms to sort Bubble Sort Insertion Sort


a group of elements such as bubble
sort,insertion sort, selection sort,
heap sort, quick sort
Builds a sorted list one element at
Compares two adjoining values
a time from unsorted list by
and exchange them if they are
inserting the element at its
not in proper order.
correct position in sorted list
lst=[10,5,6,2,4,20,8]
lst = [10,5,6,4,2,8,20]
n=len(lst)
for i in range (1, len(lst)):
for i in range(n):
key=lst[i]
for j in range(0,n-i-1):
j=i-1
if lst[j]>lst[j+1]:
while j>=0 and key < lst[j]:
lst[j],lst[j+1]=lst[j+1],lst[j]
lst[j+1]=lst[j]
print("list after sort", lst)
j=j-1
else :
lst [j+1] = key
print( "list after sort" , lst)

Developed By: Meetu Singhal PGT (Computer Science)


Kendriya Vidyalaya No 3 Agra
FUNCTIONS
Presented By: Namrata Gokhale
Kendriya Vidyalaya Bulandshahr
Objectives
• Why Functions

• Types of Functions

• To understand the details of function calls and parameter

passing in Python.

• To be able to define new functions in Python.

• To understand scope of formal parameters and variables

defined in a function.
Why functions?
• Code reuse

• Easier to maintain (modularity)

• Facilitate solving a complex problem

• It reduces program size

• It makes program readable and understandable


Types of functions
1. Built-in:These are the functions whose functionality is
pre defined in python like abs(), eval(), input() and many
more.

2. Functions in modules: There are some predefined


modules in python. If we want to use a function residing in
a module, we have to import that module into our
program. Example:
>>> import math
>>> print(math.sqrt(3))

3. User Defined functions


Functions in modules
Module is a .py file which contains the definitions of functions and
variables.

Module is a simple python file.


When we divide a program into modules then each module contains
functions and variables. And each functions is made for a special task.

Once written code in modules can be used in other programs.

When we make such functions which may be used in other programs


also then we write them in module.

We can import those module in any program and we can use the
functions.
Functions in modules
We can import a module with the help of import statement. The
import statement can be used in two forms:

➢import <module> command : To import entire module

➢from < module> import <object> command: To import selected


object from a module.

>>> import math >>> from math import sqrt


>>> print(math.sqrt(3)) >>> print(sqrt(3))
Math Module:
>>> import math Return the ceiling of x, the smallest
>>> print(math.ceil(4.542)) integer greater than or equal to x
5

>>> print(math.fabs(-4.542)) Return the absolute value of x.


4.542

>>> print(math.factorial(5)) Return x factorial as an integer.


120
>>> print(math.floor(4.542)) Return the floor of x, the largest integer
4 less than or equal to x.

>>> print(math.gcd(18,16)) Return the greatest common divisor of


2 the integers a and b.

>>> print(math.sqrt(3)) Return square root of x.


1.7320508075688772
String Module
>>> s="kendriya vidyalaya sangthan" >>>
>>> print(s.lower()) print(s.replace("sangthan","institution"))
kendriya vidyalaya sangthan kendriya vidyalaya institution

>>> print(s.upper()) >>> print(s.isupper())


KENDRIYA VIDYALAYA SANGTHAN FALSE

>>> print(s.split()) >>> print(s.islower())


['kendriya', 'vidyalaya', 'sangthan‘] TRUE

>>> print(s.find("sangthan",0)) >>> print(s.isdigit())


19 FALSE

>>> print(s.capitalize()) >>> print(len(s))


Kendriya vidyalaya sangthan 29
Random Module
random() it returns a random floating point number in the range 0.0<=N<1.0

>>> import random


>>> print(random.random())
0.22983316461676617

randint(a,b) it returns a random integer N in the range (a,b) i.e. a<=N<=b


>>> import random
>>> print(random.randint(15,20))
15

uniform(a,b) it returns a random floating point number N such that


a<= N<=b for a<=b >>> print(random.uniform(10,100))
b<=N<=a for b<a 83.74943861148414
>>> print(random.uniform(100,10))
88.09338821344895
Random Module
randrange(start, stop, step) it returns a randomly selected element from
range( start, stop, step)
random.randrange(stop)
>>> print(random.randrange(25,50,3))
40
>>> print(random.randrange(25))
8

random.seed(a=None) The seed() method is used to initialize the random


number generator.
import random Seed function is used to save the state of random
for i in range(3): function, so that it can generate some random
random.seed(0) numbers on multiple execution of the code.
print(random.randint(1,100))
If the a value is None, then by default, current
Output: system time is used.
50
50
50
random module
choice(seq) Returns a randomly selected element from a non-empty
sequence.
>>> import random
>>> l=[10,22,55,44]
>>> print(random.choice(l))
22
>>> print(random.choice("KENDRIYA"))
K

random.shuffle() This functions randomly reorders the elements in a list.


>>> import random
>>> l=[10,22,55,44]
>>> random.shuffle(l)
>>> l
[10, 22, 44, 55]
>>> random.shuffle(l)
>>> l
[10, 44, 22, 55]
Ans: (i) 0:0 (ii) 0:4
Minimum Value of j= 0
Maximum value of j= 4
Go can have values as either 0,1,2 or 3
if Go=1 then it will display only one value, no such option given
if Go=2 then it will display two values i.e X[0],X[1]
if Go=3 then it will display three values i.e. X[0],X[1],X[2]
Therefore Correct option is (i) i.e. 100$$75$$10$$
User Defined Functions
def cal (x):
””docstring””” Function
y=x*x Body of function Definition
return y

a=int(input(“Enter a value”)
print(cal(a)) Function call

Function Header: First line of function definition begins with def and
ends with :
Parameters: Variables listed in the parenthesis of function header
Function Body: Indented statements below function header that
defines the action performed by function.
docstring: The first statement in this block is an explanatory string
which tells something about the functionality. it is optional.
Structures of Python Program
def function1():
:
:
def function2():
:
:
def function3():
:
:
#__main__ Python begins execution from
Statement 1 here i.e. #__main__
Statement 2
Flow of execution in a function call
• The FLOW OF EXECUTION refers to the order in which
statements are executed during a program.

def func(): Last statement


Function : of the function
call will definition will
send the
return
send the control
control back to
flow to wherefrom the
the #__main__ function was
function : called
definition.
func()
print()
Execution always begins at the first statement of the program.
Flow of execution......
1. # Program to add two numbers
2. def sum(a,b):
3. c=a+b #statement 1
4. return c #statement 2

5. num1=int(input(“Enter value”)) #statement 4


6. num2= int(input(“Enter value”)) #statement 5
7. res=sum(num1,num2) #statement 6
8. print(“Sum=“,res) #statement 7

Flow of execution according to line numbe is


2->5->6->7->2->3->4->7->8

Function called and executed


Argument and Parameters
Arguments are values appear in function call.
Parameters are values appear in function header.

# Program to add two numbers


def sum(a,b): a, b are arguments/ formal
arguments
c=a+b

return c

num1=int(input(“Enter value”))

num2= int(input(“Enter value”))


num1 , num2 are
res=sum(num1,num2)
parameters/actual
print(“Sum=“,res)
parameters
Types of Parameters
Python supports four types of formal parameters.

1. Positional arguments

2. Defaults arguments

3. Keywords arguments

4. Variable Arguments
Positional Arguments
The function call statement must match the number and order of
arguments as defined in the function definition, this is called the
Positional argument matching.
In this no value can be skipped from function call or you can’t change the
order of arguments also
If a function definition header is like.
def check(a,b,c):
:
:
then possible function calls for this can be:
check(x,y,z) #a gets value x, b gets value y, c gets value z

check(2,x,y) #a gets value 2, b gets value x, c gets value y

check(2,5,7) #a gets value 2, b gets value 5, c gets value 7


Default Arguments
A parameter having default value in the function header is known as a
default parameter.
Example of function header with default values:
def interest ( principle, time, rate=0.10):
0.10 is default value for parameter rate. if in a function call, the value for rate is not
provided, Python will fill the missing value with this value.

if a function calls appears like:


si=interest(5400,2) #third argument missing, its default value 0.10 is used for rate
si=interest(6100,3,0.15) # no argument missing with principle=6100 , time=3, rate=0.15

Following are examples of header with default values:


def interest (p,t,r=0.5): #correct
def interest(p,t=2, r): # incorrect
Any parameter can’t have a default vale unless all parameters appearing on its right have
their default values.
Keyword Arguments
Keyword arguments are the named arguments with assigned values
being passed in function call statement.

Python offers a way of writing function calls where you can write any
argument in any order provided you name the arguments when
calling the function.

1. p gets value 2000, t gets value 2, r gets


value 0.10
1. interest (p=2000,time=2, r=0.10)
2. interest ( t=4,p= 2600, r=0.09) 2. p gets value 2600, t gets value 4, r gets
3. interest (t=2,r=0.12, p=2000) value 0.09

3. p gets value 2000, t gets value 2, r gets


value 0.12
Variable Arguments
In Python, the single-asterisk form of *args can be used as a parameter
to send variable-length argument list to functions.

def multiply(*args): Output is:


y=1 21
for num in args: 72
84
y *= num
2400
print(y)
multiply(3, 7)
multiply(9, 8)
multiply(3, 4, 7)
multiply(5, 6, 10, 8)
Excercise 1
Consider a function with following header:
def info(object, spacing=10,collapse=1):
Find out which of following of these are correct and which are incorrect stating
reason

a. info(obj) a. Correct
b. info(spacing=20) b. Incorrect
c. info(obj2, 12) c. Correct
d. info (obj3,collapse=0) d. Correct
e. info() e. Incorrect
f. info(collapse=0,obj3) f. Incorrect
a. Correct obj is positional parameter for object, spacing gets value 10, collapse
gets value 1
b. Incorrect as required positional argument missing.
c. Correct as objects gets value obj2, spacing gets value 12, collapse gets default
value 1
d. Correct as required parameter object gets value obj3, collapse gets value 0,
skipped argument spacing gets default value 10
e. Incorrect as required parameter object’s value can’t be skipped.
f. Incorrect as Positional argument should be before keyword argument.
Returning Values From Functions
➢Functions returning some value(non void functions)
➢Functions not returning any value(void functions)

➢Functions returning some ➢Functions not returning some


value(non void functions): value(void functions):
The computed value is It takes the following form
returned using return
statement. return
return <value>
Example: Example:
def sum(x,y): def sum(x,y):
s=x+y s=x+y
return s print(s)
We can call function as: return
res=sum(3,6) We can call function as:
sum(3,6)
Returning Multiple Values
Unlike other programming language, Python lets you return more than one
value from function.
def cal(x,y):
a=x+y
b=x-y
c=x*y
d=x/y
return a,b,c,d
Either receive returned values in the or you can unpack values of tuple by
form of tuple variable, specifying number of variables of left
t=cal(5,2) hand sideof function call,
print(t) r1,r2,r3,r4=cal(5,2)
print(r1,r2,r3,r4)
Tuple t will be printed as (7, 3, 10, 2.5) Output will be printed as 7 3 10 2.5)
Scope of variable
Parts of program within which a name if legal and accessible, is called
scope of the name
•A local variable is a variable that is only accessible from within a given
function. Such variables are said to have local scope.
•Formal parameters also have local scope.
•Local variables are automatically created when a function is called, and
destroyed when the function terminates.
A global variable is a variable that is defined outside of any function
definition. Such variables are said to have global scope.
def sum(x,y): x, y, s are local
s=x+y variables
return s

num1=int(input("Enter First value"))


num2=int(input("Enter second value")) num1,num2,res are
res=sum(num1,num2) global variable
print("Result=",res)
Passing Array/List to a Function
def sum(a):
s=0
for i in a:
s=s+i
print(s)

y=[5,2,4,7]
sum(y)
Question1
Find and write output of the following:
def check( n1=1,n2=2):
n1=n1+n2
n2+=1
print(n1,n2)
check()
check(2,1)
check(3)

Output is:
33
32
53
Q.1 Write a function that takes a number as a argument and calculates
cube for it. The function does not return a value. If there is no value
passed to the function in function call, function should calculate cube of
2.

Ans : Cube of 5 is= 125


def cube(n=2):
print("Cube of ",n , "is=",n*n*n) Cube of 2 is= 8
return
cube(5)
cube()
END
CONTENTS AS PER NEW CBSE CURRICULUM

File handling: Need for a data file, Types of file: Text files, Binary files
and CSV (Comma separated values) files.
● Text File: Basic operations on a text file: Open (filename – absolute
or relative path, mode) / Close a text file, Reading and Manipulation
of data from a text file, Appending data into a text file, standard input /
output and error streams, relative and absolute paths.
● Binary File: Basic operations on a binary file: Open (filename –
absolute or relative path, mode) / Close a binary file, Pickle Module –
methods load and dump; Read, Write/Create, Search, Append and
Update operations in a binary file.
● CSV File: Import csv module, functions – Open / Close a csv file,
Read from a csv file and Write into a csv file using csv.reader ( ) and
csv.writerow( ).
CONTENTS COVERAGE IN THIS PRESENTATION

File handling: Need for a data file, Types of file: Text files,
Binary files & CSV Files
● Text File: Basic operations on a text file: Open (filename –
absolute or relative path, mode) / Close a text file.
WHY DO WE NEED FILES

Till now whatever programs we have written, the standard input in coming from keyboard and output
is going to monitor i.e. no where data is stored permanent and entered data is present as long as
program is running . After that execution, the programmatically generated data is disappeared. And
when we again run those programs we start with a fresh data.

Why? This is because that data is entered in RAM which is temporary memory and its data is
volatile.

However, if we need to store the data, we may store it onto the permanent storage which is
not volatile and can be accessed every time.. Here, comes the need of file.

Files enables us to create, update, read, and delete the data stored through our python program.
And all these operations are managed through the file systems.
Program in RAM
(Random Access Hard
Memory) Disk
What is a file in python
A file (i.e. data file) is a named place on the disk where a
sequence of related data is stored.
In python files are simply stream of data, so the
structure of data is not stored in the file, along with data.
It contains data pertaining to a specific application, for
later use. The data files can be stored in two It It contains data
pertaining to a specific application, for later use.
2
TYPES OF FILES

Python allow us to create and manage


three types of file

1. TEXT FILE

2. BINARY FILE

3. CSV FILE
1. TEXT FILE

What is Text File?

 Text file stores information in ASCII


OR UNICODE character. In text file everything
will be stored as a character for example if
data is “computer” then it will take 8 bytes
and if the data is floating value like 11237.9876 it
will take 10 bytes.
In text file each like is terminated by special
character called EOL. In text file some
translation takes place when this EOL character is
read or written. In python EOL is ‘\n’ or ‘\r’ or
combination of both
2. BINARY FILE

What is Binary File?

 It stores the information in the same format


as in the memory i.e. data is stored according to its
data type so no translation occurs.
In binary file there is no delimiter for a new line
Binary files are faster and easier
for a program to read and write than text
files.
Data in binary files cannot be directly read, it can
be read only through python program for
3. CSV Files

What is CSV File?

CSV is a simple file format used to store tabular


data, such as a spreadsheet or database.
Files in the CSV format can be easily imported to
and exported from programs that store data in
tabular format.
Difference Between Text Files, Binary Files & CSV Files
TEXT FILES BINARY FILES CSV FILES
1. Text Files are sequential files 1. A Binary file contain arbitrary binary CSV is a simple file format used to
data store tabular data.

2. Text files only stores texts 2 Binary Files are used to store binary CSV are used to stores data such as a
data such as image, video, audio, text spreadsheet or database

3. There is a delimiter EOL (End of Line 3. There is no delimiter A comma-separated values file is a
i.e \n) delimited text file that uses a comma
to separate values

4. Due to delimiter text files takes 4. No presence of delimiter makes files CSV is faster to handle as these are
more time to process. while reading or to process fast while reading or writing smaller in size. Moreover CSV is easy
writing operations are performed on operations are performed on file. to generate
file.

5. Text files easy to understand 5. Binary files are difficult to understand. CSV is human readable and easy to
because these files are in human read manually
readable form
OPENING AND CLOSING FILES
OPENING AND CLOSING FILES

To handle data files in python, we


need to have a file object. Object can be
created by using open() function or file()
function.

To work on file, first thing we do is open


it. This is done by using built in function
open().
Syntax of open() function is
file_object = open(filename [, access_mode]
[,buffering])
OPENING AND CLOSING FILES

open() requires three arguments to work,


first one ( filename ) is the name of the file on secondary
storage media, which can be string constant or a variable.
The name can include the description of path, in case, the
file does not reside in the same folder / directory in which
we are working
The second parameter (access_mode) describes
how file will be used throughout the program. This is an
optional parameter and the default access_mode is
reading.
OPENING AND CLOSING FILES

The third parameter (buffering) is for specifying how much is


read from the file in one read.
When we work with file(s), a buffer (area in memory where
data is temporarily stored before being written to file), is
automatically associated with file when we open the file.
While writing the content in the file, first it goes to buffer and
once the buffer is full, data is written to the file. Also when file is
closed, any unsaved data is transferred to file. flush() function is
used to force transfer of data from buffer to file
OPENING FILE

myfile = open(“story.txt”)
here disk file “story.txt”is loaded in the memory and
its reference is linked to “myfile” object, now python
program will access “story.txt” through “myfile”
object.
here “story.txt” is present in the same folder where
.py file is stored otherwise if disk file to work is in
another folder we have to give full path.
OPENING FILE

myfile = open(“d:\\mydata\\poem.txt”,”r”)
here we are accessing “poem.txt” file stored in
separate location i.e. d:\mydata folder.
at the time of giving path of file we must use double backslash(\\) in place of
single backslash because in python single slash is used for escape
character and it may cause problem like if the folder name is “nitin” and we
provide path as d:\nitin\poem.txt then in \nitin “\n” will become escape
character for new line, SO ALWAYS USE DOUBLE BACKSLASH IN
PATH
Another solution of double backslash is using “r” before the path making
the string as raw string i.e. no special meaning attached to any character
as:
myfile = open(r“d:\mydata\poem.txt”,”r”)
Absolute Vs Relative PATH
 To understand PATH we must be familiar
with the terms: DRIVE,
FOLDER/DIRECTORY, FILES.
 Our hard disk is logically divided into many
parts called DRIVES like C DRIVE, D DRIVE
etc.
Absolute Vs Relative PATH
 The drive is the main container in which we put
everything to store.
 The naming format is : DRIVE_LETTER:
 For e.g. C: , D:
 Drive is also known as ROOT DIRECTORY.
 Drive contains Folder and Files.
 Folder contains sub-folders or files
 Files are the actual data container.
Absolute Vs Relative PATH
DRIVE
DRIVE
Folders/Subfolders
FOLDER
DRIVE/FOLDER/FILE HIERARCHY

C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE
Absolute Path
 Absolute path is the full address of any file or
folder from the Drive i.e. from ROOT
FOLDER. It is like:
Drive_Name:\Folder\Folder…\filename
 For e.g. the Absolute path of file
REVENUE.TXT will be
 C:\SALES\2018\REVENUE.TXT
 Absolute path of SEC_12.PPT is
 C:\PROD\NOIDA\Sec_12.ppt
Relative Path

 Relative Path is the location of file/folder


from the current folder. To use Relative
path special symbols are:
 Single Dot ( . ) : single dot ( . ) refers to current
folder.
 Double Dot ( .. ) : double dot ( .. ) refers to
parent
folder
 Backslash ( \ ) : first backslash before (.)
and double dot( .. ) refers to ROOT folder.
Relative addressing
Current working directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : SALES


WE WANT TO ACCESS SHEET.XLS FILE, THEN RELATIVE ADDRESS WILL BE

.\2019\SHEET.XLS
Relative addressing
Current working
directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : DELHI


WE WANT TO ACCESS SEC_8.XLS FILE, THEN RELATIVE ADDRESS WILL BE
..\NOIDA\SEC_8.XLS
Getting name of current working
directory
import os
pwd = os.getcwd()
print("Current Directory
:",pwd)
FILE ACCESS MODES
FILE ACCESS MODES

MODE File Opens in


r Text File Read Mode
rb Binary File Read Mode

These are the default modes. The file


pointer is placed at the beginning for reading
purpose, when we open a file in this mode.
FILE ACCESS MODES

MODE File Opens in


r+ Text File Read & Write Mode
rb+ Binary File Read Write Mode
w Text file write mode
wb Text and Binary File Write Mode
w+ Text File Read and Write Mode
wb+ Text and Binary File Read and Write
Mode
a Appends text file at the end of file, if file
does not exists it creates the file.
FILE ACCESS MODES

MODE File Opens in


ab Appends both text and binary files at
the end of file, if file does not exists it
creates the file.
a+ Text file appending and reading.
ab+ Text and Binary file for appending and
reading.
FILE ACCESS MODES - EXAMPLE

For Ex:
f=open(“notes.txt”, ‘r’)
This is the default mode for
a file.
notes.txt is a text file and is
opened in read mode only.
FILE ACCESS MODES - EXAMPLE

For Ex:

f=open(“notes.txt”, ‘r+’)

notes.txt is a text file and is


opened in read and write mode.
FILE ACCESS MODES - EXAMPLE

For Ex:
f=open(“tests.dat ”, ‘rb’)

tests.dat is a binary file and


is opened in read only mode.
FILE ACCESS MODES - EXAMPLE

For Ex:
f=open(“tests.dat”, ‘rb+’)

tests.dat is binary file and is


opened in both modes that is
reading and writing.
FILE ACCESS MODES - EXAMPLE

For Ex:
f=open(“tests.dat”, ‘ab+’)

tests.dat is binary file and is


opened in both modes that is
reading and appending.
close FUNCTION
close FUNCTION

fileobject. close() will be used to close


the file object, once we have finished
working on it. The method will free up all the
system resources used by the file, this means
that once file is closed, we will not be able to
use the file object any more.

For example:

f.close()
THANK YOU &
HAVE A NICE DAY
UNDER THE GUIDANCE OF KVS RO AGRA
VEDIO LESSON PREPARED BY:
KIRTI GUPTA
PGT(CS)
KV NTPC DADRI
TEXT FILE READING & WRITING METHODS
FILE READING

PYTHON
PROGRA
M

A Program reads a text/binary file


from hard disk. File acts like an input to a
program.
FILE READING METHODS

Followings are the methods to read a data


from the file.

1. readline() METHOD

2. readlines() METHOD

3. read() METHOD
readline() METHOD

readline() will return a line read, as a string


from the file. First call to function will return
first line, second call next line and so on.

It's syntax is,


fileobject.readline()
readline() EXAMPLE

First create a text file and save under


filename notes.txt
readline() EXAMPLE
readline() EXAMPLE O/P

readline() will return only one line from a


file, but notes.txt file containing three lines
of text
readlines() METHOD
readlines()can be used to read the entire content of the file. You
need to be careful while using it w.r.t. size of memory required before
using the function. The method will return a list of strings, each
separated by \n. An example of reading entire data of file in list is:

It's syntax is,


fileobject.readlines()
as it returns a list, which can then be used for manipulation.
readlines() EXAMPLE
readlines() EXAMPLE

The readlines() method will return a


list of strings, each separated by \n
read() METHOD

The read() method is used to read


entire file
The syntax is:
fileobject.read()

For example

Contd…
read() METHOD EXAMPLE
read() METHOD EXAMPLE O/P

The read() method will return entire


file.
read(size) METHOD
read(size) METHOD

read() can be used to read specific


size string from file. This function also
returns a string read from the file.

Syntax of read() function is:

fileobject.read([size])

For Example:
f.read(1) will read single
byte or character from a file.
read(size) METHOD EXAMPLE

f.read(1) will read single byte or character


from a file and assigns to x.
read(size) METHOD EXAMPLE O/P
WRITING IN TO FILE
WRITING METHODS

PYTHON
PROGRA
M

A Program writes into a text/binary file from


hard disk.
WRITING METHODS

1. write () METHOD

2. writelines() METHOD
1. write () METHOD

For sending data in file, i.e. to create /


write in the file, write() and writelines()
methods can be used.

write() method takes a string ( as


parameter ) and writes it in the file.

For storing data with end of line


character, you will have to add \n character
to end of the string
write() using “w” mode
write() using “w” mode

Lets run the


same program
again
write() using “w” mode

Now we can observe that while writing data to file using “w” mode the previous
content of existing file will be overwritten and new content will be saved.

If we want to add new data without overwriting the previous content then we
should write using “a” mode i.e. append mode.
write() USING “a” MODE

New content is
added after
previous content
2. writelines() METHOD

For writing a string at a time, we use write()


method, it can't be used for writing a list, tuple etc.
into a file.

Sequence data type can be written using


writelines() method in the file. It's not that, we can't
write a string using writelines() method.

It's syntax is:

fileobject.writelines(seq)
2. writelines() METHOD

So, whenever we have to write a


sequence of string / data type, we will use
writelines(), instead of write().

Example:
f = open('test2.txt','w')
str = 'hello world.\n this is my first file
handling program.\n I am using python
language"
f.writelines(str)
f.close()
Example Programs
Writing String as a record to file
Example :To copy the content of one file to
another file
Removing whitespaces after reading
from file
 read() and readline() reads data from file and
return it in the form of string and readlines()
returns data in the form of list.
 All these read function also read leading and
trailing whitespaces, new line characters. If
you want to remove these characters you can
use functions
 strip() : removes the given character from both
ends.
 lstrip(): removes given character from left end
 rstrip(): removes given character from right end
Example: strip(),lstrip(),
rstrip()
File Pointer

 Every file maintains a file pointer which tells


the current position in the file where reading
and writing operation will take.
 When we perform any read/write operation
two things happens:
 The operation at the current position of file pointer
 File pointer advances by the specified number of
bytes.
Example

myfile = open(“ipl.txt”,”r”)

File pointer will be by default at first position i.e. first character

ch = myfile.read(1)
ch will store first character i.e. first character is consumed, and file pointer will
move to next character
File Modes and Opening position
of file pointer
FILE MODE OPENING POSITION
r, r+, rb, rb+, r+b Beginning of file
w, w+, wb, wb+, w+b Beginning of file (overwrites the file if
file already exists
a, ab, a+, ab+, a+b At the end of file if file exists otherwise
creates a new file
Set File offset in Python
Tell() Method
This method gives you the current offset of the file pointer in a file.

Syntax:

file.tell()
The tell() method doesn’t require any argument.

Seek() Method
This method can help you change the position of a file pointer in a file.

Syntax:

file.seek(offset[, from])
The <offset> argument represents the size of the displacement.
file.seek(offset[, from])

The <from> argument indicates the start point.

If from is 0, then the shift will start from the root level.
If from is 1, then the reference position will become the current position.
It from is 2, then the end of the file would serve as the reference position.
Example: Setting offsets in Python
with open('app.log', 'w', encoding = 'utf-8') as f:
#first line
f.write('It is my first file\n')
#second line
f.write('This file\n')
#third line
f.write('contains three lines\n')
#Open a file

f = open('app.log', 'r+') App.log


data = f.read(19);
print('Read String is : ', data) It is my first file
This file
#Check current position contains three lines
position = f.tell();
print('Current file position : ', position)

#Reposition pointer at the beginning once again


position = f.seek(0, 0);
data = f.read(19);
print('Again read String is : ', data)
OUTPUT
#Close the opened file
f.close() Read String is : It is my first file
Current file position : 19
Again read String is : It is my first file
Standard INPUT, OUTPUT and ERROR STREAM

Most programs make output to "standard out“,input from "standard in“, and error
messages go to standard error).standard output is to monitor and standard input is
from keyboard.

e.g.program
import sys
a = sys.stdin.readline()
sys.stdout.write(a)
a = sys.stdin.read(5)#entered 10 characters.a contains 5 characters.
#The remaining characters are waiting to be read. sys.stdout.write(a)
b = sys.stdin.read(5)
sys.stdout.write(b)
sys.stderr.write("\ncustom error message")
THANK YOU &
HAVE A NICE DAY
UNDER THE GUIDANCE OF KVS RO AGRA
VEDIO LESSON PREPARED BY:
KIRTI GUPTA
PGT(CS)
KV NTPC DADRI
KVS RO AGRA

BINARY FILES
&
CSV(COMMA SEPARATED VALUES) FILES
KVS RO AGRA

BINARY FILES
CREATING BINARY FILES
KVS RO AGRA
SEEING CONTENT OF BINARY FILE KVS RO AGRA

Content of binary file which is in codes.


READING BINARY FILES TROUGH PROGRAM
KVS RO AGRA

CONTENT OF BINARY
FILE
PICKELING AND UNPICKLING USING PICKLE MODULE
KVS RO AGRA
PICKELING AND UNPICKLING USING PICKEL
MODULE KVS RO AGRA

Use the python module pickle for structured


data such as list or directory to a file.
PICKLING refers to the process of converting
the structure to a byte stream before writing to a
file.
while reading the contents of the file, a
reverse process called UNPICKLING is used to
convert the byte stream back to the original
structure.
KVS RO AGRA
PICKLING AND UNPICKLING USING PICKEL
MODULE KVS RO AGRA

Firstly we need to import the pickle module, It


provides two main methods:
1) dump() method
2) load() method
KVS RO AGRA

pickle.dump() Method
pickle.dump() Method KVS RO AGRA

pickle.dump() method write the object in binary file.

Syntax of dump method is:

dump(object ,fileobject)
pickle.dump() Method
# A program to write list sequence in a binary file KVS RO AGRA
KVS RO AGRA

pickle.load() Method
pickle.load() Method
KVS RO AGRA
pickle.load() method is used to read the binary file.

CONTENT OF BINARY
FILE
BINARY FILE R/W OPERATION USING PICKLE MODULE
import pickle
Wr_file = open(r"C:\Users\lenovo\Desktop\python files\bin1.bin", "wb") KVS RO AGRA
myint = 56
mylist = ["Python", "Java", "Oracle"]
mystring = "Binary File Operations"
mydict = { "ename": "John", "Desing": "Manager" }
pickle.dump(myint, Wr_file)
pickle.dump(mylist, Wr_file)
pickle.dump(mystring, Wr_file)
pickle.dump(mydict, Wr_file)
Wr_file.close()

R_file = open(r"C:\Users\lenovo\Desktop\bin1.bin", "rb")


i = pickle.load(R_file)
s = pickle.load(R_file)
l = pickle.load(R_file)
d = pickle.load(R_file)
print("myint = ", I)
print("mystring =", s)
print("mylist = ", l)
print("mydict = ", d)
R_file.close()
READING BINARY FILE THROUGH LOOP
import pickle
Wr_file = open(r"C:\Users\lenovo\Desktop\python files\bin1.bin", "wb") KVS RO AGRA
myint = 56
mylist = ["Python", "Java", "Oracle"]
mystring = "Binary File Operations"
mydict = { "ename": "John", "Desing": "Manager" }
pickle.dump(myint, Wr_file)
pickle.dump(mylist, Wr_file)
pickle.dump(mystring, Wr_file)
pickle.dump(mydict, Wr_file)
Wr_file.close()
with open(r"C:\Users\lenovo\Desktop\bin1.bin", "rb") as f:
while True:
try:
r=pickle.load(f)
print(r)
print("Next item")
Read objects one by one
except EOFError:
through loop
break
f.close()
INSERT/APPEND RECORD IN A BINARY FILE
import pickle KVS RO AGRA
Empno = int(input('Enter Employee number:'))
Ename = input('Enter Employee Name:')
Sal = int(input('Enter Salary'))

#Creating the dictionary


dict1 = {'Empno':Empno,'Name':Ename,'Salary':Sal}

#Writing the Dictionary Here we are creating


f = open(r"C:\Users\lenovo\Desktop\python files\Emp.dat",'ab') dictionary Object to
pickle.dump(dict1,f)
f.close() dump it in a binary file
f = open(r"C:\Users\lenovo\Desktop\python files\Emp.dat",'rb')
while True:
try:
dict1 = pickle.load(f)
print('Employee Num:',dict1['Empno'])
print('Employee Name:',dict1['Name'])
print('Employee Salary:',dict1['Salary'])
except EOFError:
break
f.close()
SEARCH RECORD IN A BINARY FILE
import pickle KVS RO AGRA

f = open(r"C:\Users\lenovo\Desktop\python files\Emp.dat",'rb')
Found = False
eno=int(input("Enter Employee no to be searched"))
while True:
try:
dict1 = pickle.load(f)
if dict1['Empno'] == eno:
print('Employee Num:',dict1['Empno'])
print('Employee Name:',dict1['Name'])
print('Salary',dict1['Salary'])
Found = True
except EOFError:
break
if Found == False:
print('No Records found')
f.close()
UPDATE RECORD OF A BINARY FILE
import pickle
KVS RO AGRA

f = open(r"C:\Users\lenovo\Desktop\python files\Emp.dat",'rb')
rec_File = []
r=int(input("enter Employee no to be updated"))
m=int(input("enter new value for Salary"))
while True:
try:
onerec = pickle.load(f)
rec_File.append(onerec)
except EOFError:
break
f.close()
no_of_recs=len(rec_File)
for i in range (no_of_recs):
if rec_File[i]['Empno']==r:
rec_File[i]['Salary'] = m
f = open(r"C:\Users\lenovo\Desktop\python files\Emp.dat",'wb')
for i in rec_File:
pickle.dump(i,f)
f.close()
DELETE RECORD OF A BINARY FILE
import pickle KVS RO AGRA

f = open(r"C:\Users\lenovo\Desktop\python files\Emp.dat",'rb')
rec_File = []
e_req=int(input("enter Employee no to be deleted"))

while True:
try:
onerec = pickle.load(f)
rec_File.append(onerec)
except EOFError:
break
f.close()
f = open(r"C:\Users\lenovo\Desktop\python files\Emp.dat",'wb')
for i in rec_File:
if i['Empno']==e_req:
continue
pickle.dump(i,f)
f.close()
KVS RO AGRA

COMMA SEPARATED VALUE(CSV


Files)
CSV FILE
• CSV is a simple file format used to store tabular data, such as KVS RO AGRA
• a spreadsheet or database.
• Files in the CSV format can be imported to and exported from
programs that store data in tables, such as Microsoft Excel or
OpenOffice Calc.
• CSV stands for "comma-separated values“.
• A comma-separated values file is a delimited text file that uses a
comma to separate values.
• Each line of the file is a data record. Each record consists of
one or more fields, separated by commas. The use of the
comma as a field separator is the source of the name for this file
format
CSV File Characteristics
KVS RO AGRA
• One line for each record
• Comma separated fields
• Space-characters adjacent to commas are ignored

WHEN USE CSV?

• When data has a strict tabular structure


• To transfer large database between programs
• To import and export data to office applications, Qedoc modules
CSV Advantages
KVS RO AGRA
• CSV is faster to handle
• CSV is smaller in size
• CSV is easy to generate
• CSV is human readable and easy to edit manually
• CSV is simple to implement and parse
• CSV is processed by almost all existing applications

CSV Disadvantages
• No standard way to represent binary data
• There is no distinction between text and numeric values
• Poor support of special characters and control characters
• CSV allows to move most basic data only. Complex configurations cannot be imported and
exported this way
• Problems with importing CSV into SQL (no distinction between NULL and quotes)
CSV file handling in Python
KVS RO AGRA

To perform read and write operation with


CSV file,
• we must import csv module.
• open() function is used toopen file, and
return file object.
WRITING DATA IN CSV FILE
KVS RO AGRA

 import csv module


 Use open() to open CSV file by specifying
mode
“w” or “a”, it will return file object.
 “w” will overwrite previous content
 “a” will add content to the end of previous
content.
 Pass the file object to writer object with
delimiter.
 Then use writerow() to send data in CSV file
Writing to CSV file
KVS RO AGRA

import csv
with open(r'C:\Users\lenovo\Desktop\python files\new.csv','w') as wr:
a=csv.writer(wr,delimiter=",")
a.writerow(["Roll no","Name","Marks"])
a.writerow(["1","Rahul","85"])
a.writerow(["2","Priya","80"])

wr.close()
Content of CSV file
KVS RO AGRA
Reading from CSV file
KVS RO AGRA

• import csv module


• Use open() to open csv file, it will return file
object.
• Pass this file object to reader object.
• Perform operation you want
Reading from CSV file
KVS RO AGRA
import csv
with open(r'C:\Users\lenovo\Desktop\python files\new.csv',‘r') as rr:
a=csv.reader(rr)
for i in a:
print(i)
wr.close()
THANK YOU & KVS RO AGRA

HAVE A NICE DAY


UNDER THE GUIDANCE OF KVS RO AGRA
VEDIO LESSON PREPARED BY:
KIRTI GUPTA
PGT(CS)
KV NTPC DADRI
COMPUTER NETWORKS -I
CHAPTER INCLUDES :
❖ NETWORKS
❖ TYPES OF NETWORKS
❖ NETWORK DEVICES
❖ CLOUD COMPUTING
❖ INTER NET OF THINGS(IOT)

RACHANA KATIYAR
PGT(COMPUTER SCIENCE)
K V NOIDA 2ND SHIFT
WHAT IS NETWORK ?
 A network is a collection of computers, servers, mainframes, network
devices, peripherals, or other devices connected to one another to allow the
sharing of data. An example of a network is the Internet, which connects
millions of people all over the world. To the right is an example image of a
home network with multiple computers and other network devices all
connected.
ADVANTAGES OF NETWORK

 RESOURCE SHARING
 COST SAVING
 COLLABORATIVE USER INTERACTION
 TIME SAVINGS
 INCREASED STORAGE
DISADVANTAGES OF NETWORK
 If network are badly managed, services can become unusable and
productivity fails
 If software and files held centrally, it may be impossible to carry out
any work if the central server fails.
 File security is more important especially if connected to WAN e.g.
protection from viruses
 To handle network of organization you may need specialist staff to
run the network
EOLUTION OF NETWORKS

 1969 - First network came into


existence

 ARPANET – Advanced Research Project


Agency Network

 MID 80’S -NSFNET (National Science


Foundation Network)
TYPES OF NETWORK

•PAN(Personal Area Network)

•LAN(Local Area Network)

•MAN(Metropolitan Area Network)

•WAN(Wide Area Network)


PAN
(PERSONAL AREA NETWORK)
What is pan?

A personal area network is a computer


network for interconnecting electronic devices
centered on an individual person's workspace. A
PAN provides data transmission among devices
such
as computers, smartphones, tablets and personal
digital assistants.
TYPE OF PERSONAL AREA NETWORK

WIRED PAN : Wired personal area


networks provide short connections
between peripherals using USB and
many more.

WIRELESS PAN : A wireless personal area


network (WPAN) is a personal area
network in which the connections are
wireless using
 Irda (Used in Remote Control)
 Bluetooth(headphone)
 Many more
What are the advantages of pan?

The advantages of pans are-


 They are efficient
 They are cost-effective
 They are convenient.
What are disadvantages of pan?

The disadvantages of pan are-


 Its range is less.
 Transfer of data is slow.
 It create Health problem.
 Cost is high in terms of communication devices.
 Infrared signals travel only in a straight line.
LAN
(LOCAL AREA NETWORK)
 Local Area Network is a group of computers connected to each other in a
small area such as building, office.
 LAN is used for connecting two or more personal computers through a
communication medium such as twisted pair, coaxial cable, etc.
 It is less costly as it is built with inexpensive hardware such as hubs, network
adapters, and ethernet cables.
 The data is transferred at an extremely faster rate in Local Area Network.
 Local Area Network provides higher security.
MAN
(METROPOLITAN AREA NETWORK)
 A metropolitan area network is a network that covers a larger geographic area
by interconnecting a different LAN to form a larger network.
 Government agencies use MAN to connect to the citizens and private
industries.
 In MAN, various LANs are connected to each other through a telephone
exchange line.
 The most widely used protocols in MAN are RS-232, Frame Relay, ATM, ISDN,
OC-3, ADSL, etc.
 It has a higher range than Local Area Network(LAN).
Uses Of Metropolitan Area Network:
 MAN is used in communication between the banks in a city.
 It can be used in an Airline Reservation.
 It can be used in a college within a city.
 It can also be used for communication in the military
WAN
(WIDE AREA NETWORK)
 A Wide Area Network is a network that extends over a large geographical area
such as states or countries.
 A Wide Area Network is quite bigger network than the LAN.
 A Wide Area Network is not limited to a single location, but it spans over a
large geographical area through a telephone line, fibre optic cable or satellite
links.
 The internet is one of the biggest WAN in the world.
 A Wide Area Network is widely used in the field of Business, government, and
education.
Examples Of Wide Area Network:

 Mobile Broadband: A 4G network is widely used across a region or


country.
 Last mile: A telecom company is used to provide the internet services to
the customers in hundreds of cities by connecting their home with fiber.
 Private network: A bank provides a private network that connects the 44
offices. This network is made by using the telephone leased line provided
by the telecom company.
Advantages Of Wide Area Network:
Following are the advantages of the Wide Area Network:
 Geographical area: A Wide Area Network provides a large geographical area.
Suppose if the branch of our office is in a different city then we can connect
with them through WAN. The internet provides a leased line through which we
can connect with another branch.
 Centralized data: In case of WAN network, data is centralized. Therefore, we
do not need to buy the emails, files or back up servers.
 Get updated files: Software companies work on the live server. Therefore,
the programmers get the updated files within seconds.
 Exchange messages: In a WAN network, messages are transmitted fast. The
web application like Facebook, Whatsapp, Skype allows you to communicate
with friends.
 Sharing of software and resources: In WAN network, we can share the
software and other resources like a hard drive, RAM.
 Global business: We can do the business over the internet globally.
 High bandwidth: If we use the leased lines for our company then this gives
the high bandwidth. The high bandwidth increases the data transfer rate
which in turn increases the productivity of our company.
Disadvantages of Wide Area Network
The following are the disadvantages of the Wide Area
Network:
 Security issue: A WAN network has more security issues as
compared to LAN and MAN network as all the technologies
are combined together that creates the security problem.
 Needs Firewall & antivirus software: The data is
transferred on the internet which can be changed or hacked
by the hackers, so the firewall needs to be used. Some
people can inject the virus in our system so antivirus is
needed to protect from such a virus.
 High Setup cost: An installation cost of the WAN network is
high as it involves the purchasing of routers, switches.
 Troubleshooting problems: It covers a large area so fixing
the problem is difficult.
Internetwork
 An internetwork is defined as two or more
computer network LANs or WAN or computer
network segments are connected using devices,
and they are configured by a local addressing
scheme. This process is known as internetworking.
 An interconnection between public, private,
commercial, industrial, or government computer
networks can also be defined as internetworking.
 An internetworking uses the internet protocol.
 The reference model used for internetworking
is Open System Interconnection(OSI).
Types Of Internetwork:
 1. Extranet: An extranet is a communication network based on the
internet protocol such as Transmission Control protocol and internet
protocol. It is used for information sharing. The access to the
extranet is restricted to only those users who have login credentials.
An extranet is the lowest level of internetworking. It can be
categorized as MAN, WAN or other computer networks. An extranet
cannot have a single LAN, atleast it must have one connection to the
external network.
 2. Intranet: An intranet is a private network based on the internet
protocol such as Transmission Control protocol and internet
protocol. An intranet belongs to an organization which is only
accessible by the organization's employee or members. The main aim
of the intranet is to share the information and resources among the
organization employees. An intranet provides the facility to work in
groups and for teleconferences.
Intranet advantages:
 Communication: It provides a cheap and easy communication. An
employee of the organization can communicate with another
employee through email, chat.
 Time-saving: Information on the intranet is shared in real time, so it
is time-saving.
 Collaboration: Collaboration is one of the most important advantage
of the intranet. The information is distributed among the employees
of the organization and can only be accessed by the authorized user.
 Platform independency: It is a neutral architecture as the computer
can be connected to another device with different architecture.
 Cost effective: People can see the data and documents by using the
browser and distributes the duplicate copies over the intranet. This
leads to a reduction in the cost.
NETWORK DEVICES
Modem
RJ-45 connector
Ethernet Card (NIC)
Router
Switch
Gateway
Wi-Fi Card
MODEM
 Modem is short for "Modulator-Demodulator.“
 Itis a hardware component that allows a computer or
another device, such as a router or switch, to connect
to the Internet.
 As we know phone lines work on analog signal while
computer works on digital signal, So the role of Modem
is to convert Digital signal to Analog so that it can be
carried by telephone lines and other side it again
convert analog signal to digital form
RJ-45 connector
 The "RJ" in RJ45 stands for "registered jack,“
 Registered Jack 45 (RJ45) is a standard type of
 physical connector for network cables.
 RJ45 connectors are most commonly seen with Ethernet cables and
networks. Modern Ethernet cables feature small plastic plugs on each end
that are inserted into the RJ45 jacks of Ethernet devices
Ethernet Card
 It is also known as NIC (Network Interface Card)
 Is a device that is attached to each of the workstations
 and the server and helps the workstations establish all
 – important connection with the network.
 It contain RJ-45 slot to connect Ethernet cable with RJ- 45 connector.
 Each NIC attached to workstation has a unique number identifying it, known
as MAC Address.
 Also known as Network Interface Unit.
ROUTER
 A device that works like a bridge but can handle different protocols is known
as router. For example router can link Ethernet and mainframe. It is
responsible for forwarding data from one network to different network.
 The main purpose of router is to sorting and distribution of the data packets
to their destination based on their IP Address.
 Router uses Logical Address whereas Bridge uses Physical Address
HUB
 An electronic device that connect several nodes to form a network and
redirect the received information to all the connected nodes in a broadcast
mode.
 Hub is basically used in network to increase the number computer allows
them to communicate with each other.
 It is a dumb device i.e. it forward the message to every node connected and
create huge network traffic.
 Hubs can be either Passive or Active
 Active Hub : they amplify the signals as it moves from one connected device to
another like Repeaters.
 Passive Hub: allows signals to pass from one device to another without any
change.
SWITCH
 It is known as Intelligent HUB
 Is an intelligent device that connect several nodes to form a network and
redirect the received information only to the intended node(s)
 Switch stores MAC table, and when any node transmit the data to any node,
Switch filters the desired MAC Address of that node and send the data to that
node only.
GATEWAY
 Is a device used to connect different type of networks and perform the
necessary translation so that the connected networks can communicate
properly. Gateway helps to connect different type of network i.e. following
different protocols.
Cloud computing
 Cloud computing is the on-demand availability of computer system resources,
especially data storage and computing power, without direct active
management by the user. The term is generally used to describe data centers
available to many users over the Internet.
FEATURES OF CLOUD COMPUTING
 Resources Pooling.
 On-Demand Self-Service. It is one of the important and valuable features of
Cloud Computing as the user can continuously monitor the server uptime,
capabilities, and allotted network storage. ...
 Easy Maintenance. ...
 Large Network Access. ...
 Availability.
 Automatic System. ...
 Economical. ...
 Security.
TYPES OF CLOUD COMPUTING
 Public Cloud – Whole computing infrastructure is located on the premises of a
cloud computing company that offers the cloud service.
 Private Cloud – Hosting all your computing infrastructure yourself and is not
shared. The security and control level is highest while using a private
network.
 Hybrid Cloud – using both private and public clouds, depending on their
purpose. You host your most important applications on your own servers to
keep them more secure and secondary applications elsewhere.
 Community Cloud – A community cloud is shared between organizations with
a common goal or that fit into a specific community (professional community,
geographic community, etc.).
Internet of things (IoT)
 The internet of things, or IoT, is a system of interrelated computing devices,
mechanical and digital machines, objects, animals or people that are
provided with unique identifiers (UIDs) and the ability to transfer data over a
network without requiring human-to-human or human-to-computer
interaction.
How IoT works
 An IoT ecosystem consists of web-enabled smart devices that use embedded
systems, such as processors, sensors and communication hardware, to collect,
send and act on data they acquire from their environments. IoT devices share
the sensor data they collect by connecting to an IoT gateway or other edge
device where data is either sent to the cloud to be analyzed or analyzed
locally. Sometimes, these devices communicate with other related devices
and act on the information they get from one another. The devices do most of
the work without human intervention, although people can interact with the
devices -- for instance, to set them up, give them instructions or access the
data.

IoT benefits to organizations


•monitor their overall business processes;

•improve the customer experience (CX);

•save time and money;


Pros and cons of IoT
 Some advantages of IoT
❖ ability to access information from anywhere at any time on any device;
❖ improved communication between connected electronic devices;
❖ transferring data packets over a connected network saving time and money; and
❖ automating tasks helping to improve the quality of a business's services and reducing
the need for human intervention.
 Some disadvantages of IoT
 As the number of connected devices increases and more information is shared between
devices, the potential that a hacker could steal confidential information also increases.
 Enterprises may eventually have to deal with massive numbers -- maybe even millions -
- of IoT devices, and collecting and managing the data from all those devices will be
challenging.
 If there's a bug in the system, it's likely that every connected device will become
corrupted.
 Since there's no international standard of compatibility for IoT, it's difficult for devices
from different manufacturers to communicate with each other.
THANKYOU
Computer Network-II
•Modulation
•Collision in Wireless Network
•Error Detection and correction
•Media Access Control (MAC)
•ROUTING
•I P Addresses (V4 and V6)
•Domain Name System (DNS)
•Uniform Resource Locator (URL)
•Protocols:2G, 3G, 4G, WI-FI
•Basic Networking tools
•E-mail
•Secure Communications
•Network Applications
Modulation
Modulation is a technique of conversion of an electronic or optical carrier signal in to radio waves. It is
used to increase the reach of the signals. It is of three types-
– Amplitude Modulation (AM)
– Frequency Modulation (FM)
– Phase Modulation (PM)

– We are going to discuss AM and FM as per syllabus.


Amplitude Modulation (AM)
In Amplitude Modulation, the carrier signal is modulated so that the amplitude
varies with the changing amplitudes of the signal. The frequency and
phase of the carrier remain the same, only the amplitude changes to follow
variations in the information.
Frequency Modulation (FM)
In Frequency modulation (FM), the frequency of the carrier signal is modulated to follow the
changing voltage level (amplitude) of the signal. The amplitude and phase of the carrier
signal remain the same, but as the amplitude of the information signal changes, the
frequency of the carrier changes.
Collision in Wireless Network
• In a Ethernet network, collision occurs when two or more devices transmit data at the same
time. The network detects collision and discarded both of them.
• To prevent this condition, we can implement CSMA/CD (Carrier Sense Multiple
Access/Collision Detection) . If a station detects a collision, it aborts its transmission, waits
for random amount of time and then tries again for transmission.
• CSMA/ CD have the following states:
Contention state- when two station begin transmitting at exactly same time than there will
be collision.
Transmission state- the transmission state is total time period, the station will take for
transmitting the frames successfully.
Idle state-this is the time when no station is using the channel.
Error Detection and correction
• Error occurs when output information does not match with input information.
• Digital signals can be affected by noise that can introduce error in binary bits while traveling
from one system to another. i.e. change in 0 with 1 or 1 with 0.
• Error detection is a technique which is used to observe change in data during transmission.
• Error detection ensures the reliable delivery of data in a network.
• Error detection minimizes the probability of passing incorrect frames .
• Error Detecting Codes: When a message is transmitted it may corrupted due to noise. To
resolve this, some additional data is added in message which is known as error detecting
codes . Example of this code is Parity Check.
• Error-Correcting Codes: With error detecting code, we can also pass some data to figure out
the original message from the corrupt message. This code is called Error Correcting Code.
How to Detect and Correct Errors
• To detect and correct errors, some additional bits are added to the original message. The
additional bits are called parity bits.

• The MSB or LSB bit of an 8 bit word is used as parity bit and the remaining 7 bits are used
for data. The parity bit may be even parity or odd parity.
• Even parity means the number of 1’s in the message should be even (2,4,6…)
• Odd parity means the number of 1’s in the message should be odd (1,3,5…)
• Parity bit can be set to 0 or 1 depending on the type of parity used.
Two dimensional parity checking
Performance can be improved by using two-dimensional parity check, which organizes
the block of bits in the form of a table. Parity check bits are calculated for each row,
which is equivalent to a simple parity check bit. Parity check bits are also calculated for all
columns then both are sent along with the data.
Media Access Control (MAC)
• A Media Access Control address is a 48-bit address that is used for communication between
two hosts in the network. It is a hardware address of manufactured into NIC. It can not be
changed later. It is also known as physical address.

• Each Computer or node on a network needs a special circuit known as a Network Interface
Card (NIC) or LAN Card.

• MAC address is a 6 two-digit hexadecimal numbers.


00:1B:f4:11:fA:B7 is an example of a MAC address.
Manufacturer id Card no
ROUTING
• Routing is a process which is used to
deliver the packet by choosing an
optimal path from one network to
another
• Router is responsible for routing for
traffic in a network.
• A router can work like a bridge and
also can handle different protocols.
A router can locate the destination
required by sending the traffic to
another router if the destination is
unknown to itself.
• Router contain software that
enables them to determine which
of the several possible paths is the
best for a particular transmission.
IP Addresses (V4 and V6)
IP Address – An IP address is used to identify any device on a network. This is an important
concept as devices communicate with each other across the LAN and WAN based on IP
addresses.
An example of IP address is: 192.168.10.1

There are two types of version for IP addresses:


• IPv4 which is 32 bits
• IPv6 which is 128 bits

• IPv4 (Internet Protocol Version 4) is the fourth revision of the Internet Protocol (IP) used to
identify devices on a network through an addressing system.

• An IPv6 address is represented as eight groups of four hexadecimal digits, each group
representing 16 bits (two octets, known as hextet). The groups are separated by colons (:).
An example of an IPv6 address is: 2001:0db8:85f3:0000:0000:8f2e:0370:7334
IPV4 IPV6
It is a 32-bit number It is a 128-bit number
The format is X.X.X.X, where X is octet takes The format is X.X.X.X.X.X.X.X, where X is
0-255 values. hexadecimal takes 0-ffff values.
Number of addresses 232 Number of addresses 2128
Ex: 19.117.63.125 Ex: 2001:db8:3333:4444:cccc:dddd:eeee:ffff
Domain Name System (DNS)
•To Communicate over the internet, we can use IP addresses. But it is not possible to
remember all IP addresses.
•Domain Name makes it easy to change names in IP addresses. Domain name is used to
identify a web server in a URL i.e. a domain name is an address of a web server, for ex.-
https://kvsroagra.blogspot.com.
•A domain name has two parts-
–Top-level domain name or primary domain name
–Sub-domain name (s)
•Com is the primary domain name, blogspot is the sub-domain of com and kvsroagra is the
sub-domain of blogspot.
•The top level domain names are categorized into the following domain names:
•Generic domain names are- .com, .edu, .gov, .mil, .net, .org etc
•Country specific domain names are- : .in, .au, .nz, .jp, .us etc
URL(Uniform Resource Locator) Structure
• URL (Uniform Resource Locator) is used to identify a website or webpage. HTTP locators
are used to access distributed documents world wide.
• URL is used to specify any information on internet.
• URL structure has four factors-
– Protocol  it is used to retrieve the document. Like http: , ftp:, https: etc.
– Host computer  the host is the computer on which information is located.
– Port  it is optional. Like, a port has a number 8080 and it is placed between host and path.
– Path  it is the name of that path or place where file is stored.

• In this example http://www.cbse.nic.in/academic.html , http is the protocol and second


part is IP address or domain name and academic.html is the specific document.
Protocols:2G, 3G, 4G, WI-FI
•Protocols : The most important network nowadays is Mobile Network. It is based on cellular
technology. The architecture of mobile phone network has come a long way. The changes in
mobile telephony has been recorded as generations of mobile communication.

•1G (First Generation) – The analog 1G offered simple telephony service without data.
•2G (Second Generation)-This was started in the year 1992. This protocol allows sending some
data and text messages. The speed is 250kbps. The frequency range is 900-1800 mhz.
• 3G (Third Generation)-This was started in the year 2000. This protocol allows sending
multimedia data and voice calls. The speed is 20mbps. The frequency 2100 mhz.
• 4G (Fourth Generation)-This was started in the year 2013. This protocol allows sending
multimedia data and voice calls. The speed is 50mbps. The frequency range is 1800 - 2300 mhz.
• Wi-Fi: This protocol is used to connect to the internet without a cable from your PC/Laptop to
the ISP. For this you need Internet connection, wireless router and PC.
• Generally, network tools or commands are used for-
– Netowrk configuration
– Network Troubleshooting
– To identify Network status
– To identify a User
• We will discuss some tools and commands here-
• Traceroute – This command traces the route in the internet from source to destination.
Basic Networking tools
• Ping – it is a network diagnostic tool carrying ip address or domain name . It tells that we are
connected to server or not.
Basic Networking tools
• Ipconfig – It is a network troubleshooting tool. With the help of this we get basic information
about network like MAC address, ip address, subnetmask etc.
Basic Networking tools
• nslookup – it means name server lookup and it is used to get information about internet
server.
Basic Networking tools
• whois – it is a query tool with which we can get information about registered user. It is an
external command.
Basic Networking tools
• netstat – it is used to get information about network statistics.
Basic Networking tools
• Speedtest – We can use various web services to get information about network speed.
E-mail
• One of the most common service of internet is e-mail , which is used to send a message from
sender to receiver.
• Email functioning resolves around the following three components:
• Mailer – it is also called mail program, mail application or mail client. It allows us to
manage, read and compose email.
• Mail server- the function of mail server is to receive, store and deliver the mail.
• Mail boxes- Mailbox is generally a folder that contains emails and information about them.
Email sending has following steps–
– Composition  get ready the mail
– Transfer  sending of mail from computer to server.
– Reporting  informing the sender
about status of mail i.e. it is
delivered or not.
– Displaying  reading of mail by user.
– Disposition  act is decided by user after reading mail.
Secure Communications
•Secure communication is when two entities are communicating and do not want a third
party to listen in.

•Sharing information is the vital feature of the web. Every day people share lots of private
information such as banking info, credit/debit cards info, login id’s, passwords, social media
accounts, email accounts etc.

•To ensure safety of the information being transmitted over the web, encryption is the one
of the measure and highly recommended.
HTTPS
• Hyper Text Transfer Protocol Secure is a safe
protocol to send data on internet or on world
wide web.

• It is a version of HTTP where ‘s’ stands for


secure. Because of which the communication
between web-browser and server remains
encrypted.

• It is used at the places of high security like


online banking transaction .
Network Applications
• Computer network applications are network software applications that utilize the internet to
perform useful functions. They help us to transfer the data from one point to another within
the network.
• Remote Desktop accessing a computer from a far place (or different place known as
remote computer).

• Remote Login accessing a remote computer using user name and password.

• Telnet  also used for remote login where many users can connect to a server.

HTTP: The Hypertext Transfer Protocol is a protocol used namely to access data on the World
Wide Web. HTTP functions as a combination of FTP and SMTP . In this, first Client requests a
page and HTTP returns the code for a page.
FTP: (File Transfer Protocol)
It is used to transfer any type of file from one system to another system in a network.

POP3: (Post Office Protocol)


It is a mail protocol defines the rules for receiving mails from a remote server to a local mail
client. You can also download received mails on to local computer.

IMAP: (Internet Message Access Protocol)


This is same as POP3 but allows multiple applications and multiple locations.

SMTP: (Simple Mail Transfer Protocol)


POP3 and IMAP protocols are used for receiving mails from server to client where as SMTP is
used for sending mails across the internet.
VOIP: (Voice Over Internet Protocol)
VOIP enables voice communications over the internet through the compression of voice
into data packets and transmitted over network and converted to voice at the other end.

NFC: (Near Field Communication)


It is used to provide short range wireless connectivity between two electronic devices
within the distance of 4-5 centimeters.

TCP/IP: (Transmission Control Protocol/Internet Protocol)


It is a communication protocol of the internet. IP part of the TCP\IP uses the numeric
address joints network segments and TCP part of the TCP\IP provides reliable delivery of
the messages between networked computers.
Thank you
Chapter 13 More on SQL
New
syllabus
2020-21

Computer Science
Class XII ( As per CBSE Board)
Presented by: 1
Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

Topics Covered:

 Sorting in SQL- Order By


 Functions in MySQL
 Aggregate Functions in SQL
 Group by Clause
 Aggregate functions & conditions on groups-
Having Clause

2
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL Order By clause is used to sort the table data in


either Ascending order or Descending order. By default,
data is not inserted into Tables in any order unless we have
an index.
So, If we want to retrieve the data in any particular order,
we have to sort it by using MySQL Order By statement.
Syntax:-SELECT Column_Names
FROM Table_Name
ORDER BY {Column1}[ASC | DESC] {Column2}[ASC | DESC]

3
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL Order by– e.g.


Suppose we are having student table with following data.

Now we write the query – select * from student order by class;

Query result will be in ascending order of class.If we not specify asc/desc in


query then ascending clause is applied by default
4
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL Order by– e.g.


Suppose we are having student table with following data.

Now we write the query – select * from student order by class desc;

Query result will be in descending order of class


5
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL Order by – e.g.


Suppose we are having student table with following data.

Now we write query–select * from student order by class asc, marks asc;

Query result will be ascending order of class and if same class exists
then ordering will done on marks column(ascending order)
6
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL Order by– e.g.


Suppose we are having student table with following data.

Now we write query–select * from student order by class asc, marks desc;

Query result will be ascending order of class and if same class exists
then ordering will done on marks column(descending order)
7
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

Functions in SQL
Single Row Functions
Single row functions are the one who work on single row and
return one output per row.
For example, LENGTH, SUBSTR, etc.
Multiple Row Functions (Aggrigate Functions)
Multiple row functions work upon group of rows and return one
result for the complete set of rows. They are also known as
Group Functions. AGGREGATE (GROUP) FUNCTIONS Group
functions or Aggregate functions work upon groups of rows,
rather than on single row. That is why, these function are also
called multiple row functions.
For example: AVG, SUM, etc.
8
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

9
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

An aggregate function performs a calculation on multiple values


and returns a single value. For example, you can use the AVG()
aggregate function that takes multiple numbers and returns the
average value of the numbers.Following is the list of aggregate
functions supported by mysql.

Name Purpose
SUM() Returns the sum of given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given
column.
10
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL
Aggregate Functions & NULL
Consider a table Emp having following records as-
Null values are excluded while (avg)aggregate function is used
Emp
Code Name Sal
E1 Mohak NULL
E2 Anuj 4500
E3 Vijay NULL
E4 Vishal 3500
SQL Queries E5 Anil 4000
Result of query
mysql> Select Sum(Sal) from EMP; 12000
mysql> Select Min(Sal) from EMP; 3500
mysql> Select Max(Sal) from EMP; 4500
mysql> Select Count(Sal) from EMP; 3
mysql> Select Avg(Sal) from EMP; 4000
mysql> Select Count(*) from EMP; 5
11
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

The GROUP BY clause groups a set of rows/records into a


set of summary rows/records by values of columns or
expressions. It returns one row for each group.
We often use the GROUP BY clause with aggregate
functions such as SUM, AVG, MAX, MIN, and COUNT. The
aggregate function that appears in the SELECT clause
provides information about each group.
The GROUP BY clause is an optional clause of the SELECT
statement.
Syntax –
SELECT 1, c2,..., cn, aggregate_function(ci)
FROM table WHERE where_conditions GROUP BY c1 , c2,...,cn;
Here c1,c2,ci,cn are column name

12
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL group by – e.g.


Suppose we are having student table with following data.

Now we write query–select class from student group by class;

Query result will be unique occurrences of class values,just similar


to use distinct clause like(select distinct class from student).
13
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL GROUP BY with aggregate functions


The aggregate functions allow us to perform the calculation of a set of rows and return a
single value. The GROUP BY clause is often used with an aggregate function to perform
calculation and return a single value for each subgroup.
For example, if we want to know the number of student in each class, you can use the
COUNT function with the GROUP BY clause as follows:Suppose we are having student table
with following data.

Now we write query–select class,count(*) from student group by class;

Query result will be unique occurrences of class values along with counting of
students(records) of each class(sub group).
14
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL GROUP BY with aggregate functions


we are having student table with following data.

Now we write query–select class,avg(marks) from student group by class;

Query result will be unique occurrences of class values along with average
marks of each class(sub group).
15
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL GROUP BY with aggregate functions (with where and order by clause)
we are having student table with following data.

Now we write query–select class,avg(marks) from student where class<10 group


by class order by marks desc;

Query result will be unique occurrences of class values where class<10 along with
average marks of each class(sub group) and descending ofer of marks.
16
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

The HAVING clause is used in the SELECT


statement to specify filter conditions for a
group of rows or aggregates. The HAVING
clause is often used with the GROUP BY
clause to filter groups based on a specified
condition. To filter the groups returned by
GROUP BY clause, we use a HAVING clause.
WHERE is applied before GROUP BY, HAVING
is applied after (and can filter on aggregates).
17
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL GROUP BY with aggregate functions & having clause


we are having student table with following data.

Now we write query–select class,avg(marks) from student group by class


having avg(marks)<90;

Query result will be unique occurrences of class values along with average
marks of each class(sub group) and each class having average marks<90.
18
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

MySQL GROUP BY with aggregate functions & having clause


we are having student table with following data.

Now we write query–select class,avg(marks) from student group by class


having count(*)<3;

Query result will be unique occurrences of class values along with average
marks of each class(sub group) and each class having less than 3 rows.
19
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
SQL

Thank You

20
By: Nausheen Khan, PGT CS, KV CRPF Rampur, Agra Region
COMPUTER SCIENCE

Q.11) What is the role of Django in website design?


Ans:-Django is a high level python web framework, designed to help build complex web applications simply and quickly.Django
makes it easier to build better web apps quickly and with less code.
Q.12)Write the difference between GET and POST method.
Ans:-A web browser may be the client and the application on a computer that hosts the website may be the server:(i)GET:To request
data from the server
(ii)POST:To submit data to be processed to the server

Chapter 12: Interface Python with an SQL database


 Database connectivity-Database connectivity refers to connection and communication between an application and a database system.
 Mysql.connector-Library or package to connect from python to MySQL.
 Command to install connectivity package:- pip install mysql-connector-python
 Command to import connector:- import mysql.connector
 Steps for python MySQL connectivity
1 . Install Python
2. Install MySQL
3. Open Command prompt
4. Switch on internet connection
5. Type pip install mysql-connector-python and execute
6. Open python IDLE
7. import mysql.connector
 Multiple ways to retrieve data:
fetchall()-Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples)
fetch many (size)-Fetch the next set of rows of a query result, returning a sequence of sequences. It will return number of
rows that matches to the size argument.
fetchone()-Fetch the next row of a query result set, returning a single sequence or None when no more data is available
 Functions to execute SQL queries
#CREATE DATABASE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345")
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE SCHOOL")
# SHOW DATABASE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345")
mycursor=mydb.cursor()
mycursor.execute("SHOW DATABASE")
for x in mycursor:
print (x)
# CREATE TABLE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE FEES (ROLLNO INTEGER(3),NAME VARCHAR(20),AMOUNT INTEGER(10));")
# SHOW TABLES
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
#DESCRIBE TABLE
import mysql.connector

68
COMPUTER SCIENCE

mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
mycursor.execute("DESC STUDENT")
for x in mycursor:
print(x)
# SELECT QUERY
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()
#WHERE CLAUSE
import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
if conn.is_connected==False:
print("Error connecting to MYSQL DATABASE")
c=conn.cursor()
c.execute("select * from student where marks>90")
r=c.fetchall()
count=c.rowcount
print("total no of rows:",count)
for row in r:
print(row)
# DYNAMIC INSERTION
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
r=int(input("enter the rollno"))
n=input("enter name")
m=int(input("enter marks"))
mycursor.execute("INSERT INTO student(rollno,name,marks) VALUES({},'{}',{})".format(r,n,m))
mydb.commit()
print(mycursor.rowcount,"RECORD INSERTED")
# UPDATE COMMAND
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
mycursor.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
mydb.commit()
print(mycursor.rowcount,"RECORD UPDATED")
# DELETE COMMAND
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
mycursor.execute("DELETE FROM STUDENT WHERE MARKS<50")
mydb.commit()
print(mycursor.rowcount,"RECORD DELETED")
# DROP COMMAND
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
mycursor.execute("DROP TABLE STUDENT")
# ALTER COMMAND
import mysql.connector
69
COMPUTER SCIENCE

mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT ADD GRADE CHAR(3)")

Chapter -12 Data Base Connectivity (Questions and answers)

(1 mark question)
Q.1.1 What is database.
Ans. The database is a collection of organized information that can easily be used, managed, update, and they are
classified according to their organizational approach.
Q.1.2 Write command to install connector.
Ans. pip install mysql-connector-python
Q.1.3 Write command to import connector.
Ans. import mysql.connector
(2 mark question)
Q.2 write the steps of connectivity between SQL and Python
Ans. import,connect,cursor,execute

Q.3 What is result set? Explain with example.


Ans. Fetching rows or columns from result sets in Python. The fetch functions in the ibm_db API can iterate through
the result set. If your result set includes columns that contain large data (such as BLOB or CLOB data), you can
retrieve the data on a column-by-column basis to avoid large memory usage.

Q.4 Use of functions in connectivity - INSERT, UPDATE, DELETE, ROLLBACK


Ans.

Environment Description
Variables

INSERT It is an SQL statement used to create a record into a table.

UPDATE It is used update those available or already existing record(s).

DELETE It is used to delete records from the database.

ROLLBACK It works like "undo", which reverts all the changes that you have made.

Q.5 Write code for database connectivity


Ans. # importing the module
import mysql.connector
# opening a database connection
conn = mysql.connector.connect ("localhost","testprog","stud","PYDB")
# define a cursor object
mycursor = conn.cursor
# drop table if exists
70
COMPUTER SCIENCE

mycursor.execute("DROP TABLE IF EXISTS STUDENT”)


# query
sql = "CREATE TABLE STUDENT (NAME CHAR(30) NOT NULL, CLASS CHAR(5), AGE INT,
GENDER CHAR(8), MARKS INT)"
# execute query
cursor.execute(sql)
# close object
cursor.close()
# close connection
conn.close()
Q.6 Which method is used to retrieve all rows and single row?
Ans:-Fetchall(),fetchone()
Q.7 Write python-mysql connectivity to retrieve all the data of table student.
Ans:-import mysql.connector
mydb=mysql.connector.connect(user="root",host="localhost",passwd="123",database="inservice")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
for x in mycursor:
print(x)
-------------------------------------------------------------------------------------------------------------------------------------------------------------

Chapter 13: SQL commands: aggregation functions – having, group by, order by
• ORDER BY Clause: You can sort the result of a query in a specific order using ORDER BY clause. The ORDER BY clause allow
sorting of query result by one or more columns. The sorting can be done either in ascending or descending order.
Note: - If order is not specified then by default the sorting will be performed in ascending order.
e.g., Select * from emp order by deptno
Three methods of ordering data are:
1. Ordering data on single column.
2. Ordering data on multiple column.
3. Ordering data on the basis of an expression
• Aggregate Functions: These functions operate on the multiset of values of a column of a relation, and return a value
avg: average value,
min: minimum value ,
max: maximum value ,
sum: sum of values ,
count: number of values
These functions are called aggregate functions because they operate on aggregates of tuples. The result of an aggregate function is
a single value.
e.g., Select deptno, avg (sal), sum (sal) from emp group by deptno
• GROUP BY Clause: The GROUP BY clause groups the rows in the result by columns that have the same values. Grouping is
done on column name. It can also be performed using aggregate functions in which case the aggregate function produces single
value for each group.
e.g., Select deptno, avg (sal), sum (sal) from emp group by deptno
• HAVING Clause: The HAVING clause place conditions on groups in contrast to WHERE clause that place conditions on
individual rows. While WHERE condition cannot include aggregate functions, HAVING conditions can do so.
e.g., Select deptno, avg (sal), sum (sal) from emp group by deptno having deptno=10;
Select job, count (*) from emp group by job having count (*) <3;

Revision of MySQL:-

Field: Set of characters that represents specific data element.


Record: Collection of fields is called a record. A record can have fields of different data types.
File: Collection of similar types of records is called a file.
Table: Collection of rows and columns that contains useful data/information is called a table

71
COMPUTER SCIENCE

Database: Collection of logically related data along with its description is termed as database.
Relation: Relation (collection of rows and columns) on which we can perform various operations. It is also known as table.
Tuple: A row in a relation is called a tuple. It is also known as record.
Attribute: A column in a relation is called an attribute. It is also termed as field or data item.
Degree: Number of attributes in a relation is called degree of a relation.
Cardinality: Number of tuples in a relation is called cardinality of a relation.
Primary Key: Primary key is a key that can uniquely identifies the records/tuples in a relation. This key can never be
duplicated and NULL.
Foreign Key: Non key attribute of a table acting as primary key in some other table is known as Foreign Key in its
current table. This key is used to enforce referential integrity in RDBMS.
Candidate Key: Attributes of a table which can serve as a primary key are called candidate keys.
Alternate Key: All the candidate keys other than the primary key of a relation are alternate keys for
a relation.
DBA: Data Base Administrator is a person (manager) that is responsible for defining the data base schema, setting
security features in database, ensuring proper functioning of the data bases etc.
Select Operation: The select operation selects tuples from a relation which satisfy a given condition. It is denoted by
lowercase Greek Letter σ (sigma).
Project Operation: The project operation selects columns from a relation which satisfy a given condition. It is denoted
by lowercase Greek Letter π (pi). It can be thought of as picking a sub set of all available columns.
Union Operation: The union (denoted as ∪) of a collection of relations is the set of all distinct tuples in the collection. It
is a binary operation that needs two relations.
Set Difference Operation: This is denoted by - (minus) and is a binary operation. It results in a set of tuples that are in
one relation but not in another

Structured Query Language

SQL is a non procedural language that is used to create, manipulate and process the databases(relations).

1. Data Definition Language (DDL)


DDL contains commands that are used to create, modify or remove the tables, databases, indexes, views,
sequences and synonyms etc.
e.g: Create table, create view, create index, alter table, drop table etc.

2. Data Manipulation Language (DML)


DML contains commands that can be used to manipulate the data base objects and to query the databases for information retrieval.
e.g: Select, Insert, Delete, and Update.

3. Transaction Control Language (TCL)


TCL include commands to control the transactions in a data base system. The commonly used commands in TCL are COMMIT,
ROLLBACK, and SAVEPOINT.

Operators in SQL: The following are the commonly used operators in SQL
1. Arithmetic Operators +,-,*, /
2. Relational Operators =, <,>, <=,>=,<>
3. Logical Operators OR, AND, NOT

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 e.g. Number (n, d) Number (5, 2)
2) CHAR e.g. CHAR (SIZE)
3) VARCHAR / VARCHAR2 e.g. VARCHAR2 (SIZE)
4) DATE DD-MON-YYYY

Constraints: Constraints are the conditions that can be enforced on the attributes of a relation. The constraints come in play
whenever we are trying to insert, delete or update a record in a relation.
Not null ensures that we cannot leave a column as null. That is a value has to be supplied for that column.

72
COMPUTER SCIENCE

E.g.name varchar (25) not null


Unique constraint means that the values under that column are always unique.
E.g.Roll_no number (3) unique
Primary key constraint means that a column cannot have duplicate values and not even a null value.
e.g. Roll_no number (3) primary key
The main difference between unique and primary key constraint is that a column specified as unique may have null value but
primary key constraint does not allow null values in the column.
Foreign 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 declares cust_id column as a foreign key that refers to cust_id field of table master.
That means we cannot insert that value in cust_id filed whose corresponding value is not present in cust_id field of master
table. Moreover we can’t delete any row in master table, if a corresponding value of cust_id field is existing in the dependent
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 value 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

SQL COMMANDS:
1. Create Table command is used to create a table.
The syntax of this Command is: CREATE TABLE <Table_name>
(column_name 1 data_type1 [(size) column_constraints],
column_name 1 data_type1 [(size) column_constraints],
:
:
[<table_constraint> (column_names)]);
2. The ALTER Table commandis used to change the definition (structure) of existing table.
ALTER TABLE <Table_name>ADD/MODIFY <Column_defnition>; For Add or modify column
ALTER TABLE <Table_name> DROP COLUMN <Column_name>; For Deleting a column
3. The INSERT Command: The rows (tuples) are added to a table by using INSERT command.
The syntax of Insert command is:
INSERT INTO <table_name> [(<column_list>)] VALUES (<value_list>);
e.g.,
INSERT INTO EMP (empno, ename, sex, sal, deptno) VALUES (1001, ’Ravi’, ’M’, 4500.00, 10);
If the order of values matches the actual order of columns in table then it is not required to give the column_list in INSERT
command. e.g.
INSERT INTO EMP VALUES (1001, ’Ravi’, ’M’, 4500.00, 10);
4. The Update command is used to change the value in a table. The syntax of this command is:
UPDATE <table_name>
SET column_name1=newvalue1/expression [, column_name2=newvalue2/expression …] WHERE <condition>;
e.g., to increase the salary of all the employees of department No 10 by 10%, then command will
be:
UPDATE emp
SET sal=sal*1.1
WHERE Deptno=10;
5. The DELETE command removes rows from a table. This removes the entire rows, not individual field values.
The syntax of this command is
DELETE FROM <table_name>
[WHERE <condition>];
e.g., to delete the tuples from EMP that have salary less than 2000, the following command is used:
DELETE FROM emp WHERE sal<2000;
To delete all tuples from emp table:
DELETE FROM emp;

73
COMPUTER SCIENCE

6. The SELECT command is used to make queries on database. A query is a command that is given to produce certain
specified information from the database table(s). The SELECT command can be used to retrieve a subset of rows or
columns from one or more tables. The syntax of Select Command is:
SELECT <Column-list>
FROM <table_name>
[WHERE<condition>]
[GROUP BY <column_list>]
[HAVING<condition>]
[ORDER BY <column_list [ASC|DESC]>]
The select clause list the attributes desired in the result of a query. e.g.,To
display the names of all Employees in the emp relation:
select ename from emp;
To force the elimination of duplicates, insert the keyword distinct after select. Find the
number of all departments in the emp relations, and remove duplicates
select distinct deptno from emp;
An asterisk (*) in the select clause denotes “all attributes”
SELECT* FROM emp;
The select clause can contain arithmetic expressions involving the operation, +, -, *, and /, and operating
on constants or attributes of tuples.The query:
SELECTempno, ename, sal * 12 FROM emp;
would display all values same as in the emp relation, except that the value of the attribute sal is multiplied by 12.
The WHERE clause in SELECT statement specifies the criteria for selection of rows to be returned.
• Conditions based on a range (BETWEEN Operators): The Between operator defines a range of values that the column values must
fall in to make condition true. The range includes both lower value and upper value.
e.g., Find the empno of those employees whose salary between 90,000 and 100,000 (that is, 90,000 and 100,000)
SELECT empno FROM emp WHERE sal BETWEEN 90000 AND 100000;
• Conditions based on a list (IN operator): To specify a list of values, IN operator is used.
IN operator selects values that match any value in a given list of values.
For example, to display a list of members from ‘DELHI’, ‘MUMBAI’, ‘CHENNAI’ or‘BANGALORE’ cities:
SELECT * FROM members WHERE city IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’, ‘BANGALORE’);
The NOT IN operator finds rows that do not match in the list. So if you write
SELECT * FROM members WHERE city NOT IN (‘DELHI’, ‘MUMBAI’, ‘CHENNAI’, ‘BANGALORE’);
It will list members not from the cities mentioned in the list.
• Conditions based on Pattern: SQL also includes a string-matching operator, LIKE, for comparison on character string using
patterns. Patterns are described using two special wildcard characters:
Percent (%) - ‘%’ matches any substring (one, more than one or no character).
Underscore (_) - ‘_’ character matches exactly one character.
Patterns are case-sensitive.
Like keyword is used to select row containing columns that match a wildcard pattern. The keyword not like is used to select the row
that do not match the specified patterns of characters.
 Searching for NULL: The NULL value in a column is searched for in a table using IS NULL in the WHERE
clause (Relational Operators like =,<> etc can not be used with NULL).
For example, to list details of all employees whose departments contain NULL (i.e., novalue), you use the command:
SELECT empno, ename FROM emp Where Deptno IS NULL;
 The DROP Command: The DROP TABLE command is used to drop (delete) a table from database. But there is a
condition for droping a table ; it must be an empty table i.e. a table with rows in it cannot be dropped.The syntax of this
command is :
DROP TABLE <Table_name>;
e.g., DROP TABLE EMP;
 Query Based on Two table (Join):
SELECT <Column-list>
FROM <table_name1>,<table_name2>
WHERE <Join_condition>[AND condition];
SQL (Question and Answers)
(1 mark question)
Q.1 State two advantages of using Databases.

74
COMPUTER SCIENCE

Ans: Databases help in reducing Data Duplication i.e. Data Redundancy and controls Data Inconsistency.
Q2. Name some popular relational database management systems.
Ans: Oracle, MYSQL, Sqlite, MS-Access etc
Q.3 Define – Relation, Tuple, Degree, Cardinality
Ans: A Relation is logically related data organized in the form of tables.
Tuple indicates a row in a relation.
Degree indicates the number of Columns.
Cardinality indicates the number of Columns.
Q4. What is Data Dictionary?
Ans: Data Dictionary contains data about data or metadata. It represents structure or schema of a database?
Q5. Name some data types in MySQL
Ans: Char, Varchar, Int, Decimal, Date, Time etc.
(2 mark question)
Q6. Differentiate between Char and Varchar.
Ans: Char means fixed length character data and Varchar means variable length character data. E.g. For the data “Computer” char (30)
reserves constant space for 30 characters whereas Varchar (30) reserves space for only 8 characters.
Q.7 What is a Primary Key?
Ans: A Primary Key is a set of one or more attributes (columns) of a relation used to uniquely identify the records in it.
Q.8 What is a Foreign Key? What is its use?
Ans: A Foreign key is a non-key attribute of one relation whose values are derived from the primary key of some other relation. It is
used to join two / more relations and extract data from them.
Q.9 Write SQL statements to do the following
(a)Create a table Result with two columns Roll and Name with Roll as primary key
CREATE TABLE Result
(Roll INT PRIMARY KEY, Name Varchar (30))
(b)Add a column Marks to Result table
ALTER TABLE Result
ADD (Marks DECIMAL (10,2))
Insert a record with values 1, “Raj”, 75.5
INSERT INTO Result
VALUES (1,”Raj”,75.5)
(d)Show the structure of Result table
DESCRIBE Result
(e) Display the records in ascending order of name
SELECT * FROM Result
ORDER BY Name
(f)Display records having marks>70
SELECT * FROM Result
WHERE Marks > 70
(g)Update marks of,”Raj” to 80
UPDATE Result
SET Marks = 80
WHERE Name=”Raj”
Q10. What are the various Integrity Constraints?
Ans: Various Integrity Constraints are –
NOT NULL – Ensures value for the column is not left unassigned
UNIQUE – ensures that all values in a column are distinct or no two rows can have the same values for a column having UNIQUE
constraint
CHECK – Ensures that values for a particular column satisfy the specified condition
DEFAULT – Ensures that the default value is assumed if value for the column is not specified
PRIMARY KEY – Automatically applies UNIQUE and NOT NULL for uniquely identifying rows / records in a table

6 - Marks Questions

Q1. Consider the following tables GAMES and PLAYER. Write SQL commands for the statements (i) to (iv) and give outputs for
SQL queries (v) to (viii).

75
COMPUTER SCIENCE

Table: GAMES
GCode GameName Number PrizeMoney ScheduleDate
101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004

Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103
(i) To display the name of all Games with their Gcodes.
(ii) To display details of those games which are having PrizeMoney more than 7000.
(iii) To display the content of the GAMES table in ascending order of ScheduleDate.
(iv) To display sum of PrizeMoney for each of the Number of participation groupings (as
shown in column Number 2 or 4).
(v) SELECT COUNT(DISTINCT Number) FROM GAMES;
(vi) SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
(vii) SELECT SUM(PrizeMoney) FROM GAMES;
(viii) SELECT DISTINCT Gcode FROM PLAYER;
Ans: (i) SELECT GameName,Gcode FROM GAMES;
(ii) SELECT * FROM GAMES WHERE PrizeMoney>7000;
(iii) SELECT * FROM GAMES ORDER BY ScheduleDate;
(iv) SELECT SUM(PrizeMoney),Number FROM GAMES GROUP BY Number;
(v) 2
(vi) 19-Mar-2004 12-Dec-2003
(vii) 59000
(viii) 101
103
108
Q2. Consider the following tables FACULTY and COURSES. Write SQL commands for the statements (i) to (v) and give outputs for
SQL queries (vi) to (vii).
FACULTY

F_ID Fname Lname Hire_date Salary


102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-5-2001 14000
105 Rashmi Malhotra 11-9-2004 11000
106 Sulekha Srivastava 5-6-2006 10000
COURSES

C_ID F_ID Cname Fees


C21 102 Grid Computing 40000
C22 106 System Design 16000
C23 104 Computer Security 8000
C24 106 Human Biology 15000
C25 102 Computer Network 20000
C26 105 Visual Basic 6000
i) To display details of those Faculties whose salary is greater than 12000.
ii) To display the details of courses whose fees is in the range of 15000 to 50000 (both values included).

76
COMPUTER SCIENCE

iii) To increase the fees of all courses by 500 of “System Design” Course.
iv) To display details of those courses which are taught by ‘Sulekha’ in descending order of courses.
v) Select COUNT (DISTINCT F_ID) from COURSES;
vi) Select Fname, Cname from FACULTY, COURSES where COURSES.F_ID =FACULTY.F_ID;
Ans.: (i) Select * from faculty where salary > 12000;
(ii) Select * from Courses.where fees between 15000 and 50000;
(iii) Update courses set fees = fees + 500 where Cname = “System Design”;
(iv) Select * from faculty fac, courses cour where fac.f_id = cour.f_id and fac.fname = 'Sulekha'order by
cname desc;
(v) 4
(vi)
Fname Cname
Amit Grid Computing
Rakshit Computer Security
Rashmi Visual Basic
Sulekha Human Biology

2- Marks Questions
Define the following terms with example:
(i) DDL (ii) DML (iii) Primary Key (iv) Candidate Key
(v) Alternate Key (vi) Foreign Key (vii) Cardinality of relation (viii) Degree of relation
(ix) Relation (x) Attribute (xi) Tuple (xii) Selection
(xiii) Projection

UNIT 4 SOCIETY, LAW AND ETHICS (SLE-2)


CHAPTER 14: SOCIETY, LAW AND ETHICS
Introduction
Information forms the intellectual capital for a person. Some ethical issues involved with the usage and availability of information
are:
i. Intellectual property rights
ii. Plagiarism
iii. Digital property rights

Intellectual property rights


These 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 to decide the price for doing (exchanging/sharing/distributing) so.
The intellectual property rights must be protected because:
i. Ensures new ideas and technologies are widely distributes
ii. Encourages individuals and business to create new software and improve the existing application.
iii. Promotes investment in the national economy
Plagiarism
It is stealing someone else’s intellectual work such as 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.
Digital right management
It is used to protect your software from being scraped for source code using decompilers etc.
 Digital property (digital assets)
It refers to any information about you or created by you that exists in digital form, either online or on an electronic storage device.
 Measures to protect digital property
a. Anti-temper solution
b. Legal clauses
c. Limit the sharing of software code
77
COMPUTER SCIENCE

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

 Creative commons: Creative Commons (CC) is an internationally active non-profit organization to provide free licenses for
creators to use it when making their work available to the public in advance under certain conditions. CC licenses allow the
creator of the work to select how they want others to use the work. When a creator releases their work under a CC license,
members of the public know what they can and can’t do with the work.
 General Public License: General Public License (GNU GPL), is the most commonly used free software license, written by
Richard Stallman in 1989 of Free Software Foundation for GNU Project. This license allows software to be freely used modified,
and redistributed by anyone. WordPress is also an example of software released under the GPL license, that’s why it can be used,
modified, and extended by anyone.
 Apache License: The Apache License is a free and open source software (FOSS) licensing agreement from the Apache Software
Foundation (ASF). The main features are copy, modify and distribute the covered software in source and/or binary forms, all
copies, modified or unmodified, are accompanied by a copy of the license.

Open Source
Open source means any program whose source code is made available publically for use or modification as users or other
developers see fit. Open source software is usually made freely available.
Eg: Open source software: python, java, linux, mongodb etc
Open data
Open data is data which can be accessed, used and shared by anyone to bring about social, economic and environmental
benefits. Open data becomes usable when made available in a common, machine-readable format.
 Open source terminologies and definitions:
a. Free Software: They are freely accessible and can be freely used, changed, improved, copied and distributed by all and
payments are not needed for free Software.
b. Open Source Software: Software whose source code is available to the user and it can be modified and redistributed without
any limitation .OSS may come free of cost but nominal charges have to be paid for support of Software and development of
Software.
c. Proprietary Software: Proprietary Software is neither open nor freely available, normally the source code of the Proprietary
Software is not available but further distribution and modification is possible by special permission by the developer.
d. Freeware: Freeware are the software freely available, which permit redistribution but not modification (their source code is
not available). Freeware is distributed in Binary Form (ready to run) without any licensing fees.
e. Shareware: Software for which license fee is payable after some time limit, its source code is not available and modification
to the software are not allowed.
 Privacy
It is the protection of personal information given online.
Online fraud
Fraud committed using the internet is called online fraud. Online fraud occurs in many forms such as non-delivered goods,
non-existent goods, stealing information, fraudulent payments.
 Preventive measures to stop online fraud
a. Strong security mechanism by the e-commerce site and payment gateways to prevent stealing of crucial information.
b. Official guidelines and safeguards on the selling of users’s data to third parties.
c. A monitoring official body that ensures the delivery of goods/services as promised.
Cybercrime
Any criminal offense that is facilitated by the use of electronic device, computer or internet is called cybercrime. Eg: Information
Theft, scams, illegal downloads etc.
 Phishing
78
CYBER SAFETY
CHAPTER-15

XI -Computer Science with python

Made by:
Sumit Kumar Sahu
PGT Computer Science
KV Babina Cantt,
Jhansi
PRIVACY

 Privacy means the protection of personal information


given online while carrying out some online activity or
transaction.
 It is related o a company’s policies on the use of user
data.
 An e-commerce company must clearly state: how it
intends to use the customer’s data collected this way
(such as user’s location, user's buying history, user's
preferences etc.)
 An important factor of privacy is the user consent-
whether the consumer is given a choice to decide what
information can and can not be used for.
HOW TO SAFEGUARD USER PRIVACY

To ensure that the user privacy is not compromised ,following


measures must be taken:
 The merchant or the seller must clearly state that how the user
data will be used, in the terms and conditions of its site
application.
 The merchant or seller must ensure that the user has gone
through the terms and conditions given on its sites or application
prior to making any transaction.
 The merchant must assure the user about data safety by
implementing proper data safety measures such as https
protocol and other security mechanism so that the user’s data is
safe from hackers too.
 The user must go through the terms and conditions of the
seller/merchant site before providing any sensitive information
and make sure that the site is safe site by checking https
protocols and padlock etc.
ONLINE FRAUDS

Frauds committed using the internet is called online fraud.


Online frauds may occur in many forms such as:
 Non-delivered goods
 Non-existent companies
 Stealing information
 Fraudulent payment etc.

The first two types of frauds can be countered by setting


up official bodies ensuring the validity of e-commerce
companies and promised delivery of goods.
The last two types of frauds are more frightening it includes
credit card frauds and identity theft.
MEASURES TO STOP ONLINE FRAUDS

 A monitoring official body that ensure the sanctity of E-


commerce company and delivery of goods/services as
promised.
 Strong security mechanism by the e-commerce site and
payment gateways to prevent stealing of crucial
information(such as your personal information or bank
details etc.)
 Official guidelines and safeguards on the selling of user’s
data to the third parties.
CYBERCRIME

Any criminal offence that is facilitated by , or involves the use of,


electronic communication or information system, including any
electronic device, computer or the internet is referred to as
cybercrime.

The term cybercrime is a general term that covers crimes like


phishing , credit card frauds, illegal downloading, child
pornography, cyber bullying, cyber stalking, cyber terrorism,
creation and distribution of viruses, spams and so on.
PHISHING

It is the criminally fraudulent process of attempting to acquire sensitive


information such as username, passwords, credit card information ,
account data etc. over the internet , by means of deception.
In phishing , an imposter uses an authentic looking email or website to
trick recipients into giving out sensitive personal information.

How to prevent phishing


•Always check the spelling of the URLs before click
•Watch out for URL redirects, that sent to a different website with
identical design
•If receive an email from that seems suspicious,
contact that source with a new email, rather than just hitting
reply
•Don't post personal data, like your birthday, vacation plans, or
your address or phone number, publicly on social media
ILLEGAL DOWNLOADS

 It refers to obtaining files for which you don’t have the right to
use or download from the internet. It is downloading a paid
digital item , without making any payment and using an illegal
way to download it.
 For example you are downloading a movie which is not
available for free download , this is illegal download ,
downloading a copy of the licensed software bypassing the
legal measures is also illegal download
 A product is protected by copyright law can not be
downloaded , copied, reproduced, or resold without their
permission.
CHILD PORNOGRAPHY

 Child pornography is defined as any visual or written


representation (including images , movies and/or texts) that
depict or advocate sexual activity (including sexual
molestation or exploitation) of anyone under the age of 18.
 The law also includes some child nudity , simulated sex
involving children and any material that is computer-
decorated to look like child porn.

 Information technology act, 2000 & Indian penal code, 1860


provides protection from child pornography.
 According to the new information Technology Bill , Section 67
has been amended that not only creating and transmitting
obscene material in electronic form but also to browse such
sites is an offence.
IDENTITY THEFT

 Identity theft occurs when someone uses our identity or


personal information such as our name , our license , or our
unique id number without our permission to commit a crime
or a fraud.
 It is the theft of personal information in order to commit fraud.

Online identity theft is carried out through a mix of actions such


as:
 Through phishing via your email account.
 Stealing your online purchase information where you give out
sensitive information such as your credit card number or your
Aadhar card number.
IDENTITY THEFT
Once someone’s personal information is obtained , a thief can commit any
of the following crimes.
 Credit card fraud: thieves may obtain a new credit card getting
blocked your original card and asking for a duplicate one.
 Change your personal information: After obtaining your sensitive
information thieves may use it to change crucial information of you such
as the phone number. Now you won’t be getting any SMS updates
even after your bank accounts are being robbed.
 Phone or utilities fraud: using your information, the thieves may get new
cell phones or get some utilities that require such information.
 Bank/finance fraud: thieves may take out loans for mortgages or a car
in your name.
 Other fraud: Thieves may use your Adhaar number to get variety of
services or even obtain a job in your name or rob you off any financial
benefit that is on your name.
PROTECTION AGAINST IDENTITY
THEFT

(i) Protect Personal information


(ii) Use unique ids to protect your devices and
account.
(iii)Use Biometric protection.
DIGITAL FOOOTPRINT

Digital footprints are the records And traces individuals


leave behind as the use the Internet.
Our interactions on social media sites we visit, online
purchases ,locations visited through Facebook check-ins
etc. all make up our digital footprints.
There are two kinds of digital footprints we leave behind.
Active digital footprints which includes data that we
intentionally submit online. This would include emails we
write , or responses or posts we make on different websites
or mobile apps etc.
The digital data trail that we leave online unintentionally is
called passive digital footprints. This includes the data
generated when we visit a website , use a mobile app ,
browse internet etc.
DIGITAL SOCIETY AND NETIZEN

Net etiquettes:
We follow certain etiquettes during our social interactions. Similarly ,
we need to exhibit proper manners and etiquettes while being
online.
1.Be Ethical
2. Be respectful
3. Be responsible
Social media etiquettes:
1.Be secure
2. Be reliable
Communication etiquettes:
1. Be precise
2. Be polite
3. Be credible.

You might also like