CS Class 12 Complete Study Material
CS Class 12 Complete Study Material
Advantage:
File- storage on hard disk
Input test cases could be in a file, use them multiple times
Output could be stored in a file, read the file to analyse the output
There are two types of files that can be handled in python
File_object = open(“File_Name","Access_Mode")
h=open("d:\\B.txt“, “w”)
FILE OPENING MODES
Read Only (‘r’) : Open text file for reading. The file pointer is positioned at the beginning of the file. If the file
does not exist, raises the I/O error. This is also the default mode in which a file is opened.
Read and Write (‘r+’): Open the file for reading and writing. The file pointer is positioned at the beginning of
the file. Raises I/O error if the file does not exist.
Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated and over-written. The
file pointer is positioned at the beginning of the file. Creates the file if the file does not exist.
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-
written. The file pointer is positioned at the beginning of the file.
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The file pointer is positioned
at the end of the file. The data being written will be inserted at the end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The file
pointer is positioned at the end of the file. The data being written will be inserted at the end, after the existing
data.
Closing a File
f=open("d:\\a.txt")
.
.
f.close()
READING FROM A TEXT FILE
read()
The read() method returns the specified number of bytes from the file. If no
argument given then it returns the entire file’s contents
File: a.txt
This is a text file
File Handling is easy
It is going to be fun
f=open("d:\\a.txt")
s=f.read()
print(s)
f=open("d:\\a.txt")
s=f.read(6)
print(s)
f=open("d:\\a.txt")
s=f.read(19)
print(s)
f=open("d:\\a.txt")
s=f.read(23)
print(s)
readline()
Python file method readline()reads one entire line from the file. A trailing newline character is kept in
the string.
f=open("d:\\a.txt")
s=f.readline()
print(s)
s=f.readline()
print(s)
FOR OUTPUT BASED QUESTIONS
f=open("d:\\a.txt")
s=" "
while s:
s=f.readline()
print(s, end='')
f=open("d:\\a.txt")
s=" "
while s:
s=f.readline()
print(s)
readlines()
The readlines() method returns a list containing each line in the file as a list item.
f=open("d:\\a.txt")
s=f.readlines()
print(s)
WAP Display count of number of lines in a file
f=open("d:\\a.txt")
s=f.readlines()
x=len(s)
print(x)
FOR OUTPUT BASED QUESTIONS
file=open("d:\\a.txt")
for l in file:
print(l)
For a question in which you have to code, this is the easiest approach
Display lines that start with alphabet “a” or “A”
a.txt EXPLANATION
This is a text file s=“This is a text file\nApples are healthy\nFile
Apples are healthy handling is easy\nAnger is bad for health\n”]
File Handling is easy
Anger is bad for health t=[“This is a text file”, “Apples are healthy”, “File
handling is easy”, “Anger is bad for health”]
SOLUTION-3
file=open("d:\\a.txt") FIRST RUN OF THE FOR LOOP
s=file.read() line=“This is a text file\n”
t=s.split('\n') line[0]=‘T’
SECOND RUN OF THE FOR LOOP
for line in t: line=“Apples are healthy”
if line[0]=='a' or line[0]=='A': Line[0]=‘A’
print(line) ……….so on
file.close()
write() : writelines() :
File_object.write(str1)
File_object.writelines(L)
Inserts the string str1 in the text file.
Used to insert multiple strings at a single time.
For a list of string elements, each string is inserted in the
text file.
Using write()
file=open("data.txt", "w")
file=open("data.txt", "w")
file=open("data.txt", "w")
name=["Eat healthy\n","Stay
hydrated\n","have adequate sleep\n"]
file.writelines(name)
file.close()
QUICK RECAP
f=open("data.txt","r")
s=f.read()
print(s)
f.close()
2. Write a Python program to read first n lines of a file.
f=open("data.txt","r")
n=int(input("How many lines do you want to read: "))
s=f.readlines()
for i in range(n):
print(s[i])
f.close()
3. Write a Python program to display last n lines of a file.
f=open("data.txt","r")
n=int(input("How many lines do you want from end of file: "))
s=f.readlines()
count=len(s)
beg=count-n
s=[line 1, line 2, line 3, line 4, line 5]
last=count
for i in range(beg,last): s[0] s[4]
print(s[i]) Or
s[len(s)-1]
f.close()
Write a Python function countwords() to count number of words in a text file
def countwords():
f=open("content.txt","r")
count=0
s=f.read()
wordlist=s.split()
countwords()
5. Write a Python function copy_alternate() to write alternate
lines from a.txt to b.txt
def copy_alternate():
f=open("a.txt","r")
g=open("b.txt","w")
count=0
for line in f:
if count%2==0:
g.write(line)
count=count+1
f.close()
g.close()
File Positions
The tell() method tells you the current position within the file; in
other words, the next read or write will occur at that many
bytes from the beginning of the file.
\n in Windows stored as a pair of
characters CR (Carriage return) and
LF (Line Feed)
File Positions
f.seek(2) ----place the file pointer at 2 bytes from the beginning of the file
f.seek(0) ----place the file pointer at the beginning of the file
fo=open("d:\\info.txt")
s1 = fo.read(9)
print( "First Read : ", s1)
fo.seek(0);
s2= fo.read(9)
print ("First Read : ", s2)
fo.close()
fo=open("d:\\info.txt")
s1 = fo.read(9)
print( "First Read : ", s1)
fo.seek(0);
s2= fo.read(9)
print (“Second Read : ", s2)
fo.close()
File Positions
LEARN (you must
know about reference
position 0,1 and 2)
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved.
The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of
the file would be taken as the reference position.
Python 3 does not support movement of file pointer from current or end position.
f.seekg(2) same thing as f.seekg(2,0)
0 as second argument specifies the reference position as beginning of the file
FILE MODES AND OPENING POSITION OF FILE POINTER
f=open("d:\\info.txt","r+")
print("r+ mode: ",f.tell())
f.close()
f=open("d:\\info.txt","a")
print("a mode: ",f.tell())
f.close()
f=open("d:\\info.txt","a+")
print("a+ mode: ",f.tell())
f.close()
f=open("d:\\info.txt","w")
print("w mode: ",f.tell())
f.close()
f=open("d:\\info.txt","w+")
print("w+ mode: ",f.tell())
f.close()
f=open("d:\\info.txt","r")
print("r mode: ",f.tell()) On executing the Same piece
f.close()
of code again, the output is
f=open("d:\\info.txt","r+")
print("r+ mode: ",f.tell())
f.close()
f=open("d:\\info.txt","a")
print("a mode: ",f.tell())
f.close()
f=open("d:\\info.txt","a+") WHY ??
print("a+ mode: ",f.tell())
f.close()
f=open("d:\\info.txt","w")
print("w mode: ",f.tell())
f.close()
f=open("d:\\info.txt","w+")
print("w+ mode: ",f.tell())
f.close()
Write a Python program to append text to a file and display the text.
f=open("data.txt","a") f=open("data.txt","a+")
n=int(input("How many lines do you want to n=int(input("How many lines do you want to
append: ")) append: "))
for i in range(n):
for i in range(n): s=input("Enter line ")
s=input("Enter line ") f.write(s+"\n")
f.write(s+"\n")
f.flush()
f.close()
f.seek(0)
f=open("data.txt","r") data=f.read()
data=f.read() print("\nFILE CONTENTS\n")
print("\nFILE CONTENTS\n") print(data)
print(data) f.close()
f.close()
What is the output in the file “poem.txt”?
What is the output in the file “poem.txt”?
What is the output?
f=open("d:\\poem.txt","r")
s1=f.readline()
s2=f.read(4)
s3=f.readline()
f.seek(5)
s4=f.readline()
print(s1, end="")
print(s2, end="")
print(s3, end="")
print(s4, end="")
f.close()
flush method and buffering
E:\project\a.txt
A relative path is a path that describes the location of a file or folder in relative to the current
working directory.
The symbol . (one dot) can be used for current directory and .. (two dots) denotes the parent
directory.
E:
stdin , stdout , and stderr are predefined file objects that correspond to Python's standard
input, output, and error streams.
These are file objects which are connected to standard I/O devices.
We use high level functions like input(), print() etc and hence do not use these standard stream objects.
import sys
sys.stdout.write("Hello")
sys.stdout.write("Good Morning")
sys.stdout.write("Hope you are doing fine!!\n")
sys.stdout.write("Using time effectively")
import sys
sys.stdout.write("Enter string: ")
a=sys.stdin.readline()
print("Line read: ",a)
A comma-separated values file is a 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.
Advantages:
CSV file stores data as text and can handle large amount of data.
Data is stored in a tabular form (rows and columns).
It is easy to export from data base and spread sheet software like Excel. It is easy to
import data from a csv file to a data base and spread sheet software.
CSV files are supported by nearly all data upload interfaces. If you are planning to
move your data between platforms, export and import it from one interface to another,
you might be better off with the CSV file format.
In CSV file, text data is in a format where each line is considered as a row/record with many fields.
Fields are separated by a delimiter like , or / or – etc.
The first line generally contains the header of the fields
DATA IN EXCEL FILE or DATA IN A CSV FILE
DATABASE TABLE
Writing in CSV files
write_data() write_data()
Reading CSV files
f.close()
def display():
f=open("country.csv","r")
rec=csv.reader(f)
print("Names of countries with more than 6 characters in
capital name")
next(rec)
for i in rec:
if len(i[1])>6:
print(i[0])
f.close()
write_data()
display()
A CSV file “product.csv” contains
<product id>,<product name>,<cost>
f.close()
Continued
#approach-2
def display_2():
f=open("product.csv","r")
rec=csv.reader(f)
print("Details of products with maximum cost")
next(rec)
max=0
for i in rec:
if int(i[2])>max:
max=int(i[2])
f.seek(0)
next(rec)
for i in rec:
if int(i[2])==max:
print(i)
f.close()
write_data()
display_1()
display_2()
A CSV file “product.csv” contains
<product id>,<product name>,<cost>
Write a function to append record of type product to the csv file
def append_data():
f=open("product.csv","a")
w=csv.writer(f,delimiter=',',lineterminator='\n')
id=input("Enter product id: ")
nm=input("Enter product name: ")
cost=float(input("Enter cost of product: "))
data=[id,nm,cost]
w.writerow(data)
f.close()
A CSV file “product.csv” contains
<product id>,<product name>,<cost>
Write a function to remove records on the basis of product name from the
csv file
def remove_data():
f=open("product.csv","r")
g=open("temp.csv","w")
w=csv.writer(g,delimiter=',',lineterminator='\n')
pn=input("Enter product name to be deleted for: ")
rec=csv.reader(f)
header=next(rec)
w.writerow(header)
for i in rec:
if i[1]!=pn:
w.writerow(i)
f.close()
g.close()
os.remove("product.csv")
os.rename("temp.csv","product.csv")
A CSV file “product.csv” contains
<product id>,<product name>,<cost>
Write a function to update cost of product on the basis of product name
def update_data():
f=open("product.csv","r")
g=open("temp.csv","w")
w=csv.writer(g,delimiter=',',lineterminator='\n')
pn=input("Enter product name to be updated: ")
rec=csv.reader(f)
header=next(rec)
w.writerow(header)
for i in rec:
if i[1]==pn:
i[2]=float(input("Enter updated cost: "))
w.writerow(i)
f.close()
g.close()
os.remove("product.csv")
os.rename("temp.csv","product.csv")
import csv MENU DRIVEN PROGRAM def display_data():
import os f=open("product.csv","r")
rec=csv.reader(f)
def write_data(): print("Data in the File")
f=open("product.csv","w") for i in rec:
w=csv.writer(f,delimiter=',',lineterminator='\n') print(i)
w.writerow(["Product Id", "Product name","Cost"])
w.writerow(["P1","TV", 20000] ) def search_data():
w.writerow(["P2","LAPTOP", 50000] ) f=open("product.csv","r")
w.writerow(["P3","WASHING MACHINE", 50000] ) rec=csv.reader(f)
flag=0
f.close() pn=input("Enter product name to be searched for: ")
for i in rec:
if i[1]==pn:
def append_data(): print(i)
f=open("product.csv","a") flag=1
w=csv.writer(f,delimiter=',',lineterminator='\n')
id=input("Enter product id: ") if flag==0:
nm=input("Enter product name: ") print("Unsuccessful search")
cost=float(input("Enter cost of product: ")) f.close()
data=[id,nm,cost]
w.writerow(data)
f.close()
MENU DRIVEN PROGRAM (Continued)
write_data()
while(True):
print("Enter 1 to append, 2 to read, 3 to search, 4 to delete, 5 to update")
choice=int(input("Enter choice: "))
if choice==1:
append_data()
elif choice==2:
display_data()
elif choice==3:
search_data()
elif choice==4:
remove_data()
elif choice==5:
update_data()
else:
break
FOR FILE
• Binary files are not human readable. When opened using any
text editor, the data is unrecognizable.
f.close()
BINARY FILES
Using pickle module
Python pickle module is used for serializing and de-serializing a Python
object structure. Any object in Python can be pickled so that it can be
saved on disk. What pickle does is that it “serializes” the object first
before writing it to file. Pickling is a way to convert a python
object (list, dict, etc.) into a character or byte stream. The idea
is that this character stream contains all the information necessary to
reconstruct the object in another python script.
• ‘rb’ – reading a binary file. Error message if file does not exist.
• ‘wb’- writing a binary file. New file created if the file does not exist.
• ‘ab’- for appending or adding data to the binary file. File pointer placed at the end of
the file if the file exists, otherwise a new file is created.
• ‘rb+’-opens binary file for reading as well as writing. File pointer at beginning of file
• ‘wb+’-opens binary file for reading as well as writing. If file exists data is truncated. File
pointer at beginning of file
• ‘ab+’- opens binary file for reading as well as writing. File pointer placed at the end fo
the file if the file exists, otherwise a new file is created.
WRITING INTO A BINARY FILE
import pickle
d = {1:"Avinash",2:"charu",3:"Devika"}
f= open("file_bin","wb")
pickle.dump(d, f)
f.close()
READING FROM A BINARY FILE
import pickle
pickle_f = open("file_bin","rb")
e = pickle.load(pickle_f)
print(e)
pickle_f.close()
import pickle
f=open("student","wb")
n=int(input("How many students"))
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f)
f.close()
f=open("student","rb")
t_rec=pickle.load(f)
print(t_rec)
import pickle
f=open("student","wb")
n=int(input("How many students"))
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f) How to read multiple records from a binary
file??
f.close()
An exception is raised when you reach the EOF
and still try to read
f=open("student","rb")
while True:
t_rec=pickle.load(f)
print(t_rec)
import pickle
f=open("student","wb")
n=int(input("How many students"))
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f)
Use any of the two approaches to read
f.close()
multiple records from a binary file
f=open("student","rb") f=open("student","rb")
while True: OR try:
try: while True:
t_rec=pickle.load(f) t_rec=pickle.load(f)
print(t_rec) print(t_rec)
except EOFError: except EOFError:
print('EOF!!!') print('EOF!!!')
f.close() f.close()
break
import pickle
f=open("student","wb")
n=int(input("How many students")) Single record in binary file
t=[]
for i in range(n):
s_rec=eval(input("Enter name, class, percentage"))
t.append(s_rec)
pickle.dump(t, f)
f.close()
f=open("student","rb")
t_rec=pickle.load(f)
print(t_rec)
f.close()
WRITING INTO A BINARY FILE
2 Approaches
f.close() pickle.dump(t, f)
READING FROM A BINARY FILE
2 Approaches
When EOFError
exception is raised, close File is closed
the file and break out of
the loop
f=open("student","rb")
f=open("student","rb") t_rec=pickle.load(f)
while True: # check for end of file print(t_rec)
try: f.close()
t_rec=pickle.load(f)
print(t_rec)
except EOFError:
print('EOF!!!')
f.close()
break
SEARCHING IN A BINARY FILE (done in previous class) (data stored as multiple records)
[“ravi”, 34, “Manager”] [“aarush”, 45, “Sr. Manager”] [“usha”,56,”clerk”]
import pickle
def search_agerange():
def write_rec(): f=open("employee","rb")
f=open("employee","wb") print("SEARCHING CONTENTS OF EMPLOYEE FILE ON BASIS OF AGE")
n=int(input("How many employees")) found=0
for i in range(n): while True:
e_rec=eval(input("Enter name, age, try:
designation")) t_rec=pickle.load(f)
pickle.dump(e_rec, f) if t_rec[1]>=20 and t_rec[1]<=30:
f.close() print(t_rec)
found+=1
def read_rec(): except EOFError:
f=open("employee","rb") f.close()
print("DISPLAYING CONTENTS OF EMPLOYEE FILE") break
while True: if found==0:
try: print("Record not found")
t_rec=pickle.load(f)
print(t_rec)
except EOFError: write_rec()
print('EOF!!!') read_rec()
f.close() search_agerange()
break
SEARCHING IN A BINARY FILE (done in previous class)
(data stored as single record) CAN BE LEFT FOR THE MID SEM
import pickle
def write_rec():
f=open("employee","wb") [ ["Murli",25,"Clerk"], ["Manohar",45,"Manager"] ]
n=int(input("How many employees"))
data=[]
for i in range(n): def search_agerange():
e_rec=eval(input("Enter name, age, designation")) f=open("employee","rb")
data.append(e_rec) print("SEARCHING CONTENTS OF EMPLOYEE FILE ON BASIS OF AG
pickle.dump(data,f) found=0
f.close()
t_rec=pickle.load(f)
def read_rec(): for i in t_rec:
f=open("employee","rb") if i[1]>=20 and i[1]<=30:
print("DISPLAYING CONTENTS OF EMPLOYEE FILE") print(i)
t_rec=pickle.load(f)
for i in t_rec: found=1
print(i) if found==0:
print("Not found")
write_rec()
read_rec()
Search_agerange()
APPENDING IN A BINARY FILE
(data stored as multiple records)
def append():
f=open("employee","ab")
x=eval(input("Enter name, age, designation to be appended: "))
pickle.dump(x, f)
f.close()
New Record
[“priya”, 54, “Directo”]
f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
UPDATING DATA IN A BINARY FILE
(data stored as single record)
CAN BE LEFT FOR THE MID SEM
def update_rec():
f=open("employee","rb")
g=open("temp","wb")
o_rec=pickle.load(f) Read entire data
n_rec=[]
else:
pickle.dump(o_rec,g)
except EOFError:
break
f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
QUESTIONS (Theory)
Write a function that takes the name of a file and writes n records in a binary file in the
following format
{“india”:”delhi”}, (“Indonesia”:”Jakarta”}
import pickle
def f(nm):
Write a function that transfers all records with company name “Dell” from binary file “laptop” to another
binary file “specific”
Records are stored one after the other in the following format def copy_rec():
[Model Id, company name, price] f=open(" _____","rb")
g=open("_____","wb")
found=0
pickle.dump(_____)
except EOFError:
break
____
______
Data Structure
What is DATA STRUCTURE?
Simple Words: Organising data in memory and defining the operations for the stored data
A data structure is a specialized format for organizing, processing, retrieving and storing data.
There are four built-in data structures in Python - list, tuple, dictionary and set.
List
STACKS
5
4
3 Underline
2 Bold
1 Change Colour
0 Type Text
We will use a list to implement stack
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 88 1 1 100
0 0 67 0 67 0 67 0 67
def push_stack(element):
a.append(element) CODE FOR IMPLEMENTING A STACK USING A LIST
def pop_stack():
if len(a)<=0:
print("Underflow: stack is empty")
else:
x=a.pop()
print("Element popped out of the stack ",x)
a=[]
ch="y"
def display_stack(): while(ch=="y"):
for i in range(len(a)-1,-1,-1): print()
print(a[i]) choice=int(input("Enter 1 to push element, 2 to pop element, 3 to display stack elements"))
if choice==1:
elem=input("Enter element to be pushed in: ")
push_stack(elem)
elif choice==2:
pop_stack()
elif choice==3:
display_stack()
else:
print("Invalid option")
A database may be defined as a collection of interrelated data stored together to serve multiple
applications. It is organized in a manner that it can be easily accessed, managed and updated.
DBMS
A database management system (DBMS) is system software for creating and managing databases. A
DBMS makes it possible for end users to create, read, update and delete data in a database.
ADVANTAGES OF USING A DATABASE
RDBMS: A Relational database management system (RDBMS) is a database management system (DBMS) that is
based on the relational data model. In this, data as well as relationship among the data is stored in the form of
tables. Examples of RDBMS are Microsoft Access, OpenOffice.org Base, SQL Server, Oracle etc.
Multiple tables in a database in relational data model, the data in the tables can be related.
Relational data model was propounded by EF Codd.
Relation
A relation is a table, data is arranged in the form of rows and columns. A relation has the
following properties:
• In any column of the table, all values of the same type whereas values in different columns
may belong to different data type
• For each row, every column must have one value.
• All rows of a relation are distinct. A relation does not contain two rows which are identical in
every column.
• There is no order maintained for rows inside a relation. We cannot retrieve data by saying
data of row number 5.
• The columns of a relation are assigned distinct names and the ordering of these columns is
immaterial.
PRIMARY KEY
A set of one or more attributes that can uniquely identify tuples within the relation.
RELATION: Employee
PRIMARY KEY
CANDIDATE KEYS
All attribute combinations within a relation that can serve as primary key are candidate keys
RELATION: Employee
CANDIDATE KEYS
ALTERNATE KEY
RELATION: Employee
ALTERNATE KEYS
Used to set relations
between tables
RELATION: Student
FOREIGN KEY
PRIMARY KEY
RELATION: Course
Data Abstraction in DBMS
Database systems are made-up of complex data structures. To ease the user interaction with database, the
developers hide internal irrelevant details from users. This process of hiding irrelevant details from user is
called data abstraction.
We have three levels of abstraction:
Physical level: This is the lowest level of data abstraction. It describes how data is actually stored in database. You
can get the complex data structure details at this level.
Logical level: This is the middle level of 3-level data abstraction architecture. It describes what data is stored in
database.
View level: Highest level of data abstraction. This level describes the user interaction with database system.
Example: Let’s say we are storing customer information in a customer table. At physical level these records can be
described as blocks of storage (bytes, gigabytes, terabytes etc.) in memory. These details are often hidden from
the programmers.
At the logical level these records can be described as fields and attributes along with their data types, their
relationship among each other can be logically implemented. The programmers generally work at this level
because they are aware of such things about database systems.
At view level, user just interact with system with the help of GUI and enter the details at the screen, they are not
aware of how the data is stored and what data is stored; such details are hidden from them.
TYPES OF SQL COMMANDS
Ordering of the columns is not important. You can
specify any order.
The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by
joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the
table. You should use the WHERE clause to filter the records and fetching only the necessary records.
The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE,
DELETE statement, etc.
ORDER BY clause
Student ORDER BY clause
ORDER BY clause
Student
AGGREGATE FUNCTIONS
In database management an aggregate function is a function where the values of multiple rows are
grouped together as input on certain criteria to form a single value of more significant meaning.
Table: Employee AGGREGATE FUNCTIONS
Important Points:
•GROUP BY clause is used with the SELECT statement.
•In the query, GROUP BY clause is placed after the WHERE clause.
•In the query, GROUP BY clause is placed before ORDER BY clause if used any.
GROUP BY clause
Table: Customers
GROUP BY clause
Table: Customers
GROUP BY clause
Table: Emp
HAVING clause
HAVING clause
Age, sum(salary)
Table: Customers
Age sum(salary)
25 8000
Table: Emp
No Name Age Department Date_of_join Salary Gender
Display the Name and Type of those items for which Discount has not been decided or declared.
Display the details of items whose name does not start with letter “A”
Display the Furniture Type and the number of items of that type
Display the Furniture Type and the average price of items of that type
Display the details of furniture whose stock date is in the year 2012
Select * from furniture where dateofstock>= “01/01/2012” and dateofstock<=“31/12/2012”;
UPDATE command (DML)
DELETE command (DML)
ALTER TABLE command (DDL)
DROP TABLE command (DDL)
VIEWS IN SQL
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in
a real table in the database. We can create a view by selecting fields from one or more
tables present in the database. A View can either have all the rows of a table or
specific rows based on certain condition.
Show tables ;
ADVANTAGES OF NETWORKS
•File sharing – you can easily share data between different users, or access it remotely if you keep
it on other connected devices.
•Resource sharing – using network-connected peripheral devices like printers, scanners and
copiers, or sharing software between multiple users, saves money.
•Improved Communication at low cost- people can use emails and instant messengers over the
network to communicate. Voice calling, video calling over internet has brought the world closer.
ADVANTAGES OF NETWORKS (Continued)
EVOLUTION OF INTERNET
The network did not evolve in a single day; rather, it took decades to become more powerful, efficient and reliable. The
network has passed through several stages which are described below:
• ARPANET (Advanced Research Project Agency Network): ARPANET, which was jointly designed and named by the
Advanced Research Projects Agency (ARPA) and US Department of Defence (DoD), was the first network and came into
existence in 1969. It was a project that connected a handful of computers at different universities and US DoD for sharing
of data and messages and playing long-distance games, and socializing with people to share their views. Arpanet carried
its first message on October 29, 1969, laying the foundation for today’s networked world.
When Arpanet was created, it connected five sites: UCLA, Stanford, UC Santa Barbara, the University of Utah and BBN
Technologies.
• NSFNET (National Science Federation Network): In the mid-80’s, another federal agency, NSFNET (National Science
Federation Network), created a new network which was more capable than ARPANET. Its main aim was to use network
only for academic research and not for any private business activity. Later, many private companies combined their own
private networks with ARPANET and NSFNET to make a more capable and broad network—the Internet. It is the internet
that links two or more networks to make a large network for sharing of information and messages.
INTERNET
The Internet is the global system of interconnected computer networks that uses the Internet protocol
suite (TCP/IP) to communicate between networks and devices. It is a network of networks that
consists of private, public, academic, business, and government networks.
SWITCHING TECHNIQUES
Switching sends data along different routes. Process of forwarding data from one point to another.
Two types
• Connection oriented
• Connection less
NOT IN SYLLABUS , JUST READ
Each packet is of fixed size
SWITCHING TECHNIQUES
https://www.youtube.com/watch?v=nomyRJehhnM
TCP/IP
https://www.youtube.com/watch?v=hDHJxndSups
JUST READ
https://www.youtube.com/watch?v=U9arSNHLgsc
BUS , STAR, TREE TOPOLOGIES IN SYLLABUS
Terminator is a device
connected to one end of a
bus or cable that absorbs
signals. Terminators prevent
signal reflection, which can
produce interference that
causes signal loss.
Twisted Pair Cable
Twisted pair cable consists of a pair of insulated wires twisted
together. The use of two wires twisted together helps to reduce
crosstalk and electromagnetic induction. Twisted-pair cable is
used by older telephone networks and is the least expensive type
of local-area network (LAN) cable.
Coaxial Cable
Coaxial cable, or coax, is an electrical cable with an inner
conductor surrounded by a tubular insulating layer typically of a
flexible material with a high dielectric constant, all of which are
surrounded by a conductive layer called the shield, and finally
covered with a thin insulating layer on the outside. The term
coaxial comes from the inner conductor and the outer shield
sharing the same geometric axis.
Opitcal Fibre
https://www.bluetooth.com/learn-about-bluetooth/bluetooth-technology/range/
JUST READ
Wi-Fi is the name of a popular wireless networking technology that uses radio waves to provide
wireless high-speed Internet and network connections. The name is a contraction of "Wireless
Fidelity".
1.Wi-Fi routers use 802.11 networking standards. A computer's wireless adapter translates data
into a radio signal and transmits it using an antenna. Wi-Fi 6, or 802.11ax, is the latest Wi-Fi
generation, announced in Sept. 2019
2.A wireless router receives the signal and decodes it. The router sends the information to the
Internet using a physical, wired Ethernet connection.
A WiFi hotspot is simply an area with an accessible wireless network.
Most new laptops and many new desktop computers come with built-in wireless transmitters, and just
about all mobile devices are WiFi enabled. If your computer isn't already equipped, you can buy a wireless
adapter that plugs into the PC card slot or USB port.
JUST READ
WiMAX is a family of wireless broadband communication standards based on the IEEE 802.16 set of
standards
Satellite
JUST READ
NETWORK DEVICES
1. Modem
•Function: Short for Modulator-Demodulator, a modem converts digital data from a computer into analog signals that
can be transmitted over phone lines (and vice versa). It’s essential for internet connectivity over telephone lines.
•Types: Dial-up, DSL, and Cable modems.
•Use: Common in home and office networks for accessing the internet.
2. Ethernet Card (Network Interface Card, NIC)
•Function: A hardware component that allows computers to connect to a network via an Ethernet cable.
•Type: It can be integrated into the motherboard or added as an external card.
•MAC Address: Each Ethernet card has a unique MAC (Media Access Control) address for identification.
3. RJ45 Connector
•Function: A type of connector commonly used for network cables in Ethernet networks.
•Structure: It has 8 pins and is used to connect the ends of Ethernet cables to devices like NICs or routers.
•Use: Ensures secure and reliable physical connection for Ethernet networking.
4. Repeater
•Function: Boosts or amplifies signals in a network to extend the transmission distance.
•Use: Primarily used in long-distance cabling and wireless networks to maintain signal strength.
•Application: Useful in areas where the network covers large physical spaces.
5. Hub
•Function: A basic device that connects multiple devices in a network. It forwards data packets to all connected
devices, regardless of the destination.
•Limitation: It lacks intelligence, meaning it cannot filter or direct traffic efficiently, often leading to network
congestion.
•Use: Suitable for small networks but generally replaced by switches in modern setups. 6. Switch
•Function: Connects multiple devices in a network, similar to a hub, but is more intelligent. It forwards data only to the
device it is intended for, based on MAC addresses.
•Benefit: Reduces network congestion and improves performance.
•Use: Commonly used in LAN (Local Area Network) environments.
7. Router
•Function: Connects multiple networks and directs data between them, typically from a local network to the internet.
•Intelligence: Uses IP addresses to route data to the correct destination.
•Use: Essential for internet connectivity in both home and office networks.
8. Gateway
•Function: Acts as a "gateway" between different networks, particularly those with differing protocols.
•Role: Translates data formats, protocols, and addresses for compatibility.
•Use: Typically used when connecting a local network to an external network, such as the internet.
9. Wi-Fi Card
•Function: A network adapter that allows a computer or device to connect to a Wi-Fi network.
•Connection Type: Can be internal (built into laptops) or external (USB adapters).
•Use: Essential for wireless connectivity to Wi-Fi networks.
Layer 6 device (data link layer)
SWITCH
In a telecommunications network, a switch is a device that channels incoming data from any of multiple input ports to the
specific output port that will take the data toward its intended destination. A switch is a little smarter than a hub. It records
the IP and MAC addresses in a table of all the devices connected to it. Thus when a packet is received the switch reads the
destination address information to determine if the destination device is connected to it. It it is, the switch forwards the
packet only to the destination device sparing the other devices connected to it from having to read and deal with the traffic.
Switch is the preferred answer
PROTOCOLS
What is FTP (File Transfer Protocol)?
FTP is a widely used network protocol for transferring files between
computers over a TCP/IP-based network, such as the Internet. FTP lets people
and applications exchange and share data within their offices and across the
Internet.
FTP connection needs two parties to establish and communicate on the network.
To do that, users need to have permission by providing credentials to the FTP
server. Some public FTP servers may not require credentials to access their files.
The practice is common in a so-called anonymous FTP.
FTP is the underlying protocol that is used to, as the name suggests, transfer files
over a communication network. It establishes two TCP connections: Control
Connection to authenticate the user, and Data Connection to transfer the
files.
IP (Internet Protocol)- A network layer protocol. Responsible for routing of
the packets.
An IP address (Internet Protocol address) is a unique identifier assigned to each device connected to a
network that uses the Internet Protocol for communication. It enables devices, such as computers,
smartphones, and routers, to locate and communicate with each other over the internet or local network.
Types of IP Addresses:
1.IPv4 (Internet Protocol version 4):
•Consists of four groups of numbers, each ranging from 0 to 255, separated by dots (e.g., 192.168.1.1).
2.IPv6 (Internet Protocol version 6):
•Uses a more complex, hexadecimal system with 8 groups of four characters, separated by colons (e.g.,
2001:0db8:85a3:0000:0000:8a2e:0370:7334).
Point - to - Point Protocol (PPP) is a communication protocol of the data link layer
that is used to transmit data between two directly connected (point-to-point)
computers. It is a byte - oriented protocol that is widely used in broadband
communications having heavy loads and high speeds. Since it is a data link layer
protocol, data is transmitted in frames.
•IMAP is short for Internet Message Access Protocol. With IMAP, the message does not
remain on the local device, such as a computer, it remains on the server.
•POP3 is short for Post Office Protocol. With POP3 mail, it will connect and attempt to
keep the mail located on the local device (computer or mobile).
In web 1.0, data was posted on Web sites, and users simply viewed or downloaded the content (static pages).
Web 2.0 characterized by dynamic features like blogging, social networking sites etc.
Web 2.0 (or Web 2) is the popular term for advanced Internet technology and applications including blogs, wikis,
RSS and social bookmarking. The two major components of Web 2.0 are the technological advances enabled by
Ajax (Asynchronous JavaScript and XML) and other new applications such as RSS.
Problems: Third-party cookies let advertisers or analytics companies track an individual's
browsing history across the web on any sites that contain their ads.
FIREWALL
A Firewall is used to prevent unauthorized access to the network. A Firewall can be implemented
as a software, hardware or combination of both. All data or messages entering or leaving the
network pass through the firewall. Firewall examines each message and blocks those that do not
meet the specified security criteria.
CyberLaw
JUST READ
Cyber Law is a generic term which refers to all the legal and regulatory aspects of the Internet and the World
Wide Web. It is important because it touches almost all aspects of transactions and activities concerning the
Internet, the World Wide Web and Cyberspace.
Indian IT Act
The Information Technology Act, 2000 (also known as ITA-2000, or the IT Act) is an Act of
the Indian Parliament (No 21 of 2000) notified on 17 October 2000. It is the
primary law in India dealing with cybercrime and electronic commerce.
The Act provides a legal framework for electronic governance by giving recognition to electronic
records and digital signatures. It also defines cyber crimes and prescribes penalties for them.
A major amendment was made in 2008. It introduced Section 66A which penalized sending "offensive
messages". It also introduced Section 69, which gave authorities the power of "interception or
monitoring or decryption of any information through any computer resource". Additionally, it
introduced provisions addressing - pornography, child porn, cyber terrorism and voyeurism.
Cybercrime
JUST READ
Cybercrime, or computer-oriented crime, is a crime that involves a computer and a network. The computer
may have been used in the commission of a crime, or it may be the target.Cybercrime may threaten a person,
company or a nation's security and financial health.
Examples: credit card frauds, website hacking
Common types of Intellectual Property include copyrights, trademarks, patents, industrial design rights and
trade secrets in some jurisdictions.