You are on page 1of 59

https://pythonschoolkvs.wordpress.

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

5 CREATE & IMPORT PYTHON LIBRARIES 48

6 IDEA OF EFFICIENCY 52

7 DATA STRUCTURE- (STACK AND QUEUE) 52

By: Vikash Kumar Yadav


PGT-Computer Science
K.V. No.-IV ONGC Vadodara

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?

2. Write name of modes which are used by python interpreter.

3. Find valid identifier among the following:


(i) and (ii) for_is (iii) simple-interest (iv) 4you

4. Write the type/name of token for the following:


i) 83.95
ii) ==

5. Which of the following operator has right to left associativity in python:


(i) % (ii) and (iii) ** (iv) >=

6. How many times the following loop will execute:


for L in range(7,29,4):
if L%5==0:
break
else:
print(L)

7. A string is declared as: S = “HELLO PROGRAMMER”


What will be the output of S.find("GRAM", 2, 15)

8. Given the list L=[25,8,61,80,54,17,11,99]


Write the output of print(L[-2 : -7 : -3])

9. Write output for the following python code:


>>>K=[5,7,8, [10,4], 11,2]
>>>print(len(K))

10. Write the output of the following python statements (Assume that math module
already imported):
math.floor(-44.6)
math.fabs(-67.8)

11. Write size (length) of following strings:


i) ‘\\’
ii) “father’s”

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=" ")

(i) 10#13#17#12# (ii) 11#16#17#17#


(iii) 18#12#15#17# (iv) 14#9#16#12#

13. Which type of value does input( ) return?


14. Write output for the following:
>>> str(print("KVS"))+ "CBSE"
15. Write any four features of python language.
16. >>> is known in python:
(a) compiler (b) output (c) prompt (d) shell
17. Line indentation is rigidly enforced in python:
a) True (b) False
18. Convert the following mathematical expression into equivalent python expression:

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

22. Evaluate the following expressions:


i) >>>True+8
ii) >>>36 % 3 ** 3 // 9 + 4
iii) >>> bool('0') and 13<78

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)

What will be the output produced if input is:


(i) Joy7k (ii) jump5 (iii) 2020HY
24. Write a program to search an element in a given list of numbers.
25. Write a python code to add 1 in each odd value and 2 in each even value of the
list L.
Example:
If original elements of the list L are:
L= [35, 12, 16, 69, 26]
The modified list will be:
L= [36, 14, 18, 70, 28]
26. Which type of value does print( ) function return?
27. Write the size of following strings:
(i) (ii)
str1='''ab\ str2='''ab
cd\ cd
e''' e'''

28. Rewrite the following code after removing the syntax error. Underline each
correction.

print(x)

for i is range(0, -4):

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)

33. Write the output of the following programs:


(a) for z in range(13,29):
if z%3==0:
break
else:
print(z)

(b) for z in range(13,29):

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=" ")

(i) 28@30@31@29@ (ii) 29@28@27@29


(iii) 27@33@29@30@ (iv) 31@32@33@27@

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”]

What does each of the following expressions evaluate to ?


(i) L[3:4][0] (ii) L[3:4][0][1]
(iii) L[3:4][0][1][3] (iv) “modern” in L

37. Carefully go through the code given below and answer the questions based on it:

thestr= “This is a test”

inputInt = int(input( “ Enter an integer :” ))

testStr = theStr

while inputInt>=0:

testStr = testStr[1:-1]

inputInt =inputInt – 1

testBool = ‘t’ in testStr

print(theStr) #statement-1

print(testStr) #statement-2

print(testBool) #statement-3

(i) Given the input integer 3, what output is produced by statement-1 ?

(ii) Given the input integer 3, what output is produced by statement-2 ?

(iii) Given the input integer 2, what output is produced by statement-3 ?

38. Write difference between the following:

(i) del and pop( ) (ii) append( ) and extend( )

(iii) list and tuple (iv) id( ) and type( )

39. Write the valid identifiers among the following:


data, global, with8, 23file, AND, _file, data-rec, my.data

40. if s1=’xyz’ and s2=input(“Enter a string:”)


