0% found this document useful (0 votes)
23 views66 pages

Class 12 CDF

Uploaded by

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

Class 12 CDF

Uploaded by

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

CLASS 12 BOARD REVISION STUDY MATERIAL

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.

Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 A variable name cannot be any of the Python keywords.

Valid and Invalid Variable Name Example

 Valid Identifiers are: score, highest_score, name1, _name, runs250


 Invalid Identifiers are: score@123, 250runs, while, highest score, 1name

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

EXPRESSIONS AND STATEMENTS


An expression is a combination of values, variables, and operators. A value all by itself is
considered an expression, and so is a variable, so the following are all legal expressions:
>>> 42
42
>>> n = 17
>>> n + 25
42

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

Python Arithmetic Operators

Operators Description Syntax


+ Addition: adds two operands x+y
- Subtraction: subtracts two operands x- y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided by x%y
the second
** Power (Exponent): Returns first raised to power second x ** y

Python Comparison Operators

Operators Description Syntax


> Greater than: True if the left operand is greater than the right x>y
>= Greater than or equal to: True if left operand is greater than or equal to x >= y
the right
< Less than: True if the left operand is less than the right x<y
<= Less than or equal to: True if left operand is less than or equal to the x <= y
right

Page 2 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

== Equal to: True if both operands are equal x == y


!= Not equal to – True if operands are not equal x != y

Python Assignment Operators

Operators Description Syntax


= Assign value of right side of expression to left side operand x=y+z
+= Add and Assign: Add right side operand with left side operand and a += b
then assign to left operand
-= Subtract AND: Subtract right operand from left operand and then a -= b
assign to left operand: True if both operands are equal
*= Multiply AND: Multiply right operand with left operand and then a *= b
assign to left operand
/= Divide AND: Divide left operand with right operand and then assign a /= b
to left operand
//= Divide(floor) AND: Divide left operand with right operand and then a //= b
assign the value(floor) to left operand
%= Modulus AND: Takes modulus using left and right operands and a %= b
assign result to left operand
**= Exponent AND: Calculate exponent(raise power) value using a **= b
operands and assign value to left operand

Python Logical Operators

Operators Description Syntax Example


and Returns True if both the operands are true x and y x>7 and x>10
or Returns True if either of the operands is true x or y x<7 or x>15
not Returns True if the operand is false not x not(x>7 and x> 10)

Python Membership Operators

Operators Description Syntax


in Evaluates to true if it finds a variable in the x in y
specified sequence and false otherwise
not in Evaluates to true if it does not finds a x not in y
variable in the specified sequence and false
otherwise.

Python Identity Operators

Operators Description Syntax


is Evaluates to true if the variables on either x is y
side of the operator point to the same object
and false otherwise

Page 3 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

is not Evaluates to false if the variables on either x is not y


side of the operator point to the same object
and true otherwise

Python Operators Precedence

Precedence Operators Description Associativity


1 () Parentheses Left to right
2 x[index], Subscription, Left to right
x[index:index] slicing
3 ** Exponentiation Right to left
4 *, /, //, % Multiplication, division, floor division, Left to right
remainder
5 +,- Addition and subtraction Left to right
6 in, not in, membership tests, Left to Right
is, is not, Identity tests,
<, <=, >, >=, !=, == Comparisons
7 not Boolean NOT Right to left
8 and Boolean AND Left to right
9 or Boolean OR Left to right
10 if-else Conditional expression Right to left
11 := Assignment expression Right to left

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

List of Standard Exceptions

Exception Name Description


ArithmeticError Raised when an error occurs in numeric calculations
AttributeError Raised when attribute reference or assignment fails
EOFError Raised when the input() method hits an "end of file" condition (EOF)
FloatingPointError Raised when a floating point calculation fails
ImportError Raised when an imported module does not exist
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
NameError Raised when a variable does not exist
OverflowError Raised when the result of a numeric calculation is too large
RuntimeError Raised when an error occurs that do not belong to any specific
exceptions
SyntaxError Raised when a syntax error occurs
TypeError Raised when two different data types are combined
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero

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)

The elif Statement

NESTED CONDITIONALS (nested if...else STATEMENT)


Syntax

Page 6 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

PYTHON ITERATION - Iteration - is the ability to run a block of statements repeatedly

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:

for letter in 'Python':


if letter == 'h':
break
print('Current Letter :', letter)
Output:
Current Letter : P
Current Letter : y
Current Letter : t

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

for letter in 'Python':


if letter == 'h':
continue
print('Current Letter :', letter)
Output:

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.

for letter in 'Python':


if letter == 'h':
pass
print("Pass Occur No change in Code")
print('Current Letter :', letter)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Pass Occur No change in Code
Current Letter : h
Current Letter : o
Current Letter : n

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

Methods Description Example


+ Concatenation String concatenation means add name = 'James Bond'
strings together. number = '007'
print(name + number)
James Bond007
* Repetition Repeat a string ‘n’ Times number = '007'
print(number * 3)
007007007
len(str) To Get the Length of the string name = 'James Bond 007'
print(len(name))
14
str.capitalize() Return a copy of the string with its name = 'james BOND 007'
first character capitalized and the print(name.capitalize())
rest lower cased James bond 007
str.title() Returns a string where the first name = 'JAMES BOND 007'
character in every word is upper print(name.title())
case James Bond 007
str.count(value, start, returns the number of times a name = 'I am a Hero! Not a Zero!'
end) specified value appears in the print(name.count('a'))
string 3
name = 'Hello World! Hello Hello'
print(name.count('Hello',12,25))
2
str.find(value, start, finds the first occurrence of the name = 'Hello World! Hello Hello'
end) specified value print(name.find('Hello'))
returns -1 if the value is not found 0
name = 'Hello World! Hello Hello'
print(name.find('e',5,10))
-1
name = 'Hello World! Hello Hello'
print(name.find('e',1,30))
1
str.index(value, start, finds the first occurrence of the name = 'Hello World! Hello Hello'
end) specified value print(name.index('Hello'))
raises an exception if the value is 0
not found name = 'Hello World! Hello Hello'
print(name.index('e',1,30))
1
name = 'Hello World! Hello Hello'
print(name.index('e',5,10))
ValueError
str.startswith(value, returns True if the string starts with name = 'Hello World! Hello Hello'
start, end) the specified value, otherwise False print(name.startswith('He'))
True

