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

12th CS

Uploaded by

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

12th CS

Uploaded by

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

UNIT I

What is a Function
A Function is a set of codes that are design to perform a single or related task, it
provide modularity and increase code reusability. A function executes only when
t is being called. Python provides many build in function like print(), len(),
type()..etc, whereas the functions created by us, is called User Defined
Functions.When a function is called for execution, Data can be passes to the
function called as function parameters. After execution the function may return
data from the function.

Benefits of using Function


Code Reusability: A function once created can be called countless number of
times.

Modularity: Functions helps to divide the entire code of the program into
separate blocks, where each block is assigned with a specific task.

Understandability: use of Functions makes the program more structured and


understandable by dividing the large set of codes into functions

Procedural Abstraction: once a function is created the programmer doesn’t


have to know the coding part inside the functions, Only by knowing how to
invoke the function, the programmer can use the function.

Types of Functions in Python


Built-in Function:

Ready to use functions which are already defined in python and the programmer
can use them whenever required are called as Built-in functions. Ex: len(),
print(), type()..etc

Functions defined in Modules:

The functions which are defined inside python modules are Functions defined
in modules. In order to use these functions the programmer need to import the
module into the program then functions defined in the module can be used.

import math
p=math.pow(5,2)
print(p)
User Defined Function

Functions that are defined by the programmer to perform a specific task is called
as User Defined Functions. The keyword def is used to define/create a function
in python.

Elements in Function Definition


 Function Header: The first line of the function definition is called
as function header. The header start with the keyword def, and it also
specifies function name and function parameters. The header ends
with colon ( : ). def sum(a,b): #function Header
 Parameter: Variables that are mentioned inside parenthesis ( ) of the
function Header.
 Function Body: The set of all statements/indented-statements
beneath the function header that perform the task for which the
function is designed for.
 Indentation: All the statements inside the function body starts with
blank space (convention is four statements).
 Return statement: A function may have a return statement that is
used to returning values from functions. A return statement can also
be used without any value or expression.

Flow of Execution in a Function Call

Arguments and parameters in Function


In Python, the variables mentioned withing parathesis () of a function definition
are referred as parameters(also as formal parameter/formal argument) and the
variables present inside parathesis of a function call is referred as arguments
(also as actual parameter/actual argument). Python supports 4 types of
parameters/formal arguments

1. Positional Argument

2. Default Argument

3. Keyword Argument
4. Variable length argument

Positional Arguments:

When function call statement must contain the same number and order of
arguments as defined in the function definition, then the arguments are referred
as positional argument.

Default Argument:

Default values can be assigned to parameter in function header while defining a


function, these default values will be used if the function call doesn’t have
matching arguments as function definition.

*Note: non-default arguments cannot follow default arguments

Keyword Argument

Python allows to call a function by passing the in any order, in this case the
programmer have to spcify the names of the arguments in function call.
Variable Length Argument

Variable Length Argument in python permits to pass multiple values to a single


parameter. The variable length argument precedes the symbol ‘*’ in the function
header of the function call.

Returning Values from Function


Functions in python can return back values/variables from the function to the
place from where the function is called using return statement. Function may or
may not return values, python function can also return multiple values.

return statement terminates the function execution if it is encountered.


Scope of Variables
Part(s) of the program where the variable is legal and accessible is referred as its
scope. Based on scope, variable are categorized into 2 categories

Local Variable: Variable defined inside a function is called as Local


Variable. Its scope is limited only within the function in which it is defined.

Global Variable: Variable defined outside all function is called as Global


variable.

Using a Global variable in local scope:

To access a variable declared outside all functions(Global Variable) in a local


scope then global statement is used.

When global statement is used for a name, it restrict the function to create a
local variable of that name instead the function uses the global variable.
Exception Handling in Python-
Types of Errors

(i)Compile-time errors. These are the errors resulting out of violation of


programming language’s grammar rules. All syntax errors are reported during
compilation.

(ii) Run-time errors. The errors that occur during runtime because of unexpected
situations. Such errors are handled through exception handling routines of
Python.

Syntax Error
These are the errors resulting out of violation of programming language’s
grammar rules. All syntax errors are reported during compilation. Example:

Exception
Exceptions are unexpected events or errors that occur during the execution of a
program, such as a division by zero or accessing an invalid memory location.
These events can lead to program termination or incorrect results.

“It is an exceptional event that occurs during runtime and causes normal
program flow to be disrupted.”
Observe that there is nothing wrong with the program syntax, it is only when
we try to divide an integer with zero , an exception is generated.

Exception (Examples):

Only When we are trying to access a list element with an non existing index an
exception is generated.
Only When we are trying to convert a string to integer the Exception generated.
What is Exception Handling?
Exception handling in Python is a mechanism used to handle runtime errors that
occur during the execution of a Python program

Exception handling allows a program to gracefully handle such exceptions and


recover from errors by taking corrective actions instead of terminating abruptly.
In Python, exception handling is implemented using a try-except block

Exception Handling using. try and except Block:

The try and except block in Python is a way to handle exceptions or errors that
may occur during code execution. This mechanism prevents the program from
crashing by allowing it to continue running even if an error is encountered.
In a try block, you write the code that might raise an exception. If an exception
occurs, the code execution jumps to the corresponding except block, where you
can handle the error or take alternative actions.

Exception (Example-1):

Exception (Example-1):

Write a program to ensure that an integer is entered as input and in case any
other value is entered, it displays a message – ‘Not a valid integer’

General Built-in Python Exceptions:


Exception Name Description

Raised when one of the built-in functions (input( )) hits an end-of-file condition (EOF)
EOFError without reading any data. (NOTE. the file.read( ) and file.readline( ) methods return an
empty string when they hit EOF.)