if a user enters the string ‘xyz’ then what will be the output of the following
statements:

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

42. Write the valid identifiers among the following:


bool, and, 8digit, _Sum, first+second, Hello7, min value, Else

43. Write type of token for the following:


(i) 88.7 (ii) continue

44. Write name of python module which is to be imported in program to use the
following functions:
(i) ceil ( ) (ii) date( )

45. Write the output of the following python statements:

(i) >>> type(7<3) (ii) >>>36 % 3 ** 3 // 9 + 4

(iii) >>> bool('0') and 13<78 (iv) >>>True+8

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:

print(VALUE, end= '@')

VALUE=VALUE+1

(i) 1@2@3@ (ii) 2@3@4@

(iii) 6@7@8@ (iv) 8@9@10@

47. Write the output of the following python code:

for dept in ['Research', 'Marketing', 'Production', 'HR']:

print(dept)

if dept[0]=='P':

https://pythonschoolkvs.wordpress.com/ Page 7
print("Completed")

break

else:

print("Traversed")

48. Consider a dictionary given below:

Marks ={‘Physics’ : 67, ’Chemistry’ : 78, ‘CS’ : 75}

Write the python statements for the following:

(i) Add ‘Maths’ : 71 to the given dictionary.

(ii) Update the marks of ‘CS’ 75 to 81.


49. Write a statement to add a single element (element is =57) in given tuple:
T = (15, 28, 45, 78)
50. Name the python library need to be imported to invoke following functions:
(i) randint( ) (ii) date( )

51. A string is declared as: S = “OFFICIAL WARRANTY”


What will be the output of S.find("ARRA", 4, 13)

52. Given the list L=[23,7,38,82,54,45,10,91]


Write the output of print(L[-3 : -8 : -3])

53. Evaluate the following expressions:


i) 12*(3%4)//2+6**2
ii) 54>52 or 23>56 and not 5
iii)
54. Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
str=list("Python Program@2021')
for Y is range(len(str)-1):
if Y==7:
str[Y]=str*2
elif(str[Y].isupper():
str[Y]=str*3
elif(str[y].isdigit()):
str[Y]='D'
print(str)

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

56. Given the lists L=[25,8,61,80,54,17,11,99]

Write the output of print(L[-2:-7:-3])

57. Suppose a tuple TP is declared as TP = (15, 32, 10, 28), which of the following is
incorrect?

i) print(TP[1]) ii) print(max(TP)) iii) T[2] = 52 iv) print(len(TP))

58. A string is declared as: S = “PERIODIC TEST3”

What will be the output of S.find("IODI",2,15)

59. Write a statement in Python to declare a dictionary whose keys are ‘Phy’, ‘Chem’,
‘Maths’ and values are 68, 74 and 81 respectively.

60. Write output for the following:


>>> S1="AISSCE PRACTICE PAPER"
>>> S2=S1.split( )
>>> print(type(S2))

61. Write output for the following:


>>> ‘aBcD’<= ‘abCd’

62. Find the output -


>>>A = [17, 24, 15, 30]
>>>A.insert( 2, 33)
>>>print ( A [-4])

63. Which of the following are valid operator in Python:


(i) */ (ii) is (iii) ^ (iv) like

64. Which of the following statements will create a tuple ?


(a) Tp1 = (“a”, “b”)
(b) Tp1= (3) * 3
(c) Tp1[2] = (“a”, “b”)
(d) None of these
65. What will be the result of the following code?
>>>d1 = {“abc” : 5, “def” : 6, “ghi” : 7}
>>>print (d1[0])

https://pythonschoolkvs.wordpress.com/ Page 9
(a) abc (b) 5 (c) {“abc”:5} (d) Error

66. Find the output of the following:


>>>S = 1, (2,3,4), 5, (6,7)
>>> len(S)

67. Which of the following are Keywords in python ?


(i) break (ii) check (iii) range (iv) while

68. Find the output of the following:


>>>Name = “Python Examination”
>>>print (Name [ : 8 : -1])

69. Evaluate the following expressions:


