Professional Documents
Culture Documents
com/
CLASS-XII (SESSION 2021-22)
SUBJECT: COMPUTER SCIENCE (083) – PYTHON
INDEX
CHAPTER PAGE
CHAPTER NAME (UNIT-1)
NO. NO.
1 REVIEW OF CLASS-XI 2
2 FUNCTIONS IN PYTHON 14
3 RECURSION 26
4 FILE HANDLING 28
6 IDEA OF EFFICIENCY 52
https://pythonschoolkvs.wordpress.com/ Page 1
CHAPTER-1
REVIEW OF CLASS-XI
Questions based on python topics of class-XI:
1. What is case sensitivity of a language?
10. Write the output of the following python statements (Assume that math module
already imported):
math.floor(-44.6)
math.fabs(-67.8)
https://pythonschoolkvs.wordpress.com/ Page 2
12. Look at the following python code and find the possible output(s) from the options
(i) to (iv) following it.
import random
for i in range(4):
VALUE = random.randint (4,11) + 7
print(VALUE, "#", end=" ")
3√7𝑚
𝐾=
(𝑚 + 𝑛)2
19. Write difference between mutable and immutable data types. Write name of any
two immutable data types.
20. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
for mn in loop(4, 20, 2):
if mn%4=0:
print("Number is divided by 4")
else
print("Number is not divided by 4)
21. Convert the following for loop into while loop without change in output of the
code.
for p in range(6,21,3):
print(p+2)
print("Loop Conversion")
https://pythonschoolkvs.wordpress.com/ Page 3
23. Consider the following code:
str=input("Enter a string: ")
for j in range(1, 5):
if str[-1]=='k':
str=str[0:2]+ 'p'
elif 'j' in str:
str=str[1:]+ 'r'
else:
str= 'T' +str[1:]+ 'z'
print(str)
28. Rewrite the following code after removing the syntax error. Underline each
correction.
print(x)
print(i)
5+7=y
Print(y)
29. What is type casting? Write the example of type casting in python.
30. Write the following expression in python:
𝑅
(i) 𝜋𝑟 2 ℎ (ii) 𝐶𝐼 = 𝑃(1 + )𝑇 − 𝑃
100
https://pythonschoolkvs.wordpress.com/ Page 4
31. Write the output of the following expressions:
(i) 5.7//2-1+4 (ii) 4*2**4
32. Evaluate the following and write the output of the following:
(i) math.fabs(-4.7)
(ii) math.floor(78.6)
(iii) math.ceil(-3.2)
(iv) math.pow(-5,2)
if z%3==0:
continue
else:
print(z)
34. Look at the following python code and find the possible output(s) from the options
(i) to (iv) following it. Also, write the highest and lowest values that can be
pointed by label LABEL.
>>>import random
>>>for b in range(5,9):
LABEL = random.randint (20,26) + 7
print(LABEL, "@", end=" ")
35. Rewrite following python code fragment using for loop. Output of the program
should not be changed.
n=39
while(n<=45):
print(“Python”)
n+=2
https://pythonschoolkvs.wordpress.com/ Page 5
36. Suppose that L is a list as given below:
[“Book”, “is”, “the”, [“best”, “friend”], “of”, “a”, “human”, “being”]
37. Carefully go through the code given below and answer the questions based on it:
testStr = theStr
while inputInt>=0:
testStr = testStr[1:-1]
inputInt =inputInt – 1
print(theStr) #statement-1
print(testStr) #statement-2
print(testBool) #statement-3
>>>s1==s2
>>>s1 is s2
https://pythonschoolkvs.wordpress.com/ Page 6
41. Evaluate the following and write the output of the following:
(i) 0 or None and “none”
(ii) 1 or None and “you” or “me”
(iii) (6<19) or (30<80/0)
(iv) bool(‘0’) and 13<78
44. Write name of python module which is to be imported in program to use the
following functions:
(i) ceil ( ) (ii) date( )
46. Look at the following python code and find the possible output(s) from the options
(i) to (iv). Also, write the Maximum and Minimum values that can be pointed by
label LBL.
import random
VALUE=random.randint(2,7)
LBL= VALUE+3
while VALUE<LBL:
VALUE=VALUE+1
print(dept)
if dept[0]=='P':
https://pythonschoolkvs.wordpress.com/ Page 7
print("Completed")
break
else:
print("Traversed")
55. Consider a given list L. Write output for the following code:
L=['hurry', 'up', 'its','time','for','coding']
https://pythonschoolkvs.wordpress.com/ Page 8
L.sort(reverse=True)
print(L) #statement-1
print(L.pop(2)) #statement-2
print(L.index('for')) #statement-3
57. Suppose a tuple TP is declared as TP = (15, 32, 10, 28), which of the following is
incorrect?
59. Write a statement in Python to declare a dictionary whose keys are ‘Phy’, ‘Chem’,
‘Maths’ and values are 68, 74 and 81 respectively.
https://pythonschoolkvs.wordpress.com/ Page 9
(a) abc (b) 5 (c) {“abc”:5} (d) Error
70. What possible output(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Also specify the minimum
values that can be assigned to each of the variables BEGIN and LAST.
import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80]
BEGIN = random.randint (1, 3)
LAST = random.randint(2, 4)
for I in range (BEGIN, LAST+1):
print (VALUES[I], end = "-")
76. What possible outputs(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Also specify the maximum
values that can be assigned to each of the variables FROM and TO.
import random
AR=[20,30,40,50,60,70]
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO):
print (AR[K],end=”#“)
https://pythonschoolkvs.wordpress.com/ Page 11
79. Evaluate the following expressions:
(i) not(20>6) or (19>7)and(20==20)
(ii) 17%20
80. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)
What could be the possible outputs out of the given four choices?
i) 2 3 4 ii) 9 4 4 iii)16 16 16 iv)2 4 9
https://pythonschoolkvs.wordpress.com/ Page 12
88. Consider the following code and find out the possible output(s) from the options
given below. Also write the least and highest value that can be generated.
import random as r
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15))
i) 25 25 25 21 iii) 23 22 25 20
ii) 23 27 22 20 iv) 21 25 20 24
89. Suppose a tuple Tup is declared as Tup = (12, 15, 63, 80),
which of the following is incorrect?
a) print(Tup[1])
b) Tup[2] = 90
c) print(min(Tup))
d) print(len(Tup))
https://pythonschoolkvs.wordpress.com/ Page 13
CHAPTER-2
FUNCTIONS IN PYTHON
2.1 Definition: Functions are the subprograms that perform specific task. Functions
are the small modules.
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
3. User Defined Functions: The functions those are defined by the user are called
user defined functions.
https://pythonschoolkvs.wordpress.com/ Page 14
S. Function Description Example
No.
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668
Where:
https://pythonschoolkvs.wordpress.com/ Page 15
A function name to uniquely identify it. Function naming follows the
same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They
are optional.
A colon (:) to mark the end of function header.
One or more valid python statements that make up the function body.
Statements must have same indentation level.
An optional return statement to return a value from the function.
Example:
def display(name):
1. Formal Parameter: Formal parameters are written in the function prototype and
function header of the definition. Formal parameters are local variables which are
assigned values from the arguments when the function is called.
Python supports two types of formal parameters:
i. Positional parameters
ii. Default parameters
Example:
Then we can call the function using these possible function calling statements:
https://pythonschoolkvs.wordpress.com/ Page 16
p,q,r = 4,5,6
Test(p,q,r) # 3 variables which have values, are passed
Test(4,q,r) # 1 Literal value and 2 variables are passed
Test(4,5,6) # 3 Literal values are passed
So, x,y,z are positional parameters and the values must be provided these
parameters.
ii. Default Parameters: The parameters which are assigned with a value in
function header while defining the function, are known as default parameters.
This values is optional for the parameter.
If a user explicitly passes the value in function call, then the value which is
passed by the user, will be taken by the default parameter. If no value is
provided, then the default value will be taken by the parameter.
Default parameters will be written in the end of the function header, means
positional parameter cannot appear to the right side of default parameter.
Example:
Let a function defined as given below:
def CalcSI(p, rate, time=5): # time is default parameter here
.
.
.
Then we can call the function using these possible function calling statements:
CalcSI(5000, 4.5) # Valid, the value of time parameter is not provided, so it will
take # default value, which is 5.
CalcSI(5000,4.5, 6) # Valid, Value of time will be 6
2. Actual Parameter: When a function is called, the values that are passed in the call
are called actual parameters. At the time of the call each actual parameter is assigned
to the corresponding formal parameter in the function definition.
Example :
https://pythonschoolkvs.wordpress.com/ Page 17
def ADD(x, y): #Defining a function and x and y are formal
parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
https://pythonschoolkvs.wordpress.com/ Page 18
OUTPUT:
Sum = 30.0
How function works?
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
b. Function not returning any value (void function) : The function that performs
some operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
OUTPUT:
Hello
None
1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the
function. In this scope, The lifetime of variables inside a function is as long as the
function executes. They are destroyed once we return from the function. Hence, a
function does not remember the value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime
of a variable is the period throughout which the variable exits in the memory.
https://pythonschoolkvs.wordpress.com/ Page 20
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
Here, we can see that the value of x is 20 initially. Even though the
function my_func()changed the value of x to 10, it did not affect the value outside the
function.
This is because the variable x inside the function is different (local to the function) from
the one outside. Although they have same names, they are two different variables with
different scope.
On the other hand, variables outside of the function are visible from inside. They have a
global scope.
We can read these values from inside the function but cannot change (write) them. In
order to modify the value of variables outside the function, they must be declared as
global variables using the keyword global.
Example:
https://pythonschoolkvs.wordpress.com/ Page 21
Output:
PythonClassXII
Example:
Output:
Physics
CS
Chemistry
English
Maths
https://pythonschoolkvs.wordpress.com/ Page 22
Questions/Programs related to Functions in Python topic:
1. Define a function.
2. What is scope of a variable?
3. Write difference between a local scope and global scope.
4. Define different types of formal arguments in Python, with example.
5. Find and write the output of the following Python code:
def makenew(mystr):
newstr = " "
count = 0
for i in mystr:
if count%2 !=0:
newstr = newstr+str(count)
else:
if i.islower():
newstr = newstr+i.upper()
else:
newstr = newstr+i
count +=1
newstr = newstr+mystr[:1]
print("The new string is :", newstr)
makenew("sTUdeNT")
https://pythonschoolkvs.wordpress.com/ Page 23
def Change(P ,Q=20):
P=P+Q
Q=P-Q
print( P,"*",Q)
return (P)
R=40
S=10
R=Change(R,S)
print(R,"&",S)
S=Change(S)
t=Example(2,7)
print(t)
w=Example(6,2,4)
print(w)
PRACTICAL PROGRAMS
1. Write a python program to sum the sequence given below. Take the input n from
the user.
1 1 1 1
1 + + + + ⋯+
1! 2! 3! 𝑛!
Solution:
def fact(x):
j=1
res=1
while j<=x:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
https://pythonschoolkvs.wordpress.com/ Page 24
2. Write a program to compute GCD and LCM of two numbers
def gcd(x,y):
while(y):
x, y = y, x % y
return x
https://pythonschoolkvs.wordpress.com/ Page 25
CHAPTER-3
RECURSION
OUTPUT:
enter the number: 5
The factorial of 5 is 120
https://pythonschoolkvs.wordpress.com/ Page 26
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
OUTPUT:
Sum of How Many Natural Numbers : 6
Sum of 6 Natural numbers is: 21
https://pythonschoolkvs.wordpress.com/ Page 27
CHAPTER-4
FILE HANDLING
4.1 INTRODUCTION:
File:- A file is a collection of related data stored in a particular area on the disk.
Stream: - It refers to a sequence of bytes.
Need of File Handling:
File handling is an important part of any web application.
To store the data in secondary storage.
To Access the data fast.
To perform Create, Read, Update, Delete operations easily.
S.
Text Files Binary Files
No.
https://pythonschoolkvs.wordpress.com/ Page 28
4.3 Opening and closing a file:
4.3.1 Opening a file:
To work with a file, first of all you have to open the file. To open a file
in python, we use open( ) function.
The open( ) function takes two parameters; filename, and mode. open( ) function
returns a file object.
Syntax:
file_objectname= open(filename, mode)
Example:
To open a file for reading it is enough to specify the name of the file:
f = open("book.txt")
The code above is the same as:
f = open("book.txt", "rt")
Where "r" for read mode, and "t" for text are the default values, you do not need to
specify them.
4.3.2 Closing a file:
After performing the operations, the file has to be closed. For this, a close( ) function is
used to close a file.
Syntax:
file-objectname.close( )
Text Binary
file File Description
mode Mode
‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file does
not exist.
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not exist
‘a’ ‘ab’ Append - Opens a file for appending, creates the file if it does not
exist
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file exists
https://pythonschoolkvs.wordpress.com/ Page 29
In addition you can specify if the file should be handled as binary or text mode
“t” – Text-Default value. Text mode
“b” – Binary- Binary Mode (e.g. images)
Relative path :This is the file path without slash. It describes the location
of a file in relative to the current working directory.
Example: “Book.txt”
https://pythonschoolkvs.wordpress.com/ Page 30
Create and Open a file
Print/Access data
fin=open("D:\\python fin=open("D:\\python
programs\\Book.txt",'r') programs\\Book.txt",'r')
str=fin.read( ) str=fin.read(10)
print(str) print(str)
fin.close( ) fin.close( )
OUTPUT: OUTPUT:
Python is interactive language. It is case Python is
sensitive language.
It makes the difference between uppercase
and lowercase letters.
It is official language of google.
https://pythonschoolkvs.wordpress.com/ Page 31
Example-3: using readlines( ) function:
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.readlines( )
print(str)
fin.close( )
OUTPUT:
['Python is interactive language. It is case sensitive language.\n', 'It makes the
difference between uppercase and lowercase letters.\n', 'It is official language of
google.']
Some important programs related to read data from text files:
Program-a: Count the number of characters from a file. (Don’t count white
spaces)
fin=open("Book.txt",'r')
str=fin.read( )
L=str.split( )
count_char=0
for i in L:
count_char=count_char+len(i)
print(count_char)
fin.close( )
https://pythonschoolkvs.wordpress.com/ Page 32
for i in str:
count_line=count_line+1
print(count_line)
fin.close( )
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
L=str.split( )
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
https://pythonschoolkvs.wordpress.com/ Page 33
write(byte_string) (for binary files)
To write the data to an existing file, you have to use the following mode:
Example: Open the file "Book.txt" and append content to the file:
fout= open("Book.txt", "a")
fout.write("Welcome to the world of programmers")
Example: Open the file "Book.txt" and overwrite the content:
fout = open("Book.txt", "w")
fout.write("It is creative and innovative")
Program: Write a program to take the details of book from the user and write
the record in text file.
fout=open("D:\\python programs\\Book.txt",'w')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :3
Enter details of record : 1
Enter the title of book : java
Enter price of the book: 250
Enter details of record : 2
Enter the title of book : c++
Enter price of the book: 300
Enter details of record : 3
Enter the title of book : python
https://pythonschoolkvs.wordpress.com/ Page 34
Enter price of the book: 450
Program: Write a program to take the details of book from the user and write
the record in the end of the text file.
fout=open("D:\\python programs\\Book.txt",'a')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :2
Enter details of record : 1
Enter the title of book : DBMS
Enter price of the book: 350
Enter details of record : 2
Enter the title of book : Computer
Networking
Enter price of the book: 360
d. Delete a file: To delete a file, you have to import the os module, and use remove(
) function.
import os
os.remove("Book.txt")
https://pythonschoolkvs.wordpress.com/ Page 35
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to
delete it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("Book.txt"):
os.remove("Book.txt")
else:
print("The file does not exist")
https://pythonschoolkvs.wordpress.com/ Page 36
OUTPUT:
Enter student Roll No:1201
Enter student Name :Anil
Want to add more record(y/n) :y
Enter student Roll No:1202
Enter student Name :Sunil
Want to add more record(y/n) :n
(b) Read data from a Binary File: To read the data from a binary file, we have to use
load( ) function of pickle module.
Example:
import pickle
OUTPUT:
[{'roll': '1201', 'name': 'Anil'}, {'roll': '1202', 'name': 'Sunil'}]
(c) Update a record in Binary File:
import pickle
roll = input('Enter roll number whose name you want to update in binary file
:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = [ ]
for x in list:
if roll in x['roll']:
found = 1
x['name'] = input('Enter new name: ')
lst.append(x)
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
https://pythonschoolkvs.wordpress.com/ Page 37
print('roll number does not exist')
file.close( )
OUTPUT:
Enter roll number whose name you want to update in binary file :1202
Enter new name: Harish
Record Updated
(d) Delete a record from binary file:
import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close( )
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
import pickle
roll = input('Enter roll number that you want to search in binary file :')
file = open("student.dat", "rb")
list = pickle.load(file)
file.close( )
for x in list:
if roll in x['roll']:
https://pythonschoolkvs.wordpress.com/ Page 38
print("Name of student is:", x['name'])
break
else:
print("Record not found")
OUTPUT:
Enter roll number that you want to search in binary file :1202
Name of student is: Harish
Output:
14
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output:
5
https://pythonschoolkvs.wordpress.com/ Page 39
4.9 File I/O Attributes
Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
encoding Returns the encoding format of the file
Returns True if the file closed else returns
closed
False
Example:
f = open("D:\\story.txt", "r")
print("Name of the File: ", f.name)
print("File-Mode : ", f.mode)
print("File encoding format : ", f.encoding)
print("Is File closed? ", f.closed)
f.close()
print("Is File closed? ", f.closed)
OUTPUT:
Name of the File: D:\story.txt
File-Mode : r
File encoding format : cp1252
Is File closed? False
Is File closed? True
To use the picking methods in a program, we have to import pickle module using import
keyword.
Example:
import pickle
https://pythonschoolkvs.wordpress.com/ Page 40
In this module, we shall discuss to functions of pickle module, which are:
i. dump( ) : To store/write the object data to the file.
ii. load( ) : To read the object data from a file and returns the object data.
Example:
Write the object to the file: dump( )
OUTPUT:
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 41
4.11 CSV Files:
CSV (Comma Separated Values). A csv file is a type of plain text file that uses
specific structuring to arrange tabular data. csv is a common format for data
interchange as it is compact, simple and general. Each line of the file is one line of
the table. csv files have .csv as file extension.
As you can see each row is a new line, and each column is separated with a
comma. This is an example of how a CSV file looks like.
To work with csv files, we have to import the csv module in our program.
CODE:
import csv
with open('C:\\data.csv','rt') as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)
OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
https://pythonschoolkvs.wordpress.com/ Page 42
CODE:
import csv
with open('C:\\data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"' )
#write new record in file
writer.writerow(['3', 'Shivani', 'Commerce', '448'])
writer.writerow(['4', 'Devansh', 'Arts', '404'])
OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']
When we shall open the file in notepad (Flat file) then the contents of the file will
look like this:
https://pythonschoolkvs.wordpress.com/ Page 43
5. Alok Kumar of class 12 is writing a program to create a CSV file “project.csv”
which will contain student name and project name for some entries. He has
written the following code. As a programmer, help him to successfully execute the
given task.
def AddProject (StudentName, ProjectName): # to write data into the CSV file
newFileWriter = csv.writer(f)
newFileWriter.writerow([Sname,Pname])
f.close( )
print (row[0],row[1])
newFile.______________ # Line 4
ReadProject( ) #Line 5
https://pythonschoolkvs.wordpress.com/ Page 44
iv. Fill in the blank in Line 4 to close the file.
v. Write the output he will obtain while executing Line 5.
6. Write a function CountYouMe( ) in python which reads the content of a text file
“BIOGRAPHY.TXT” and counts the words You and Me separately. (Not case
sensitive).
Example:
If the “BIOGRAPHY.TXT” contents are as follows:
7. Write a function CountLineP( ) in python which reads the content of a text file
“Daily.TXT” and counts number of lines which start with the character ‘P’ in a text
file.
Example:
If the “Daily.TXT” contents are as follows:
Pray to God.
Stay home stay safe.
Please wear mask when you
go to outside.
ii. Write a function CountRec(Brand) in Python which accepts the Brand name
as parameter and count and return number of products of the given Brand
are stored in the binary file “PRODUCT.dat”
https://pythonschoolkvs.wordpress.com/ Page 45
i. Write a user defined function WriteData() to input data for a record and add
to PEOPLE.DAT.
ii. Write a function CountRec() in Python that would read contents of the file
“PEOPLE.DAT” and display the details of those people whose age is above
50.
11. Priti of class 12 is writing a program to create a CSV file “emp.csv”. She has
written the following code to read the content of file emp.csv and display the
employee record whose name begins from “S‟ also show no. of employee with
https://pythonschoolkvs.wordpress.com/ Page 46
first letter “S‟ out of total record. As a programmer, help her to successfully
execute the given task.
Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write Python function DISPEMP( ) to read the content of file emp.csv and
displayonly those records where salary is 4000 or above.
https://pythonschoolkvs.wordpress.com/ Page 47
CHAPTER-5
CREATE & IMPORT PYTHON LIBRARIES
5.1 INTRODUCTION:
Python has its in-built libraries and packages. A user can directly import the libraries and its
modules using import keyword. If a user wants to create libraries in python, he/she can create
and import libraries in python.
Example:
Let’s create a package named Shape and build three modules in it namely Rect, Sq and Tri to
calculate the area for the shapes rectangle, square and triangle.
Step-1 First create a directory and name it Shape. (In this case it is created under
C:\Users\ViNi\AppData\Local\Programs\Python\Python37-32\ directory path.)
Step-2 Create the modules in Shape directory.
To create Module-1(Rect.py), a file with the name Rect.py and write the code in it.
class Rectangle:
def __init__(self):
print("Rectangle")
https://pythonschoolkvs.wordpress.com/ Page 48
To create Module-2(Sq.py), a file with the name Sq.py and write the code in it.
class Square:
def __init__(self):
print("Square")
def Area(self, side):
self.a=side
print("Area of square is : ", self.a*self.a)
To create Module-3 (Tri.py), a file with the name Tri.py and write the code in it.
class Triangle:
def __init__(self):
print("Trinagle")
Step-3 Create the __init__.py file. This file will be placed inside Shape directory and can be
left blank or we can put this initialisation code into it.
from Shape import Rect
from Shape import Sq
from Shape import Tri
That’s all. Package created. Name of the package is Shape and it has three modules namely
Rect, Sq and Tri.
https://pythonschoolkvs.wordpress.com/ Page 49
from Shape import Rect
from Shape import Sq
from Shape import Tri
OUTPUT:
Rectangle
Area of Rectangle is : 200
Square
Area of square is : 100
Trinagle
Area of Triangle is : 24.0
https://pythonschoolkvs.wordpress.com/ Page 50
r=Shape.Rect.Rectangle( )
s=Shape.Sq.Square( )
t=Shape.Tri.Triangle( )
Method-2:
If we want to access a specific module of a package then we can use from and import
keywords.
Syntax:
from package-name import module-name
Example:
from Shape import Rect
r=Rect.Rectangle( )
s=Sq.Square( )
t=Tri.Triangle( )
Method-3:
If a user wants to import all the modules of Shape package then he/she can use * (asterisk).
Example:
from Shape import *
r=Rect.Rectangle( )
s=Sq.Square( )
t=Tri.Triangle( )
https://pythonschoolkvs.wordpress.com/ Page 51
CHAPTER-6
IDEA OF EFFICIENCY
6.1 INTRODUCTION:
Program efficiency is a property of a program related to time taken by a program for
execution and space used by the program. It is also related to number of inputs taken
by a program.
Complexity
Time and space complexity depends on lots of things like hardware, operating system,
processors, size of inputs etc.
Best case: The minimum number of steps that an algorithm can take for any
input data values.
Worst case: The maximum number of steps that an algorithm can take for any
input data values.
https://pythonschoolkvs.wordpress.com/ Page 52
Complexity of certain well known algorithms:
(a) Linear Search : Best case – O(1), Average - O(n), Worst- O(n)
(b) Binary Search : O(log n)
(c) Bubble Sort : O(n2)
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
https://pythonschoolkvs.wordpress.com/ Page 53
6.2.2 Program (Linear Search):
Linear Search: It is a simple searching technique.
L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")
https://pythonschoolkvs.wordpress.com/ Page 54
CHAPTER-7
DATA STRUCTURE (STACK AND QUEUE)
7.1 INTRODUCTION:
Definition: The logical or mathematical model of a particular organization of data is
called data structure. It is a way of storing, accessing, manipulating data.
DATA STRUCTURE
LINKED
ARRAY STACK QUEUE TREE GRAPH
LIST
1. Linear data structure: It is simple data structure. The elements in this data
structure creates a sequence. Example: Array, linked list, stack, queue.
2. Non-Linear data structure: The data is not in sequential form. These are
multilevel data structures. Example: Tree, graph.
https://pythonschoolkvs.wordpress.com/ Page 55
7.3 OPERATION ON DATA STRUCTURE:
There are various types of operations can be performed with data structure:
1. Traversing: Accessing each record exactly once.
2. Insertion: Adding a new element to the structure.
3. Deletion: Removing element from the structure.
4. Searching: Search the element in a structure.
5. Sorting: Arrange the elements in ascending and descending order.
6. Merging: Joining two data structures of same type. (not covered in syllabus)
https://pythonschoolkvs.wordpress.com/ Page 56
7.4.2 Program for Stack:
L=[ ] #empty list
def push(item): #Insert an element
L.append(item)
def size( ): # Size of the stack i.e. total no. of elements in stack
return len(L)
delete 10 20 30 40 50 60 Insert
front rear
RNo integer
Name String
Age integer
def isEmpty(stk):
https://pythonschoolkvs.wordpress.com/ Page 58
if stk == [ ]:
return True
else:
return False
def stk_push(stk, item):
def isEmpty(stk):
if stk == [ ]:
return True
else:
return False
def stk_pop(stk):
5. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From 3 this
list push all numbers divisible by 5 into a stack implemented by using a list.
Display the stack if it has at least one element, otherwise display appropriate
error message.
https://pythonschoolkvs.wordpress.com/ Page 59