Page 10 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

name = 'Hello World! Hello Hello'


print(name.startswith('W'))
False
name = 'Hello World! Hello Hello'
print(name.startswith('W',6,20))
True
str. endswith(value, returns True if the string ends with name = 'Hello World! Hello Hello'
start, end) the specified value, otherwise False print(name.endswith('Hello'))
True
name = 'Hello World! Hello Hello'
print(name.endswith('H'))
False
name = 'Hello World! Hello Hello'
print(name.endswith('World',5,15))
False
str.lower() returns a string where all characters name = "James BOND 007"
are lower case print(name.lower())
james bond 007
str.upper() returns a string where all characters name = "James Bond 007"
are in upper case print(name.upper())
JAMES BOND 007
str.islower() returns True if all the characters are first = "James bond"
in lower case, otherwise False second = "james bond"
Numbers, symbols and spaces are third = "jamesbond"
not checked, only alphabet four = "jamesbond007"
characters print(first.islower())
print(second.islower())
print(third.islower())
print(four.islower())
False
True
True
True
str.isupper() returns True if all the characters are first = "James bond"
in upper case, otherwise False second = "JAMES BOND"
Numbers, symbols and spaces are third = "jamesbond"
not checked, only alphabet four = "jamesbond007"
characters print(first.isupper())
print(second.isupper())
print(third.isupper())
print(four.isupper())
False
True
False
False
str.isalpha() returns True if all the characters are first = "Jamesbond"

Page 11 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

alphabet letters (a-z). print(first.isalpha())


characters that are not alphabet True
letters: (space)!#%&? etc first = "James bond"
print(first.isalpha())
False
first = "Jamesbond007"
print(first.isalpha())
False
str.isdigit() returns True if all the characters are first = "007"
digits, otherwise False print(first.isdigit())
Exponents are also considered as True
digits first = "007 007"
print(first.isdigit())
False
str.isalnum() method returns True if all the first = "JamesBond007"
characters are alphanumeric, print(first.isalnum())
meaning alphabet letter (a-z) and True
numbers (0-9). first = "JamesBond 007"
characters that are not print(first.isalnum())
alphanumeric: (space)!#%&? etc. False
first = "JamesBond@007"
print(first.isalnum())
False
str.isspace() returns True if all the characters in first = "James Bond @ 007"
a string are whitespaces, otherwise print(first.isspace())
False False
first = " "
print(first.isspace())
True
str.replace(oldvalue, replaces a specified phrase with modify = "Java Programming"
newvalue, count) another specified phrase change =
modify.replace('Java','Python')
print(change)
Python Programming
modify = "Java Programming"
change =
modify.replace('Python','Java')
print(change)
Java Programming
str.join(iterable) takes all items in an iterable and sep = "-"
joins them into one string. A string phone = ("91", "44", "37181111")
must be specified as the separator print (sep.join(phone))
91-44-37181111

Page 12 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

str.partition(value) method searches for a specified modify = "Python Java Programming"


string, and splits the string into a change = modify.partition("Java")
tuple containing three elements. print(change)
The first element contains the part ('Python ', 'Java', ' Programming')
before the specified string. The
second element contains the
specified string. The third element
contains the part after the string
str.split(separator, splits a string into a list. You can phone = "91-44-37181111"
maxsplit) specify the separator, default print(phone.split("-"))
separator is any whitespace ['91', '44', '37181111']

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

 Lists are the most versatile of Python's compound data types.


 A list contains items separated by commas and enclosed within square brackets ([]).
 To some extent, lists are similar to arrays in C. One difference between them is that all the items
belonging to a list can be of different data type.
 The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1.
 The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

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

Methods Description Example


+ Concatenation concatenation means add list >>> a = [1, 2, 3]
together. >>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
* Repetition Repeat a list ‘n’ Times >>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
len() find the length of an object prolang = ['CPP', 'Java', 'Python']
pl = len(prolang)
print(pl)
3
list() returns a list in Python, takes a vowel_list = ['a', 'e', 'i', 'o', 'u']
single argument: print(list(vowel_list))
['a', 'e', 'i', 'o', 'u']
append() adds a new element to the end of a >>> t = ['a', 'b', 'c']
list >>> t.append('d')
>>> t
['a', 'b', 'c', 'd']
extend() takes a list as an argument and >>> t1 = ['a', 'b', 'c']
appends all of the elements >>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> t1
['a', 'b', 'c', 'd', 'e']
insert() inserts the specified value at the prolang = ['CPP', 'Java', 'Python']
specified position prolang.insert(1, 'Swift')
print(prolang)
['CPP', 'Swift', 'Java', 'Python']
count() returns the number of elements lang = ["Java", "Python", "Go","Java"]
with the specified value pro = lang.count("Java")
print(pro)
2
index() returns the position at the first lang = ["Java", "Python", "Go","Java"]
occurrence of the specified value pro = lang.index("Java")
print(pro)
0
remove() removes the first occurrence of the lang = ["Java", "Python", "Go","Java"]
element with the specified value. lang.remove("Java")
print(lang)
[‘Python’, ‘Go’,’Java’]
pop() pop modifies the list and returns >>> t = ['a', 'b', 'c']
the element that was removed. If >>> x = t.pop(1)