a) 12*(3%4)//2+6
b) not 12 > 6 and 7 < 17 or not 12 < 4

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 = "-")

(i) 30-40-50- (ii) 10-20-30-40-


(iii) 30-40-50-60- (iv) 30-40-50-60-70-

71. Find the invalid identifier from the following


a) def b) For c)_bonus d)First_Name

72. What will be the output of following program:


a='hello' b='virat'
for i in range(len(a)): print(a[i],b[i])

73. Give Output:


colors=["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
del colors[4]
colors.remove("blue")
colors.pop(3)
print(colors)
https://pythonschoolkvs.wordpress.com/ Page 10
74. Which statement is correct for dictionary?
(i) A dictionary is a ordered set of key:value pair
(ii) each of the keys within a dictionary must be unique
(iii) each of the values in the dictionary must be unique
(iv) values in the dictionary are immutable

75. If given A=2,B=1,C=3, What will be the output of following expressions:


(i) print((A>B) and (B>C) or(C>A))
(ii) print(A**B**C)

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=”#“)

(i)10#40#70# (ii)30#40#50# (iii)50#60#70# (iv)40#50#70#

77. What will be the output of following program:


s="welcome2kv"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'#'
print(m)

78. Which is the correct form of declaration of dictionary?


(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]

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)

81. Consider the following code:


import math
import random
print(str(int(math.pow(random.randint(2,4),2))),end= ' ')
print(str(int(math.pow(random.randint(2,4),2))),end= ' ')
print(str(int(math.pow(random.randint(2,4),2))))

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

82. Find the invalid identifier from the following


a) Subtotal b) assert c) temp_calc d) Name2

83. Which operator is used for replication?


a) + b) % c) * d) //

84. Give the output of the following code:


L = [ 1,2,3,4,5,6,7]
B=L
B[3:5] = 90,34
print(L)

85. A tuple is declared as T = (1,2), (1,2,4), (5,3)


What will be the value of min(T) ?

86. Which of the following functions generates an integer?


a) uniform( ) b) randint( )

c) random( ) d) None of the above

87. What is the output of the following code:


for i in range(-3,4,2):
print(i, end = '@')

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

90. Identify the valid declaration of P:


P= [‘Jan’, 31, ‘Feb’, 28]

a. dictionary b. string c.tuple d. list

91. What is the length of the tuple shown below?


t=(((('a',1),'b','c'),'d',2),'e',3)
92. Define the following:
(i) docstring (ii) literal
93. Write difference between list and tuple.
94. Write difference between keyword and identifier.
95. What is operator precedence and associativity?

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.

2.2 Types of Functions:


There are three types of functions in python:
1. Library Functions (Built in functions)
2. Functions defined in modules
3. User Defined Functions

Built in functions

Functions defined in
Types of functions modules

User defined functions

1. Library Functions: These functions are already built in the python library.

2. Functions defined in modules: These functions defined in particular modules.


When you want to use these functions in program, you have to import the
corresponding module of that function.

3. User Defined Functions: The functions those are defined by the user are called
user defined functions.

1. Library Functions in Python:


These functions are already built in the library of python.
For example: type( ), len( ), input( ), id( ), range( ) etc.
2. Functions defined in modules:
a. Functions of math module: To work with the functions of math module,
we must import math module in program.
import math

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

b. Function in random module:


random module has the following functions:
 random( ) : returns random value between 0 to 1. It doesn’t include 0
and 1.
 randint(start, stop): returns any integer number from start to stop. It
includes start and stop also.
 randrange(start, stop) : returns a number between start and stop. It
doesn’t include start and stop value.
Example:
import random
n=random.randint(3,7)
*The value of n will be 3 to 7.
c. Functions in datetime module:
It has date function. Which has three parameters named as year, month
and day.
3. USER DEFINED FUNCTIONS:
The syntax to define a function is:
def function-name ( parameters) :
#statement(s)

Where:

 Keyword def marks the start of function header.

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

print("Hello " + name + " How are you?")

2.3 Function Parameters:


A functions has two types of parameters:
1. Formal Parameter
2. Actual Parameter

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

