Downloaded from [Link].
com
Comprehensive Notes
Computer Science (083)
Class 12 for 2025-26
Periods Periods Total
Unit Unit Name Marks
Theory Practical Period
Computational Thinking and
1 40 70 50 120
Programming – 2
2 Computer Networks 10 15 - 15
3 Database Management 20 25 20 12
Total 70 110 70 180
Unit I: Computational Thinking and
Programming – 2
➢ Revision of Python topics covered in Class XI.
➢ Functions: types of function - built-in functions, functions defined in
module, user defined functions, creating user defined function,
arguments and parameters - default parameters, positional
parameters, function returning value(s), flow of execution, scope of a
variable (global scope, local scope)
➢ Exception Handling: Introduction, handling exceptions using try-
except-finally blocks
➢ Introduction to files, types of files (Text file, Binary file, CSV file),
relative and absolute paths
➢ Text file: opening a text file, text file open modes (r, r+, w, w+, a,
a+), closing a text file, opening a file using with clause,
writing/appending data to a text file using write() and writelines(),
reading from a text file using read(), readline() and readlines(), seek
and tell methods, manipulation of data in a text file
Page 1 of 124
Downloaded from [Link]
➢ Binary file: basic operations on a binary file: open using file open
modes (rb, rb+, wb, wb+, ab, ab+), close a binary file, import pickle
module, dump() and load() method, read, write/create, search,
append and update operations in a binary file
➢ CSV file: import csv module, open / close csv file, write into a csv file
using writer(),writerow(),writerows() and read from a csv file using
reader()
➢ Data Structure: Stack, operations on stack (push & pop),
implementation of stack using list.
Page 2 of 124
Downloaded from [Link]
Chapter 1 Python Revision Tour
Python Basics
Named after
famous BBC
Widely used Developed
Developed First released comedy
high-level from ABC &
by Guido Van in February show namely
programming Modula-3
Rossum 1991 Monty
language Languages
Python’s
Flying circus
Python Advantages
Easy to use
Expressive Language
Interpreted Language
Its completeness
Cross platform language
Free & Open Source Language
Variety of Usage/Application
Page 3 of 124
Downloaded from [Link]
Python Disadvantages
Slower Weak on type Not easily
Less libraries
language binding convertible
• Takes time in • Not vast • Weak into • Difficult to
execution collection of catching translate in
• Line by line libraries “Type- other
execution Mismatch” lanaguages
Working in python
➢ Python can be downloaded from [Link].
➢ This is called CPython installation which provides Python interpreter,
Python IDLE & pip installer.
➢ CPython provides two modes for working with python:
o Interactive Mode
o Script Mode
Interactive Mode Script Mode
Allows to type a single command at Allows to type multiple commands
a time and save them as a program
Give the output immediately after Gives output after saving and
typing command running the program , the output is
displayed on interactive mode
In interactive mode the previous In script mode any line can be
command cannot be altered altered any time
➢ Apart from Python there are some other distributions also available,
they are as follows:
o Anaconda Python – preloaded with NumPy, SciPy, Pandas etc.,
provide tools like jupyter notebook, Spyder IDE
Page 4 of 124
Downloaded from [Link]
o Spyder IDE provides an environment for python with advanced
editing, interactive testing and introspection features. It is
recommended as most preferred choice for programmer by
DataCamp community
Python Fundamentals
The routine work on computers are governed by the IPO (Input-Process-
Output) cycle. First the input is taken, then the process is done and finally
the result is produced. Similarly, every program also does the same thing.
A program is a set of instructions that govern the
processing.
In other words A program is base for processing data or
instructions.
Now let’s see what a typical python program contains:
Python character set
The set of any legal combination of characters are known as python
character set. A character represents any letter, digit or symbol in program.
The characters are as follows:
Letters A to Z or a to z
Digits 0 to 9
Symbols !@#$%^&*()[]{}?|\/~
Space A white space
Others Any ASCII character
Page 5 of 124
Downloaded from [Link]
Observe the program first then memorize the definitions:
Comment
Identifier
Output
Input Function
function
Tokens
In program every program words and punctuations are used.
Every individual word and punctuation marks used in
program are called tokens.
In other word tokens are lexical unit or lexical elements
or smallest unit of a program.
There are 5 tokens in Python:
Keyword Identifier Literal Punctuators Operators
Page 6 of 124
Downloaded from [Link]
Keywords
Keywords are reserve words. Each keyword has a
specific meaning to the Python interpreter, and we can
use a keyword in our program only for the purpose for
which it has been defined.
As Python is case sensitive, keywords must be written exactly.
Python keywords:
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
Used with exceptions, a block of code that will be executed
finally
no matter if there is an exception or not
Page 7 of 124
Downloaded from [Link]
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To return a list of values from a generator
Identifiers
In programming languages, identifiers are names used to identify (Name) a
variable, function, or other entities in a program.
Page 8 of 124
Downloaded from [Link]
The rules for naming an identifier in Python are as follows:
Variables
✓ A variable in a program is uniquely identified by a name (identifier).
✓ Variable in Python refers to an object an item or element that is stored
in the memory.
✓ Value of variable can be a string or numeric (e.g., 345) or any
combination of alphanumeric characters (CD67).
✓ In Python we can use an assignment statement to create new variables
and assign specific values to them.
✓ Variable declaration is explicit in python
Comments
Comments are used to add a remark or a note in the source code. Comments
are not executed by interpreter.
Page 9 of 124
Downloaded from [Link]
Comments in python can be created as:
Single Line •Write a single
line text
Comment •Begins with #
•Write a
Multiline descriptive text
Comment •Enclosed with
triple quotes
Literals
Data items holding a value is called literals.
1. String Literals: are sequence of characters surrounded by quotes (single,
double or triple)
S1=”Python”
S2=”Python3”
S3=”””this is triple
quoted string literals”””
2. Numerical Literals: are numeric values in decimal/octal/hexadecimal
form.
D1=10
D2=0o56 (Octal)
D3=0x12 (Hex)
3. Floating point literals: real numbers and may be written in fractional
form (0.45) or exponent form (0.17E2).
4. Complex number literal: are of the form a+bJ, where a, b are int/floats
and J(or i) represents i.e. imaginary number. Ex: C1=2+3j
Page 10 of 124
Downloaded from [Link]
5. Boolean Literals: It can have value True or False. Ex: b=False
6. Special Literal None: The None literal is used to indicate absence of value.
Ex: c=None
Data Types
Every value belongs to a specific data type in Python. Data type identifies the
type of data values a variable can hold and the operations that can be
performed on that data.
Python core
data types
Numbers Set None Sequence Mappings
Integer Float Complex String List Tuple Dictionary
Boolean
Page 11 of 124
Downloaded from [Link]
Number
Number data type stores numerical values only. It is further classified
into three different types: int, float and complex.
num1 = 10 #(integer positive value )
type(num1)
num2 = -1210 #(integer negative value)
type(num2)
float1 = -1921.9 #(float1 variable contain decimal value so it
type(float1) contains float value)
float2 = -9.8*10**2 #(float2 variable contain decimal value so it
print(float2, contains float value)
type(float2))
var2 = -3+7.2j #(var2 variable contain complex value)
print(var2, type(var2))
Boolean
var3= True # (var3 variable contain Boolean Value)
print(type(var3)) # print type Bool
Variables of simple data types like int, float, boolean, etc. hold single values.
But such variables are not useful to hold a long list of information.
For example, names of the months in a year, names of students in a class,
names and numbers in a phone book or the list of artefacts in a museum.
For this, Python provides sequence data types like tuples, lists, dictionaries
and sets.
Let us discuss about python sequence in detail.
Sequences
A Python sequence is an ordered collection of items, where each item is
indexed by an integer.
Page 12 of 124
Downloaded from [Link]
A brief introduction to these data types is as follows:
(A) String
❖ Group of characters
❖ May be alphabets, digits or special characters
❖ enclosed in quotation marks
❖ cannot perform numerical operations
❖ immutable datatype
(B) List
❖ sequence of items separated by commas
❖ the items are enclosed in square brackets [ ]
❖ mutable datatype
#To create a list list1 = [5, 3.4, "Gujarat", "12B", 45]
print(list1) # printing the elements of list1
Output: [5, 3.4, "Gujarat", "12B", 45]
(C) Tuple
❖ items separated by commas
❖ enclosed in parenthesis ( )
❖ immutable datatype
Example:
T=9,
T=(9,)
T=9,8,,6
(D) Dictionary
❖ holds data items in key : value pairs
❖ enclosed in curly braces { }
❖ Every key is separated from its value using a colon (:) sign
❖ The key : value pairs of a dictionary can be accessed using the key
❖ keys are usually immutable types and their values can be any data type
❖ to access any value specify its key in square brackets [ ].
Page 13 of 124
Downloaded from [Link]
Example:
dict1 = {'Fruit':'Apple', 1:'Monday', 'Price Rs':120}
print(dict1)
output: {'Fruit': 'Apple', 1:'Monday' ,'Price Rs': 120}
print(dict1['Price Rs'])
output: 120
print(dict1[1]) → output: ’Monday’
(E) None
❖ a special data type with a single value
❖ signify the absence of value
❖ supports no special operations
❖ it is neither False nor 0 (zero).
Mutable and Immutable Data Types
Variables whose values can be changed after they are
created and assigned without changing their memory
location are called mutable.
Variables whose values cannot be changed after they
are created and assigned or upon changing values their
memory location is changed, are called immutable.
When an attempt is made to update the value of an immutable variable, the
old variable is destroyed and a new variable is created by the same name in
new memory location.
Operators
A token that performs a specific task on variables. They are as follows:
Arithmetic +, -, *, /, %, **, //
Bitwise &,^,|
Identity is, is not
Page 14 of 124
Downloaded from [Link]
Relational >, >=, <, <=,!=, ==
Logical and, or
Assignment =
Membership in, not in
Arithmetic assignment /=, +=, -=, *=, %=, **=, //=
Precedence of Operators
Evaluation of the expression is based on precedence of operators. When an
expression contains different kinds of operators, precedence determines which
operator should be applied first. Higher precedence operator is evaluated
before the lower precedence operator. Order of Precedence (higher to lower)
PE(MD) (AS) = read PEMDAS
→ P=parenthesis () , E=exponential
→ M, D = multiplication and division
→ A, S=addition and subtraction
[Link] Operator Remarks
1 ** Exponentiation (raised to the power)
2 ~ ,+, - Complement, unary plus and unary minus
3 * ,/, %, // Multiply, divide, modulo and floor division
4 +, - Addition and subtraction
5 <= ,< ,> ,>= Relational operators
6 == ,!= Equality operators
=, %=, /=, //=, -
7 Assignment operators
=, +=, *=, **=
8 is , is not Identity operators
9 in, not in Membership operators
10 not, and, or Logical operators
* For operators with equal precedence, the expression is evaluated from left
to right except ** which is executed from right to left.
Page 15 of 124
Downloaded from [Link]
PUNCTUATORS
Punctuators are symbols that are used to organize sentence structure.
Common punctuators used in Python are: ‘ “ # \ ( ) [ ] { } @ , : .
Components of python program
A python program has following components:
Expressions
•Any legal
Function
combination of •A named code
symbols •Can be reused by its
•Represents a value name
•Ex.: x + 2, (17/3)*2 •Ex. Add(5,3)
Statements block &
•It does something indentation
•Some action taken •A group of
place statements
•Ex. print •Part of another
("TutorialAICSIP") statement or
function
•Known as suit or
code-block
Lvalue and Rvalue
Lvalue Rvalue
• Expression comes at left • Literals & expression come at right
• Objects which has a value • Rvalues always come on rhs
• It can be both lhs or rhs
Page 16 of 124
Downloaded from [Link]
Dynamic Typing
A variable pointing to a value of a certain type can be
made to point to a value of another type is called
dynamic typing.
Ex. a= 23 Output:
print(a) 23
a=”TutorialAICSIP” TutorialAICSIP
print(a)
Here a is first pointing to 23 then the string “TutorialAICSIP”. Hence the
memory representation of variable a is something like this.
Dynamic type is different from static typing. In static typing data type of a
variable remains fixed and cannot be changed.
Programming language like C,C++, Java support static typing.
Type Casting
Type casting refers to conversion of a data type from
one to another.
Page 17 of 124
Downloaded from [Link]
Python supports two types of type casting:
(i) Implicit type casting: The type conversion performed without
programmer’s intervention is known as implicit type casting. In a mixed
arithmetic expression python converts all operands up to the type of
largest operand which is called type promotion.
(ii) Explicit type casting: This is type of user defined type conversion forces
to an expression to be of specific type. It is performed by a specific type()
function for an appropriate data type such as int(), str(), float() etc.
Input and Output Function
Python offers input() for input:
• The input accepts input from user through keyboard.
• It always returns a value of string type.
• For number you need to use int() or float() function.
Python offers print() for output:
• The print() function sends the output to the standard output device.
• It accepts message, separator and endline character.
• It converts any type of items to string.
• A print() function return a blank line without any value or expression.
Features of print() function;
• Auto converts the supplied parameters into string
• Inserts a space between items automatically because default sep is space
• To change the default endline character, end parameter is used
• To extend the text written in print function \ is used
Introduction to python standard library module
Python provides certain modules to perform specialized actions. So let us
discuss what is module?
Page 18 of 124
Downloaded from [Link]
A module is python file having variables, constants,
functions and objects defined in it which can be used
into the other programs.
These modules can be accessed by importing modules in the program. The
modules need to be import using three ways:
Method 1: import <module name>
Example:
>>>import math
>>>[Link](100)
10.0
Method 2: import <module name> as <alias name>
Example:
>>>import math as m
>>>[Link](100)
10.0
Method 3: from <module> import <function/variable/object>
>>>from math import sqrt
>>>sqrt(100)
10.0
Math constants
1. pi – Returns the math constant value of pi. The value returned by this
constant is s 3.14 1592653589793
Example:
>>>import math
>>>[Link]
3.141592653589793
Page 19 of 124
Downloaded from [Link]
2. e – Returns the constant value of the Eular’s Number. The value
returned by this constant is 2.718281828459045.
Example:
>>>import math
>>>math.e
2.718281828459045
Math module functions
1. sqrt(): Returns the square root of given number. Returns error with negative
numbers.
Example:
>>>import math
>>>[Link](100)
10.0
2. ceil(): It returns the smallest integer of the given number but the
number returned is not more than the specified number.
>>>import math
>>>[Link](5.56)
6
>>>[Link](5.12)
6
>>>[Link](-5.56)
-5
3. floor(): It returns largest integer not greater than number
>>>import math
>>>[Link](5.56)
5
>>>[Link](5.12)
5
>>>[Link](-5.56)
-6
Page 20 of 124
Downloaded from [Link]
4. pow(): It returns the power of specified number. It requires two
arguments i.e. the base and exponent value.
>>>import math
>>>[Link](5,2)
25.0
>>>[Link](-5,2)
25.0
>>>[Link](5,-2)
0.04
>>>[Link](5,0)
1.0
5. fabs():Returns the absolute value of the given number. Basically
converts negative number to positive number.
>>>import math
>>>[Link](-15)
15.0
>>>[Link](-15)
15.0
Random module functions
The random module generates random number. This module provides three
functions as follows:
➢ random(): It returns random numbers from 0.0 to 1.0. The number
retuned by this function is always less than 1.
>>>import random
>>>[Link]()
0.9629983747184706
To generate floating generate number within range multiply random()
with difference of upper limit with lower limit and then add lower limit.
Page 21 of 124
Downloaded from [Link]
>>>import random
>>>[Link]()*(40-18)+18
38.437349792720944
>>>[Link]()*(40-18)+18
31.124594769863897
>>>[Link]()*(40-18)+18
23.959450191703525
➢ randint(x,y): Returns a random integer numbers between x and y. Both
x and y are inclusive.
>>>import random
>>>[Link](5,9)
8
>>>[Link](5,9)
6
➢ randrange(start,stop,step):Generate random numbers as specified
start,stop and step value. By default start is 0 and step is 1.
>>>import random
>>>[Link](5)
3
>>>[Link](5,9)
6
>>>[Link](5,9,2)
7
>>>[Link](5,9,2)
7
Page 22 of 124
Downloaded from [Link]
Statistics Module
It offers various statistics functions for data analysis. These functions are
used in python programs from this module:
1. mean(): This function returns the average of the given sequence.
>>>import statistics as s
>>>[Link]([11,22,33])
22
2. median(): Returns the middle value of the specified sequence.
>>>import statistics as s
>>>[Link]([11,22,33])
22
>>>[Link]([33,11,22])
22
3. mode(): It returns most repeated value from the specified sequence.
>>>import statistics as s
>>>s. [Link]([33,11,22,22,45,67,22,89,22])
22
>>>s. [Link]([33,11,22])
33
Flow of Control
In a program sometimes we need to take a decision using statements, repeat
statements on specific conditions or counting steps etc.
Python provides some statements to do these all. These statements are known
as program control statements.
Page 23 of 124
Downloaded from [Link]
Types of statements in python
Python supports three types of statements:
1 2
Empty Simple/Single
Statement statement
3
Compund statement
Empty Statement
➢ It is simplest statement in python program
➢ It does nothing in python program
➢ It requires when the presence of statement is needed but logic of
program is not needed
➢ The pass keyword is used to write empty statement
➢ When pass is written in python program the interpreter does nothing
just move to the next statement
➢ It is also known as null statement
Simple Statement
➢ A single executable statement is simple statement in python
➢ In other words, a single line statement of python program
➢ Example
print(“Python Revision”)
Page 24 of 124
Downloaded from [Link]
Compound Statement
➢ It represents a group of statements executed as a unit
➢ It has two parts:
A header: • Begins with a keyword
• ends with a colon
• contains one or more statements
• each statement is indented inside
A body: the header line
• all statement are written in same
level of indentation
Statement flow control
In a python program the statement may execute in a sequence or selection or
iteration (repetition) form.
There are various programming constructs to execute statements in python.
These constructs are:
• Statements executes in an order
Selection • Some statements repeat again
• Default flow of statement and again based on a condition
• It is simplest programing • Execution depends on a • It is known as loop
construct condition • Repeated statements are called
• A course of action is performed body of the loop
when condition is true other wise
another
• It is also known as decision
construct
Sequence Repetition
Page 25 of 124
Downloaded from [Link]
Selection
The if statement has following syntaxes:
1)
if condition:
statement(s)
2)
if condition:
statement(s)
else:
statement(s)
3)
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Indentation
Python uses indentation for block as well as for nested
block structures. Leading whitespace (spaces and tabs)
at the beginning of a statement is called indentation.
Page 26 of 124
Downloaded from [Link]
In Python, the same level of indentation associates statements into a single
block of code. The interpreter checks indentation levels very strictly and
throws up syntax errors if indentation is not correct. It is a common practice
to use a single tab for each level of indentation.
Repetition
Repetition of a set of statements in a program is made possible using looping
constructs.
For Loop
➢ used to iterate over a range of values or a sequence
➢ executed for each of the items in the range
➢ values can be either numeric, or they can be elements of a data type
like a string, list, tuple or even dictionary
➢ known as counting loop
Syntax of the for Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
While loop
➢ executes a block of code repeatedly as long as the control condition of
the loop is true
➢ The control condition of the while loop is executed before any statement
inside the loop is executed
➢ After each iteration, the control condition is tested again and the loop
continues as long as the condition remains true
➢ When this condition becomes false, the statements in the body of loop
are not executed and the control is transferred to the statement
immediately following the body of while loop
➢ If the condition of the while loop is initially false, the body is not
executed even once.
➢ It is also known as entry-controlled loop or pre-conditional loop
Page 27 of 124
Downloaded from [Link]
Syntax of while Loop
while test_condition:
body of while
The loop else statement
➢ The else statement with loop is little bit different from if-else
➢ The else statement with loop executes only loop ends normally
➢ It executes when the condition gets false in while loop and in for loop,
when the loop has executed for the last value
➢ Example (While):
i=10
while i>0:
print(i)
i-=1
else:
print(“Loop is over”)
➢ Example (For):
for i in range():
print(i)
i-=1
else:
print(“Loop is over”)
Break and Continue Statement
In certain situations, when some particular condition occurs, we may want to
exit from a loop (come out of the loop forever) or skip some statements of the
loop before continuing further in the loop.
These requirements can be achieved by using break and continue statements,
respectively.
Page 28 of 124
Downloaded from [Link]
break
Nested Loops
➢ The loop contains another loop inside is called nested loop
➢ The inner loop must terminate before the outer loop
➢ In nested loop, if break statement is used then the break will
terminate that loop in which it is written
Strings processing and other functions
➢ An empty string is a string that has 0 characters.
➢ Strings are sequence of characters, where each character has a unique
position-id/index.
➢ The indexes of a string begin from 0 to (length -1) in forward direction
and -1,-2, -length in backward direction.
Traversing String
Traversing string refers to accessing each character of
string using for loop.
Example:
S=”TutorialAICSIP” S=”TutorialAICSIP”
for i in S: for i in range(len(S)):
print(i) print(i)
Page 29 of 124
Downloaded from [Link]
Basic string operators
The following operators are useful on python strings:
• Joins two strings
Concatenate (+) • Create a new string
• Requires two strings only
• Replicate the string as specified number
Replication (*)
• Requires one string and one number
• Checks for the given character or substring is
Membership exist or not in string
(In, not in)
• If its present return True otherwise false
• Compare the string letter by letter in dictionary
Relational order
operator
• In == and != it checks exact match
(<,>,<=,>=)
• In comparison it checks for ord() value
Slicing
Slice refers to part of a string containing some contiguous characters from the
string.
The syntax is str_variable[start:end:step]
start: from which index number to start
end: upto (end-1) index number characters will be extracted
step: is step value. (optional) By default it is 1
Example: s=’TutorialAICSIP’
String T u t o r i a l A I C S I P
Forward 0 1 2 3 4 5 6 7 8 9 10 11 12 13
index
Backward -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
index
Page 30 of 124
Downloaded from [Link]
Slicing
Command Output Prints
S TutorialAICSIP Complete String
s[:] TutorialAICSIP Complete String
s[::] TutorialAICSIP Complete String
s[2] t Character at 2nd index
s[1:5] utor From 1 to (5-1 =4)
s[1:9:2] uoil From 1 to (9-1=8) every second letter
s[::2] TtraACI From start to end, every 2nd letter
s[::3] ToaII From start to end, every 2rd letter
s[::-1] PISCIAlairotuT Reverse the string
s[:-1] TutorialAICSI Entire string except last letter
s[-1] P Only last letter
s[-6::] AICSIP From index -6 to last letter
s[-8:-4:] alAI From index -8 to -4
String functions and methods
➢ Every string object that you create in Python is actually an instance of
String class.
➢ The string manipulation methods that are being discussed below can
be applied to string as per following syntax:
<stringObject>.<methodname>()
1. capitalize(): Returns a copy of the string with its first character
capitalized
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
‘Python revision tour class 12’
Page 31 of 124
Downloaded from [Link]
2. title(): Returns a copy of the string with first character of each word
into capital.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
‘Python Revision Tour Class 12’
3. upper(): Converts the specified entire string into capital.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
‘PYTHON REVISION TOUR CLASS 12’
4. lower(): Convert entire string into lower case.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
‘python revision tour class 12’
5. count(str,start,end): Counts the given substring from the string and
returns the occurrence of the same. Returns 0 if substring does not
exists in the string. The start and end are optional.
Example:
>>>S=”python revision tour class 12”
>>>[Link](‘n’)
2
>>>[Link](‘n’,6)
1
>>>[Link](‘n’,6,12)
0
Page 32 of 124
Downloaded from [Link]
6. find(sub[,start,end]): Returns the lowest index in the string where
the substring sub is found within the given range. Returns -1 if sub is
not found.
Example:
>>>S=”python revision tour class 12”
>>>[Link](‘tour’)
16
>>>[Link](‘class’,15,30)
21
>>>[Link](‘computer’)
-1
7. index(str): If given substring is found in the string then returns the
lowest index otherwise raise ValueError.
Example:
>>>S=”python revision tour class 12”
>>>[Link](‘class’)
21
>>>[Link](‘class’,15,30)
21
>>>[Link](‘computer’)
ValueError : Substring not found
8. endswith(): Returns True if the string ends with the specified
substring otherwise False.
Example:
>>>S=”python revision tour class 12”
>>>[Link](‘12’)
True
Page 33 of 124
Downloaded from [Link]
9. startswith(): Returns True if the string starts with the specified
substring otherwise False.
Example:
>>>S=”python revision tour class 12”
>>>[Link](‘python’)
True
>>>[Link](‘12’)
False
10. isalnum(): Returns True if the characters in the string are
alphanumeric (alphabets or numbers) and there is at least one
character, False otherwise.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
False
>>>S=”PythonClass12”
>>>[Link]()
True
11. islower(): Returns True if all characters in the string are lowercase.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
True
>>>S=”PythonClass12”
>>>[Link]()
False
Page 34 of 124
Downloaded from [Link]
12. isupper(): Returns True if all characters in the string are uppercase.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
True
>>>S=”PythonClass12”
>>>[Link]()
False
13. isspace(): Returns True if there are only whitespace characters in
the string.
Examples:
>>>S=”python revision tour class 12”
>>>[Link]()
False
>>>S=” ”
>>>[Link]()
True
14. isalpha(): Returns True if all characters in the string are alphabets,
False otherwise.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
False
>>>S=”PythonRevision”
>>>[Link]()
True
Page 35 of 124
Downloaded from [Link]
15. isdigit(): Returns True if all the characters in the string are digits
otherwise it returns False.
Example:
>>>S=”python revision tour class 12”
>>>[Link]()
False
>>>S=”12”
>>>[Link]()
True
16. lstrip([chars]): Removes the leading specified characters from
string or remove leading whitespaces from the specified string.
Example:
>>>S=” TutorialAICSIP”
>>>[Link]()
‘TutorialAICSIP’
>>>S=”******TutorialAICSIP”
>>>[Link](‘*’)
‘TutorialAICSIP’
17. rstrip([chars]): Removes the specified trailing characters from
string or removes the trailing spaced from the string if characters not
specified.
Example:
>>>S=”TutorialAICSIP ”
>>>[Link]()
‘TutorialAICSIP’
>>>S=”TutorialAICSIP******”
>>>[Link](‘*’)
‘TutorialAICSIP’
Page 36 of 124
Downloaded from [Link]
18. strip([chars]): removes the specified leading and trailing characters
from the string or leading and trailing spaces from the string if not
specified.
Example:
>>>S=” TutorialAICSIP ”
>>>[Link]()
‘TutorialAICSIP’
>>>S=”*******TutorialAICSIP******”
>>>[Link](‘*’)
‘TutorialAICSIP’
19. split([<sep>]): Separate the string from specified characters in a
list form. Divide the string into parts considering the given
string/character as separator. If no character is specified the it will
separate the text from space by default.
Example:
>>>S=”Tutorial AICSIP”
>>>[Link]()
[‘Tutorial’,’AICSIP’]
>>>S=” CS Class 12 @2024”
>>>[Link](‘2’)
[‘CS Class 1', ' @', '0', '4']
20. partition(<sep>): The partition() method searches for a specified
string, and splits the string into a tuple containing three elements.
These three elements are:
1. Text before separator
2. The separator
3. Text after separator
It separates the text from the first occurrence of separator.
Page 37 of 124
Downloaded from [Link]
Example:
>>>S=” CS Class 12 @2024”
>>>[Link](‘2’)
('CS Class 1', '2', ' @2024')
21. replace(<old string>,<new string>): This functions replaces all
occurrences of <old string> with <new string> in the given string.
Example:
>>>S=” CS Class 12 @2024”
>>>[Link](‘2’,’@’)
'CS Class 1@ @@0@4'
22. join(‘str’): It joins a string or character after each member of the
string iterator.
Example:
>>>S=” Tutorials”
>>>’*’.join(S)
'T*u*o*r*i*a*l*s'
Lists in Python
➢ Containers that are used to store a list of values of any type
➢ They are mutable i.e., you can change the elements of a list in place
➢ Python will not create a fresh list when any changes made to an element
➢ List is a type of sequence like strings and tuples
Difference from Strings
You cannot change individual elements of a string in place, but Lists allow
you to do so. That is, following statement is fully valid for Lists:
L[i] = <element>
L=[13,45,67,89]
L[3]=98
Page 38 of 124
Downloaded from [Link]
Creating Lists
Python lists can be created using following:
Empty List • L=[]
• L=[5,6,7,8]
List of numbers • L=[56.75,85.50,65.45]
• L=[‘a’,’b’,’c’]
List of string • L=[‘Python’,’C’,’C++’,’Java’]
List of mixed type • L=[12,’Suveni’,’XII A’, 85.65]
• L=list(“Python”)
List of sequence • L=list((‘a’,’b’,’c’))
Nested Lists • L=[1,[34,56,78],32,11]
List of user defined • L=eval(input(“Enter the list:”))
values
Accessing Lists
➢ List elements are stored at particular index
➢ The index of lists are starting from 0
➢ Each element can be accessed using its index
L=[1,[45,78,90],'XII
B'] L[0] 1 L[1][1] 78
Page 39 of 124
Downloaded from [Link]
Modifying List
➢ Lists are mutable
➢ Each element can be modified easily
➢ For example:
>>>L=[34,56,78,990]
>>>L[1]=85
>>>L
[34, 85, 78, 990]
Similarities with String
Length len() function returns total no. of elements from list
L=[3,4,5,6]
print(len(l)) → 4
Indexing List also supports backward and forward indexing
L=[3,5,6,7]
L 3 5 6 7
Forward 0 1 2 3
Backward -4 -3 -2 -1
Slicing List supports slicing as strings
L=[2,44,56,77,43,32]
L[:4]=[2,44,56,77]
Membership in and not in can be used as same as string
L=[3,5,6,7]
If 5 in L:
print(“Found”)
Concatenation It supports concatenation similarly as string
L=[1,2]
L=L+[3,5] → L[1,2,3,5]
Replication It allows replicating lists as strings
L=[1,2]
L=L*2=[1,2,1,2]
Page 40 of 124
Downloaded from [Link]
Comparison Lists can be compared using relational operators
L1=[6,7,8]
L2=[4,6,7]
L1<L2→ False
Traversing List traversing can be done using for loop
L=[7,8,9,10]
Without Index With Index
for i in L: for i in range(len(L)):
print(i) print(i,”-”,L[i])
List Functions
1. append() - adds an item to the end of the list
Example:
>>>l=[11,25,36,89]
>>>[Link](99)
>>>l
[11, 25, 36, 89, 99]
2. extend(): Adds multiple items into the list
Example:
>>>l=[11,25,36,89]
>>>[Link]([56,78,90])
>>>l
[11, 25, 36, 89, 56,78,90]
3. insert(): insert an element to specified position
Example:
>>>l=[11,25,36,89]
>>>[Link](2,44)
>>>l
[11, 25, 44,36, 89]
Page 41 of 124
Downloaded from [Link]
4. count(): Counts the frequency of an specified element, if element is not
present in the list, it returns zero.
Example:
>>>L = [31,81,21,11,81,24]
>>>print([Link](81))
2
>>>print([Link](39))
0
5. index(): Returns the index of specified element of the list. If elements
are repeated, it will display the index of first occurrence. If the element is
not present in the list, it will raise a ValueError.
>>>L = [31,81,21,11,81,24]
>>>print([Link](81))
1
>>>print([Link](39))
ValueError: 39 is not in list
6. remove(): Removes the first occurrence of specified value. If the value
is not present in the list it will raise ValueError.
>>>L = [31,81,21,11,81,24]
>>>[Link](81)
>>>L
[31,81,21,11,81,24]
>>>[Link](39)
ValueError: [Link](x): x is not in list
Page 42 of 124
Downloaded from [Link]
7. pop(): It removes the element at specified index. If no index is specified,
it will removes the last index. If the specified index is not present in the
list, it will raise IndexError. It returns the popped element.
>>>L = [31,81,21,11,81,24]
>>>[Link]()
24
>>>[Link](1)
81
>>>[Link](7)
IndexError: pop index out of range
8. reverse() : It reverses the list in place.
>>>l=[33,85,74,63,15]
>>>[Link]()
>>>l
[15, 63, 74, 85, 33]
9. sort(): It sorts the list items in ascending order by default. It is done in
place, it does not create a new list. To sort in descending order
reverse=True parameter is required.
>>>l=[33,85,74,63,15]
>>>[Link]()
>>>l
[15, 63, 74, 85, 33]
>>>[Link](reverse=True)
>>>l
[85, 74, 63, 33, 15]
Page 43 of 124
Downloaded from [Link]
Introduction to Python Tuples
❖ Python tuples are immutable
❖ cannot change the elements of a tuple in place
❖ Python will create a fresh tuple when changes made to an element
Tuple functions
• returns length of tuple i.e. the count of elements in
len() the tuple
• returns the element having maximum value
• Please note that max() applied on sequences like
max() tuples/lists etc. will return a maximum value ONLY IF
the sequence contains values of same type.
• returns the element minimum value Like max(), for min()
min() to work, the element of tuple should be of same type.
• works with tuples in the same way it works with lists and
index() returns the index of an existing element
count() • returns the count of a member element/object
• converts this tuple to a sorted list. If reverse is set to True
sorted() then tuple is sorted in descending order
Indirectly Modifying Tuples
Tuples can be modified using two ways:
(a) Using Tuple Unpacking
To change a tuple, unpack it, change the values, and then again
repack it:
Page 44 of 124
Downloaded from [Link]
Example:
t=(11,22,33,44)
First unpack the
tuple a,b,c,d = t
Now repack the
Redefine or change
tuple with changed
desired variable b=7
value t = (a,b,c,d)
(b) Using the lists and tuples functions i.e., list() and tuple()
There is another way of doing the same as explained below:
1. Convert the tuple to list using list(), l=list(t)
2. Make changes in the desired element in the list, l[1]=7
3. Create a tuple from the modified list with tuple() , t=tuple(l)
Convert the tuple to
list using list(), l=list(t)
Create a tuple from Make changes in the
the modified list with desired element in
tuple() , t=tuple(l) the list, l[1]=7
Page 45 of 124
Downloaded from [Link]
Dictionary
Dictionaries are mutable unordered collections with elements in the form of
a {key:value} pairs that associate keys to values.
Characteristics of a Dictionary
1. Unordered Set: A dictionary is a unordered set of key:value pairs. Its
values can contain references to any type of object.
2. Not a sequence: Unlike a string, list and tuple, a dictionary is not a
sequence because it is unordered set of elements.
3. Indexed by Keys, Not Numbers: Dictionaries are indexed by keys and
not by any index like in sequences.
4. Keys must be unique: Each of the keys within a dictionary must be
unique. Since keys are used to identify values in a dictionary, there
cannot be duplicate keys in a dictionary. However, two unique keys
can have same values.
6. Internally stored as Mappings: Internally, the key:value pairs of a
dictionary are associated with one another with some internal function
(called hash function), this way of linking is called mapping.
Dictionary functions
1. The len() function
This method returns length of the dictionary, i.e., the count of elements
(key:value pairs) in the dictionary.
2. The clear() function
This method removes all items from the dictionary and the dictionary
becomes empty dictionary.
3. The get() function
With this method, you can get the item with the given key, similar to
dictionary[key], If the key is not present Python by default gives error, but
you can specify your own message through default argument as per
following syntax:
Page 46 of 124
Downloaded from [Link]
4. The items() function
This function returns all of the items in the dictionary as a sequence of
(key, value) tuples. Note that these are returned in no particular order
<dictionary>.items()
Example:
myList = [Link]()
for x in myList:
print(x)
The output of the above code will be like:
5. The keys() method
This method returns all of the keys in the dictionary as a sequence of keys
in form of a list.
6. The values() function
This method returns all the values from the dictionary as a list.
7. The update() function
This function merges key:value pairs from the new dictionary into the
original dictionary, adding or replacing as needed.
Page 47 of 124
Downloaded from [Link]
The items in the new dictionary are added to the old one and
override(overwrite) any item already there with the same keys. The
syntax to use this method is given below:
<dictionary>.update(<other-dictionary>)
Example:
[Link](Employee2)
print(Employee1)
8. The fromkeys() function
➢ This method creates a dictionary from the given sequence of keys and
a value.
➢ It assigns same value for all keys.
➢ If value is not given then it assigns None as the value of all keys.
d1 = [Link](month, 31)
print(d1) will give us:
{'Jan': 31, 'Mar': 31, 'May': 31} and
d2 = [Link](month)
print(d2) will give us:
{'Jan': None, 'Mar': None, 'May': None}
9. The copy() function
➢ This method creates a copy of the dictionary.
➢ This method does not make any change in the original dictionary.
➢ It only makes a copy of this dictionary.
10. The pop() function
➢ Like lists pop() method removes an element from a dictionary.
➢ This method removes a key:value pair from the dictionary and
returns the value removed.
➢ For this a key need to be specified.
Page 48 of 124
Downloaded from [Link]
11. The popitem() function
In Python 3.7 and higher version this method of dictionary removes the
last inserted key:value pair from the dictionary and return it as a tuple.
12. The setdefault() method
➢ This method of dictionary takes two arguments key and default-value.
➢ If key is found in the dictionary then it returns its corresponding value.
➢ If key is not found in the dictionary then it inserts the default-value
with key in the dictionary and returns default-value.
➢ If default-value is not given then None is inserted as defaultvalue of
the key and returns nothing.
➢ Its syntax is: <dict>.setdefault(<key>[,<default-value>])
For example:
>>>d1={'Jan':31, 'Feb':28, 'Mar':31}
>>>[Link]('Jan')
31
>>>[Link]('Apr',30)
30
>>>[Link]('May')
>>>d1
{'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': None}
13. The max() function
This function when applied with dictionary returns the maximum key
value of all keys of dictionary.
For example: d1={'Jan':31, 'Feb':28, 'Mar':31}
print(max(d1))
Page 49 of 124
Downloaded from [Link]
14. The min() function
This function when applied with dictionary returns the
smallest key value of all keys of dictionary. For example:
d1={'Jan':31, 'Feb':28, 'Mar':31}
print(min(d1))
15. The sorted() function
This function returns the keys of the dictionary in ascending order in the
form of a list.
For example: d1={'Jan':31, 'Feb':28, 'Mar':31} sorted(d1)
['Feb', 'Jan', 'Mar']
For getting result in descending order use reverse=True with sorted()
function.
sorted(d1,reverse=True)
['Mar', 'Jan', 'Feb']
Page 50 of 124
Downloaded from [Link]
Chapter 2 Working with functions
Introduction to functions
➢ Large programs need to be divided into smaller units
➢ A function is a small unit of a program
➢ It consists of different functions
➢ A function has a few statements and instructions written in its body
➢ A function is invoked from other parts of program as and when needed
For example, if A school is organizing an Annual Day function which is a
combination of some cultural programs and events.
Here we can consider all the cultural programs and events as a function.
These functions will be executed on the Annual day in a specific order. In a
similar way, it does for the Python program.
Function Definition
A function is a small unit of a program/subprogram that
processes the data and often returns a value.
The need for functions
Easy program handling
Reduce the size of the program
Reduce the repeated statements
Ambiguity can be reduced
Make the program more readable and understandable
Page 51 of 124
Downloaded from [Link]
How to create a function in Python?
Python allows to create a function in a program that
➢ Can have arguments
➢ Can perform certain tasks
➢ Can produce a result
For example:
def add(n1,n2):
res= n1 + n2
return res
add(5,6)
x=add(5,6)
print("Addition is:",x)
In the above example:
➢ def starts the function
➢ add(n1,n2) – add is a function name and n1, n2 are arguments
➢ A function header ends with a colon
➢ After colon body of the function starts
➢ It is indented part contains the statements to follow the instructions
➢ It is called body-of-function
➢ The return keyword returns the final result
➢ To use this function for result we need to call/invoke it
➢ If the function is returning a value we need to store a function in a
variable or directly print by calling it
Page 52 of 124
Downloaded from [Link]
To create a function in Python consider the following parts of a function:
Parts of Function
Part Description
Function Always starts with the “def” keyword followed by the
Header function name and its parameters, ends with a colon (:)
Parameters Variables supplied in brackets of the function header
Function Block of statements/instructions that define the action
Body performed by the function, indentation must be followed
White space at the beginning of every statement with
Indentation
the same block
Function
writing function name including parameter values
Calling
Page 53 of 124
Downloaded from [Link]
The following five basic steps are used to create and invoke a function.
Watch the following for more details:
Introduction to Functions
Follow this link for important questions:
QnA Functions
Page 54 of 124
Downloaded from [Link]
After writing the function it must be invoked through calling by following these
steps:
• Save a program and click run or press the F5 button
• Now interactive mode will appear with the message RESTART ……
• Write a function call statement as shown in the below image
• A function call statement is just like a function name with required
parameters
• Press enter and supply input as per requirements
Function Calling
Structure of Python Program
A Python program is a set of a few statements and blocks. A Python program
may have the following:
• Physical line structure: A Python program is divided into no. of logical
lines, the logical line is created from one or more physical lines
• Joining two lines: A logical line can be broken into two or more
physical lines using a backslash ()
• Multiple statements on a single line: Semicolon (;) is used to write
multiple statements on a single line
• The top-level statement or _main_: Unindented statements
• Comments: Begins with a hash symbol (#), python interpreter ignores
them, multi-line comments will be written in """ (triple-double quotes).
• Indentation: White spaces used at the beginning of every line. The
indented part is known as one block.
Page 55 of 124
Downloaded from [Link]
Python Program Structure
The flow of Execution in the Function call
➢ A function in the python program is called by a function call statement
➢ To call a function, write the function name followed by parameter values
in brackets
➢ A block of statements executed in the execution frame
➢ When a function is called, an execution frame is created and controls
the transfer
➢ Within the execution frame, the statements written in the function body
are executed and return a value or execute the last statement
➢ Python follows top to bottom approach for executing program
➢ Comments are ignored in the execution
➢ If Python notices a function definition with a def statement it just
executes the function header line and skips all statements in the
function body these statements execute when a function will be called
Page 56 of 124
Downloaded from [Link]
Understand the flow of execution:
1. # A program to add two integers using a function
2. def add(n1,n2):
3. res=n1 + n2
4. return res
5. X = int(input(‘Enter number 1:’))
6. Y = int(input(‘Enter number 2:’))
7. Sum = add(X, Y)
8. print(“The sum of two integers are:”, Sum)
The execution of above program is done as follows line wise:
2 2 3 8
5&6 7 4 7
Function is calling another function is called the caller
and the function being called is called function or callee.
In above code __main__ is the caller and add() is called function or callee.
Let's start with an understanding of the Python flow of execution in the
function calls.
Watch this video for more details:
Structure of python program
Page 57 of 124
Downloaded from [Link]
Python Function types
Python supports three types of functions:
➢ Built-in Functions: Pre-defined functions of Python such as input(),
int(), max(), len() etc.
➢ Functions defined in modules: Functions defined in particular
modules, can be used when the module is imported. A module is a
container of functions, variables, constants, and classes in a separate
file that can be reused. The module can be imported in two ways
o import statement: Used to import the entire module.
EX. import math
o from statement: import all functions or the selected one.
EX. from random import randint
• User-Defined Functions: Function created by the programmer
Page 58 of 124
Downloaded from [Link]
User-Defined Functions
Python UDF example
In the above program, two functions were created
i) simple_interest()
ii) main()
The simple_interest() function receives three parameters p,r and n.
main() function prompts to input these values and is accepted as an
argument in calling simple_interest() function.
Parameters and Arguments in Function
Parameters are the values provided at the time of
function definition.
For Ex. p,r and n.
Arguments are the values passed while calling a
function.
For Ex. princ_amt, r, n in main().
Argument in python can be one of these types:
1. Literals
2. Variables
3. Expressions
Page 59 of 124
Downloaded from [Link]
Arguments are also as actual parameters or actual arguments. And
Parameters are formal parameters or formal arguments.
There are two mechanisms for function calling:
1. Call by value - In this mechanism, the called function makes a
separate copy of passed values then works with them. Hence the
original values remain unchanged. In python, immutable types
implement Call by value.
2. Call by reference – In this mechanism, the called function works with
the original value. Hence any changes made to them will change the
original values. In python, mutable types implement Call by reference.
Types of Arguments
Python supports four argument types:
➢ Positional Arguments:
o Arguments passed to a function in correct positional order, no. of
arguments must match with no. of parameters required.
Positional arguments in Python Functions
➢ Default Arguments:
o Assign default to value to a certain parameter, it is used when
the user knows the value of the parameter, default values are
specified in the function header.
o It is optional in the function call statement. If not provided in the
function call statement then the default value is considered.
o Default arguments must be provided from right to left.
Page 60 of 124
Downloaded from [Link]
default arguments default parameters
➢ Key Word Arguments:
o Keyword arguments are the named arguments with assigned
values being passed in function call statement, the user can
combine any type of argument.
o The key word arguments can be written in any order in function
call statement
Example:
def add(n1,n2,n3=2):
return n1 + n2 + n3
res=add(n1=4,n2=5)
print(res)
res=add(n2=6,n1=5,n3=4)
print(res)
➢ Variable Length Arguments: It allows the user to pass as many
arguments as required in the program. Variable-length arguments are
defined with * symbol.
def prod(*n):
pr=1
for i in n:
pr*=i
print(“Product = “, total)
# Calling function
prod() # o/p 1
prod(3) #o/p 3
prod(1,2,3,4) #o/p 24
Page 61 of 124
Downloaded from [Link]
Rules for combining three types of arguments
1. An argument list must contain positional arguments followed by any
keyword argument.
2. Keyword arguments should be taken from the required arguments
preferably.
3. Value of argument can’t be specified more than once.
Returning values from function
A function in Python may or may not return a value.
There are two types of functions:
1. Void
A function that does not return values is called a void
function.
Example:
def fun1():
print(“Python Void Functions”)
The void function returns None.
2. Non Void
A function returning value is called non void function.
A value returned can be one of the following:
1. A literal
2. A variable
3. An expression
➢ A result will be printed in the same function.
Page 62 of 124
Downloaded from [Link]
➢ A function that returns a value is a function that displays the
calculated result.
➢ The value returned to a specific variable.
➢ The result will be printed in some other function.
Example:
Function returning literal Function returning Function return a
None: expression: variable:
return return 3 * 3 return x
Function returning a value is also known as fruitful function. The return
statement in function ends execution of function.
There are four possible combinations of functions are as follows:
a) non-void Function without arguments
b) non-void Function with some arguments
c) void functions without arguments
d) void functions with arguments
Returning multiple values
To return multiple values from a function follow these:
• return statement should follow these – return value1, value2, ….
• The returned value should be either in tuple or in tuple unpack form
Composition
➢ It refers to using an expression as part of a larger expression or
statement as a part of large statement.
➢ The composition is as follows:
o Arithmetic - large_check((4*3),(4+3))
o Logical – logic_test(4<5 or 6>7)
o Function call – int (float(“12.5”)*2)
Follow this link to watch the video for more understanding:
Watch Now
Page 63 of 124
Downloaded from [Link]
Scope of Variable
A variable scope refers to access location of a variable.
There are two kinds of scopes:
Global Variable
➢ A variable that is declared in top-level statements is called a global
variable.
➢ It is usable to entire program.
➢ To access the value of a global variable user needs to write a global
keyword in front of the variable in a function.
Local Variable
➢ A name declared in a specific function body is called a local variable.
➢ It can be used in only within the function in which is declared and
some internal blocks where it is declared.
➢ A local variable can be a multi-level scope because sometime it has
enclosing local scope in nested block.
Example:
def add(n1,n2,n3):
Local Variables
s=n1+n2+n3 - avrg → n1,n2,3
return s
def avrg(x,y,z):
Local Variables
s=add(x,y,z) - avrg → x,y,z
- enclosed:add()→ n1,n2,n3
return s/3
no1=int(input(“Enter the value:”))
no2=int(input(“Enter the value:”)) Global Variables
no3=int(input(“Enter the value:”))
print(“The average is:”,avrg(no1,no2,no3))
Page 64 of 124
Downloaded from [Link]
Here one more term is also introduced, this term is lifetime of a
variable.
The time for which a variable or name remains in
memory is called lifetime of variable.
➢ For global variables, their lifetime is entire program and for
local variables their lifetime is their function’s run.
➢ It means global variables live in memory as long as the
program is running where as local variables live in memory
as long as their function is executed.
The LEGB rule
Python is following name resolution rule known as LEGB rule. It
means for every variable name reference python follows the
resolution:
a) It checks within local environment for a variable in the function
and uses its value otherwise moves to step (b)
b) Now its check enclosing environment, if yes uses its value
otherwise repeats the step to higher level enclosing environment
then moves to step (c)
c) Now its checks for global environment , if yes it uses the value
otherwise move to step (d)
d) Check the built-in environment which contains all built-in
variables
Watch this video for more understanding:
Watch now
Page 65 of 124
Downloaded from [Link]
Mutable/immutable of arguments/parameters & function
calls
All variables during working with function arguments.
Immutable objects are those objects
whose values cannot be changed.
They allocate new memory
whenever the value is changed.
New memory allocated for x when
value assigned x=45. Every time
when value is changed memory
address also gets changed. When new
object is created old object will be
discarded and memory cells make free
for use.
Passing immutable type value
Page 66 of 124
Downloaded from [Link]
Passing mutable type value (List)
As you know list, dictionary etc are mutable data types in python.
mutable objects passing in functions
Passing Strings
Consider following program:
passing string into python function
Watch this video for understanding:
Watch Now
Page 67 of 124
Downloaded from [Link]
Chapter 3 Exception Handling
Introduction to Exception Handling
As a student of computer science, you know that many times while executing
the program we are getting some errors. These errors are categorized as
follows:
Compile Time Errors
Compile time errors occur
when the programmer is
compiling a program. The
Python source code is
checked for any violation of
Python rules in the
programming at compile time and if anything is not as per rule, it reports an
error.
As you have observed the above chart compile time errors are classified into
two categories:
➢ Syntax Errors
➢ Semantic Errors
Syntax Errors
A syntax error occurs when any of the Python programming rules are
violated or the program is not written correctly as per the format required.
For Example,
x =+3 #statement 1
if a = (a+b) #Statement 2
In statement 1, =+ is used which is not the correct operator, the correct
operator is +=. Hence the correct statement is x += 3.
In statement 2, = is used with it, which is incorrect.
The correct statement is: a== (a+b)
Page 68 of 124
Downloaded from [Link]
So while writing a program, a programmer should ensure that the right code
is written.
Syntax errors are reported by python interpreter with a full description of
error along with suggestions to rectify them.
Semantic Errors
Semantic Errors occur when the statement has no meaning in the program.
For example,
"Ayush is playing cricket."
This is syntactically and semantically correct. But
"Cricket is playing Ayush."
This is syntactically correct but semantically not.
As the rule of RHS and LHS followed in Python, the left side statement
cannot be written in the right and vice versa.
For example
a=5 #Sattement 1
b=7 #Statement 2
a+b=res #Statement 3
In the above code, Statement 3 has a semantic error because an expression
never comes to the left side of the assignment operator. It should be always
on the right side.
Logical Errors
Quite often the programmer has written the code correctly without any
syntax error or semantic error. But didn't get the exact result that is desired.
This happens because of the programmer's mistake where the appropriate
logic is not used.
For example, in place of addition, subtraction is done.
Page 69 of 124
Downloaded from [Link]
Runtime errors
Sometimes the program is correct syntactically and semantically, but when
the programmer runs the program, errors occur. Such kinds of errors are
called runtime errors.
Runtime errors are very harder to detect in the programs. These errors may
stop the program execution abnormally or crash in between or runs infinite
loops.
Basically, Python terminates the program when such errors occur. But it is
not advisable that the program crashes due to unwanted things.
Exceptions
An exception is a program event that occurs during
program execution and disrupts the flow of a program.
When a Python program cannot cope with a situation, it
raises an exception. An exception is a Python object
that represents an error.
Some common Python exceptions are as follows:
I/O Error opening a file that is not present
user tries to access an element that is
Array out of range
beyond the range from list
divide by zero any number which is divided by zero - 5/0
invalid input opening a file that is not present
opening a file that does The user has given incorrect input
not exists
What is Exception Handling?
The process of catching and preventing errors when they occurred is called
exception handling.
It is a mechanism to overrule the exceptions using some blocks.
Page 70 of 124
Downloaded from [Link]
In other words, way of handling unexpected error during runtime
is called exception.
It is the concept of error handling when something goes wrong, tracking the
error, and calling the handling code.
The following terms are used for exception handling:
Some syntax errors are also an exception. Whereas other exceptions can be
generated through code. Let us discuss some built-in exceptions in Python.
Built-in exceptions
The exceptions already defined by python are known as built-in exceptions.
Python standard library consists of large number of built-in exceptions. They
are as follows:
Exception Explanation
ValueError It is raised when a built-in method or operation
mismatched or inappropriate values are provided as
input.
IOError It is raised when the file specified in a program
statement cannot be opened.
Page 71 of 124
Downloaded from [Link]
KeyboardInterrupt It is raised when the user accidentally presses
delete or esc key or cancels the execution.
ImportError It is raised when the specified module is not
installed or not working.
EOFError It is raised when the end of file condition is reached
without reading any data by input().
ZeroDivisionError It is raised when any number is having denominator
zero.
IndexError It is raised when the index or subscript in a
sequence is out of range.
NameError It is raised when a variable is accessed before
declaration.
IndentationError It is raised due to incorrect indentation in the
program code.
TypeError It is raised when an operator is supplied with a
value of incorrect data type.
OverFlowError It is raised when the result of a calculation exceeds
the maximum limit for numeric data type.
Examples:
Watch this video for an understanding:
Watch Now
Page 72 of 124
Downloaded from [Link]
User-defined exceptions
The exception created by the programmer according to the requirement of
the program is called user-defined exceptions.
The user defined-exception can be created using two methods:
• raise statement
• assert statement
raise statement
It is used to throw an exception. The syntax is as follows:
raise exception-name[(optional argument)]
The optional argument is a string passed to the exception, that displays the
message. The exception may be user-defined or built-in.
Example:
d={'A':9,'B':10}
k=input("Enter key to search:")
if k in [Link]():
print("Key found in dict...")
else:
raise KeyError("Key not present in dict...")
Output:
assert statement
➢ An assert statement in Python is used to check a condition in the
program code.
➢ If the result after evaluation is false, then the exception is raised.
➢ This statement is generally used at the beginning of the function or
after a function call to check for valid input.
Page 73 of 124
Downloaded from [Link]
➢ The syntax for the assert statement is:
assert Expression[,arguments]
➢ On encountering an assert statement, Python evaluates the expression
given immediately after the assert keyword.
➢ If this expression is false, an AssertionError exception is raised which
can be handled like any other exception.
Example:
def odd_even(n):
assert (n%2==0),"Even Number..."
print("Odd Number")
odd_even(6)
odd_even(5)
➢ Watch this video for more understanding:
Watch Now
Page 74 of 124
Downloaded from [Link]
Process of exception handling
Step 1: The exception object is created by a Python interpreter that contains
information related to the error such as type, file name, and position where
an error has occurred.
Step 2: The object is handed over to the runtime system to find an
appropriate code to handle exceptions. This process is called throwing an
exception.
Step 3: The runtime system searches for a block of code known as an
exception handler that handles the raised error. First, it searches for the
method by which the error has occurred. If not found then it search method
from which this method is called. This process continues till the exception
handler is found. When it found a handler it will be executed. This process is
known as catching.
Step 4: Finally, the program gets terminated
Catching Exceptions
➢ Catching exceptions refers to the execution of code that handles
particular exceptions.
➢ Any exception caught through try block and handled through except
block.
Page 75 of 124
Downloaded from [Link]
try and except block
➢ The try block contains the actual codes that need to be executed.
➢ Every try block is followed by except block.
➢ The exception handling code is written inside the except block.
➢ In the execution of the program, if an exception is raised the try block
execution is stopped and the control is shifted to except block.
➢ The syntax of try and except is as follows:
try:
program statement in which exception may occur
except [exception_name]:
exception handler code
Example 1 : NameError Exception
try:
print(x)
except NameError:
print("Varibale is not defined...")
Output:
Example 2: ValueError Exception
try:
a = int(input("Enter your age: "))
except ValueError:
#Print message for ValueError
print("Invalid input:Enter numbers only")
Output:
Page 76 of 124
Downloaded from [Link]
Example 3: ImportError
try:
import Datetime
print("Module")
except ImportError:
print("Invalid module Can't import")
Example 4: ZeroDivisionError
try:
c=5/0
except ZeroDivisionError:
print("You cannot divide")
Example 5: IndexError
l=[11,45,67,89]
try:
print(l[5])
except IndexError:
print("Index not found")
Example 6: TypeError
try:
a=5
print(a+'b')
except TypeError:
print("Invalid Datatypes")
You can also raise exceptions without exception names in except block.
Observe this code:
print ("Handling multiple exceptions")
try:
a=10 / 0
except:
print("Exception Raised...")
Page 77 of 124
Downloaded from [Link]
Handling multiple exceptions
➢ Multiple exceptions can be handled together using multiple exceptions
with multiple exception handlers.
➢ There are two ways to handle multiple exceptions.
o Writing multiple exception handlers together
o Writing multiple exception handlers with separate except blocks
writing multiple exception handlers together
➢ The multiple exception handlers can be written within one except block.
➢ When the first exception is raised it will stop execution and evaluate the
first except block.
Example:
try:
result = 10 / 0
result = 10 +'d'
except ZeroDivisionError, TypeError as e:
print("Error occurred:", e)
➢ In the above code, the ZeroDivisionError exception is raised in the first
line, and the relevant message is generated.
➢ If the first exception is not raised then it will jump to another
exception i.e. TypeError.
Writing multiple exception handlers with separate except blocks
Multiple except blocks are required for this method. Observe the example:
try:
result = 10 / 0
result = 10 + 'd'
except ZeroDivisionError as e:
print("Error occurred:", e)
except TypeError as e1:
print("Error occurred:",e1)
Page 78 of 124
Downloaded from [Link]
Use of else clause in exception handling in Python
➢ Now you are familiar with the process of exception handling, where
except block will be executed if any exception is raised in the try block.
➢ But when no error is reported, then no except block will be executed.
In this scenario else block comes into play a role.
➢ The else block in exception handling in Python will be executed in a
similar manner as it is executed in if...else, while..else etc.
➢ Observe this code:
print ("Handling multiple exceptions")
try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1+n2
except ValueError:
print("Enter integers only...")
else:
print("The result is:",res)
Finally Clause
➢ The finally clause ends the exception-handling process.
➢ In bottom last clause after handling all except clauses including else block.
➢ The finally clause always executes at the end.
Page 79 of 124
Downloaded from [Link]
➢ Just have a look at the following:
print ("Handling multiple exceptions")
try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1+n2
except ValueError:
print("Enter integers only...")
else:
print("No exception raised...")
print("The result is:",res)
finally:
print("You have done it!!! Bye Bye")
If sometimes any exception which is not caught in exception handler, in this
scenario too the finally clause will execute first and the exception is re-
raised.
Page 80 of 124
Downloaded from [Link]
Just observe this code:
print ("Handling multiple exceptions")
try:
n1=int(input("Enter number1:"))
n2=int(input("Enter number2:"))
res=n1/n2
except ZeroDivisionError:
print("Enter integers only...")
else:
print("No exception raised...")
print("The result is:",res)
finally:
print("You have done it!!! Bye Bye")
Output:
➢ After execution of finally block, Python transfers the control to a
previously entered try or to the next higher level default exception
handler.
➢ In such a case, the statements following the finally block is executed.
That is, unlike except, execution of the finally clause does not
terminate the exception.
➢ Rather, the exception continues to be raised after execution of finally.
Page 81 of 124
Downloaded from [Link]
Chapter 4 File Handling
Introduction to file
A file is a set of bytes stored on storage devices such as
hard-disk, pen-drive etc.
The programming languages offers to save data and read data from the
storage devices.
➢ As we know, Files are an essential part of computers.
➢ Everything stored on the computer is saved in files.
➢ These files are a collection of bytes stored in computers.
➢ Data can be represented in specific forms in files.
➢ These files can be accessed at any time.
➢ These files are saved with an extension or file types.
➢ They need a specific program to read data and write data.
For Ex. Documents can be opened and read through Word Processing
software such as MS Word, OO Writer, Word Star, etc.
File handling is the process of handling data by
software including IO operations.
These files stored in a directory on a hard drive. Whenever any operation is
carried out, the file is opened and make available to write upon on reading
purposes on RAM.
Need for a data file
➢ The computer has a powerful feature of saving data.
➢ As you know data means raw facts and figures and meaningful data is
known as information.
➢ These data can be stored in a file.
➢ Whenever users need such data, data can be presented by files.
Page 82 of 124
Downloaded from [Link]
Data Files
➢ When you develop a program in python, the final output of the
program is not available for future use. Data files serve this purpose.
➢ They can store the output in the following files.
➢ The data files can be stored in two ways:
Text Files
➢ It has an extension .txt.
➢ It can be directly opened by a text editor like notepad, Wordpad,
etc.
➢ It is capable to handle textual data and information.
➢ The text files contain a series of lines.
➢ A line is a set of characters or strings.
➢ These characters can be in ASCII or UNICODE form.
➢ In the text files, each line is terminated by 'EOL-End Of Line' i.e '/n'
in python.
Binary Files
➢ Binary files are capable to store large files such as images, videos,
audio files, etc.
➢ It can’t be read by human being directly.
➢ These files have a specific pattern to read data in the correct type.
➢ These files don't have any delimiter.
➢ They are easier and faster than text files.
➢ In binary files data interpreted by correct data type.
➢ Python provides specific functions to handles these data types and
data files.
➢ Binary files store the information in form of stream of bytes.
➢ It contains information in same format in which the information is held
in memory.
➢ It has not specific extension. It can take variety of extensions.
Page 83 of 124
Downloaded from [Link]
CSV (Comma Separated Values) Files
➢ It is a plain text file that contains a list of data.
➢ CSV files can be opened and operated by MS Excel and allow to export
and import data.
➢ It can handle big data.
➢ All the values are separated by a comma.
➢ It is most common format for saving data for data analysis.
Data file operations
The following tasks will be performed on data files.
Creation
of files
Reading
files
Opening Writing
files files
Deleting
Updating
Data from
files data
files
Appending
Creating Merging
data in
copy data
files
Page 84 of 124
Downloaded from [Link]
Text Files
Open a text file:
Syntax:
<file object> = open(file_name,access_mode)
file object : It is just like a variable or object. It is also known as file
handle. It serves as a link to a file residing in computer. It is a reference
point to file on disk. It opens a file and makes available it for different tasks.
open(): It is a function with two parameters.
• file_name: It accepts a file name with .txt extension. It is the first
parameter for open function. If only filename is provided, it searches
the file in current folder. While writing files names and path the
slashes are important. Slashes have special meaning in python and
should be written as \\. If single slash is required the file name may
written with prefix ‘r’.
For example:
F=open(“D:\\Files\\[Link]”)
F=open(r“D:\Files\[Link]”)
• access_mode: It specifies the mode to access the file. The default
mode is reading mode.
• These modes are
o r: to read a file
o w: to write
o a: append contents
• If no second parameter is provided, then by default file opens in read
(r) mode.
• When a file is opened in reading mode and if the given file does not
exist in the folder then it raises FileNotFoundError.
Page 85 of 124
Downloaded from [Link]
File modes in python
Text Binary Description Remarks
➢ Default mode
“r” “rb” Read only
➢ File must exists, otherwise raises an I/O error
➢ If file does not exist, create a new file
“w” “wb” Write only
➢ If file exists with data it over-write in the file
➢ File opens in write mode
➢ If file exists, the existing data will be retained and new
“a“ “ab” append
data will be written to the end
➢ If file doesn’t exist it will creates a file
r+b or ➢ File must exists otherwise raise error
“r+” Read & Write
rb+ ➢ Both reading and writing operations can be performed
➢ If file does not exist, creates a file
w+b or
“w+” Write & Read ➢ If file exists, the existing data will be lost
wb+
➢ Both reading and writing of data can be done
➢ If file does not exist, will be created
a+b or ➢ If file exists, existing data remains as it is and new
“a+” Write & Read
ab+ data will be written to the end of file
➢ Both reading and writing operations can be performed
1. '+' sign is used to open the file for both modes of reading and writing
after access_mode. When it is used, the file pointer will be at the beginning
of the file
2. 'b' along with the above modes to work with binary files
Example:
f = open("[Link]","r") - Open file for reading
f = open("[Link]","w") - Open file for writing
Page 86 of 124
Downloaded from [Link]
Reading file
Python provides the following functions for reading files:
1) read(): To read the whole file. Returns the read bytes in form string.
Just take a look at the following example.
2) read(n): It read n number of characters from the beginning of the file. If
the file contains less than n number of characters, then it will read file up to
EOF (End Of File).
3) readline(): It read a line from starting the place of the cursor where it's
placed up to EOL (End of Line). Returns the read bytes in form of string or
returns blank string if no more bytes are left for reading file. It always one
character extra than number of characters in the line for endline character.
Page 87 of 124
Downloaded from [Link]
4) Reading the entire file using readline():
5) readlines(): To read all lines from text file and returns them in a list
form.
6) Reading specific lines:
When a variable is assigned with [Link]() it stores no. of lines in
a list with starting index 0(zero).
Writing to File
The following functions are used to writing into files.
1. write(): It takes a string as a parameter to write in the file. 'n' is used to
specify the end of the string.
Page 88 of 124
Downloaded from [Link]
2) writelines(): This method is used to write a sequence of lines, strings,
tuples, etc in a file.
Manipulation of Data
Program 1. Counting lower case characters from a text file
Page 89 of 124
Downloaded from [Link]
Program 2. Counting words from a text file
Program 3. Counting no. lines starting with 'S' in the file
Page 90 of 124
Downloaded from [Link]
Program 4. Count occurrences of a specific word in text file (Exact
Match)
The flush() function
➢ While writing data onto file using any of the write functions python hold
data to be written in buffer
➢ Then these data from buffer will be pushed on storage device later
➢ It used to write contents of buffer onto storage forcefully
➢ By default, python automatically flushes the file buffers when closing the
file using close() function
➢ The flash() function flush data before closing the file
Example:
f=open(“file”,”w+”)
[Link](“The output file is \n”)
[Link](“The line is written using write function”)
[Link]()
[Link]()
Page 91 of 124
Downloaded from [Link]
Appending data to a text files
➢ In w mode, the existing will be lost when user wants to add something
once file is created.
➢ To overcome this python provides a (append) mode to save data after
creating a file.
➢ The a mode, also creates a new file if the file is nor present in the
memory
Example:
F=open(“[Link]”,”a”)
Line=input(“Enter single line to insert in the file:”)
[Link](Line+”\n”)
[Link]()
The file pointer
➢ Every file has a file pointer which tells the cursor position in the file
➢ It is helpful reading and writing data from current position
➢ It is just like a book mark in a book
➢ There are two basic things will happen related to file pointer
o The operation takes place at the position of file pointer
o File pointers advances by the specified number of bytes
➢ Observe the codes and read out the comments:
F=(“[Link]”,”r”) # File pointer placed at the beginning of file
dt=[Link](1) #read 1 byte and file pointer moves to next byte
dt=[Link](2) #read 2 bytes from the previous position and file pointer
moves to next 2 bytes
File modes and opening positions of file pointer
r, rb, r + , r+b Beginning of the file
w, wb, w+, wb+, w+b Beginning of the file
a, ab, a+, ab+, a+b At the end of file, if file already exists,
otherwise creates a new file
Page 92 of 124
Downloaded from [Link]
Python provides two functions to manipulate the file-pointer position. It
allows to read and write the file from the specified position. These two
functions work with text files as well as binary files.
Tell and Seek functions
The tell() function
➢ The meaning of tell is to say something
➢ Similarly tell function () say/tell us about the current position of the
cursor in file.
f = open("[Link]","r")
print("The initial position of file pointer" ,[Link]())
print("Moving to the next 3 characters:")
dt=[Link](3)
print("Now the file pointer moves to:",[Link]())
print("Moving next 7 characters:")
dt=[Link](7)
print("Now the file pointer moves to:",[Link]())
Output:
The seek() function:
➢ It moves the cursor at required position in the file.
<file-object>.seek(offset[, from])
Where
✓ file-object is the file handle to work up on the file
✓ offset is the position where you want to move your file
✓ From is the place from which place you want to move, it is a
number either 0 or 1 or 2
o 0 refers to beginning & it is default position
o 1 refers to current position of file-pointer
o 2 refers to end of the file
Page 93 of 124
Downloaded from [Link]
Example:
f = open("[Link]","rb")
print("The initial position of file pointer" ,[Link]())
print("Moving to the next 4 characters:")
[Link](4,0)
dt=[Link](3)
print("Now the file pointer moves to:",[Link]())
print("Moving next 10 characters:")
[Link](10,1)
dt=[Link](7)
print("Now the file pointer moves to:",[Link]())
[Link](-5,2)
print("Now the file pointer moves to:",[Link]())
Output:
Watch this video for practical understanding:
Watch Now
Follow this link to access important questions and answers for text file:
File handling in python class 12 important questions
Follow this link to access important practical programs for the practical file
on the topic file handling class 12:
File Handling programs for practical file class 12
Watch the following video for some more programs:
Watch Practical Programs
Page 94 of 124
Downloaded from [Link]
Standard input, output and Error streams
➢ The keyboard is standard input device.
➢ The monitor is standard output device.
➢ If any errors occur, is displayed on monitor. Hence monitor is also
standard error device.
➢ In python we have separate objects for the same
o stdin – read from keyboard
o stdout – display the content redirected as standard input
o stderr – to read error message as output
➢ These standard devices are implemented as files called standard
streams.
➢ In python, standard streams files can be used by sys module.
➢ The sys needs to be imported as – import sys
Example:
import sys
f=open("[Link]","r")
dt=[Link]()
[Link](dt+”\n”)
[Link]("No errros")
Absolute and relative path
➢ A path is a sequence of directory and filename with the hierarchy
structure to access the specific file.
➢ Pathname: A pathname is the full name of file or a directory.
➢ Absolute path is a path that starts from the root directory of the file
system or we can say that it describes how to access a given file or
directory, from the starting of the file system.
Page 95 of 124
Downloaded from [Link]
➢ The absolute paths are from the topmost level of directory structure.
➢ Relative path is a path that is relative to the current working directory
or we can say that is interpreted from the perspective of the current
working directory.
➢ In relative path the CWD is denoted by a . (single dot) and the top
most directory is also known as Parent Directory denoted by .. (two
dots).
File Absolute Path Relative Path
[Link] D:\School\Academics\[Link] ..\School\Academics\Syllabus,jpg
[Link] D:\School\Examination\[Link] ..\School\Examination\[Link]
[Link] D:\School\Sports\[Link] ..\ School\Sports\[Link]
The parent directory is: School
The current working directory is: Academics for [Link], Examination for
[Link] & sports for [Link]
Page 96 of 124
Downloaded from [Link]
Working with binary files
➢ The binary file refers to a file which is not readable by users directly.
➢ It is stored in a numeric pattern or follows some binary codes or a file
which is processed quicker than text files.
➢ Unlike text files, binary doesn't have any end-line character or any
character which is going to be translated into machine-readable form.
➢ The files like images, audio files or video files are examples of binary
files.
Open a file (FileName - Absolute and relative path, mode)
➢ When you are working with computers everything finally saved into
files.
➢ To save these files we are using folders or directories.
➢ Folders can have subfolders. The complete address of a file is called a
path.
For example: D:\School Work\ School Work 2021-12\Website
Contents\CS [Link].
This example is known as the absolute path as it contains all folder names
from top to bottom.
Page 97 of 124
Downloaded from [Link]
In windows, you can access files and folders using file explorer. When you
are using MS Word or Excel or any other software for opening or saving file,
the file dialog box opens a recently used folder or documents folder by
default. This folder is marked as Current Working Directory (CWD) in the
Operating System. This path is known as a relative path.
The default relative path of python is:
C:\Users\utcl\AppData\Local\Programs\Python\Python38-32
Working with binary files:
➢ Data in computers can be represented in plain text as well as in a
structural hierarchy.
➢ The plain text data can be handled using text files.
➢ The structural hierarchy can be handled using binary files.
➢ The structural data is stored in such a way that their structure is
maintained.
➢ To maintain this structure python offers serialization and deserialization
process.
➢ Serialization and Deserialization also refers to pickling and un-pickling
respectively.
Serialization
The process of converting Python object hierarchy into
a byte stream which can be written on file is called
serialization.
Deserialization
It is the inverse process of serialization. A byte stream
is converted into an object hierarchy.
Basic modes of binary file
Page 98 of 124
Downloaded from [Link]
There are three basic modes of a binary file:
➢ read: This mode is written as rb
➢ write: This mode is written as wb
➢ append: This mode is written as ab
The plus symbol followed by file mode is used to perform multiple operations
together.
For example, r+ is used for reading the opening file for reading and writing.
The cursor position is at the beginning when + symbol is written with file
mode.
To open a binary file follow this syntax:
file = open(<filepath>, mode)
For example: f = open("[Link]","rb")
While opening a binary file the file must exist. If the file doesn’t exist in
raises an exception – FileNotFoundError.
If the file exists then while reading last record it raises EOFError Exception.
Hence exception handling is necessary to work with files in read mode. This
is done through try and except block.
Close File
When you are leaving the program or at the end of your file operation in the
program file should be closed to avoid data corruption or any garbage data
generation. The syntax of closing a binary file is similar to a text file.
[Link]()
Click here to read Binary File Programs
Pickle Module - dump() and load() functions
Page 99 of 124
Downloaded from [Link]
When you are working with files in computers either you need to understand
or convert the files from one mode to another.
Let's understand in a simple way. If a person who is speaking in Spanish
language and a person who is speaking in the Hindi language in
communication, then it has meaning at all. In this process, we need one
person who knows both languages.
Similarly in computers also pickle module is doing something exactly
(conversion of python objects) in binary. This process is known as pickling.
It is also known as serialization or flattening or marshalling.
The reverse process is known as unpickling. To do this process you need to
import pickle module.
dump() function
The dump() function or method is usually used with write to object or we
can say encoding in python when the file is accessed in binary mode.
This dump() function accepts two parameters.
• Python Object which needs to be encoded or write (List, Dictionary etc.)
• Data File object in which values of the python object should be written
load() function
The load() function or method is used to reading data from a binary file or
we can say decoding in python when the file is accessed in binary mode. A
variable should be used to assign the values from the file and decoded.
Write into a binary file
To write into binary file follow these steps:
• Initiate a python object such as list, dictionary or any other object
• create a file using the open function
• use [Link]() method with parameters python object and file
object
read from binary file
Page 100 of 124
Downloaded from [Link]
To read from binary file follow these steps:
➢ Open file using open() function
➢ instantiate an object to store data read from a file using load()
function
➢ Print the data
Look at this example:
import pickle
def bin_write():
d = {'Windows 95':1995,'Windows 98':1998,'Windows
ME':2000,'Windows XP':2001,
'Windows 95':1995,'Windows 7':2009,'Windows 8':2012,'Windows
10':2015}
f = open('pcm_result.dat','wb')
[Link](d,f)
[Link]()
f = open('pcm_result.dat','rb')
d1 = [Link](f)
[Link]()
for n,y in [Link]():
print(n,"-->", y)
bin_write()
Output
In the above example,
Page 101 of 124
Downloaded from [Link]
➢ one dictionary object is created and instantiated with d
➢ Then initialized with values like windows versions and their launching
years.
➢ The binary file is opened using "wb" mode with a relative path.
➢ Then the data are written into a binary file with [Link](d,f)
method.
➢ A file closed with [Link]() and then reopened for reading purposes
with "rb" mode with a relative path.
➢ Then data read through a [Link](f) into d1 object.
➢ Finally, data printed on the screen with for loop.
Recommended - Assignment Binary File
Binary file operations in Python - Search, Append, Update
and Delete Records
Here you will learn about Binary file operations in Python such as Append,
Search, update and delete.
So let's start now, the contents are as follows:
Append data in Binary File
To append data in binary follow these steps:
➢ Open the file in append mode using "ab"
Ex.: f = open ("[Link]","ab")
➢ Enter data to append
➢ Append entered data into the dictionary/list object
➢ Use [Link]() method to write the dictionary/list data
➢ Close the file
Observe the following code:
Page 102 of 124
Downloaded from [Link]
def bf_append():
f = open("[Link]","ab")
print("Append Data")
pcode = int(input("Enter the Player code:"))
pname = input("Enter Player Name:")
score = int(input("Enter individual score:"))
rank = int(input("Enter Player Rank:"))
rec={'Pcode':pcode,'Pname':pname,'Score':score,'Rank':rank}
[Link](rec,f)
[Link]()
bf_append()
Do not run your code without reading the contents.
Reading Data
Follow these steps to read data:
• Open the file in read mode using "rb"
Ex.: f = open("[Link]", "rb")
• Use while loop with True statement to read the entire contents of the
file individually.
• Use try - except for Exception handling to avoid runtime EOFError
• Now load data into an object through the load function
• Print data as per need
• Close the file
Observe the following code:
Page 103 of 124
Downloaded from [Link]
def bf_read():
f = open("[Link]","rb")
print("*"*78)
print("Data stored in File....")
while True:
try:
rec= [Link](f)
print("Player Code:",rec['Pcode'])
print("Player Name:",rec['Pname'])
print("Individual Score:",rec['Score'])
print("Player Rank:",rec['Rank'])
print("."*78)
except Exception:
break
[Link]()
bf_read()
Search Records from binary file
Follow these steps to search the record in the binary file:
o Open the file in reading mode using "rb"
o Prompt a message to ask unique field from data to search
o Declare a Boolean variable flag to store False for the record not found
and True when the record found
o Use a while loop to access records individually
o Now load the data into the dictionary object using load() function
o Use if condition to compare the data with the variable taken in step 2
o Print the record found
o Assign True to the flag variable declared in step 3
o Use the except block to handle EOFError and terminate the loop using
the break
Page 104 of 124
Downloaded from [Link]
o Print record not found message when Flag is False
o Finally, close the file using [Link]()
Observe the following code:
def bf_search():
f = open("[Link]","rb")
pc = int(input("Player to code to search:"))
flag=False
while True:
try:
rec= [Link](f)
if rec['Pcode']==pc:
print("Player Name:",rec['Pname'])
print("Individual Score:",rec['Score'])
print("Rank:",rec['Rank'])
flag = True
except Exception:
[Link]()
if flag==False:
print("Record not found...")
[Link]()
bf_search()
Update record in Binary file
Have look at the following code:
Page 105 of 124
Downloaded from [Link]
def bf_update():
f = open('[Link]','rb')
reclst = []
while True:
try:
rec = [Link](f)
[Link](rec)
except EOFError:
break
[Link]()
pc=int(input("Enter player code to update:"))
pn=input("Enter new name:")
ps=int(input("Enter Player Score:"))
pr=int(input("Enter Player Rank:"))
for i in range (len(reclst)):
if reclst[i]['Pcode']==pc:
reclst[i]['Pname'] = pn
reclst[i]['Score'] = ps
reclst[i]['Rank'] = pr
f = open('[Link]','wb')
for i in reclst:
[Link](i,f)
[Link]()
bf_update()
To update record, you can use the search record code if you wish. To update
the record, follow these steps:
o Open the file using read mode
o Declare a variable for unique value to be updated
o Use try-except and while loop as explained above
Page 106 of 124
Downloaded from [Link]
o Add record fetched from binary file into a list
o Enter the new record information to update
o Compare the fetched records with entered record and assign the new
values to update
o Write the data using dump() function
o Close the file
Delete the record
def bf_delete():
f = open('[Link]','rb')
reclst = []
while True:
try:
rec = [Link](f)
[Link](rec)
except EOFError:
break
[Link]()
pc=int(input("Enter Player code to delete record:"))
f = open('[Link]','wb')
for i in reclst:
if i['Pcode']==pc:
continue
[Link](x,f)
[Link]()
bf_delete()
Deleting a record is a little bit tricky. Just we are overwriting contents except
for the record which is asked to be deleted. Let's have look at these steps:
1. Open the file in reading mode
2. Load data using the load function
Page 107 of 124
Downloaded from [Link]
3. Close file
4. Prompt a message to delete a record with a variable
5. Open file in writing mode
6. Declare a list object to store data from the file
7. Use for loop and if condition as used in the update
8. Now in if condition write continue if the record is found
9. Write data using the dump method
[Link] the file
Observe this code (Assume the Pickle module is included):
Download the complete program
Follow the below-given link to download the complete program.
Download Binary File Menu Driven Program
Working with CSV files
➢ CSV files are representing data in tabular format delimited by comma
➢ The rows and columns are similar as spreadsheet or database
➢ Every value is separated by comma, hence comma is default separator
➢ This delimiter can be changed using code
➢ Each line in CSV file is a record
➢ CSV files are handled as similar as text files in Python
➢ CSV files are easier to create
➢ It can be imported/exported easily into databases and spreadsheets
➢ It can store large amount of data
Python CSV module
➢ The csv module in python offers functionality to read and write data in
CSV files
➢ The module contains two objects:
o reader – to read data
Page 108 of 124
Downloaded from [Link]
o writer – to write data
➢ Before performing reading or writing operations you need to import
csv module - import csv
➢ As you know python module is a .py file with code that defines various
classes, functions, and variables in python.
➢ A python module can be added to any program later using the import
keyword. For more details about the python module refer python
documentation.
➢ The CSV module is also one of them.
import csv module
To import csv module you can use any one of the following syntax:
import csv
from csv import writerow
from csv import writerow, reader
from csv import *
In above statements,
➢ first example is used to import the complete csv module therefore you
can access anything from the module using csv and .(dot) symbol.
➢ In second syntax it won't access the complete code, it will just allow to
use writerow() function only in your program.
➢ In next part two functions used from the module and last all the
classes, functions and variables can be access using *.
Note: To save the memory and reduce the program size third syntax can be
used for your project with a number of required functions only.
Opening CSV file
➢ Remember the following while opening a CSV file
Page 109 of 124
Downloaded from [Link]
Specify the
Specify the Open the file
newline
file extension same as text
character if
.csv file
required
➢
The CSV file can be also opened in different modes such as
w,w+,a,a+,r,r+.
Role of newline in Opening CSV file
➢ The newline argument is additional in open function
➢ Although it is optional but very important argument
➢ It specifies how would python handle newline characters while working
with csv file
➢ In text file the EOL character is ‘\n’ which is translated in csv file using
newline argument
➢ Each operating system has its own new line characters.
OS Newline Meaning
character
Macintosh \r Carriage Return
UNIX \n Line Feed
MS-DOS, Windows \r \n Carriage Return or Line Feed
Other OSs \0 Null character
➢ The newline = ‘ ’ is added as third argument in open function while
working with CSV file
➢ It will create a CSV file with no EOL translation and make the file able to
use CSV file in normal way on any platform
Example:
f=open(“[Link]”,”w”,newline=””)
Page 110 of 124
Downloaded from [Link]
Writing in CSV
➢ Writing data in CSV file is little bit different from text file
➢ It needs conversion of user data into the writable delimited form then
store into CSV file
➢ For writing in CSV file there three main functions:
wo = [Link](f) [Link]() [Link]()
Creates a writer
object instantiate write a single row write multiple rows
an object with a at a time at a time
variable
Accepts file handle
accept a python accept a python
as argument to
sequence as sequence as an
write python data
argument argument
into csv
The writerow() function
The writerow() function is used to write data in CSV file.
Creating header row and CSV file
➢ When we are writing data into CSV file we have to create a header row
first. Follow the below given steps to write a header row.
➢ Observe the following code which creates a CSV file and creates one
object to write a header row in CSV file.
➢ Here I have used writer() function to feed data and writerow()
function to insert values into a row.
Page 111 of 124
Downloaded from [Link]
from csv import writer
def f_CSVwrite():
f = open("[Link]","w")
dt = writer(f)
[Link](['Rank','Batsman','Team','Rating'])
[Link]()
f_CSVwrite()
Inserting data into CSV file
You can insert single row or multiple rows together in CSV file.
Insert a single row at a time
If you have already created a header row then you have to use append
mode to insert data.
from csv import writer
def f_CSVwrite():
f = open("[Link]","a")
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
dt = writer(f)
[Link]([r,b,t,rt])
print("Record has been added.")
[Link]()
f_CSVwrite()
Page 112 of 124
Downloaded from [Link]
Insert multiple rows at a time
To insert multiple rows use while loop inside the function and use validation
to stop the input by the user. For validation, I have used a string variable to
check user want to restrict the data entry or want to continue. Observe the
following code I have done the same.
from csv import writer
def f_CSVwrite():
f = open("[Link]","a")
dt = writer(f)
while True:
r = int(input("Enter rank:"))
b = input("Enter name:")
t = input("Enter team:")
rt = int(input("Enter rating:"))
[Link]([r,b,t,rt])
print("Record has been added.")
print(“More record?Type YES!!!")
ch = input()
ch = [Link]()
if ch=="YES":
print("**************")
else:
break
[Link]()
f_CSVwrite()
Now when you insert a row using this method it will add a blank row by
default before each new record. You can specify the newline character into
an open function to avoid this.
Page 113 of 124
Downloaded from [Link]
To solve above problem I have used the following code:
from csv import writer
def f_CSVwrite():
f = open("[Link]","a",newline="\n")
dt = writer(f)
while True:
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
[Link]([r,b,t,rt])
print("Record has been added.")
print("Want to add more record?Type YES!!!")
ch = input()
ch = [Link]()
if ch=="YES":
print("*************************")
else:
break
[Link]()
f_CSVwrite()
Output in CSV File
Page 114 of 124
Downloaded from [Link]
Use of quotechar and quoting parameter
➢ Sometimes we are using quotes to enclose the data like dates and text
values in MySQL.
➢ To accept those kinds of data directly we can use quotechar and
quoting parameter in writer()/writerow() function.
quoting parameter values
➢ csv.QUOTE_MINIMAL: It by default case, it will apply quotes to the
field s only they contain the delimiter or quote character
➢ csv.QUOTE_ALL: Quote all fields
➢ csv.QUOTE_NONNUMERIC: It applies data like MySQL form where
strings and dates enclosed with quotes except numeric data
➢ csv.QUOTE_NONE: Ignores the values to quote, when this value is
passed in writerow() function you must specify the escapechar
optional parameter
Apply this code where you have used writer() function the code:
dt = writer(f,quotechar="'",quoting=[Link])
Use of delimiter
When you need to store data which can be separated through any other
character except ,(comma) you can use delimiter parameter in
writer()/writerow() function.
Write code like this where you have written writer()/writerow() function:
dt = writer(f, delimiter="@")
When you write or use this method excel will display your data into
single column only. Because CSV accepts only comma to separate
values in excel.
The reader() function
The reader() function is used to read the data from CSV file. The syntax of
reader() function is as following:
[Link](csvfile, dialect='excel', **fmtparams)
Page 115 of 124
Downloaded from [Link]
Where,
csvfile
• is the path of CSV file which is going to be read.
dialect
• It is used to set a specific parameters like delimiter, single/double quotes or a
space
**fmtparams
• These are keyword arguments and can be used as per the need of the
program
Let's have a look at the following code:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
data = list(dt)
[Link]()
print(data)
f_CSVread()
Explanation:
In the above code, I have created one CSV file named [Link].
Line 1: The stepts As I am going to read data only therefore I have written
the import statement with from csv import reader statement.
Line 2: It is a function header defines a function f_CSVread().
Line 3: f is defined as file object to open the CSV file with "r" mode.
Line 4: In this line dt is an object which stores data in from CSV file using
reader() function.
Page 116 of 124
Downloaded from [Link]
Line 5: By default read() function returns object from CSV file not the actual
data. So actual data is stored in data named list object using list()
conversion method.
Line 6: This statement close the file to avoid any conflict in future.
Line 7: This statement prints the output eventually.
Line 8: The function is called to execute the program.
Display data in proper format
Observe the following code:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
data = list(dt)
[Link]()
for i in data:
print(i)
f_CSVread()
➢ To print the data in proper format for loop can be used.
➢ In the above code, I have used for loop and traverse data from the
list.
➢ Yet the output is displayed according to the list.
➢ To get it more clear and concise format we have to use another for
loop to traverse the values separately.
Page 117 of 124
Downloaded from [Link]
Observe this code:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
data = list(dt)
[Link]()
for i in data:
for j in i:
print('\t|',j,end=" ")
print()
f_CSVread()
In the above code I have used nested loop to print each value separately
from the list and formatted using '\t\' hence the output looks like as
following:
Displaying output without list object
Observe the below-given code where list object is not used to store data
read from CSV file:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
for i in dt:
for j in i:
print('\t|',j,end="")
print()
[Link]()
f_CSVread()
Page 118 of 124
Downloaded from [Link]
Chapter 5 Data Structure - Stack
Introduction to Python data structure stack
As data structure is a very important aspect of any programming language
so is python too.
A data structure is a way of store, organize, or manage
data in efficient and productive manner.
In other words, A data structure is a data collection
with well defined operations and behavior or properties.
➢ The python data structure stack is a linear data structure.
➢ It follows the principle of LIFO (Last In First Out).
➢ LIFO means the element inserted last will be deleted first.
➢ In stack the insertion and deletion will be done from one end i.e. top.
➢ Stack is dynamic data structure; it can grow or shrink.
➢ The representation of data is something like this:
Page 119 of 124
Downloaded from [Link]
By observing the above image you can understand the following:
➢ The data can be inserted or deleted from the top only
➢ Elements can be inserted or deleted any time
➢ The insert operation is known as push
➢ The delete operation is known as pop
➢ When the top element is inspected, it is known as a peek or
inspection
➢ When we have a fixed-length list and we are trying to push an element
in a list, it raises one error that is known as overflow
➢ When the list is empty and we are trying to pop an element, it will
raise an error that is known as underflow
Stack Applications
1) Reversing a line
2) Polish String
3) Recursion
4) Backtracking
5) Evaluating Expression – Postfix notation
6) Memory Management
Examples of stack
Call history in Browser history Palindrome
Undo Command
phone (Back Button) Check
Watch this video for more understanding:
Stack and Data Structure Basics
Page 120 of 124
Downloaded from [Link]
Implementation of stack using a list
To implement a python data structure stack create a menu-driven program
followed by the functions for push, pop, peek, display and empty.
Process
Create a menu-driven program
I have created a function named main_menu() as follows:
s=[] # An empty list to store stack elements, initially its empty
top = None # This is top pointer for push and pop operation
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
#push function calling
elif ch==2:
#pop function calling
elif ch==3:
#peek function calling
elif ch==4:
#display function calling
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
Page 121 of 124
Downloaded from [Link]
Checking stack underflow
To check whether the stack is empty or not write a function. Here I have
written a function named check_stack_isEmpty(stk).
def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
Push function
A function to push an element. To push the element append() method is
used as well as the position of the top should be changed. Observe the
following code:
def push(stk,e):
[Link](e)
top = len(stk)-1
Call this function in main_menu() function when ch = 1. Observe this code:
ele=int(input("Enter the value to push an element:"))
push(s,ele)
Display function
Write a function to check the element is inserted or not, observe this code:
def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
Page 122 of 124
Downloaded from [Link]
Calling display in main_menu() function:
display(s)
Pop Function
The pop function requires validation to check whether the stack is underflow
or not if it is not then use the logic to delete the element from the top. Have
a look at this code:
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = [Link]()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
Function call code in main_menu:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
Peek Function
The code is similar to pop, instead of popping elements just write a
statement to display the value. Observe this code:
def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
Page 123 of 124
Downloaded from [Link]
Function call code in main_menu() function:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
Watch this video for more understanding and practical demonstration:
Complete Program explanation Stack data
structure
If you looking for questions based on the stack:
Important Questions Stack Implementations
Download the complete program .py file
Download now
Page 124 of 124