Page 15 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

you don’t provide an index, it >>> t


deletes and returns the last ['a', 'c']
element. >>> x
'b'
reverse() the element you want to remove >>> t = ['a', 'b', 'c']
(but not the index), you can use >>> t.remove('b')
remove >>> t
return value from remove is None ['a', 'c']
sort() arranges the elements of the list >>> t = ['d', 'c', 'e', 'b', 'a']
from low to high >>> t.sort()
>>> t
['a', 'b', 'c', 'd', 'e']
min() returns the item with the lowest game =
value, or the item with the lowest ['Volleyball','Cricket','Hockey','Football']
value in an iterable. print(min(game))
If the values are strings, an jersy = [10,7,333,100]
alphabetically comparison is done print(min(jersy))
Cricket
7
max() returns the elements from game =
the list with maximum value ['Volleyball','Cricket','Hockey','Football']
print(max(game))
jersy = [10,7,333,100]
print(max(jersy))
Volleyball
333
sorted() Sorted in low to high numbers = [1,2,3,4,5,1,4,5]
print(sorted(numbers))
[1, 1, 2, 3, 4, 4, 5, 5]
numbers = [1,2,3,4,5,1,4,5]
print(sorted(numbers,reverse = True))
[5, 5, 4, 4, 3, 2, 1, 1]
sum() adds up all the numbers in the list numbers = [1,2,3,4,5,1,4,5]
Sum = sum(numbers)
print(Sum)
Sum = sum(numbers, 10)
print(Sum)
25
35

Page 16 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

Python Tuples

 A tuple is another sequence data type that is similar to the list.


 A tuple consists of a number of values separated by commas.
 Unlike lists, however, tuples are enclosed within parentheses.
 The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements
and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
 Tuples can be thought of as read only lists.

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

Methods Description Example


len(tuple) returns the number of elements in tuple1, tuple2 = (123, 'xyz', 'zara'),
the tuple (456, 'abc')
print "First tuple length : ", len(tuple1)
print "Second tuple length : ",
len(tuple2)
First tuple length : 3
Second tuple length : 2
tuple.count(value) returns the number of times a thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
specified value appears in the tuple x = thistuple.count(5)
print(x)
2
tuple.index(value) finds the first occurrence of the thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
specified value. x = thistuple.index(8)
raises an exception if the value is print(x)
not found 3
sorted(iterable, returns a sorted list of the specified a = ("b", "g", "a", "d", "f", "c", "h", "e")
key=key, iterable object x = sorted(a)
reverse=reverse) print(x)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
min(tuple) returns the elements from the tuple tuple1, tuple2 = (123, 'xyz', 'zara',
with minimum value 'abc'), (456, 700, 200)
print "min value element : ",
min(tuple1)
print "min value element : ",
min(tuple2)
min value element : 123
min value element : 200
max(tuple) returns the elements from the tuple tuple1, tuple2 = (123, 'xyz', 'zara',
with maximum value 'abc'), (456, 700, 200)
print "Max value element : ",
max(tuple1)
print "Max value element : ",
max(tuple2)
Max value element : zara
Max value element : 700
sum(iterable, start) returns a number, the sum of all a = (1, 2, 3, 4, 5)
items in an iterable x = sum(a)
print(x)
15
a = (1, 2, 3, 4, 5)
x = sum(a, 7)
print(x)
22

Page 18 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

Python Dictionary

 Python's dictionaries are kind of hash table type.


 They work like associative arrays or hashes found in Perl and consist of key-value pairs.
 A dictionary key can be almost any Python type, but are usually numbers or strings.
 Values, on the other hand, can be any arbitrary Python object.
 Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces
([]).

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

Methods Description Example


len(dict) gives the total length dict = {'Name': 'Zara', 'Age': 7};
of the dictionary This print (len (dict))
would be equal to the 2
number of items in
the dictionary
dict(), creates a dictionary emptydict = dict()
obj print(emptydict)
ect from the specified numdict = dict(I='1', II='2', III='3')
keys and values, or print(numdict)
iterables of keys and namedict = dict(I='one', II='two', III='three')
values or mapping print(namedict)
objects {}
{'I': '1', 'II': '2', 'III': '3'}
{'I': 'one', 'II': 'two', 'III': 'three'}
dict.keys() Returns a list bike =
containing the {"brand":"Yamaha","model":"Aerox","year":2021}
dictionary's keys check = bike.keys()
print(check)
bike["color"] = "Blue"
print(check)
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
dict.values() Returns a list of all bike =
the values in the {"brand":"Yamaha","model":"Aerox","year":2021}
dictionary check = bike.values()
print(check)
bike["color"] = "Blue"
print(check)
dict_values(['Yamaha', 'Aerox', 2021])
dict_values(['Yamaha', 'Aerox', 2021, 'Blue'])
dict.items() Returns a list bike =
containing a tuple for {"brand":"Yamaha","model":"Aerox","year":2021}
each key value pair check = bike.items()
print(check)
bike["color"] = "Blue"
print(check)
dict_items([('brand', 'Yamaha'), ('model',
'Aerox'), ('year', 2021)])
dict_items([('brand', 'Yamaha'), ('model',
'Aerox'), ('year', 2021), ('color', 'Blue')])

Page 20 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