i. Positional parameter: These are mandatory arguments. Value must be


provided to these parameters and values should be matched with parameters.

Example:

Let a function defined as given below:


def Test(x,y,z):

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

Valid/Invalid examples to define the function with default arguments:


CalcSI(p, rate=4.5, time=5): #Valid
CalcSI(p, rate=4.5, time=5): # Valid
CalcSI(p, rate=4.5, time): #Invalid, Positional argument cannot come
after default #parameter
CalcSI(p=5000, rate=4.5, time=5): #Valid

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.

Difference between formal parameter and actual parameter:

Formal parameter Actual parameter


Formal parameters are written in When a function is called, the
the function prototype and function values that are passed in the call
header of the definition. Formal are called actual parameters. At the
parameters are local variables time of the call each actual
which are assigned values from the parameter is assigned to the
arguments when the function is corresponding formal parameter in
called. the function definition.
Example:
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.

2.4 Calling the function:


Once we have defined a function, we can call it from another function, program or even
the Python prompt. To call a function we simply type the function name with
appropriate 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)

… .. …
… .. …

2.5 The return statement:


The return statement is used to exit a function and go back to the place from where it
was called.
There are two types of functions according to return statement:
a. Function returning some value (non-void function)
b. Function not returning any value (void function)
a. Function returning some value (non-void function) :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x

Example-2 Function returning multiple values:


def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple
print(S)
OUTPUT:
(7, 7, 11)
Example-3: Storing the returned values separately:
https://pythonschoolkvs.wordpress.com/ Page 19
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)
OUTPUT:
7 7 11

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

2.6 Scope and Lifetime of variables:

Scope of a variable is the portion of a program where the variable is recognized.


Parameters and variables defined inside a function is not visible from outside. Hence,
they have a local scope.

There are two types of scope for variables:

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:

Value inside function: 10

Value outside function: 20

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.

2.7 Passing Strings, Lists, Tuples and Dictionaries to functions:

2.7.1 Passing Strings to Function:

Example:

https://pythonschoolkvs.wordpress.com/ Page 21
Output:

PythonClassXII

2.7.2 Passing List to function:

Example:

Output:

Physics
CS
Chemistry
English
Maths

Note: Same process for tuple and dictionaries.

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

6. Find and write the output of the following python code:


def Exam(s):
k=len(s)
m='' #empty string
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i+1].lower( )
elif s[i].isalpha():
m=m+s[i].upper( )
else:
m=m+'T'
print(m)
Exam('CSpaPeR@21')

7. Find and write the output of the following python code:


a=20
def CheckMe(x):
global a
print(a)
b=x
a=18
print(a+b)
CheckMe(5)

8. Find and write the output of the following python code:

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)

9. Find and write the output of the following python code:


def Example(x, y, z=5):
z, x= y, z
return x

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

def lcm(x, y):


lcm = (x*y)//gcd(x,y)
return lcm

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))

print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))


print("The G.C.D. of", num1,"and", num2,"is", gcd(num1, num2))

https://pythonschoolkvs.wordpress.com/ Page 25
CHAPTER-3
RECURSION

3.1 Definition: A function calls itself, is called recursion.

3.2 Python program to find the factorial of a number using recursion:


Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)

num=int(input("enter the number: "))


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num = = 0:
print("The factorial of 0 is 1")
else:
print("The factorial of ",num," is ", factorial(num))

OUTPUT:
enter the number: 5
The factorial of 5 is 120

3.3 Python program to print the Fibonacci series using recursion:


Program:
def fibonacci(n):
if n<=1:

https://pythonschoolkvs.wordpress.com/ Page 26
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))

num=int(input("How many terms you want to display: "))


for i in range(num):
print(fibonacci(i)," ", end=" ")

OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13

3.4 Sum of n Natural Numbers using recursion:


def SumNatural(num):
if num<=1:
return 1
else:
return num+SumNatural(num-1)

n=int(input("Sum of How Many Natural Numbers : "))


sum=SumNatural(n)
print("Sum of", n, "Natural numbers is:",sum)

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.

4.2 Data Files:


