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

CS Class 12 Complete Study Material

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

CS Class 12 Complete Study Material

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

FILE HANDLING IN PYTHON

USER INPUT PYTHON PROGRAM OUTPUT ON


KEYBOARD READ DATA WRITE DATA MONITOR
CONSOLE Using input() Using print() CONSOLE
Using file handling your program can read data from a file and write output in
a file as per the requirements

FILE READ DATA PYTHON PROGRAM WRITE DATA FILE

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

Text files: Binary files:


• In this type of file, Each line • It contains information in the same
of text is terminated with a format as in memory. In this type of
special character called EOL file, there is no terminator for a line.
(End of Line), which is the • No translations take place in binary
new line character (‘\n’) in files, hence reading and writing
python by default. binary files through a program is
• Internal translations take faster.
place when text files are • Cannot be read and interpreted by
read or written. us.
• Text files and be read and
interpreted by us.
Opening a File

File_object = open(“File_Name","Access_Mode")

Default is read mode

f=open("d:\\a.txt") No second argument


Default value is
g=open(r"d:\t.txt") “r”…..i.e read 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

USING A FOR LOOP TO READ A FILE

file=open("d:\\a.txt")
for l in file:
print(l)

You must know this for output based questions


Display lines that start with alphabet “a” or “A”
a.txt EXPLANATION
This is a text file s=[“This is a text file\n”, “Apples are healthy\n”, “File
Apples are healthy handling is easy\n”, “Anger is bad for health\n”]
File Handling is easy
Anger is bad for health FIRST RUN OF THE FOR LOOP
line=“This is a text file\n”
line[0]=‘T’
SOLUTION SECOND RUN OF THE FOR LOOP
file=open("d:\\a.txt") line=“Apples are healthy”
s=file.readlines() Line[0]=‘A’
for line in s: ……….so on
if line[0]=='a' or line[0]=='A':
print(line,end=‘’)
file.close()

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()

Alternative approach to the question on the earlier slide, for understanding


Display count of number of digits in the file data.txt
file=open("d:\\a.txt")
count=0
s=file.read()
for ch in s:
if ch.isdigit():
count =count+1
print("Number of digits in the file are: ", count)
file.close()
WRITING INTO A TEXT FILE

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")

n=int(input("How many names do you want to enter: "))


for i in range(n):
name=input("Enter name: ")
file.write(name)
file.close()

write() does not add a


newline character on its
own
Using write()
file=open("data.txt", "w")

n=int(input("How many names do you want to enter: "))


for i in range(n):
name=input("Enter name: ")
file.write(name+"\n")
file.close()

file=open("data.txt", "w")

n=int(input("How many names do you want to enter: "))


for i in range(n):
name=input("Enter name: ")
file.write(name)
file.write(“\n”)
file.close()
Using writelines()

file=open("data.txt", "w")

name=["Eat healthy\n","Stay
hydrated\n","have adequate sleep\n"]
file.writelines(name)
file.close()
QUICK RECAP

The split() method splits a string into a list.


You can specify the separator, default separator is any whitespace.

txt = "hello, my name is Peter, I am 26 years old"


x = txt.split()
print(x)
QUICK RECAP

The split() method splits a string into a list.


You can specify the separator, default separator is any whitespace.

txt = "hello, my name is Peter, I am 26 years old"


x = txt.split(", ")
print(x)
1. Write a Python program to read and display an entire text file.

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()

print("Total number of words in file: ",len(wordlist))

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

The seek(offset) method changes the current file position.


The offset argument indicates the number of bytes to be moved from the
beginning of the file.

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

POSITION OF FILE POINTER


FILE MODE
Beginning of file
r, r+
Beginning of file, overwrites the file if it
w, w+ exists

At the end of file if it exists, otherwise


a, a+ creates a new file
f=open("d:\\info.txt","r")
print("r mode: ",f.tell())
f.close()

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

Buffering is the process of storing data temporarily before it is moved to a


new location.
In the case of files, the data is not immediately written to the disk instead it
is stored in the buffer memory.
This rationale behind doing this is that the writing data to disk takes time as
opposed to writing data to the physical memory. Imagine a program writing
data every time the write() method is called. Such a program would be very
slow.
When we use a buffer, the data is written to the disk only when the buffer
becomes full or when the close() method is called. This process is called
flushing the output. You can also flush the output manually using
the flush() method of the file object. Note that the flush() only saves the buffered
data to the disk. It doesn't close the file.
Usage: f.flush()
ABSOLUTE AND RELATIVE PATHS
An absolute path is a path that describes the location of a file or folder regardless of the
current working directory; in fact, it is from the root directory. It contains the complete
location of a file or directory.

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:

If the current working directory is Project then


Project Images
..\Images\b.jpg
.\a.txt a.txt b.jpg
STANDARD INPUT OUTPUT AND ERROR STREAMS IN PYTHON

We use file object(s) to work with data files.


Similarly, input/output from devices is also performed using standard I/O stream objects.

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)

sys.stdout.write("Enter number: ")


number=sys.stdin.readline()
n=int(number)
if n<0:
sys.stderr.write("error")
CSV FILES
CSV – COMMA SEPARATED VALUE FILE
Extension of the file- .csv

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

• Csv module is used to read/write in a csv file

• Csv.writer() function to convert file object into writer object

• Csv.writerow() function to insert records in the csv file


• (records will be in the form of lists)
import csv import csv
def write_data(): def write_data():
f=open("classxii.csv","w") f=open("classxii.csv","w“, newline=“\n”)
OR
w=csv.writer(f,delimiter=',',lineterminator='\n') w=csv.writer(f,delimiter=',')
w.writerow(["AdmnNo","Name","Age"]) w.writerow(["AdmnNo","Name","Age"])
n=int(input("How many records: ")) n=int(input("How many records: "))
for i in range(n): for i in range(n):
adm=input("Enter admission number: ") adm=input("Enter admission number: ")
nm=input("Enter name: ") nm=input("Enter name: ")
age=int(input("Enter age: ")) age=int(input("Enter age: "))
rec=[adm,nm,age] rec=[adm,nm,age]
w.writerow(rec) w.writerow(rec)
f.close() f.close()

write_data() write_data()
Reading CSV files

• Csv module is used to read/write in a csv file

• Csv.reader() function is used to read records from the


file

• The records are in the form of list of list


import csv
Reading, Writing, Searching
def write_data(): def search_data():
f=open("d.csv","w") f=open("d.csv","r")
w=csv.writer(f,delimiter=',',lineterminator='\n') rec=csv.reader(f)
w.writerow(["AdmnNo","Name","Age"]) #print(rec)
n=int(input("How many records: ")) next(rec)
for i in range(n): for i in rec:
adm=input("Enter admission number: ") if i[1][0]=="u" or i[1][0]=="U":
nm=input("Enter name: ") print(i)
age=int(input("Enter age: ")) f.close()
rec=[adm,nm,age]
w.writerow(rec)
f.close() write_data()
print("*****reading data*****")
def read_data(): read_data()
f=open("d.csv","r") print("*****searching data*****")
rec=csv.reader(f) search_data()
#print(rec)
for i in rec:
print(i)
f.close()
A CSV file “country.csv” contains
<country>,<capital>

Display names of countries where capital is more than 6 characters long


import csv
def write_data():
f=open("country.csv","w")
w=csv.writer(f,delimiter=',',lineterminator='\n')
w.writerow(["Country","Capital"])
w.writerow(["INDIA","NEW DELHI"] )
w.writerow(["FRANCE","PARIS"] )
w.writerow(["US","WASHINGTON"] )

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>

Display details of products with the highest price


import csv #approach-1
def display_1():
def write_data(): f=open("product.csv","r")
f=open("product.csv","w") rec=csv.reader(f)
w=csv.writer(f,delimiter=',',lineterminator='\n') print("Details of products with maximum cost")
w.writerow(["Product Id", "Product name","Cost"]) next(rec)
w.writerow(["P1","TV", 20000] )
w.writerow(["P2","LAPTOP", 50000] ) Val=[]
w.writerow(["P3","WASHING MACHINE", 50000] ) for i in rec:
Val.append(int(i[2]))
f.close() m=max(Val)
f.seek(0)
next(rec)
print("Result")
for i in rec:
if int(i[2])==m:
print(i)

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)

def remove_data(): def update_data():


f=open("product.csv","r") f=open("product.csv","r")
g=open("temp.csv","w") g=open("temp.csv","w")
w=csv.writer(g,delimiter=',',lineterminator='\n') w=csv.writer(g,delimiter=',',lineterminator='\n')
pn=input("Enter product name to be deleted for: ") pn=input("Enter product name to be updated: ")
rec=csv.reader(f) rec=csv.reader(f)
header=next(rec) header=next(rec)
w.writerow(header) w.writerow(header)
for i in rec:
if i[1]!=pn: for i in rec:
w.writerow(i) if i[1]==pn:
f.close() i[2]=float(input("Enter updated cost: "))
g.close() w.writerow(i)
os.remove("product.csv") f.close()
os.rename("temp.csv","product.csv") g.close()
os.remove("product.csv")
os.rename("temp.csv","product.csv")
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

A CSV file “book.csv” contains


<book id>,<book name>,<price>
Write a menu driven program to append, display, search (on basis of price
range), delete (on basis of book name), update (update price on basis of
book name)
BINARY FILES
• Binary files the data is stored in the same manner as it is stored
in memory.

• Binary files are not human readable. When opened using any
text editor, the data is unrecognizable.

• They can be anything from image files to pdf files


In Text files, everything that you read or write is in the form
of strings.

• Python allows you to define several types of data structures, E.g.


such as lists, dictionaries, custom objects, etc. a =["Rohan", "XI-A", 90.5]
• To store data in a text file, you will have to think about how to b =["Radha", "XI-B", 89.5]
transform the object (list, dictionary etc.) into a series of f=open("student.txt","w")
strings and use the opposite operation to recover the variable. s=""
• However, this is very cumbersome, also it is very susceptible to for i in a:
small changes. s=s+ str(i)+", "

Fortunately, Python comes with a module that allows us to save s=s+"\n"


almost everything we want, called Pickle. f.write(s)
import pickle s=""
for i in b:
a =["Rohan", "XI-A", 90.5] s=s+ str(i)+", "
b =["Radha", "XI-B", 89.5] s=s+"\n"
f=open("student.txt","wb") f.write(s)
pickle.dump(a,f) f.close()
pickle.dump(b,f)

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

DATA IS WRITTEN AS MULTIPLE RECORDS DATA IS WRITTEN AS SINGLE RECORD

Binary file is opened Binary file is opened

Data is accepted in the Data is accepted, added


form of records and to one variable(list) and
written into the file one then one record is added
by one to the file

After all records have


After all records have
been written, file is
been written, file is
closed
closed
f=open("student","wb")
f=open("student","wb") n=int(input("How many students"))
n=int(input("How many students")) t=[]
for i in range(n): for i in range(n):
s_rec=eval(input("Enter name, class, percentage")) s_rec=eval(input("Enter name, class, percentage"))
pickle.dump(s_rec, f) t.append(s_rec)

f.close() pickle.dump(t, f)
READING FROM A BINARY FILE
2 Approaches

DATA IS WRITTEN AS MULTIPLE RECORDS DATA IS WRITTEN AS SINGLE RECORD


Binary file is opened
Binary file is opened
Handle exception
Read records one by one Data is read using a
in a loop single load() statement

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”]