dict.get(keyname, Returns the value of bike =


value) the specified key {"brand":"Yamaha","model":"Aerox","year":2021}
check = bike.get("price",175000)
print(check)
175000
dict.update(iterable) Updates the bike =
dictionary with the {"brand":"Yamaha","model":"Aerox","year":2021}
specified key-value bike.update({"color":"Blue","price":17500})
pairs print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021,
'color': 'Blue', 'price': 17500}
del() delete entire bike =
dictionary {"brand":"Yamaha","model":"Aerox","year":2021}
del(bike)
print(bike)
del remove entry with bike =
key {"brand":"Yamaha","model":"Aerox","year":2021}
print(bike)
del bike['model']
print(bike)
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
{'brand': 'Yamaha', 'year': 2021}
dict.clear() Removes all the bike =
elements from the {"brand":"Yamaha","model":"Aerox","year":2021}
dictionary bike.clear()
print(bike)
{}
fromkeys() Returns a dictionary vehicle = {'Yamaha','Jawa','Hardley'}
with the specified category = 'Bike'
keys and value together = dict.fromkeys(vehicle,category)
print(together)
{'Hardley': 'Bike', 'Jawa': 'Bike', 'Yamaha':
'Bike'}
copy() Returns a copy bike =
of the dictionary {"brand":"Yamaha","model":"Aerox","year":2021}
print(bike)
print(bike.copy())
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
{'brand': 'Yamaha', 'model': 'Aerox', 'year': 2021}
dict.pop(keyname, removes the specified bike =
defaultvalue) item from the {"brand":"Yamaha","model":"Aerox","year":2021}
dictionary print(bike)
vehicle = bike.pop("year")
Page 21 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

sorted list of our "Grapefruit" : "Pink",


dictionary in "Blackberry" : "Purple",
alphabetical order "Sapodilla" : "Brown"}
fruitscolor = sorted(fruitscolor)
print(fruitscolor)
fruitscolor = sorted(fruitscolor,reverse = True)
print(fruitscolor)
['Apple', 'Banana', 'Blackberry', 'Grapefruit',
'Mango', 'Sapodilla']
['Sapodilla', 'Mango', 'Grapefruit',
'Blackberry', 'Banana', 'Apple']

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.

Importing Modules in a Python Program

To make use of the function in a module, you will need to import the module with an ‘import’
statement.

Syntax import module_name

In Python, import statement can be used in two forms

To Import Entire Module

To import entire module, import statement is used. Import statement is also used to import
selecting modules.

Syntax import module_name

e.g. import math


print (math.sqrt (16))
Output
4.0

To Import Selected Objects from a Module

you can refer to the functions by name rather than through dot notation.

Syntax from module_name import object_name

e.g. from math import sqrt


print (sqrt(16))
Output
4.0

To Import Multiple Objects


We can also import multiple objects in a single line. To import multiple objects, we can write
the multiple objects or functions name using the comma (,) operator.
e.g. from math import sqrt, pi

Page 24 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

To Import All Objects of a Module


When you want to import all objects, you can use asterisk (*) symbol at last of keyword import.

Syntax from module_name import *


e.g. from math import *

Mathematical Functions - In Python, different number of mathematical operations or


functions can be performed by importing the math module which contains the definition of
these functions.

Function Name Syntax Example


sqrt () math.sqrt(number) >>>import math
>>>s = math.sqrt(4)
This function is used to find >>>print(s)
the square root of a specified 2.0
expression or an individual >>>s1 = math.sqrt (15)
number. >>>print(s1)
If you give negative number 3.872983346207417
as argument it will give an >>>print(math.sqrt (0))
error. 0.0
>>>print(math.sqrt (4.5))
2.1213203435596424
ceil() math.ceil(x) >>>import math
This method returns ceiling >>>c = math.ceil(45.23)
value of x i.e. the smallest >>>print(c)
integer not less than x. 46
>>>c1 = math.ceil(−76.89)
>>>print(c1)
–76
>>>a = 456.14
>>>print(math.ceil(a))
457
>>>x = math.pi
>>>print(math.ceil(x))
4
floor() math.floor(x) >>>import math
This method is used to return >>>f = math.floor (145.35)
a value which is less than or >>>print(f)
equal to a specific expression 145
or value. >>>a = 102.78
>>>print(math.floor(a))
102
>>>b = −75.50
Page 25 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

pow (x, y, mod) pow(x, y, mod) >>>x = 4


converts its arguments into >>>y = 3
float and then computes the >>>z = 10
power. >>>pow(x, y, z)
4
6
>>>print(pow(6, 0, 2))
1
>>>pow(0, 4, 2)
0
>>>pow (8, 3, 0)
Trackback (most recent call
last):
File “<pyshell#7>”, line 1, in
<module>
pow(8, 3, 0)
ValueError : pow() 3rd
argument cannot be 0.
fabs() math.fabs(x) >>>import math
This method returns the >>>x = –25
absolute value (positive value) >>>math.fabs (x)
of x. 25.0
>>>print(math.fabs (65))
65.0
Page 26 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

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

Function Name Syntax Example


random() random.random() >>>import random
This method is used to >>>random.random()
generate a float random 0.7358047613841759
number less
than 1 and greater than or
equal to 0. This function does
not
require any arguments
randint () random.randint(start, end) >>>import random
This method is one of >>>random.randint(10, 50)
methods that handle random 34
numbers. >>>print(random.randint(5,
It has two parameters start 70))
and end and generate an 19
integer >>>random.randint(–80, –20)
between start and end –20
(including both). >>>random.randint(–12, 60)
35
randrange() random.randrange(start, stop, >>>import random
This method returns a step) >>>random.randrange (10,
random selected element from 100, 5)
the 70
range created by the start, >>>random.randrange(20, 30,
stop and step arguments. The 10)
value of start is 0 by default. 20
Similarly, the value of step is 1 >>>random.randrange(–50, –
by default. 20, 10)
–30
>>>random.randrange(–10, 0,
4)
–6

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.