Raised when an I/O operation (such as a print statement, the built-in open( ) function or a
IO Error method of a file object) fails for an I/O-related reason, e.g., “file not found” or “disk
full”.

Raised when a local or global name is not found. This applies only to unqualified names.
NameError
The associated value is an error message that includes the name that could not be found.

Raised when a sequence subscript is out of range, e.g., from a list of length 4 if you try to
IndexError read a value of index like 8 or E8 etc. (Slice indices are silently truncated to fall in the
allowed range ; if an index is not a plain integer, TypeError is raised.)

Raised when an import statement fails to find the module definition or when a from …
ImportError
import fails to find a name that is to be imported.

Raised when an operation or function is applied to an object of inappropriate type, e.g., if


TypeError you try to compute a square-root of a string value. The associated value is a string giving
details about the type mismatch.

Raised when a built-in operation or function receives an argument that has the right type
ValueError but an inappropriate value, and the situation is not described by a more precise exception
such as IndexError.

ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.

KeyError Raised when a mapping (dictionary) key is not found in the set of existing keys

ImportError Raised when the module given with import statement is not found.

Raised when keys Esc, Del or Ctrl+C is pressed during program execution and normal
KeyboardInterrupt
program flow gets disturbed.

Built-in Python Exceptions

Second Argument of the Exception Block:


We can also provide a second argument (optional) for the except block, which
gives a reference to the exception object.

Handling Multiple Errors


Handling multiple exceptions in Python allows a single try-except block to
handle different types of exceptions using multiple except blocks. This allows a
program to handle various types of errors that may occur during runtime and take
corrective measures accordingly.
In a try-except block, each except block is associated with a specific exception
type, and the block containing the code to handle that exception is executed if
the corresponding exception occurs in the try block. By handling multiple
exceptions, programmers can write more robust and less error-prone code.

Syntax:

Example: Program to handle multiple exceptions:


Execution Order:

The <try suite> is executed first ; if, during the course of executing the <try
suite>, an exception is raised that is not handled otherwise, and the <except
suite> is executed, with <name> bound to the exception, if found ; if no
matching except suite is found then unnamed except suite is executed.

finally Block
The finally block is a part of the try-except block in Python that contains the
code that is executed regardless of whether an exception is raised or not. The
syntax of the try-except-finally block is as follows:

the try block contains the code that may raise an exception. If an exception
occurs, the control is transferred to the corresponding except block, which
contains the code to handle the exception. The finally block contains the code
that is executed after the try-except blocks, regardless of whether an exception
occurred or not.
Example :Program using finally block

Example :Program using finally an else block together

In this example, if the user enters an invalid input or attempts to divide by zero,
the corresponding except block handles the exception and prints an error
message to the user. If no exception occurs, the else block is executed and prints
the result. Finally, the finally block is executed and prints a message to indicate
the completion of the program execution.
What Is File Handling In Python?
Files are named location on the disk used to store data permanently. Files are
non-volatile in nature. Python offers a wide range of methods to handle the files
stored on the disk, we can perform various operation like reading, writing,
editing files stored in computer permanent storage though python programs.

File Handling Steps


1. Open the File

2. Process the file (Read/write/append)

3. Close the file

4. Opening a file:

Opening A File

To perform any kid of operation on a file, the programmer first need to open the
file by using open() method.

Syntax:

<file_object_name>=open(<filename>,<mode>)

File Pointer: File pointer/file handler is reference to the file on the disk which is
being opened.
File Path: The Location of the file on the disk

File Access Mode: This specifies the nature of operation(read/write/append) to


be performed on the file.

File Access Modes

Read Mode: when a file is opened in read mode then the file must exist,
otherwise python will raise an I/O error.

Write Mode: When a file is opened in write mode and if the file does not exist
then a new file will be created at the specified location on the disk with the same
name. If the file exist on the disk, then the file will be truncated, the user can
overwrite new data into the file.

Append Mode: When a file is opened in append mode and if the file does not
exist then a new file will be created at the specified location on the disk with the
same name. If the file exist on the disk, then the file’s exixting data will be
retained and new data can be appended at the end of the file.

Closing a File

The close() method is used to close an opened file, the execution of close()
method breaks the reference of the file object to file on disk, so after execution
of close() method no operation on the file can be performed, without reopening
the file.

Syntax: <fileHandle>.close()
Closing a
file

File Handling and File Types


Python offers wide range of modules/methods to perform file handling operation
on both Text File and Binary File

Text File:

Text files stores the information on the file as sequence of ASCII or Unicode
characters. These files can be open in any text editor in a human readable form.

Binary File:

Binary files stores information as a sequence of bytes, Binary files stores the
information in the same format as it is stored in the memory.

Text File Handling:

Reading a Text File:

We can use any of these 3 methods/functions In order to perform read operation


on a text file:

read([n])

readline([n])

readlines()

read() method:
read() function is used to read contents of a text file and returns the result as a
string. If invoked with argument n it returns n number of bytes(characters) from
file.

Syntax:

<file_object>.read([n])

#program to read a text file

f=open(“C:\\myfolder\\cs.txt”, “r”)

data=f.read()

print(data)

f.close()

#program to read first n characters of a text file

n=int(input(“Enter no of chracetr you want to read” ))

f=open(“C:\\myfolder\\cs.txt”, “r”)

data=f.read(n)

print(data)

f.close()

readline() method:

This function is used to read a line of input text file and returns the result as a
string. If argument n specified then reads at n bytes(characters) of the current
line.

Syntax:

<file_object>.readline([n])

#program to read first 2 lines of a text file