Data files can be stored in two ways:
1. Text Files: Text files are structured as a sequence of lines, where each line
includes a sequence of characters.
2. Binary Files : A binary file is any type of file that is not a text file.

S.
Text Files Binary Files
No.

Stores information in the same


Stores information in ASCII
1. format which the information is
characters.
held in memory.

Each line of text is terminated with a


2. special character known as EOL (End No delimiters are used for a line.
of Line)

Some internal translations take place


No translation occurs in binary
3. when this EOL character is read or
files.
written.

Binary files are faster and easier for


4. Slower than binary files. a program to read and write the
text files.

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

4.4 File Modes:

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.

‘w+’ ‘wb+’ Read and Write-File is created if does not exist.

‘a+’ ‘ab+’ Read and write-Append new data

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

4.5 Absolute and relative path:


 Absolute path: This is the path of a file in a system which starts from the
root of the file system. It describes the location of a file regardless of the
current working directory.
Example: "D:\\python programs\\Book.txt"

 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”

4.6 WORKING WITH TEXT FILES:

4.6.1 Basic operations with files:


a. Read the data from a file
b. Write the data to a file
c. Append the data to a file
d. Delete a file

a. Read the data from a file:


There are 3 types of functions to read data from a file.
 read( ) : reads n bytes. if no n is specified, reads the entire file.
 readline( ) : Reads a line. if n is specified, reads n bytes.
 readlines( ): Reads all lines and returns a list.

Steps to read data from a file:


 Create and Open a file using open( ) function
 use the read( ), readline( ) or readlines( ) function
 print/access the data
 Close the file.

https://pythonschoolkvs.wordpress.com/ Page 30
Create and Open a file

Read or Write data

Print/Access data

Close the file

Let a text file “Book.txt” has the following text:


“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”
Example-1: Program using read( ) function:

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.

Example-2: using readline( ) function:


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.readline( )
print(str)
fin.close( )
OUTPUT:
Python is interactive language. It is case sensitive language.

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

Program-b: Count the number of words in a file.


fin=open("Book.txt",'r')
str=fin.read( )
L=str.split( )
count_words=0
for i in L:
count_words=count_words+1
print(count_words)
fin.close( )

Program-c: Count number of lines in a text file.


fin=open("Book.txt",'r')
str=fin.readlines( )
count_line=0

https://pythonschoolkvs.wordpress.com/ Page 32
for i in str:
count_line=count_line+1
print(count_line)
fin.close( )

Program-d: Count number of vowels in a text file.


fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
count=0
for i in str:
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1
print(count)
fin.close( )

Program-e : Count the number of ‘is’ word in a text file.

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

b. Write data to a file:


There are 2 types of functions to write the data to a file.

 write( ):Write the data to a file. Syntax:

write(string) (for text files)

https://pythonschoolkvs.wordpress.com/ Page 33
write(byte_string) (for binary files)

 writelines( ): Write all strings in a list L as lines to file.

To write the data to an existing file, you have to use the following mode:

"w" - Write - will overwrite any existing content

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

c. Append the data to a file:


This operation is used to add the data in the end of the file. It doesn’t overwrite the
existing data in a file. To write the data in the end of the file, you have to use the
following mode:
"a" - Append - will append to the end of the file.

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

4.7 WORKING WITH BINARY FILES:


Binary files store data in the binary format (0’s and 1’s) which is understandable by the
machine. So when we open the binary file in our machine, it decodes the data and
displays in a human-readable format.
(a) Write data to a Binary File: Pickle is a special python package that is used to
generate data in binary format. Pickle comes with few methods like dump( ) to write
data in binary format.
Example:
import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname} # create a dictionary
list.append(student) # add the dictionary as an element in
the list
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break

file = open("student.dat","wb") # open file in binary and write


mode
pickle.dump(list, file)
file.close( )

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

file = open("student.dat", "rb")


list = pickle.load(file)
print(list)
file.close( )

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

(e) Search a record in a binary file:

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

4.8 tell( ) and seek( ) methods:


 tell( ): It returns the current position of cursor in file.
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
print(fout.tell( ))
fout.close( )