[“ravi”, 34, “Manager”] [“aarush”, 45, “Sr. Manager”] [“usha”,56,”clerk”]


APPENDING IN A BINARY FILE
(data stored as single record)
CAN BE LEFT FOR THE MID SEM
def append():
f=open("employee","rb+")
t_rec=pickle.load(f)
x=eval(input("Enter name, age, designation to be appended: "))
t_rec.append(x)
f.seek(0)
pickle.dump(t_rec, f)
f.close()
DELETING IN A BINARY FILE
(data stored as single record)
CAN BE LEFT FOR THE MID SEM
import os
def remove_rec():
f=open("employee","rb")
g=open("temp","wb")
o_rec=pickle.load(f) Read entire data
n_rec=[]

a=input("Enter name of employee to be deleted")


for i in o_rec:

if i[0]!=a: Create a new record with all data


n_rec.append(i) except the one to be deleted

pickle.dump(n_rec, g) Dump the new record


f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
DELETING IN A BINARY FILE
(data stored as multiple records)
def remove_rec():
f=open("employee","rb")
g=open("temp","wb")

a=input("Enter name of employee to be deleted")


while True: # check for end of file
try:
o_rec=pickle.load(f) Read one record at a time
if o_rec[0]!=a:
pickle.dump(o_rec,g) Dump the record if it is to be retained
except EOFError:
break

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=[]