f=open(“C:\\myfolder\\cs.txt”, “r”)

line1=f.readline()

print(line1)
line2=f.readline()

print(line2)

f.close()

readlines() method:

This function is reads all the line of the input text file and returns each line as
string encapsulated inside a List.

Syntax:

<file_object>.readlines()

#program to read a text file using readlines()

f=open(“C:\\myfolder\\cs.txt”, “r”)

data=f.readlines()

print(data)

f.close()

Writing into a Text File:

Python provides these two functions for writing into a text file

#program to write a string into a text file

f=open(“C:\\myfolder\\new.txt”,”w”)

f.write(“Programming is fun”)

f.close()

#program to write multiple lines into a text file using writeline()


L=[“programming is fun”, ”lets start writing python programs” ]

f=open(“C:\\myfolder\\new.txt”,”w”)

f.writeline(L)

f.close()

Appending into a Text File:

When a file is opened in append mode, then new data can be added into the file
without erasing the existing old data in the file, the new data will be appended at
the end of the existing data. To open a file append mode, file mode need to be
set as append “a” while executing open() method.

#program to append a string into a text file

f=open(“C:\\myfolder\\new.txt”,”a”)

f.write(“Lets start programming”)

f.close()

Binary File Handling

Binary files can store more structed python objects like list, tuple, dictionary by
converting these objects into byte stream( called serialization/pickling), these
objects can brought back to original form while reading the file (called
unpickling).

Pickle module is very useful when it come to binary file handling. We will use
dump() and load() methods of pickle module to write and read data objects into
binary files.

Writing into a binary file:

The dump() function of pickle module can be used to write an object into a
binary file.

Syntax: pickle.dump( <object_to_be_witten>, <filehandle>)

#Program to write a tuple object into the binary file using dump() method

import pickle
f=open(‘csSubjects.dat’, ’wb’)

tup1=(“AI”,”Networking”,”DBMS”,”Python” )

pickle.dump(tup1,f)

f.close()

Reading a binary file

To read from a binary file the load() method of the pickle module can be used.
This method unpickles the data from the binary file(convert binary stream into
original object structure).

Syntax: <object>=pickle.load(<filehandle>)
#program to read objects from a binary file using load() method

import pickle

f=open(‘cs.dat’,’wb’)

d={“name”:”amit”,”roll”:20,”mark”:320}

pickle.dump(d,f)

header=Pickle.load(f)

sdata=pickle.load(f)

print(”Name:”,sdata[name])

print(”Roll No:”,sdata[roll])

print(”Mark:”,sdata[mark])

f.close()

Writing into Binary File (Example Program )

#program to write details(name, rollno, mark) of n number of students into a binary


file

import pickle

f=open(“C:\\myfolder\\students.dat”,”wb”)

n=int(input(“Enter how many students details you want to enter” ))


for i in range(n):

name=input(“Enter students name:”)

roll=int(input(“Enter students Roll No:”))

mark=int(input(“Enter students Mark:”))

data={“Name”:name,”RollNo”:roll,”Mark”:mark }

f.dump(data,f)

print(“Details of ”,n,” number of students saved successfully” )

f.close()

Reading from Binary File (Example Program )

#Program to read the details of all students in the binary file Students.dat created in
the last example

import pickle

f=open(“C:\\myfolder\\students.dat”,”rb” )

print(“*******Students Details*********” )

while True:

try:

data=pickle.load(f)

print(“Name:”,data[”Name”])

print(“Roll Number:”,data[”RollNo”])

print(“Mark:”,data[”Mark”])

except EOFError:

print(“Reached end of the file”)

break

f.close()
Performing Search operation on a Binary File (Example Program )

#Program to search the details of students based on students Roll Number

import pickle

f=open(“C:\\myfolder\\students.dat”,”rb” )

sroll=int(input(“Enter the Roll Number of the student” ))

found=False

print(“*******Student Details*********” )

while True:

try:

data=pickle.load(f)

if data[“RollNo”]==sroll:

found=True

print(“Name:”,data[“Name”])

print(“Roll Number:”,data[”RollNo”])

print(“Mark:”,data[“Mark”])

except EOFError:

break

If found==False:

print(“Data not found”)

f.close()

Append into a Binary File (Example Program )

#Program to append details of a new student into the binary file Student.dat

import pickle

f=open(“C:\\myfolder\\students.dat”,”ab”)
name=input(“Enter students name:”)

roll=int(input(“Enter students Roll No:”))

mark=int(input(“Enter students Mark:”))

data={“Name”:name,”RollNo”:roll,”Mark”:mark }

f.dump(data,f)

f.close()

Update a Binary File (Example Program )

#Program to update mark of a student in the the binary file Student.dat

import pickle

f=open(`C:\\myfolder\\students.dat’,`rb’)

alldata=[]

sroll=int(input(`Enter the Roll Number of the student:’ ))

newmark=int(input(`Enter the Mark to be updated: ‘ ))

while True:

try:

sdata=pickle.load(f)

alldata.append(sdata)

except EOFError:

break

f.close()

for record in alldata:

if record[`RollNo’]==sroll:

record[`Mark’]=newMark

f=open(`C:\\myfolder\\students.dat’,`rb’)
for record in alldata:

pickle.dump(record)

f.close()

Comma Separated File (CSV) File Handling

CSV stands for “Comma Separated Values.” It is used to store data in a tabular
form in a text file. The fact that CSV files are actually text files, It becomes very
useful to export high volume data to a database or to a server.

Structure of a .csv file


Reading/Writing operations on a CSV file can be performed using the csv
module of python. to use the methods of csv module we have to import the csv
module into our program.