Output:
14

 seek(offset) : Change the cursor position by bytes as specified by the


offset.

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

4.10 Pickle Module:


Python Pickle is used to serialize and deserialize a python object structure. Any object
on python can be pickled so that it can be saved on disk.
Pickling: Pickling is the process whereby a Python object hierarchy is converted into a
byte stream.
Unpickling: A byte stream is converted into object hierarchy.

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:

Read the object from a file: load( )

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.

Let us take a data.csv file which has the following contents:


Roll No., Name of student, stream, Marks
1, Anil, Arts, 426
2, Sujata, Science, 412

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.

4.11.1 Read a CSV file:

To read data from a CSV file, we have to use reader( ) function.


The reader function takes each row of the file and make a list of all columns.

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']

4.11.2 Write data to a CSV file:


When we want to write data in a CSV file you have to use writer( ) function. To
iterate the data over the rows (lines), you have to use the writerow( ) function.

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:

Roll No.,Name of student,stream,Marks


1,Anil,Arts,426
2,Sujata,Science,412
3,Shivani,Commerce,448
4,Devansh,Arts,404

Questions/Programs related to File Handling in Python topic:

1. Write difference between text file and binary file.


2. Write a function to count the number of vowels in a text file “Vowel.txt”
3. Write a function CountYouMe( ) in python which reads the content of a text file
“STORY.TXT” and counts the words You and Me separately. (Not case sensitive).
4. Write output for the following program:
f=open("Sample.txt",'wt')
str="hello python"
f.write(str)
print(f.tell( ))
f.close( )

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.

import _____________ # Line 1

def AddProject (StudentName, ProjectName): # to write data into the CSV file

f=open(' project.csv', '________') # Line 2

newFileWriter = csv.writer(f)

newFileWriter.writerow([Sname,Pname])

f.close( )

#csv file reading code

def ReadProject( ): # to read data from CSV file

with open(' project.csv', 'r') as newFile:

newFileReader = csv._________(newFile) # Line 3

for row in newFileReader:

print (row[0],row[1])

newFile.______________ # Line 4

AddProject(“Ranjana”, “Traffic Control System”)

AddProject(“Ankit”, “Parking Allotment Problem”)

AddProject(“Krishna”, “Billing System”)

ReadProject( ) #Line 5

i. Name the module he should import in Line 1.


ii. Which mode he has to write in Line-2, to add data into the file.
iii. Fill in the blank in Line 3 to read the data from a csv file.

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:

You are a hero for me.


you gifted a book to me which helped me
a lot to learn the programming.
It gave me chance to develop a business software.

The output of the function should be:


Count of You in file: 2
Count of Me in file: 4

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.

The output of the function should be:


No. of lines start with character P are: 2

8. A binary file “PRODUCT.dat” has structure [PNo, Pname, Brand, Price].


i. Write a user defined function WriteData() to input data for a record and add
to PRODUCT.dat .

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”

9. A binary file “PEOPLE.DAT” has structure (Adhaar_number, Name, Gender, Age).

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.

10. Ashok Kumar of class 12 is writing a program to create a CSV file


“empdata.csv” with empid, name and mobile no and search empid and display the
record. He has written the following code. As a programmer, help him to
successfully execute the given task.
import _____ #Line1
fields=['empid','name','mobile_no']
rows=[['101','Rohit','8982345659'],['102','Shaurya','8974564589'],
['103','Deep','8753695421'],['104','Prerna','9889984567'],
['105','Lakshya','7698459876']]
filename="empdata.csv"
with open(filename,'w',newline='') as f:
csv_w=csv.writer(f,delimiter=',')
csv_w.___________ #Line2
csv_w.___________ #Line3
with open(filename,'r') as f:
csv_r=______________(f,delimiter=',') #Line4
ans='y'
while ans=='y':
found=False
emplid=(input("Enter employee id to search="))
for row in csv_r:
if len(row)!=0:
if _____==emplid: #Line5
print("Name : ",row[1])
print("Mobile No : ",row[2])
found=True
break
if not found:
print("Employee id not found")
ans=input("Do you want to search more? (y)")

