Class 12 CDF
Class 12 CDF
VARIABLES
One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value
ASSIGNMENT STATEMENTS
An assignment statement creates a new variable and gives it a value:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.141592653589793
Multiple Assignments
Python allows you to assign a single value to several variables simultaneously
a=b=c=1
a, b, c = 1, 2, "john"
VARIABLE NAMES
A variable is basically a name that represents (or refers to) some value. Variable are reserved
memory locations to store values.
KEYWORDS
Keywords are the reserved words in Python. We cannot use keywords as variable name,
function name or any other identifier. They are used to define the syntax and structure of the
Python language. In Python, keywords are case sensitive. Python 3 has these keywords:
Page 1 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
PYTHON OPERATORS
Operators are the constructs which can manipulate the value of operands
Types of Operators
1) Arithmetic Operators
2) Comparison (Relational) Operators
3) Assignment Operators
4) Logical Operators
5) Membership Operators
6) Identity Operators
Page 2 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 3 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 4 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Errors
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them
Exception Handling.
Assertions.
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions.
An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits
Page 5 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
PYTHON – CONDITIONALS
Decision making is anticipation of conditions occurring while execution of the program and specifying
actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to
determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise
conditional (if)
alternative (if…else)
Page 6 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
REASSIGNMENT
As you may have discovered, it is legal to make more than one assignment to the same variable. A new
assignment makes an existing variable refer to a new value (and stop referring to the old value)
UPDATING VARIABLES
A common kind of reassignment is an update, where the new value of the variable depends on the old.
>>> x = x + 1
While Loop - A while loop statement in Python programming language repeatedly executes a target statement
as long as a given condition is true
Syntax
while(test-condition):
body of the loop;
statement-x;
THE for STATEMENT - A for statement is also called a loop because the flow of execution runs through the
body and then loops back to the top
Syntax
for variable in sequence:
body of the loop;
statement-x;
break STATEMENT
Sometimes you don’t know it’s time to end a loop until you get halfway through the body. In that case
you can use the break statement to jump out of the loop. break is used to break out of the innermost loop.
For example, suppose you want to take input from the user until they type done. You could write:
continue STATEMENT - continue is used to skip execution of the rest of the loop on this iteration and continue
to the end of this iteration
Page 7 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
pass STATEMENT - ‚pass‛ statement acts as a place holder for the block of code. It is equivalent to a null
operation. It literally does nothing.
Page 8 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
PYTHON STRINGS - A string is a sequence, which means it is an ordered collection of other values.
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks.
Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator
Strings are immutable
Example:
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Page 9 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
String Methods
Page 10 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 11 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 12 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
str.strip(characters) removes any leading, and trailing straight =" banana "
whitespaces. Leading means at the change = straight.strip()
beginning of the string, trailing print("of all fruits", change, "is my
means at the end favorite")
of all fruits banana is my favorite
str.rstrip(characters) method removes any trailing straight =" banana "
characters (characters at the end a change = straight.rstrip()
string), space is the default trailing print("of all fruits", change, "is my
character to remove favorite")
of all fruits banana is my favorite
str.lstrip(characters) removes any leading characters straight =" banana "
(space is the default leading change = straight.lstrip()
character to remove) print("of all fruits", change, "is my
favorite")
of all fruits banana is my favorite
Page 13 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Lists
Example:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Page 14 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
List Methods
Page 15 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 16 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Tuples
Example:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete list
print (tuple[0]) # Prints first element of the list
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists
Output:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Page 17 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Tuple Methods
Page 18 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Dictionary
Example:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
Output:
This is one
This is two
{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])
Page 19 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Dictionary Methods
Page 20 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
{'brand': 'Yamaha', 'model': 'Aerox'}
popitem() Removes the last bike =
inserted key- {"brand":"Yamaha","model":"Aerox","year":2021}
value pair print(bike)
vehicle = bike.popitem()
print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
{'brand': 'Yamaha', 'model': 'Aerox'}
setdefault() returns the value of bike =
the item with the {"brand":"Yamaha","model":"Aerox","year":2021}
specified key print(bike)
vehicle = bike.setdefault("color","Blue")
print(vehicle)
print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
Blue
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021,
'color': 'Blue'}
max() get the dictionary key fruitscolor = {"Banana" : "Yellow",
with the max values "Mango" : "Green",
"Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}
maximum = max(fruitscolor,key =
fruitscolor.get)
print(maximum)
Banana
min() get the dictionary fruitscolor = {"Banana" : "Yellow",
key "Mango" : "Green",
with the min values "Apple" : "Red",
"Grapefruit" : "Pink",
"Blackberry" : "Purple",
"Sapodilla" : "Brown"}
minimum = min(fruitscolor,key =
fruitscolor.get)
print(minimum)
Sapodilla
Sorted() sort the items of the fruitscolor = {"Banana" : "Yellow",
dictionary. This "Mango" : "Green",
method returns a "Apple" : "Red",
Page 22 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 23 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Modules
A Python module can be defined as a Python program file which contains a Python code
including Python functions,class or variables.
To make use of the function in a module, you will need to import the module with an ‘import’
statement.
To import entire module, import statement is used. Import statement is also used to import
selecting modules.
you can refer to the functions by name rather than through dot notation.
Page 24 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
>>>print(math.floor(b))
−75
>>>x = math.pi
>>>print(math.floor(x))
3
pow() pow(x,y) >>>import math
This method offers to >>>x = 3
compute the power of a >>>y = 4
number and >>>print(pow(y, x))
hence can make task of 64
calculating power of a >>>print(pow(7, 2))
number easier. In this, two 49
types to calculate power. >>>print(pow(–3, 2))
● 9
pow (x, y) converts its >>>print(pow(–4, 3))
arguments into float and then –64
computes the power >>>print(pow(5, –2))
0.04
>>>print(math.fabs(–4.3))
4.3
sin() math.sin(x) >>>import math
This method returns the sine >>>x = 65
of value passed as argument. >>>math.sin(x)
The value passed in this 0.8268286794901034
function should be in radians. >>>print(math.sin(5.3245521))
–0.8184069203707078
>>>a = math.pi
>>>x = a/4
>>>math.sin(x)
0.7071067811865475
cos() math.cos(x) >>>import math
This method returns the >>>x=9
cosine of value passed as >>>math.cos(x)
argument. –0.9111302618846769
The value passed in this >>>math.cos(0)
function should be in radians 1.0
>>>print(math.cos(30))
0.15425144988758405
>>>math.cos(–4)
–0.6536436208636119
>>>a = math.pi
>>>math.cos(a)/2
–0.5
tan() math.tan(x) >>>import math
This method returns the >>>x=30
tangent of value passed as >>>math.tan(x)
argument. –6.405331196646276
The value passed in this >>>math.tan(0)
function should be in radians. 0.0
>>>math.tan(90)
–1.995200412208242
>>>print(math.tan(–5))
3.380515006246586
pi math.pi >>>import math
It is a mathematical constant, >>>math.pi
the ratio of circumference of a 3.1415926.....
circle to its diameter.
e math.e >>>import math
It is a mathematical constant >>>math.e
2.71828182846
Page 27 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Random Module/Functions
Python offers random module that can generate random numbers. These random modules
depend on a pseudo random number that generate function random() and this number
generates a random float number between 0.0 and 1.0.
Statistics Module
Python is a very popular language when it comes to data analysis and statistics. Python has
ability to solve the mathematical expression, statistical data by importing statistics keyword.
Statistics module was added in Python 3.4 version. Earlier version of Python cannot access this
Page 28 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
module. To access Python’s statistics functions, we need to import the functions from the
statistics module.
Page 30 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Python Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
functionname( parameters )
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses (( )).
Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the
function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return none.
SCOPE OF VARIABLES
All variables in a program may not be accessible at all locations in that program. This depends on where
you have declared a variable. The scope of a variable determines the portion of the program where you
can access a particular identifier. There are two basic scopes of variables in Python:
Page 31 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Global variables
Local variables
Example 1
Output:
Inside the function local total : 30
Outside the function global total : 0
Example 2
Output:
Inside the function local total : 30
Outside the function global total : 30
Required Arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
Example 1
def add(fn,sn):
print("sum of 2 number is",fn+sn)
Page 32 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Output:
Enter First Number: 25
Enter Second Number: 35
sum of 2 number is 60
Example 2
def add(fn,sn):
print("sum of 2 number is",fn+sn)
fn = int(input("Enter First Number: "))
sn = int(input("Enter Second Number: "))
add()
Output:
Enter First Number: 10
Enter Second Number: 20
TypeError: add() missing 2 required positional arguments: 'fn' and 'sn'
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters.
Example 1
Output:
Department : EEE
Section : A
Page 33 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Example 2
def IYear(Dept, Sec):
print ("Department :", Dept)
print ("Section :", Sec)
IYear(Dept = "EEE", Name = "A")
Output:
TypeError: IYear() got an unexpected keyword argument 'Name
Default Arguments
A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument.
Example 1
Output:
First Number : 25
Second Number : 35
First Number : 35
Second Number : 35
Note that when defining a function all the argument with default values should come at the end
Page 34 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
What is Stack?
Operations on Stack
There are mainly two types of Operation that can be done with stack.
i) Push
ii) Pop
Pop : Removal of an element from the top of the stack is called Pop.
Push and Pop Operations are done from single end called TOP
Page 35 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Underflow : It refers to a situation when one tries to pop/delete an item from an empty
stack or queue. That is stack or queue is currently having no element and still one tried
to pop an element.
1. Creating a stack
2. Push/Adding elements to the stack
3. Checking for empty stack
4. Pop/Deleting elements from a stack
5. Traversal/Displaying a stack
Stack Implementation
Write a python program to maintain book details like book code, book title and price
using stack.
#(implement push(), pop() and traverse() functions)
book=[]
def push():
bcode=input("Enter bcode ")
btitle=input("Enter btitle ")
price=input("Enter price ")
bk=(bcode,btitle,price)
book.append(bk)
def pop():
Page 36 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
if(book==[]):
print("Underflow / Book Stack in empty")
else:
bcode,btitle,price=book.pop()
print("poped element is ")
print("bcode ",bcode," btitle ",btitle," price ",price)
def traverse():
if not (book==[]):
n=len(book)
for i in range(n-1,-1,-1):
print(book[i])
else:
print("Empty , No book to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
Page 37 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Computer Networks
Types of Networks
There are various types of computer networks ranging from network of handheld devices
(like mobile phones or tablets) connected through Wi-Fi or Bluetooth within a single room to
the millions of computers spread across the globe. Some are connected wireless while others
are connected through wires. Based on the geographical area covered and data transfer rate,
computer networks are broadly categorised as:
PAN ( Personal Area Network)
LAN (Local Area Network)
MAN (Metropolitan Area Network)
WAN (Wide Area Network)
It is a network formed by connecting a few personal devices like computers, laptops, mobile
phones, smart phones, printers etc.,
All these devices lie within an approximate range of 10 metres.
A personal area network may be wired or wireless.
For example, a mobile phone connected to the laptop through USB forms a wired PAN while
two smartphones communicating with each other through Bluetooth technology form a
wireless PAN or WPAN.
It is a network that connects computers, mobile phones, tablet, mouse, printer, etc., placed
at a limited distance.
The geographical area covered by a LAN can range from a single room, a floor, an office
having one or more buildings in the same premise, laboratory, a school, college, or
university campus.
The connectivity is done by means of wires, Ethernet cables, fibre optics, or Wi-Fi.
LAN is comparatively secure as only authentic users in the network can access other
computers or shared resources.
Users can print documents using a connected printer, upload/download documents and
software to and from the local server.
Such LANs provide the short range communication with the high speed data transfer rates.
These types of networks can be extended up to 1 km.
Data transfer in LAN is quite high, and usually varies from 10 Mbps (called Ethernet) to
1000 Mbps (called Gigabit Ethernet), where Mbps stands for Megabits per second.
Ethernet is a set of rules that decides how computers and other devices connect with each
other through cables in a local area network or LAN
Page 38 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Network Devices
To communicate data through different transmission media and to configure networks with
different functionality, we require different devices like Modem,Hub, Switch, Repeater, Router,
Gateway, etc.
Modem
Modem stands for ‘MOdulator DEModulator’.
It refers to a device used for conversion between analog signals and digital bits.
We know computers store and process data in terms of 0s and 1s.
However, to transmit data from a sender to a receiver, or while browsing the internet,
digital data are converted to an analog signal and the medium (be it free-space or a physical
media) carries the signal to the receiver.
There are modems connected to both the source and destination nodes.
The modem at the sender’s end acts as a modulator that converts the digital data into
analog signals.
The modem at the receiver’s end acts as a demodulator that converts the analog signals into
digital data for the destination node to understand.
Ethernet Card
Ethernet card, also known as Network Interface Card (NIC card in short) is a network
adapter used to set up a wired network.
It acts as an interface between computer and the network.
It is a circuit board mounted on the motherboard of a computer
The Ethernet cable connects the computer to the network through NIC.
Ethernet cards can support data transfer between 10 Mbps and 1 Gbps (1000 Mbps).
Page 39 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Each NIC has a MAC address, which helps in uniquely identifying the computer on the
network.
RJ45
RJ 45 or Registered Jack-45 is an eight-pin connector that is used exclusively with Ethernet
cables for networking.
It is a standard networking interface that can be seen at the end of all network cables.
Basically, it is a small plastic plug that fits into RJ-45 jacks of the
Ethernet cards present in various computing devices.
Repeater
Data are carried in the form of signals over the cable.
These signals can travel a specified distance (usually about 100 m).
Signals lose their strength beyond this limit and become weak.
In such conditions, original signals need to be regenerated.
A repeater is an analog device that works with signals on the cables to which it is connected.
The weakened signal appearing on the cable is regenerated and put back on the cable by a
repeater.
Hub
An Ethernet hub is a network device used to connect different devices through wires.
Data arriving on any of the lines are sent out on all the others.
The limitation of Hub is that if data from two devices come at the same time, they will
collide
Switch
A switch is a networking device that plays a central role in a Local Area Network (LAN).
Like a hub, a network switch is used to connect multiple computers or communicating
devices.
When data arrives, the switch extracts the destination address from the data packet and
looks it up in a table to see where to send the packet.
Thus, it sends signals to only selected devices instead of sending to all.
It can forward multiple packets at the same time.
A switch does not forward the signals which are noisy or corrupted.
It drops such signals Cables connected to a network switch and asks the sender to resend it.
Ethernet switches are common in homes/offices to connect multiple devices thus creating
LANs or to access the Internet
Router
A router is a network device that can receive the data, analyse it and transmit it to other
networks.
A router connects a local area network to the internet.
Compared to a hub or a switch, a router has advanced capabilities as it can analyse the data
Page 40 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
being carried over a network, decide/alter how it is packaged, and send it to another
network of a different type.
For example, data has been divided into packets of a certain size. Suppose these packets are
to be carried over a different type of network which cannot handle bigger packets. In such a
case, the data is to be repackaged as smaller packets and then sent over the network
by a router.
A router can be wired or wireless.
A wireless router can provide Wi-Fi access to smartphones and other devices.
Usually, such routers also contain some ports to provide wired Internet access. These days,
home Wi-Fi routers perform the dual task of a router and a modem / switch.
These routers connect to incoming broadband lines, from ISP (Internet Service Provider),
and convert them to digital data for computing devices to process
Gateway
As the term “Gateway” suggests, it is a key access point that acts as a “gate” between an
organisation's network and the outside world of the Internet.
Gateway serves as the entry and exit point of a network, as all data coming in or going out
of a network must first pass through the gateway in order to use routing paths.
Besides routing data packets, gateways also maintain information about the host network's
internal connection paths and the identified paths of other remote networks.
If a node from one network wants to communicate with a node of a foreign network, it will
pass the data packet to the gateway, which then routes it to the destination using the best
possible route
For simple Internet connectivity at homes, the gateway is usually the Internet Service
Provider that provides access to the entire Internet.
Generally, a router is configured to work as a gateway device in computer networks.
But a gateway can be implemented completely in software, hardware, or a combination of
both.
Because a network gateway is placed at the edge of a network, the firewall is usually
integrated with it
Switching Techniques
In a network having multiple devices, we are interested to know how to connect the sender
and receiver so that one-to-one communication is possible.
One solution is to make a dedicated connection between each pair of devices (mesh
topology) or between a central device and every other device (a star topology).
However, we know that such methods are costly in case of large networks.
An alternative to this is switching whereby data is routed through various nodes in a
network.
This switching process forms a temporary route for the data to be transmitted. Two
commonly used switching techniques are — Circuit Switching and Packet Switching.
Page 41 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Circuit Switching
In circuit switching, before a communication starts, a dedicated path is identified between
the sender and the receiver.
This path is a connected sequence of links between network nodes.
All packets follow the same path established during the connection.
In earlier days, when we placed a telephone call, the switching equipment within the
telephone system finds out a physical path or channel all the way from our telephone at
home to the receiver’s telephone.
This is an example of circuit switching.
Packet Switching
In packet switching, each information or message to be transmitted between sender and
receiver is broken down into smaller pieces, called packets.
These packets are then transmitted independently through the network. Different packets
of the same message may take different routes depending on availability.
Each packet has two parts — a header containing the address of the destination and other
information, and the main message part.
When all the packets reach the destination, they are reassembled and the complete message
is received by the receiver.
Unlike circuit switching, a channel is occupied in packet switching only during the
transmission of the packet.
On completion of the transmission, the channel is available for transfer of packets from
other communicating parties.
Tips to solve technical questions based on Networking Where Server should be placed:
Server should be placed in the building where the number of computers is maximum.
1. Suggest a suitable cable layout of connection: A suitable cable layout can be suggested
in the following two ways:
(a) On the basis of Server: First, the location of the Server is found out. Server should be placed
in that building where the number of computers is maximum (according to the 80:20 rule).
After finding the server position, each building distance is compared with the Server building
directly or indirectly (taking other building(s) in between). The shortest distance is counted,
whether it is directly or indirectly calculated.
(b) On the basis of distance from each building: The distance between each building is
compared to all other buildings, either directly or indirectly. The shortest distance is calculated,
whether it is direct or through some other building.
Page 42 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 43 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
File handling
A file is a named location on a secondary storage media where data are permanently stored for later
access.
TYPES OF FILES
Computers store every file as a collection of 0s and 1s i.e., in binary form
There are mainly two types of data files — text file and binary file.
A text file consists of human readable characters, which can be opened by any text editor.
A Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents.
Text file
A text file can be understood as a sequence of characters consisting of alphabets, numbers and other
special symbols.
Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
Each line of a text file is terminated by a special character, called the End of Line (EOL).
Contents in a text file are usually separated by whitespace, but comma (,) and tab (\t) are also
commonly used to separate values in a text file.
In real world applications, computer programs deal with data coming from different sources like
databases, CSV files, HTML, XML, JSON, etc. We broadly access files either to write or read data from
it. But operations on files include creating and opening a file, writing data in a file, traversing a file,
reading data from a file and so on. Python has the io module that contains different functions for
handling files.
Opening a file
To open a file in Python, we use the open() function. The syntax of open() is as follows:
Page 44 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Closing a file
Once we are done with the read/write operations on a file, it is a good practice to close the file. Python
provides a close() method to do so. While closing a file, the system frees the memory allocated to it.
file_object.close()
Opening a file using with clause
The advantage of using with clause is that any file that is opened using this clause is closed
automatically
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode
rb Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode
r+ Opens a file for both reading and writing. The file pointer is placed at
the beginning of the file
rb+ Opens a file for both reading and writing in binary format. The file
pointer is placed at the beginning of the file
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing
wb Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing
w+ Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and
writing
wb+ Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing
a Opens a file for appending. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing
ab Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing
Page 45 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing
ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.
file_object.read(n)
To read the entire file line by line using the readline(), we can use a loop.
This process is known as looping/ iterating over a file object.
It returns an empty string when EOF is reached.
For writing to a file, we first need to open it in write or append mode. If we open an existing file in
write mode, the previous data will be erased, and the file object will
be positioned at the beginning of the file. On the other hand, in append mode, new data will be added
at the end of the previous data as the file object is at the end of the file. After opening the file, we can
use the following methods to write data in the file.
Page 46 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
write() method takes a string as an argument and writes it to the text file. It returns the number of
characters being written on single execution of the write() method.
Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.
fileObject.write(string)
to write multiple strings to a file. We need to pass an iterable object like lists, tuple, etc.
containing strings to the writelines() method.
The functions that we have learnt till now are used to access the data sequentially from a file.
But if we want to access data in a random fashion, then Python gives us seek() and tell() functions to do
so
File_object.tell()
Page 47 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
offset is the number of bytes by which the file object is to be moved. reference_point
indicates the starting position of the file object
Page 48 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
first.close()
lines()
#To read the contents of a file and display the Coming
word charcater is more than 5 Kovilpatti
def bigwords(): studying
first = open("mydetails.txt") school
big = first.readlines() roaming
count = 0 streets
for lines in big: Count of Big Words are: 6
check = lines.split()
for word in check:
if len(word) > 5:
print(word)
count = count + 1
print("Count of Big Words are: ",count)
first.close()
bigwords()
#To read the contents of a file and display the My
word charcater is less than 5 name
def shortwords(): is
first = open("mydetails.txt") Ramu
short = first.readlines() I
count = 0 am
for lines in short: from
check = lines.split() i
for word in check: am
if len(word) < 5: in
print(word) 11
count = count + 1 at
print("Count ofSshort Words are: ",count) CBSE
first.close() my
shortwords() is
in
the
Count of Sshort Words are: 17
#To read the contents of a file and display the i am studying in class 11 at CBSE school
line whose charcaters are more than 20 my hobby is roaming in the streets
def morechar():
first = open("mydetails.txt")
char = first.readlines()
for line in char:
if len(line) > 30:
print(line,end='')
first.close()
morechar()
#To Count and display the specific characters Count of Letter E or e in a File is: 5
Page 49 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 50 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
#To read the contents of a file and replace the My name at RAMU
specific word I am Coming from KOVILPATTI
def replace(): i am studying in CLASS 11 at CBSE school
first = open("mydetails.txt") my hobby at ROAMING in the streets
text = first.read()
print(text.replace('is','at'))
first.close()
replace()
Page 51 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
CSV Files
1. writer( )
2. reader( )
Both the methods return an Object of writer or reader class. Writer Object again have two methods
1. writerow( )
2. writerows( )
Page 52 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
reader( ) Methods
This function returns a reader object which will be used to iterate over lines of a given CSV file.
r_obj = csv.reader(csvfile_obj)
first.close()
How to write multiple rows in CSV File
Program Code Output:
Write a Program to add / Insert records in a file ‘insert.csv”. Structure of a record is roll_number,
name and class.
Program Code Output
Page 54 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 55 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Binary File
A binary file contains arbitrary binary data i.e. numbers stored in the file, can be used for
numerical operation(s).
Binary Files are used to store binary data such as image, video, audio, text There is no delimiter
Binary files are difficult to understand
Binary files are having .dat extension
The key function for working with files in Python is the open() function
The open() function takes two parameters; filename, and mode
There are different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist "a" - Append -
Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Use the python module pickle for structured data such as list or directory to a file.
PICKLING refers to the process of converting the structure to a byte stream before writing to a file.
while reading the contents of the file, a reverse process called UNPICKLING is used to convert
the byte stream back to the original structure.
Use pickle.dump() method to write the object in file which is opened in binary access mode.
Syntax of dump method is:
dump(object,fileobject)
Example: A program to write list sequence in a binary file using pickle.dump() method
import pickle
def bin_create():
list1 = [40,50,60,70,80,90]
f = open("list.dat","wb")
pickle.dump(list1,f)
print("Information added to Binary File")
f.close()
bin_create()
Page 56 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Output:
Information added to Binary File
def bin_create():
list1 = [40,50,60,70,80,90]
f = open("list.dat","wb")
pickle.dump(list1,f)
print("Information added to Binary File")
f.close()
bin_create()
def bin_read():
f = open("list.dat","rb")
list1 = pickle.load(f)
print("The Content of Binary File is: ",list1)
f.close()
bin_read()
Output
Information added to Binary File
The Content of Binary File is: [40, 50, 60, 70, 80, 90]
Page 57 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
def readall():
file = open('stud.dat','rb')
stu = pickle.load(file)
for i in stu:
print(i)
file.close()
readall()
#To search a record in Binary File Enter Student No to be search: 2500
import pickle Record Found
def search(): Raju : 98
file = open("stud.dat","rb")
stu = pickle.load(file) Enter Student No to be search: 5000
found = 0 No Record Found
sno = int(input("Enter Student No to be search: "))
for i in stu:
if i[0] == sno:
print("Record Found")
print(i[1],":",i[2])
found = 1
break
if found == 0:
print("No Record Found")
file.close()
search()
Page 58 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Keys
Keys play an important role in the relational database.
It is used to uniquely identify any record or row of data from the table. It is also used to
establish and identify relationships between tables.
Types of keys:
Primary key
It is the first key used to identify one and only one instance of an entity uniquely.
Candidate key
A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
Except for the primary key, the remaining attributes are considered a candidate key. The
candidate keys are as strong as the primary key.
Super Key
Super key is an attribute set that can uniquely identify a tuple.
A super key is a superset of a candidate key.
Page 59 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Foreign key
Foreign keys are the column of the table used to point to the primary key of another
table.
Alternate key
There may be one or more attributes or a combination of attributes that uniquely
identify each tuple in a relation. These attributes or combinations of the attributes are
called the candidate keys. One key is chosen as the primary key from these candidate
keys, and the remaining candidate key, if it exists, is termed the alternate key.
Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite
key. This key is also known as Concatenated Key.
Artificial key
The key created using arbitrarily assigned data are known as artificial keys. These keys
are created when a primary key is large and complex and has no relationship with many
other relations. The data values of the artificial keys are usually numbered in a serial
order
Page 60 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
ATTRIBUTE - the columns of a relation are the attributes which are also referred as fields
TUPLE - Each row of data in a relation (table) is called a tuple.
DEGREE - The number of attributes(column) in a relation is called the Degree of the relation
CARDINALITY - The number of tuples(row) in a relation is called the Cardinality
Constraints Description
NOT NULL Ensures that a column cannot have NULL values where NULL means
missing/unknown/not applicable value.
UNIQUE Ensures that all the values in a column are distinct/unique
DEFAULT A default value specified for the column if no value is provided
PRIMARY KEY The column which can uniquely identify each row/record in a table.
FOREIGN KEY The column which refers to value of an attribute defined as primary key in
another table
Page 61 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
10 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student;
<table name>;
11 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> WHERE WHERE feespaid > 15000;
<condition(s)>;
12 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> ORDER BY <field ORDER BY stname DESC;
name> ASCENDING /
DESCENDING;
13 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> WHERE field WHERE feespaid BETWEEN 10000 AND 25000;
name BETWEEN <lower limit>
and <upper limit>;
14 SELECT field1, field2…. FROM SELECT stno, stname, dob FROM student
<table name> WHERE <field WHERE stname LIKE ‘___M__%’;;
name> like <pattern matching>;
Page 62 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Page 63 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the
condition is satisfied. It returns the combination of all rows from both the tables where the
condition satisfies.
Syntax
Example
LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right
table. If there is no matching join value, it will return NULL.
Syntax
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Example
RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the
matched values from the left table. If there is no matching in both tables, it will return NULL.
Syntax
Example
FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables
have all the records from both tables. It puts NULL on the place of matches not found.
Syntax
Example
Page 65 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL
Database connectivity
Database connectivity refers to connection and communication between an application
and a database system.
The term “front-end” refers to the user interface, while “back-end” means the server,
application and database that work behind the scenes to deliver information to the user.
Mysql.connector- Library or package to connect from python to MySQL.
Before we connect the program with mysql , we need to install connectivity package named
mysql-connector- python
Page 66 of 66