Writing into a csv File

As csv file is basically a text file, to write into a csv file mode “w” must be
specified along with the file path in the open() method to open the file.

f=open(`C:\\myfolder\\new.csv’,`w’)

After the the file is being open and a file handle is created, we need to create a
writer object using writer() method.

<writerObject>=csv.writer(<fileHandle>)

The writerow() method can be used to write a List object into the csv file.
<writerObject>.writerow(<[List]>)

#program to write four rows into csv file

import csv

f=open(`C:\\myfolder\\new.csv’,`w’)

writer1=csv.writer(f)

Writer1.writerow([`Name’,`Class’,`Mark’])

Writer1.writerow([`Amit’,12,450)

Writer1.writerow([`Sahil’,12,460])

Writer1.writerow([`Anjali’,11,410)

f.close()

Reading From a csv File

To read data from a csv file, the file need to opened in the same way as any text
file

( Note: The file extension is .csv)

f=open(`C:\\myfolder\\new.csv’,`r’)

After the the file is being open and a file handle is created, we need to create a
reader object using reader() method.

<readerObject>=csv.reader(<fileHandle>)

Once created, a reader object carries all data from the referenced csv file.

#program to read a csv file

import csv

f=open(`C:\\myfolder\\new.csv’,`r’)

reader1=csv.reader(f)

for record in reader1:

print(record)

f.close()
What is Data Structure?
A data structure is not only used for organizing the data. It is also used for
processing, retrieving, and storing data. Different basic and advanced types of
data structures are used in almost every program or software system that has been
developed. So we must have good knowledge of data structures.
Data structures are an integral part of computers used for the arrangement of
data in memory. They are essential and responsible for organizing, processing,
accessing, and storing data efficiently.

Classification of Data Structure:


Data structure has many different uses in our daily life. There are many different
data structures that are used to solve different mathematical and logical problems.
By using data structure, one can organize and process a very large amount of data
in a relatively short period. Let’s look at different data structures that are used in
different situations.

 Linear data structure: Data structure in which data elements are


arranged sequentially or linearly, where each element is attached to
its previous and next adjacent elements, is called a linear data
structure.
Examples of linear data structures are array, stack, queue, linked
list, etc.

 Non-linear data structure: Data structures where data elements are


not placed sequentially or linearly are called non-linear data
structures. In a non-linear data structure, we can’t traverse all the
elements in a single run only.
Examples of non-linear data structures are trees and graphs.

Stack:
Stack is a linear data structure that follows a particular order in which the
operations are performed. The order is LIFO(Last in first out) . Entering and
retrieving data is possible from only one end. The entering and retrieving of data
is also called push and pop operation in a stack. There are different operations
possible in a stack like reversing a stack using recursion, Sorting, Deleting the
middle element of a stack, etc.
Push and Pop Operation in Stack in Data
Structure
The Last-In-First-Out (LIFO) concept is used by Stacks, a type of linear data structure. The
Queue has two endpoints, but the Stack only has one (front and rear). It only has one pointer, top
pointer, which points to the stack's topmost member. When an element is added to the stack, it is
always added to the top, and it can only be removed from the stack. To put it another way, a stack
is a container that allows insertion and deletion from the end known as the stack's top.

LIFO (Last in First Out)


According to this method, the piece that was added last will appear first. As an actual illustration,
consider a stack of dishes stacked on top of one another. We may claim that the plate we put last
comes out first because the plate we put last is on top and we take the plate at the top.

Due to the possibility of understating inventory value, LIFO is not a reliable indicator of ending
inventory value. Due to increasing COGS, LIFO leads to reduced net income (and taxes).
However, under LIFO during inflation, there are fewer inventory write-downs. Results from
average

push()
It stacks up a new item. A stack overflow circumstance is when the stack is completely full.

Algorithm for push():


push()
It stacks up a new item. A stack overflow circumstance is when the stack is completely full.

Algorithm for push():

1. begin
2. if stack is full
3. return
4. endif
5. else
6. increment top
7. stack[top] assign value
8. end else
9. end procedure

pop()
It takes something out of the stack. In the opposite sequence from which they were pushed, the
things are popped. The condition is referred to as an underflow if the stack is empty.

Algorithm for pop():

1. begin
2. if stack is empty
3. return
4. endif
5. else
6. store value of stack[top]
7. decrement top
8. return value
9. end else
10. end procedure

Push Operation Using List in Python


In this operation, we push data to the stack which is implemented by a list. As we
all know stack data structure follows the LIFO principle i.e., Last in First Out.

# Created a Empty List


stack = []
# Pushing the elements in the list
stack.append(1)
stack.append(2)
stack.append(3)

print(“The Stack items are:”)


for i in stack:
print(i)
Output
The Stack items are :
1
2
3

Pop Operation Using List in Python


The pop Operation in stack use to remove the last element from the stack. Here,
we will use pop() function to perform pop operation in list. If the stack is empty it
return none.

stack = []

def pop(stack):
if len(stack) == 0:
return None
else:
return stack.pop()

# Pushing the elements in the list


stack.append(1)
stack.append(2)
stack.append(3)

print(“Initial Stack:”)
print(stack)

print(“Popped Element:”, pop(stack))

Output

Initial Stack
[1, 2, 3]
Popped Element: 3
UNIT II

Evolution of networking
A Computer Network is a group of computers and other devices, such as printers,
scanners, and servers, that are connected together by a transmission media to
share resources and communicate with each other.

The evolution of computer networks started with the development of


the ARPANET (Advanced Research Projects Agency Network) in the 1960s. It
was the first packet-switching network and was developed by the U.S.
Department of Defence. ARPANET was initially used for military purposes, but
later it was opened up for academic and research purposes.

In the 1980s, the National Science Foundation Network (NSFNET) was


developed to provide high-speed connectivity to research institutions and
universities. NSFNET played a crucial role in the development of the modern
internet.

The internet, as we know it today, evolved from ARPANET and NSFNET. It is a


global network of interconnected networks, and it enables users to communicate
and share information over long distances.

Components of Data communication


Data communication is the exchange of information between two or more devices
via some form of transmission medium. The following are the key terminologies
related to data communication:

•Sender: The device that sends the information is called the sender.

•Receiver: The device that receives the information is called the receiver.
•Message: The information being exchanged is called the message.

•Communication media: The physical medium used to transmit the message is


called the communication media

•Protocols: Protocols are rules that govern the communication between devices.

Measuring capacity of communication media


1.Bandwidth:

In computer networking, bandwidth refers to the maximum amount of data that


can be transmitted over a network in a given period of time. It is usually
measured in bits per second (bps), kilobits per second (Kbps), megabits per
second (Mbps), or gigabits per second (Gbps).

2.Data transfer rate:

Data transfer rate, also known as data rate or bit rate, is the amount of data that
can be transmitted over a network in a given period of time. It is usually
measured in bits per second (bps), kilobits per second (Kbps), megabits per
second (Mbps), or gigabits per second (Gbps).

Switching Techniques
1.Circuit switching:

In circuit switching, a dedicated communication path is established between two


devices for the duration of a communication session. This path is reserved for the
exclusive use of the devices, and no other devices can use it until the
communication session ends.
In circuit switching, the entire capacity of the communication path is reserved
for the duration of the session, even if no data is being transmitted.

Circuit switching is typically used in situations where a constant, high-quality


connection is required, such as in voice communications over a telephone
network.

2.Packet switching:

In packet switching, data is divided into small packets and transmitted over a
network. Each packet contains information about its destination, source, and
position in the sequence of packets.

Packet switching does not require the establishment of a dedicated


communication path between two devices. Instead, each packet is independently
routed through the network based on its destination address.

Transmission media:
In computer networks, Transmission media are used to transfer data between
devices. There are two main types of transmission media: wired and wireless. In
this explanation, we will discuss both wired and wireless transmission media.

Wired Transmission Media: Wired transmission media refers to the use of


physical cables or wires to transmit data between devices.

Wireless Transmission Media: Wireless transmission media refers to the use of


electromagnetic waves to transmit data between devices without physical cables.

Wired Transmission Media:

The most common types of wired transmission media are:


1.Coaxial Cable: Coaxial cable consists of a copper wire surrounded by an
insulating material, which is then surrounded by a metal shield. It is commonly
used in cable television and Ethernet networks.

2. Twisted Pair Cable: Twisted pair cable consists of two copper wires twisted
together. It is commonly used in telephone systems and Ethernet networks.

3. Fiber Optic Cable: Fiber optic cable consists of thin glass fibers that transmit
data using light signals. It is commonly used in high-speed internet connections
and long-distance communications.

Wireless Transmission Media:

Radio Waves: Radio waves are the longest wavelength and lowest frequency
electromagnetic waves. They are used for communication in various devices such
as radios, television, and cell phones. Radio waves can travel through various
materials such as air, water, and solid objects

Microwaves: Microwaves are electromagnetic waves that have shorter


wavelengths and higher frequencies than radio waves. They are commonly used
for communication purposes, such as in satellite communication, cellular
networks, and microwave ovens.

Infrared Waves: Infrared waves are electromagnetic waves that have shorter
wavelengths and higher frequencies than microwaves. They are used for
communication between devices in close proximity and are commonly used in
remote controls, heat sensing cameras, and security systems. Infrared waves
cannot pass through solid objects but can pass through certain materials such as
glass.
Network Devices

Modem: A modem is a device that converts digital signals from a computer into
analog signals that can be transmitted over telephone lines. It is used to connect
a computer to the internet or other remote networks. Modems can be either
internal or external and come in various types, such as dial-up, cable, and DSL.

Ethernet Card: An Ethernet card, also known as a network interface card (NIC),
is a hardware component that allows a computer to connect to a local area
network (LAN) or wide area network (WAN). It is responsible for sending and
receiving data packets over the network. Ethernet cards can be either integrated
into a computer’s motherboard or added as an expansion card.

RJ45: RJ45 is a type of connector used to connect Ethernet cables to network


devices. It is the most common type of connector used in Ethernet networks and
can be found on Ethernet cards, switches, and routers.
Repeater: A repeater is a network device that regenerates and amplifies network
signals to extend the distance that signals can travel without loss of data. It is
used to extend the range of a network by amplifying signals and sending them to
the next network device.

Hub: A hub is a network device that connects multiple devices in a LAN. It


operates by receiving data from one device and broadcasting it to all other
devices connected to it.

Switch: A switch is a network device that connects multiple devices in a LAN. It


operates by forwarding data packets only to the device it is intended for,
reducing network congestion and improving performance. Switches are more
efficient than hubs.
Router: A router is a network device that connects multiple networks together,
such as LANs or WANs. It is responsible for forwarding data packets between
networks based on their destination addresses

Gateway: A gateway is a network device that connects two or more different


networks, such as a LAN and the internet. It acts as a bridge between networks
and is responsible for translating data between different protocols and formats.

WiFi Card: A WiFi card, also known as a wireless network card or wireless
adapter, is a hardware component that allows a computer to connect to a wireless
network.

Network Topologies
A Topology refers to the arrangement of nodes (computers, servers, printers,
etc.) and connections in a network. There are several types of network
topologies, including bus, star, and tree topologies.
Bus Topology: In this type of topology, all devices are connected to a single
backbone cable. The data is transmitted from one device to another in a linear
fashion. The bus topology is simple to set up and cost-effective but it can be
prone to signal reflection and collisions.

Star Topology: In a star topology, all devices are connected to a central hub or
switch. The hub acts as a central point of communication, and all data
transmitted between devices passes through the hub. This topology is easy to
manage and troubleshoot because each device connects directly to the central
hub. However, the failure of the hub can result in the failure of the entire
network.
Tree Topology: A tree topology is a combination of bus and star topologies. In
this type of topology, groups of star topologies are connected together in a bus
configuration. This allows for more devices to be connected to the network, and
provides a greater level of redundancy in case of device failure. However, it can
be complex to set up and manage.

Network Types
Personal Area Network (PAN): A PAN is a network that connects devices
within a short range, typically centered around an individual person. It is used
for connecting personal devices like smartphones, tablets, laptops, and peripheral
devices such as headphones, printers, and wearable gadgets.

Local Area Network (LAN): A LAN is a network that connects devices within a
limited geographical area, such as a home, office, or school building. LANs
typically use wired connections like Ethernet cables or wireless connections like
Wi-Fi for data transmission

Metropolitan Area Network (MAN): A MAN is a network that covers a larger


geographical area, such as a city or a town.

Wide Area Network (WAN): A WAN is a network that spans a vast


geographical area, such as a country or even the entire world. It connects
multiple LANs or MANs, typically using high-speed communication links like
leased lines, satellite connections, or fiber-optic cables. The Internet is the most
prominent example of a WAN.
Network protocol:

1.HTTP (Hypertext Transfer Protocol): It is an application-level protocol used


for transmitting data over the internet. HTTP is the foundation of data
communication for the World Wide Web (WWW). It is used by web browsers to
communicate with web servers.

2.FTP (File Transfer Protocol): It is an application-level protocol used for


transferring files between client and server computers over a network. FTP is
used to upload and download files from a remote server.

3.PPP (Point-to-Point Protocol): It is a data link layer protocol used to


establish a direct connection between two nodes in a network. PPP is commonly
used in dial-up connections and VPNs.

4.TCP/IP (Transmission Control Protocol/Internet Protocol): It is a suite of


protocols used for communication between devices over the internet. TCP is
responsible for the reliable transmission of data, and IP is responsible for the
routing of data packets.
5.SMTP (Simple Mail Transfer Protocol): It is an internet standard protocol
used for email transmission. SMTP is responsible for sending emails from a mail
client to a mail server.

6.POP3 (Post Office Protocol version 3): It is an application-level protocol


used for retrieving emails from a remote mail server. POP3 is used by mail
clients to download emails from a mail server.

7.TELNET (Teletype Network): It is a protocol used for remote login to a


computer over a network. TELNET allows users to remotely access another
computer’s command-line interface.

8.HTTPS (Hypertext Transfer Protocol Secure): It is an extension of HTTP


that adds security features, such as encryption and authentication, to ensure
secure communication over the internet.

9.VoIP (Voice over Internet Protocol): It is a protocol used for transmitting


voice and multimedia over the internet. VoIP allows users to make voice and
video calls over the internet.
UNIT III
Database Concepts

What is a Database?
Database is a systematic collection of organized data or information typically
stored on a electronic media in a computer system. With database data can be
easily accessed, managed, updated, controlled and organised.

Many website on the world wide web widely use database system to store and
manage data (commonly referred as backend).

Advantages of Database
Minimize Data Redundancy: In traditional File processing system same piece
of data may be held in multiple places resulting in Data redundancy
(duplicacy). Database system minimizes redundancy by data normalization.

Increased Data consistency: When multiple copies of same data do not match
with one another is called as data inconsistency.

Data Security: Database allows only the authorized user to access data in the
database.

Data Sharing: Database allow its users to share data among themselves.

Data Integrity: Data in the database accurate and consistent.

Database Management System (DBMS)


A DBMS refers to a software that is responsible for storing, maintaining and
utilizing database. Some examples of the popular database software include
MySQL, Microsoft Access, Microsoft SQL Server, FileMaker Pro, Oracle
Database, and dBASE.

Data Model:
A data model is the way data is organised in a database. There are different types
data models controls the representation of data in a database, these are:

•Relational Data model

•Network Data Model


•Hierarchical Data Model

•Object Oriented Data Model

The Relational data Model is far being used by most of the popular Database
Management Systems. In his course we limit our discussion on Relational data
model.

Relational Data Model


In Relational data model data is organized into tables( rows and columns).
Tables in a relational model is called as Relations. Each row of a relation
represents a relationship between all the values in the row.

Relational Database:
A relational database is collection of multiple data sets organised as tables. A
relational database facilitates users to organize data in a well defined
relationship between database tables/relations. It uses Structured Query
Language(SQL) to communicate with the database and efficiently maintain data
in the database.

Relation & Associated Terminologies

Relational Database Terminologies


Tuple/Record: In Relational Database, rows in the Relation/Table are referred
as records

Attributes/Fields: Columns are referred as Attributes/Fields.

Cardinality: Total number of records in the relation is called as its Cardinality.


Degree: Total number of Attributes/Fields in the relation is called as its Degree.

Domain: permitted range of values of an attribute for an entity.

Primary key: The attribute or the set of attributes that uniquely identifies
records in a relation is called as the Primary key of the Relation.

Types of Keys:
Candidate Key: A Candidate key is a attribute/set of attributes that uniquely
identifies tuples in a relation. A relation may be more then one candidate key.

Primary Key: A Primary key is a attribute/set of attributes that uniquely


identifies tuples in a relation. All the values in the primary Key need to be
unique and NOT NULL.

Among all the candidate keys the Database Administrator(DBA) selects one as
Primary key. A relation may have multiple Candidate Keys but ONLY ONE
Primary Key.

Alternate Key: A alternate is basically is/are those candidate key which is/are
not used as Primary key of the relation.

Foreign Key: Foreign key is a attribute of a relation(called as Child table) that


refers to the Primary Key of another relation(called as parent table).

Structured Query Language (SQL)

What is a Structured Query Language (SQL)?


SQL is a standard language for storing, retrieving and manipulating data on a
relational database. All the relational database like MySql, Oracle, MS Access,
SQL server uses Structured query language(SQL) for accessing and manipulating
data.

SQL provides wide range of effective command to perform all sort of required
operations on data such as create tables, insert record, view recodes, update,
alter, delete, drop, etc.

What is DDL and DML?


All the SQL commands are categorized into five categories:
DDL,DML,DCL,DQL,TCL. In this course we are going to cover only DDL and
DML commands in detail.
Data definition Language(DDL): Data Definition Language actually consists of
the SQL commands that can be used to define the database schema. It simply
deals with descriptions of the database schema and is used to create and modify
the structure of database objects in the database. Example: Create, Drop, Alter,
Truncate.

Data Manipulation Language(DML): The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data
Manipulation Language and this includes most of the SQL statements. Example:
Insert, Delete, Update.

Data Types in MySQL


Data stored in a database table are of different types, As SQL developers we
have chose the suitable data types for each field while defining a table. SQL
offers supports a wide range of data types from which the developer can choose
the most appropriate data types for each column.

char(size): used for fixed length string data.

Example: A column defined as char(10) , it can contain string values of


maximum 10 length. SQL allocates 10 bytes of memory irrespective of legth of
data to be stored.

varchar(size): used for variable length string data.

Example: If a column defined as varchar(10) , SQL allocates maximum 10 bytes


to each value, but bytes allocated may vary depending on the length of data.

int( ): Used for integer/digits data without decimal. Can accommodate maximum
11 digit numbers.

float(M,D): Permits real numbers upto M digits, out of which may be D digits
after decimal .

Example: a column data type defined as float(6,3) may have 234.684

Date: used to store date in YYYY-MM-DD format.

Constraints In SQL
constraints are used to specify rules for the data in a table. Commonly used
constraints are:

Not Null- Ensures that a column cannot have a NULL value

Unique- Ensures that all values in a column are different


Primary Key- A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table

Foreign Key- Prevents actions that would destroy links between tables

Check – Ensures that the values in a column satisfies a specific condition

Default- Sets a default value for a column if no value is specified

MySql Commands
CREATE Database: Used to create a new database.

Syntax: CREATE DATABASE <database name>

e.g. CREATE Database MySchool;

SHOW Databases: Used to list all existing databases.

Syntax: SHOW Databases;

DROP Database: Used to delete an existing database.

Syntax: DROP Database <databasename>

e.g. DROP Database MyStore;

USE Database: Used to select/enter a existing database.

e.g. USE MySchool;

Show Tables: After a database has been selected this command can be Used to
list all the tables in the database. e.g. SHOW TABLES;

CREATE Table:

Syntax: CREATE TABLE <table name>( column1 datatype,


column2 datatype,

……..

columnN datatype,

PRIMARY KEY( one or more columns ) );

E.g. CREATE TABLE cs_students(sid int(3), sname varchar(30), sclass int(2),


smark int(3), skill varchar(30), primary key(sid));

Creating a table with multiple constraints:

CREATE TABLE Employee (Eid int(5) Primary Key,

Ename varchar(30) Not Null,

age int(2),

Dept varchar(20) Default “Manufacturing”,

contactno int(10) unique,

Constraint ChkAge Check(Age>18));

DESCRIBE Tables: A DDL command to display the structure of the table.

Syntax: DESCRIBE <table name>;


ALTER Tables:

ALTER TABLE is a DDL command that can change the structure of the table.
Using ALTER TABLE command we can add, delete or modify the
attributes/constraints of a table.

Adding a column using Alter table:

Syntax: ALTER TABLE <table name> ADD column <Column Name Data
type>;

Deleting a column using Alter table:

Syntax: ALTER TABLE <table name> DROP column <Column Name >;

Modify a column using Alter table:

Syntax: ALTER TABLE <table name> MODIFY column <Column Name Data
type>;

E.g. MODIFY the data type of an existing column


Adding a Primary Key Constraint using Alter table:

Syntax: ALTER TABLE <table name> ADD Primary Key (<column names>);

Drop Primary Key Constraint using Alter table:

Syntax: ALTER TABLE <table name> DROP Primary Key;

DROP Tables: DROP TABLE is a DDL command used to delete a table from
the database.

Syntax: DROP TABLE <table name>;

E.g. DROP Table Employee;

INSERT INTO:

INSERT is a DML command used to insert a new record/row in an existing


table.

Syntax: INSERT INTO <Table Name> values (val1,val2,val3..);

Insert a new record in the table with specific field value.

Syntax: INSERT INTO <Table Name> (Column1,Column2,..ColumnN) values


(val1,val2,..valN);

SELECT Command:
Used to retrieve and display data from the tables .

Syntax: SELECT column1, column2,..

FROM <Table Name>;

To Select all the columns from the table:

SELECT * FROM <Table Name>;

WHERE Clause:

The WHERE Clause can be used with SELECT command to select the data from
the table based on some condition.

Syntax: SELECT column1, column2,..

FROM <Table Name>

WHERE <condition>;

Operators That Can Be Used In Where Clause :

Mathematical: +, -, *, /

Relational: >, >=, <, <=, =, <>


Logical: AND, OR, NOT

E.g. Select * From cs_students WHERE smark>90;

To select ID and Name of the students whose skill is Database:

Using Logical Operators in Where clause:

IN Operator: Used To specify multiple possible values for a column


E.g. Select * from cs_student where skill in(“Networking”, ”Database”);

BETWEEN Operator: Used To specify values in a certain range.

E.g. Select * from cs_student where smark BETWEEN 95 AND 100;

DISTINCT Clause: Used to retrieve the distinct values in a field.

Syntax: Select * from student where mark is null;


ORDER BY: It is used to sort the data in ascending or descending order.

By default ORDER BY sort the data in ascending order, for descending order we
need to use ”DESC”.

Handling NULL Values: To handle NULL entries in a field we can use “IS” and
“IS NOT”, as NULL value is a Value which is Unknown so we can use =, <>
operators to select NULL values.
Lets Consider the Employee table above, to select all the employees whose
salary is specified as NULL in the salary field we must use IS NULL operator.

LIKE OPERATOR

LIKE is used for string matching in MySql, it can be used for comparison of
character strings using pattern. LIKE uses the following two wildcard characters
to create string patterns.

•Percent(%): used to match a substring of any length.


•Underscore( _ ): Used to match any single character.

The LIKE keyword selects the rows having column values that matches with the
wildcard pattern.

Update Command

UPDATE is a DML command used to change values in the rows of a existing


table. It specifies the rows to be changed using WHERE clause and the new
values to be updated using SET keyword.

Syntax: UPDATE <Table Name> SET column=<new value> WHERE


<condition>

E.g. To change the salary to 70000 of the employee having Eid 204.

UPDATE employee SET salary=70000 WHERE Eid=204.

To change the Department of an employee

UPDATE employee SET Dept=“Marketing” where Ename=“Kunal”;


Delete Command :

Delete is a DML command used to delete rows of an existing table. It specifies


the rows to be deleted using WHERE clause.

Syntax: DELETE FROM <Table Name> WHERE <condition;

To delete the record/row of the employee having Eid 204.

DELETE FROM employee WHERE Eid=204;

To delete the records of all the employee working in Sales Department.

DELETE FROM employee WHERE Dept=“salary”;

To delete all rows of employee table

DELETE FROM employee;


Aggregate Functions :
MySql supports the following aggregate/multiple row functions:

•count( ): returns the number of rows in the given column or expression.

•min( ): returns the minimum value in the given column or expression.

•max( ): returns the maximum value in the given column or expression.

•sum( ): returns the sum of values in the given column or expression.

•avg( ): returns the average of values in the given column or expression.

Let us Consider the employee table:

SELECT sum(salary) FROM employee;

Result: 80000

SELECT avg(salary) FROM employee;

Result: 26666.6666

SELECT max(salary) FROM employee;

Result: 32000

SELECT min(salary) FROM employee;

Result: 23000
SELECT count(salary) FROM employee;

Result: 3

SELECT count(*) FROM employee;

Result: 5

GROUP BY:
•GROUP BY clause combines all those records that have identical values in a
particular field or a group of fields.

•It is used in SELECT statement to divide the table into groups. Grouping can be
done by a column name or with aggregate functions.

For Example let us consider the cs_students table,

To find the number of students in each skill, we can use the command.

SELECT skill, count(*) from cs_students GROUP BY skill;


Let us now consider the Employee Table

To find the average salary of employees of each department, we can use the
command.

SELECT dept, avg(salary) from employee GROUP BY dept;

HAVING Clause:
HAVING clause is used to apply conditions on groups in contrast to WHERE
clause which is used to apply conditions on individual rows.

Let us consider the cs_students table,


To find the average marks of the group of students having a particular skill ,
where the skill group must have at least 5 students.

SELECT skill, avg(smark) FROM cs_students GROUP BY skill HAVING


count(*)>=5;

Let us consider the employee table,


To find the average salary of employees of each department, where the average
age of all the employees working in the department is less then 32.

SELECT dept,avg(salary) FROM employee GROUP BY dept HAVING


avg(age)>32;

JOIN:
A JOIN clause combines rows from two or more tables. In a join query, more
then one table are listed in FORM clause.

Types of Join Operation:

•Cartesian product on two tables,

•Equi-join

•Natural join

Cartesian Product (X):

The Cartesian Product operation of two tables produces all possible


concatenations of all the rows of both tables.

The Cartesian product(also known as Cross Join) multiplies all rows present in
the first table with all the rows present in the second table
Syntax: SELECT * FROM Table1,Table2;

Or

SELECT * FROM Table1 CROSS JOIN Table2;

The Cardinality of cartesian product of two relations R1 and R2 is equal to the


multiplication of cardinalities of R1 and R2. Whereas The Degree of cartesian
Product is equal to addition of degrees of R1 and R2.

Cartesian Product (X) Example:

Let us Consider the Cartesian Product/Cross Join the of following Customer and
Order Tables

Equi Join :

To perform Equi/Inner Join on two relations R1 and R2, we have to specify a


equality condition using the common attribute in both the relations R1 and
R2. Syntax: SELECT * FROM R1 Inner Join R2.
Natural Join :

The Join in which only one of the identical columns(coming from joined tables)
exists, is called as Natural Join.

The Equi Join and Natural join are equivalent except that duplicate columns are
eliminated in the Natural Join that would otherwise appear in Equi Join.

Syntax: SELECT * FROM Table1 Natural Join Table2


JOIN Examples:

You might also like