Function Name Syntax Example


mean() statistics.mean(data_set) >>>import statistics
It returns the simple >>>list=[45,78,21,32,45,56]
arithmetic mean of data >>>statistics.mean(list)
which can be a 46.166666666666664
sequence or iterator. >>>list=[–14,25,-32,-12,0,65]
Arithmetic mean is the sum >>>statistics.mean(list1)
of data 5.333333333333333
divided by the number of >>>t = (14,14,12,32,78)
data set. >>>statistics.mean(t)
30.0
>>>t1=(–12,–23,45,–2,0,16)
>>>statistics.mean(t1)
4.0
>>>l1=[1.2,2.3,4.5,6,–8]
>>>statistics.mean(l1)
1.2
>>>statistics.mean()
Traceback (most recent call last):
File ‘‘<pyshe||#11>’’, line 1, in
<module>
statistics.mean()
TypeError:mean()missing 1
required positional
argument:‘data’
median() statistics.median(data_set) >>>import statistics
This function calculates >>>list=[12,54,89,65,78]
middle value of the >>>statistics.median(list)
arithmetic data 65
in iterative order. If there >>>list1=[45,–12,–65,78,0]
are an odd number of >>>statistics.median(list1)
values, 0
median() returns the >>>list2=[–12,4.65,78,–98,45,6.5]
middle value. If there are >>>statistics.median(list2)
an even 5.575
number of values it returns >>>t=(78,98,23,–32,8.6,–9)
an average of two middle >>>statistics.median(t)
values. 15.8
mode() statistics.mode(dataset) >>>import statistics
This function returns the >>>list=[45,89,45,78,65,32,45,66]
Page 29 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

number with maximum >>>statistics.mode(list)


number of occurrences. 45
>>>list1=[4.5,6.5,7.0,6.5,98,4.5,6.5]
When two numbers have >>>statistics.mode(list1)
same occurrence of number 6.5
then it >>>t=(–45,–89,0,–89,36,–86,–36)
will give first number of >>>statistics.mode(t)
maximum occurrence. –89
>>>list2=[–45,–89,0,–89,36,–36,–36]
>>>statistics.mode(list2)
− 89

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 and Lifetime of variables (Global and Local Variables)


 Scope of a variable is the portion of a program where the variable is recognized.
 Parameters and variables defined inside a function is not visible from outside. Hence, they have a
local scope.
 Lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetime of variables inside a function is as long as the function executes.
 They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls

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

Global vs. Local Variables


Variables that are defined inside a function body have a local scope, and those defined outside have a
global scope.

Example 1

total = 0 # This is global variable.


def add(arg1, arg2):
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total :", total)
return total
add(10, 20)
print("Outside the function global total :", total )

Output:
Inside the function local total : 30
Outside the function global total : 0

Example 2

total = 0 # This is global variable.


def add(arg1, arg2):
global total
total = arg1 + arg2; # Here total is global variable.
print ("Inside the function global total :", total)
return total
add(10, 20)
print("Outside the function global total :", total )

Output:
Inside the function local total : 30
Outside the function global total : 30

FUNCTION ARGUMENTS - The


argument types and their meanings, however, are pre-defined and can’t be changed.

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

fn = int(input("Enter First Number: "))


sn = int(input("Enter Second Number: "))
add(fn,sn)

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

def IYear(Dept, Sec):


print ("Department :", Dept)
print ("Section :", Sec)
IYear(Dept = "EEE", Sec = "A")

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

def add(fn,sn = 35):


print("First Number :",fn)
print("Second Number :",sn)
add(25,35)
add(35)

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

Data Structure Using Stack

What is Stack?

 Stack is a Linear Data Structure


 Stack is a list of elements in which an element may be inserted or deleted only at
one end ,called the TOP of the stack
 It follows the principle of Last In First Out (LIFO).
 LIFO means the elements inserted last would be the first to be deleted

Operations on Stack

There are mainly two types of Operation that can be done with stack.

i) Push

ii) Pop

Push: Insertion of a element on the top of the stack is called Push.

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

Overflow and Underflow case

Overflow : It refers to a situation , when one tries to push an element an element in


stack/queue, that is already full . In Python, (for stacks and list implemented as list ),
since list can grow, OVERFLOW condition does not arise until the memory is exhausted .

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.

Implementation of stack using list

The implementation of stack using list in Python is the easiest of all


programming language.

Basic operations performed on stack are:

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

List methods used and Important things to remember

1. list.append(element) – It is used to implement push operations(used to append


or add elements at the end of the list)
2. list.pop() –It is used to implement pop operations(removing elements at the end)
3. list[::-1]-List slicing is used to print the elements in the reverse order from
top position to list[0]
4. top=len(list)-1 (length of list -1)
5. stack – LIFO(Last In First Out)
6. Push and Pop through one end(Top)

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)

Personal Area Network (PAN)

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

Local Area Network (LAN)

 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

Metropolitan Area Network (MAN)


 Metropolitan Area Network (MAN) is an extended form of LAN which covers a larger
geographical area like a city or a town.
 Data transfer rate in MAN also ranges in Mbps, but it is considerably less as compared to
LAN.
 Cable TV network or cable based broadband internet services are examples of MAN.
 This kind of network can be extended up to 30-40 km.
 Sometimes, many LANs are connected together to form MAN

