12th CS
12th CS
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.
Modularity: Functions helps to divide the entire code of the program into
separate blocks, where each block is assigned with a specific task.
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
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.
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:
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
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
(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
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’
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 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.
Syntax:
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
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.
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
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
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.
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])
f=open(“C:\\myfolder\\cs.txt”, “r”)
data=f.read()
print(data)
f.close()
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])
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()
f=open(“C:\\myfolder\\cs.txt”, “r”)
data=f.readlines()
print(data)
f.close()
Python provides these two functions for writing into a text file
f=open(“C:\\myfolder\\new.txt”,”w”)
f.write(“Programming is fun”)
f.close()
f=open(“C:\\myfolder\\new.txt”,”w”)
f.writeline(L)
f.close()
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.
f=open(“C:\\myfolder\\new.txt”,”a”)
f.close()
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.
The dump() function of pickle module can be used to write an object into a
binary file.
#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()
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()
import pickle
f=open(“C:\\myfolder\\students.dat”,”wb”)
data={“Name”:name,”RollNo”:roll,”Mark”:mark }
f.dump(data,f)
f.close()
#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:
break
f.close()
Performing Search operation on a Binary File (Example Program )
import pickle
f=open(“C:\\myfolder\\students.dat”,”rb” )
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:
f.close()
#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:”)
data={“Name”:name,”RollNo”:roll,”Mark”:mark }
f.dump(data,f)
f.close()
import pickle
f=open(`C:\\myfolder\\students.dat’,`rb’)
alldata=[]
while True:
try:
sdata=pickle.load(f)
alldata.append(sdata)
except EOFError:
break
f.close()
if record[`RollNo’]==sroll:
record[`Mark’]=newMark
f=open(`C:\\myfolder\\students.dat’,`rb’)
for record in alldata:
pickle.dump(record)
f.close()
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.
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]>)
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()
To read data from a csv file, the file need to opened in the same way as any text
file
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.
import csv
f=open(`C:\\myfolder\\new.csv’,`r’)
reader1=csv.reader(f)
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.
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.
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.
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.
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
stack = []
def pop(stack):
if len(stack) == 0:
return None
else:
return stack.pop()
print(“Initial Stack:”)
print(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.
•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.
•Protocols: Protocols are rules that govern the communication between devices.
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:
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.
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.
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.
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
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.
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
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 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:
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 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.
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.
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.
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.
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.
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 .
Constraints In SQL
constraints are used to specify rules for the data in a table. Commonly used
constraints are:
Foreign Key- Prevents actions that would destroy links between tables
MySql Commands
CREATE Database: Used to create a new database.
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:
……..
columnN datatype,
age int(2),
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.
Syntax: ALTER TABLE <table name> ADD column <Column Name Data
type>;
Syntax: ALTER TABLE <table name> DROP column <Column Name >;
Syntax: ALTER TABLE <table name> MODIFY column <Column Name Data
type>;
Syntax: ALTER TABLE <table name> ADD Primary Key (<column names>);
DROP Tables: DROP TABLE is a DDL command used to delete a table from
the database.
INSERT INTO:
SELECT Command:
Used to retrieve and display data from the tables .
WHERE Clause:
The WHERE Clause can be used with SELECT command to select the data from
the table based on some condition.
WHERE <condition>;
Mathematical: +, -, *, /
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.
The LIKE keyword selects the rows having column values that matches with the
wildcard pattern.
Update Command
E.g. To change the salary to 70000 of the employee having Eid 204.
Result: 80000
Result: 26666.6666
Result: 32000
Result: 23000
SELECT count(salary) FROM employee;
Result: 3
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.
To find the number of students in each skill, we can use the command.
To find the average salary of employees of each department, we can use the
command.
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.
JOIN:
A JOIN clause combines rows from two or more tables. In a join query, more
then one table are listed in FORM clause.
•Equi-join
•Natural join
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
Let us Consider the Cartesian Product/Cross Join the of following Customer and
Order Tables
Equi 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.