i. Name the module he should import in Line 1.


ii. Write a code to write the fields (column heading) once from fields list in Line
2.
iii. Write a code to write the rows all at once from rows list in Line 3.
iv. Fill in the blank in Line4 to read the data from a csv file.
v. Fill in the blank to match the employee id entered by the user with the
empid of record from a file in Line 5.

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

import ________ # Line 1


def SNAMES():
with open(_________) as csvfile: # Line 2
myreader = csv._______(csvfile, delimiter=',') # Line 3
count_rec=0
count_s=0
for row in myreader:
if row[1][0].lower()=='s':
print(row[0],',',row[1],',',row[2])
count_s+=1
count_rec+=1
print("Number of 'S' names are ",count_s,"/",count_rec)

i. Name the module he should import in Line 1


ii. In which mode, Priti should open the file to print data.
iii. Fill in the blank in Line 2 to open the file.
iv. Fill in the blank in Line3 to read the data from a csv file.
v. Write the output he will obtain while executing the above program.

12. Consider the following CSV file (emp.csv):


Sl,name,salary
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.

5.2 How to create Libraries/Package in Python?


To create a package/Library in Python, we need to follow these three simple steps:
1. First, we create a directory and give it a package name. Name should be meaningful.
2. Then create the python files (Modules) which have classes and functions and put these .py
files in above created directory.
3. Finally we create an __init__.py file inside the directory, to let Python know that the
directory is a package.

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

def Area(self, length, width):


self.l=length
self.w=width
print("Area of Rectangle is : ", self.l*self.w)

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

def Area(self, base, height):


self.b=base
self.h=height
ar= (1/2)*self.b*self.h
print("Area of Triangle is : ", ar )

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.

5.3 How to use the package in a program:


Following steps should be followed to use the created package.
Step-1 Create a file main.py in the same directory where Shape package is located.
Step-2 Write the following code in main.py file

https://pythonschoolkvs.wordpress.com/ Page 49
from Shape import Rect
from Shape import Sq
from Shape import Tri

r=Rect.Rectangle( ) #Create an object r for Rectangle class


r.Area(10,20) # Call the module Area( ) of Rectangle class by passing argument

s=Sq.Square( ) #Create an object s for Square class


s.Area(10) # Call the module Area( ) of Square class by passing argument

t=Tri.Triangle( ) #Create an object t for Triangle class


t.Area(6,8) # Call the module Area( ) of Triangle class by passing argument

OUTPUT:
Rectangle
Area of Rectangle is : 200
Square
Area of square is : 100
Trinagle
Area of Triangle is : 24.0

5.4 Import the package in program:


Method-1
To use the package/library in a program, we have to import the package in the program. For
this we use import keyword.
If we simply import the Shape package, then to access the modules and functions of Shape
package, we have to write the following code:
Syntax:
Package-name.Module-name.function-name(parameter)
Example:
import Shape

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: To measure the efficiency of an algorithm or program in terms of space


and time.
The program which uses minimum number of resources, less space and minimum time,
is known as good program.

Complexity

Time Complexity Space Complexity

Time and space complexity depends on lots of things like hardware, operating system,
processors, size of inputs etc.

Time Complexity of an algorithm:


 Best case
 Average case
 Worst case

 Best case: The minimum number of steps that an algorithm can take for any
input data values.

 Average case: The efficiency averaged on all possible inputs. We normally


assume the uniform distribution.

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

6.2 Calculate Number of Operations:


6.2.1 Program (Bubble Sort):

L=eval(input("Enter the elements:"))

n=len(L)

for p in range(0,n-1):

for i in range(0,n-1):

if L[i]>L[i+1]:

L[i], L[i+1] = L[i+1],L[i]

print("The sorted list is : ", L)

Step CODING No. of Operations


1 L=eval(input("Enter the elements:")) 1

2 n=len(L) #for example 1


n=7
3 for p in range(0,n-1): one operation for each pass (executes
6 times, 0 to 5)
4 for i in range(0,n-1): executes 6 times for elements, same
will repeat 6 times under each pass
(outer loop) so 6x6=36 operations