Wide Area Network (WAN)


 Wide Area Network connects computers and other LANs and MANs, which are spread
across different geographical locations of a country or in different countries or continents.
 A WAN could be formed by connecting a LAN to other LANs
 Large business, educational and government organisations connect their different branches
in different locations across the world through WAN.
 The Internet is the largest WAN that connects billions of computers, smartphones and
millions of LANs from different continents

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.

2. Where the following devices should be placed:


Server : Large number of computers in the building
HUB/Switch : Each building

Page 42 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

Modem : In the server room


Repeater : It is used if the distances are higher than 70m. It regenerates data and voice signals.
Router : When one LAN is required to be connected to the other LAN
Best Layout : Star (from Server), BUS topology
Best Cable : Twisted Pair, Ethernet Cable, Coaxial cable (when distance is in metres);
For large distances—Fibre optics cable.
Best connecting technique : In hilly regions, radio waves should be used and city-to-city,
state-to-state satellite should be used.

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:

file_object= open(file_name, access_mode)

Here are parameter details:


file_name: The file_name argument is a string value that contains the name of the file that
you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened,
i.e., read, write, append, etc. This is optional parameter and the default file access mode is
read (r).

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

with open (file_name, access_mode) as file_ object:

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.

READING FROM A TEXT FILE


We can write a program to read the contents of a file.
Before reading a file, we must make sure that the file is opened in “r”, “r+”, “w+” or “a+” mode.
There are three ways to read the contents of a file:
The read() method
This method is used to read a specified number of bytes of data from a data file.
The syntax of read() method is

file_object.read(n)

The readline([n]) method


This method reads one complete line from a file where each line terminates with a newline (\n)
character.
It can also be used to read a specified number (n) of bytes of data from a file but maximum up to the
newline character (\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.

The readlines() method


The method reads all the lines and returns the lines along with newline as a list of strings.

WRITING TO A TEXT FILE

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() - for writing a single string


writelines() - for writing a sequence of strings

The write() method

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)

The writelines() method

to write multiple strings to a file. We need to pass an iterable object like lists, tuple, etc.
containing strings to the writelines() method.

SETTING OFFSETS IN A FILE

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

The tell() method


This function returns an integer that specifies the current position of the file object in the file.
The position so specified is the byte position from the beginning of the file till the current position of
the file object.
The syntax of using tell() is:

File_object.tell()

The seek() method


This method is used to position the file object at a particular position in a file. The syntax of seek() is:
file_object.seek(offset [, reference_point])

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

It can have any of the following values:

0 - beginning of the file


1 - current position of the file
2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file

Text File Practice Program

Program Code Output


#To write Multiple Lines of text contents into Enter a Line: My name is Ramu
a text file Enter More Lines (Y/N)? Y
def addline(): Enter a Line: I am Coming from Kovilpatti
first = open("mydetails.txt","w") Enter More Lines (Y/N)? n
while True:
line = input("Enter a Line: ") Mydetails.txt
first.write(line) My name is Ramu
first.write("\n") I am Coming from Kovilpatti
choice = input("Enter More Lines (Y/N)? ")
if choice in 'Nn':
break
first.close()
addline()
#To read lines from a text file and display the My name is Ramu
lines starting from 'M'
def lines():
first = open("mydetails.txt")
check = first.readlines()
for char in check:
if char[0] == 'M':
print(char,end = ' ')
first.close()
lines()
#To read lines from a text file and display the My name is Ramu
lines starting from 'M' or ‘i’ i am studying in class 11 at CBSE school
def lines():
first = open("mydetails.txt")
check = first.readlines()
for char in check:
if char[0] == 'M'or char[0] == 'i':
print(char,end='')

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

in a file Count of Letter T or t in a File is: 7


def specificchar():
first = open("mydetails.txt")
char = first.read()
E=T=0
for line in char:
if line in 'Ee':
E=E+1
if line in 'Tt':
T=T+1
print("Count of Letter E or e in a File is: ",E)
print("Count of Letter T or t in a File is: ",T)
first.close()
specificchar()
#To Count and display total number of words Total Number of Words in a File is: 25
in a file
def countwords():
count = 0
first = open("mydetails.txt")
line = first.read()
words = line.split()
for word in words:
count = count + 1
print("Total Number of Words in a File is:
",count)
first.close()
countwords()
#To read the content of a file and convert into MY NAME IS RAMU
upper case words I AM COMING FROM KOVILPATTI
def showwords(): I AM STUDYING IN CLASS 11 AT CBSE
first = open("mydetails.txt") SCHOOL
line = first.read() MY HOBBY IS ROAMING IN THE STREETS
print(line.upper())
first.close()
showwords()
#To read lines from a text file and display the the
lines ends with specific character
def endswith():
first = open("mydetails.txt")
check = first.read()
end = check.split()
for char in end:
if char[-1] == 'e':
print(char,end='')
first.close()
endswith()

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

CSV stands for "comma-separated values“.


CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
Each line of the file is a data record.
Each record consists of one or more fields, separated by commas
To perform read and write operation with CSV file, we must import csv module

How to create CSV file

Method 1 (From MS-Excel):

Open Excel, delete all the sheet except sheet 1


Type all the data, in separate cells
Save it as csv file in your desired location.
If any warning comes, click on „YES‟
When you close the excel, choose „NO‟
Now file is created at your desired location, go and double click or open with notepad to check
the content

Method 2 (From any editor):

Open Notepad or Editor


Type record by separating each column value by comma(,)
Every record in separate line
Save it by giving extension .csv
E.G. if you want it to save with name emp then give name as “emp.csv” in double quotes
File is created close it and double click to open and check

Methods of CSV Module :

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

writer( ) Object Methods –

Page 52 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

 w_obj . writerow( <Sequence> ) : Write a Single Line


 w_obj . writerows ( <Nested Sequence> ) : Write Multiple Lines

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)