a=input("Enter name of employee whose designation is to be modified")


for i in o_rec:
if i[0]==a: Make changes to the record being
i[2]=input("Enter new designation") modified and then dump it
n_rec.append(i)
else:
n_rec.append(i) Dump the records directly that are not to
be modified
pickle.dump(n_rec,g)
f.close()
g.close()
os.remove("employee")
os.rename("temp","employee")
def update_rec(): UPDATING IN A BINARY FILE
f=open("employee","rb") (data stored as multiple records)
g=open("temp","wb")

a=input("Enter name of employee to be modified: ")


while True: # check for end of file
try:
o_rec=pickle.load(f) Read one record at a time
if o_rec[0]==a:
o_rec[2]=input("Enter new designation") Make changes if needed
pickle.dump(o_rec,g) and then dump it

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):

n=int(input("How many records do you want to enter: "))


f=open(nm,"wb")
for i in range(n):
d={}
country=input("Enter country name ")
capital=input("Enter capital of “ + country)
d[country]=capital
pickle.dump(d,f)
f.close()
QUESTIONS (Theory)

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

while True: # check for end of file


try:
o_rec=pickle.load(f)
if o_rec[1]==_________:

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

TWO MAJOR OPERATIONS


STACKS
Every day examples of stacks:
• Stack of plates/books in a cupboard
• Stack of chairs
• Wearing and removing bangles

Practical applications of stack:


• Undo operation (generally in editors, drawing app)
• Back (in history) button in browsers
• Compilers: Maintaining function calls
• Compilers: Evaluating mathematical expressions
• Reversing strings
• Compilers: Parenthesis checking
• Evaluation of Postfix expression
• Conversion from Infix to Postfix expression
STACKS
Push Operations Pop Operations (Undo)

5
4
3 Underline
2 Bold
1 Change Colour
0 Type Text
We will use a list to implement stack

Push() - append() method of list We keep track of topmost element of Stack


Pop() - pop() method of list Insertions take place at top end
Removals take place at top end

Push(67) Push(88) Pop() Push(100)


a.append(67) a.append(88) a.pop() a.append(100
a=[] 88
)

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")

ch=input("Enter y to continue: ")


Write code to implement a Stack that stores employee details (name and age)
DATABASE

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

A candidate key that is not a primary key is called an 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.

Select Name, Salary, Age, Address from Customers;


Sno Sname City
Delhi
Mumbai
Delhi
Bangalore
Jaipur
Sno Sname City
Delhi
Mumbai
Delhi
Bangalore
Jaipur
Using where clause with Select statement

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

What would be the output of the following?

Select count(Id) from Employee;


Select count(*) from Employee where Salary between 60 and 70;

Select count(Salary) from Employee where Salary between 60 and 70;

Select count(*) from Employee;


Select count(salary) from Employee;
Select count(Distinct salary) from Employee;
Table: Employee AGGREGATE FUNCTIONS
GROUP BY clause
The GROUP BY clause in SQL is used to arrange identical data into groups on the basis of column
name.

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.

CREATE VIEW Brazil_Cust AS


SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

SELECT * FROM Brazil Cust;


SQL EQUI JOIN performs a JOIN against equality or matching column(s) values of the associated tables.
An equal sign (=) is used as comparison operator in the where clause to refer equality.
You may also perform EQUI JOIN by using JOIN keyword followed by ON keyword and then specifying
names of the columns along with their associated tables to check equality.
A natural join is a type of equi join which occurs implicitly by comparing all the same names columns in both
tables. The join result has only one column for each pair of equally named columns.

SELECT * FROM foods NATURAL JOIN company;


EXAMPLE: JOIN
EQUI JOIN
NATURAL JOIN
CREATE TABLE command

Datatypes that can be used:


Int or Integer or Int(15)
Decimal or Decimal(m,n) i.e. Decimal(10,2) ---- total number of digits is 10 including 2 digits after decimal point
Numeric or Numeric(m,n i.e. Numeric(10,2) ---- total number of digits is 10 including 2 digits after decimal point
Char or char(width)
Varchar(width)
Date
datetime
SQL command to see a list of all tables in a database

Show tables ;

SQL command to see current system date

Select curdate() from dual;

SQL command to see current system date and time

Select now() from dual;


We can apply constraints
at the time of table
creation.
mysql> alter table student modify column name char(10) unique ;
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
Insert into <table> values (…., ….., ….);
Insert into (<fieldname>, <fieldname>,……) values (….., ……., …….);
COMPUTER NETWORKS
WHAT IS A NETWORK?

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

Fiber optic cable consists of a center glass core surrounded by


several layers of protective material. It transmits data in the
form of light rather than electronic signals. Thus it eliminates
the problem of electrical interference.

It uses the principle of total internal reflection of light.

Fiber optic cable is expensive as compared to coaxial and


twisted pair cable but can transmit signals over much longer
distances. It also has the capability to carry data at very high
speed.
Radio waves are easy to generate, can travel long distances and penetrate through buildings easily so they are widely used
for communication both indoors and outdoors. Radio waves are omnidirectional meaning that they travel in all directions
from the source, so that the transmitter and receiver do not have to be carefully aligned physically. The properties of radio
waves are frequency dependent. At low frequencies radio waves pass well through obstacles. At high frequencies, radio
waves tend to travel in straight lines and bounce off obstacles. They are also absorbed by rain. At all frequencies radio
waves are subject to interference from motors and other electrical equipment.
Radio Wave Communication
•Frequency Range: Radio waves have frequencies from about 30 Hz to 300 GHz.
•Wavelength Range: They range from about 1 millimeter to several kilometers in wavelength.
•Propagation: Radio waves can travel long distances, especially in the lower frequency ranges. They can be transmitted
through the ionosphere, enabling long-distance communication.
•Applications: Commonly used for AM/FM radio, television broadcasting, mobile phones, and communication with remote
regions due to their extensive reach.
•Modulation: To carry information, radio waves can be modulated in amplitude (AM) or frequency (FM), which encodes the
data for transmission.
Microwave Communication
•Frequency Range: Microwaves occupy the higher frequency range, typically from 1 GHz to 300 GHz.
•Wavelength Range: Their wavelengths range from 1 millimeter to 1 meter.
•Propagation: Unlike radio waves, microwaves travel in straight lines and are not reflected by the ionosphere, so they’re
used primarily for line-of-sight communication.
•Applications: They are widely used for satellite communications, Wi-Fi, radar systems, and Bluetooth. Due to their higher
frequency, microwaves can carry more information than radio waves, making them ideal for data-intensive applications.
•Modulation: Microwaves use techniques like frequency modulation (FM), amplitude modulation (AM), and phase
modulation (PM) for efficient data transmission.
Key Differences:
•Range: Radio waves have a longer range than microwaves, which are limited to line-of-sight.
•Frequency & Wavelength: Microwaves have higher frequencies and shorter wavelengths compared to radio waves,
enabling them to carry more data.
•Applications: Radio waves are generally used for broader broadcasts, while microwaves are ideal for targeted, high-
bandwidth communication like satellite links.
JUST READ
JUST READ

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

Few Base stations are enough to cover a considerable area.


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).

Pop3 vs. IMAP: Which is better?


IMAP is better if you are going to be accessing your email from multiple devices, such as
a work computer and a smart phone. POP3 works better if you are only using one device,
but have a very large number of emails. It is also better if you have a poor internet
connection and need to access your emails offline. For most people, IMAP will suit their
needs better.
Note: If emails start disappearing from your inbox without you deleting them, it almost
always means one of your devices is on POP3. Backing up the emails and then resetting
up the email account as IMAP will fix the problem.
Telnet
Provides a command-line interface for remote login and communication.
•Function: Allows users to control and manage a computer over a network as if they
were logged in locally.
•Security Note: TELNET sends data in plaintext, making it less secure than newer protocols
like SSH.
Telnet is an application level protocol that allows you to connect to remote computers
(called hosts) over a TCP/IP network (such as the internet).
Using telnet client software on your computer, you can make a connection to a telnet server
(that is, the remote host). Once your telnet client establishes a connection to the remote host,
your client becomes a virtual terminal, allowing you to communicate with the remote host
from your computer. In most cases, you'll need to log into the remote host, which requires
that you have an account on that system. Occasionally, you can log in as guest or public
without having an account.
Scripts
A Script is a list of commands embedded in a web page. Scripts
are interpreted and executed by a certain program or scripting
engine.
Client-side scripting generally refers to the scripts that are
executed client-side, by the user's web browser, instead of
server-side (on the web server).
This type of computer programming is an important part of the
Dynamic HTML (DHTML) concept, enabling web pages to be
scripted; that is, to have different and changing content
depending on user input, environmental conditions (such as the
time of day), or other variables.
E.g. of clent scripting languages – VB Script, JavaScript, PHP
(Hypertext Preprocessor)
Server-side scripting generally refers to the scripts that are
executed at the server end and the result is sent to the client end. Client-side scripting Server-side scripting
E.g. Server-side scripting languages – ASP (Active Server Main Defn Main Defn
Pages), JSP (Java Server Pages), Perl, PHP (Hypertext Browser Dependant Browser Independent
Preprocessor) Affected by the Affected by the processing speed of
processing speed of the host server
the user’s computer
Examples of Examples of languages
languages
Web 2.0 is characterized especially by the change from static web pages to dynamic or user-generated
content and the growth of social networking.

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

Intellectual Property Right (IPR)


Under intellectual property law, owners are granted certain exclusive rights to a variety of intangible assets,
such as musical, literary, and artistic works; discoveries and inventions; and words, phrases, symbols, and
designs.

Common types of Intellectual Property include copyrights, trademarks, patents, industrial design rights and
trade secrets in some jurisdictions.

You might also like