5 if L[i]>L[i+1]: executes 6 times for comparisons in


each pass, same will repeat 6 times
under each pass (outer loop) so
6x6=36 operations
6 L[i], L[i+1] = L[i+1],L[i] statement related to step-5, so
6x6=36 operations
7 print("The sorted list is : ", L) 1

TOTAL: 1+1+6+36+36+36+1=117 operations

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

Step CODING No. of Operations


1 L=eval(input("Enter the elements:")) 1

2 n=len(L) #for example 1


n=10
3 item=eval(input("Enter the element 1
that you want to search : "))
4 for i in range(0, n): one operation for each element
(executes 10 times, 0 to 9)
5 if L[i]==item: 10
6 print("Element found at the 10
position :", i+1)
7 break 10
8 else: 1
9 print("Element not found”) 1

TOTAL: 1+1+1+10+10+10+10+1+1=45 operations

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.

7.2 TYPES OF DATA STRUCTURE:


There are two types of data structure:
1. Linear data structure
2. Non-Linear data structure

DATA STRUCTURE

LINEAR DATA NON-LINEAR


STRUCTURE DATA STRUCTURE

LINKED
ARRAY STACK QUEUE TREE GRAPH
LIST

Fig: Types of data structure

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)

7.4 STACK IN PYTHON:


7.4.1 INTRODUCTION:
 Stack is a linear data structure.
 Stack is a list of elements in which an element may be inserted or deleted only at
one end, called the TOP of the stack.
 It follows the principle Last In First Out (LIFO).
 There are two basic operations associated with stack:
o Push : Insert the element in stack
o Pop : Delete the element from stack

Example: Stack Push and Pop operations

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 pop( ): # Delete an element


return L.pop( )

def peek( ): #Check the value of top


return L[len(L)-1]

def size( ): # Size of the stack i.e. total no. of elements in stack
return len(L)

7.5 QUEUE IN PYTHON:


7.5.1 INTRODUCTION:
 Queue is a linear data structure.
 Queue is a list of elements in which insertion takes place at one end, called the
REAR and deletion takes place only at the other end, called the FRONT.
 It follows the principle First In First Out (FIFO).
 There are two basic operations associated with stack:
o Enqueue : Insert the element in queue
o Dequeue : Delete the element from queue

delete 10 20 30 40 50 60 Insert

front rear

7.5.2 Program for Enqueue and Dequeue Operations:


L=[ ]
def Enqueue(laptop): #Insert an element
L.append(laptop)
if len(L)==1:
front=rear=L[0]
else:
https://pythonschoolkvs.wordpress.com/ Page 57
rear=L[len(L)-1]
front=L[0]
print("Front is: ", front)
print("Rear is : ", rear)

def Dequeue( ): # Delete an element


if len(L)==0:
print("List is Empty")
elif len(L)==1:
print("Deleted Element is :", L.pop( ))
print("Now list is empty")
else:
d=L.pop(0)
rear=L[len(L)-1]
front=L[0]
print("Front is: ", front)
print("Rear is : ", rear)
print("Deleted Element is :", d)

Questions based on the topic stack and queue:


1. Write Enqueue(Marks) and Dequeue( ) methods in Python to add marks of
students and delete marks from list, considering them to act as insert and delete
operations of the Queue data structure.
2. Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list
push all numbers divisible by 3 into a stack implemented by using a list. Display
the stack if it has at least one element, otherwise display appropriate error
message.
3. Write a program to perform push operations on a Stack containing Student details
as given in the following definition of student node:

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

 Write the code to push student details using stack.

4. Write a program to perform pop operations on a Stack containing Student details


as given in the following definition of student node:
RNo integer
Name String
Age integer

def isEmpty(stk):
if stk == [ ]:
return True
else:
return False
def stk_pop(stk):

 Write the code to pop a student using stack.

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.

6. Write a function in Python POP(Arr), where Arr is a stack implemented by a list of


numbers. The function returns the value deleted from the stack.

https://pythonschoolkvs.wordpress.com/ Page 59

You might also like