CSV Program can be use list and dictionary methods

How to read entire data in CSV File


Program Code Output:

import csv ['Name', ' Class', ' Subject']


first = open("data.csv") ['Ramu', ' XI', ' MPCB']
row = csv.reader(first) ['Raghu', ' XI', ' MPCCS']
for i in row: ['Rama', ' XI', ' MPCSB']
print(i) ['Rupesh', ' XI', ' AEBSCS']
first.close()
How to read Specific Column from CSV File
Program Code Output:

import csv Name Subject


first = open("data.csv") Ramu MPCB
row = csv.reader(first) Raghu MPCCS
for i in row: Rama MPCSB
print(i[0],i[2]) Rupesh AEBSCS
first.close()
How to skip the first row in CSV File Use next() - Jump to the next row
Program Code Output:

import csv Ramu MPCB


first = open("data.csv") Raghu MPCCS
row = csv.reader(first) Rama MPCSB
next(row) Rupesh AEBSCS
for i in row:
print(i[0],i[2])
first.close()
How to write a row in CSV File
Program Code Output

import csv Name,Class


first = open("row.csv",'w') Muthu,XII
wr = csv.writer(first)
wr.writerow(['Name','Class'])
wr.writerow(['Muthu','XII'])
Page 53 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

first.close()
How to write multiple rows in CSV File
Program Code Output:

import csv Name,Class,Subject


fields = ['Name', 'Class', 'Subject'] Umar,XII,MPCB
rows = [['Umar', 'XII', 'MPCB'],['Umesh', 'XI', Umesh,XI,MPCCS
'MPCCS'],['Ukiran','XII','PCCSB']] Ukiran,XII,PCCSB
first = open("rows.csv", 'w',newline = '')
wr = csv.writer(first)
wr.writerow(fields)
wr.writerows(rows)
first.close()

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

import csv Enter Roll Number: 123


header = ["Roll No", " Name", "Class"] Enter Name: Babu
first = open("insert.csv","w",newline='') Enter Class: XII
one = csv.writer(first) Enter More Record [Y/N]) ?y
one.writerow(header) Enter Roll Number: 234
ch = 'y' Enter Name: Balaji
while ch in'Yy': Enter Class: XII
rn = int(input("Enter Roll Number: ")) Enter More Record [Y/N]) ?n
nm = input("Enter Name: ")
cls = input("Enter Class: ") Roll No, Name,Class
record = [rn,nm,cls] 123,Babu,XII
one.writerow(record) 234,Balaji,XII
ch = input("Enter More Record [Y/N]) ?")
first.close()
Write a Program to read all content of “student.csv” and display records of only those students
who secured more than 80 Marks. Records stored in students is in format : Roll No, Class, Marks
Program Code Input - student.csv
Roll No, Name, Marks
import csv 101, Akbar, 92
first = open("student.csv") 201, Amal, 79
detail = csv.reader(first) 301, Antony, 81
next(first)
print("Students Scored More than 80 Marks") Output:
for row in detail: Students Scored More than 80 Marks
if int(row[2]) > 80: Roll Number = 101
print("Roll Number = ",row[0]) Name = Akbar
print("Name = ",row[1]) Marks = 92
print("Marks = ",row[2]) ---------END--------

Page 54 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

print("---------END--------") Roll Number = 301


first.close() Name = Antony
Marks = 81
---------END--------
Write a Program to search the record from “record.csv” according ot the admission number
input from the user structure of the record saved in “record.csv”is aAdm no, Name, Class,
Section, Marks
Program Code Input - record.csv
Adm No, Name, Class, Section, Marks
import csv 101, "Babu', 'XII', 'A', 85
first = open("record.csv") 201, 'Dany', 'XI', 'B', 75
detail = csv.reader(first) 301, 'Florence', 'XII', 'C', 95
next(first) 401, 'Henry', 'XI','D',100
adm = int(input("Enter Admission Number: "))
for row in detail: Output:
if int(row[0]) == adm: Enter Admission Number: 101
print("Admission Number = ", row[0]) Admission Number = 101
print("Name = ", row[1]) Name = "Babu'
print("Class = ", row[2]) Class = 'XII'
print("Section = ", row[3]) Section = 'A'
print("Marks = ", row[4]) Marks = 85
break
else: Enter Admission Number: 708
print("Admission Number Not Found") Admission Number Not Found
Write a program to modify the record of a student in CSV file
Program Code Input - student.csv
Roll No, Name, Marks
import csv 101, Akbar, 92
f = open("student.csv",'r') 201, Amal, 79
f1 = open("modify.csv",'w',newline = '') 301, Antony, 81
d = csv.reader(f)
d1 = csv.writer(f1) Output - modify.csv
next(f) Rollno,Name,marks
rollno = int(input("Enter Roll Number: ")) 101,Balu,89
mn = input("Enter Modified Name: ") 201, Amal, 79
mm = int(input("Enter Modified Marks: ")) 301, Antony, 81
mr = [rollno, mn, mm]
header = ["Rollno","Name","marks"]
d1.writerow(header)
for i in d:
if int(i[0]) == rollno:
d1.writerow(mr)
else:
d1.writerow(i)
f.close()
f1.close()

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

Opening a Binary File

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.

First we need to import the module,


It provides two main methods for the purpose:-
1) dump() method
2) load() method

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

pickle.load() method is used to read the 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]

Program Code Output


#To add a record in Binary File Enter Student Number: 1500
import pickle Enter Name: Raman
def add(): Enter Marks: 89
student = [] Want to add more(y/n) ?: y
ch = 'y' Enter Student Number: 2500
while ch == 'y': Enter Name: Raju
sno = int(input("Enter Student Number: ")) Enter Marks: 98
sn = input("Enter Name: ") Want to add more(y/n) ?: y
mks = int(input("Enter Marks: ")) Enter Student Number: 3500
record = [sno,sn,mks] Enter Name: Raghu
student.append(record) Enter Marks: 78
ch = input("Want to add more(y/n) ?: ") Want to add more(y/n) ?: n
file = open('stud.dat','wb') [1500, 'Raman', 89]
pickle.dump(student,file) [2500, 'Raju', 98]
file.close() [3500, 'Raghu', 78]
add()

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

Data Base Management System

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

Data Types and Constraints

Data Type Description


CHAR(n) CHAR is of fixed length,
VARCHAR(n) VARCHAR(n) is a variable-length data type
INT INT specifies an integer value. For larger values specifies BIGINT
FLOAT Holds numbers with decimal points
DATE The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is the 4
digit year, MM is the 2 digit month and DD is the 2 digit date

Commonly used SQL Constraints

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

Sno Commands Example


1 CREATE DATABASE <database CREATE DATABASE school;
name>;

2 SHOW DATABASES; SHOW DATABASES;

3 SHOW TABLES; SHOW TABLES;


4 USE <database name>; USE school;

5 CREATE TABLE <TABLE CREATE TABLE student


NAME> (stno int(5) PRIMARY KEY,
( field name1 <datatype>(data Stname varchar(20),
size) PRIMARY KEY, Fname varchar(20),
Field name2 <datatype > (data Dob date,
size), Gender char(1),
….…. ); Fees int(5));
6 INSERT INTO <table name> INSERT INTO student
VALUES ( data1, data2, …..); VALUES( 1001,”RAM”,”Dasarathan”,”2005/-03-
21”,”M”,65000);
7 DESCRIBE <table name>; DESCRIBE student;
8 DROP TABLE <table name>; DROP TABLE student;
9 SELECT * FROM <table name>; SELECT * FROM student;

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

15 SELECT field1, field2…. FROM SELECT gender, count(gender) FROM student


<table name> GROUP BY <field GROUP BY gender HAVING
name> HAVING <condition COUNT(gender) >2;
clause>;
16 UPDATE <table name> (i) UPDATE student
SET field name = value of Set fees = fees + 5000;
formula (ii) UPDATE emp
WHERE <condition(s)>; Set bonus = salary * 20 /100
Where desig= “manager” or desig = “CLERK”;
17 DELETE FROM <table name> DELETE FROM student
WHERE <CONDITION>; Where stno=1001;
DELETE FROM student;
18 SELECT <column names> SELECT eno, ename FROM emp WHERE grade
FROM <table name> WHERE IN (‘E3’,’E5’);
<column name> IN <list of
values>;
19 SELECT <column name> FROM SELECT eno, ename FROM emp WHERE grade
<table name> WHERE IS NULL;
<condition-name> is NULL;
20 SELECT DISTINCT <column SELECT DISTINCT grade FROM emp;
name> FROM <table name>
WHERE <condition if any>;
21 ALTER TABLE <table- ALTER TABLE emp ADD (tel_no long int(10));
name>ADD <column name>
<datatype> (data size) ;
22 ALTER TABLE <table- ALTER TABLE emp MODIFY (ename
name>MODIFY <column name> VARCHAR(30));
<datatype> (data size) ;
23 ALTER TABLE <table- ALTER TABLE emp CHANGE ename empname
name>CHANGE <old-column VARCHAR(30);
name> <new-column name>
<data type> (data-size);
24 ALTER TABLE <table-name> ALTER TABLE emp DROP COLUMN tel_no;
DROP COLUMN <column-
name);
25 AGGREGATE FUNCTIONS : SELECT SUM(fees) FROM student;
SUM() - SELECT SUM(column-
name) FROM <table_name>
WHERE <condition>;
26 AVG() - SELECT AVG(column- SELECT AVG(fees) FROM student;
name) FROM <table_name>
WHERE <condition>;

Page 63 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

27 MAX() - SELECT MAX(column- SELECT MAX(fees) FROM student;


name) FROM <table_name>
WHERE <condition>;
28 MIN() - SELECT MIN(column- SELECT MIN(fees) FROM student;
name) FROM <table_name>
WHERE <condition>;
29 COUNT() - SELECT SELECT COUNT(fees) FROM student;
COUNT(column-name) FROM
<table_name> WHERE
<condition>;

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

SELECT table1.column1, table1.column2, table2.column1,....


FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Example

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

SELECT table1.column1, table1.column2, table2.column1,....


Page 64 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

Example

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

SELECT table1.column1, table1.column2, table2.column1,....


FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

Example

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

SELECT table1.column1, table1.column2, table2.column1,....


FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

Example

SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT


FROM EMPLOYEE

Page 65 of 66
CLASS 12 BOARD REVISION STUDY MATERIAL

FULL JOIN PROJECT


ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

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

#TO INSERT A RECORD (ROLLNO,NAME,AND MARKS) IN MYSQL TABLE student


USING #PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system
",database="student") mycursor=mydb.cursor()
r=int(input("enter the rollno"))
n=input("enter name")
m=int(input("enter marks"))
mycursor.execute("INSERT INTO student(rollno,name,marks)
VALUES({},'{}',{})".format(r,n,m))
mydb.commit()
print(mycursor.rowcount,"RECORD INSERTED")

Page 66 of 66

You might also like