Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Last Minutes Revision Material: Session: 2020-21

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

LAST MINUTES REVISION MATERIAL

Session: 2020-21

Class-XII
COMPUTER SCIENCE
LAST MINUTES REVISION MATERIAL
Session: 2020-21

CHIEF PATRON
Shri B L Morodia Deputy Commissioner KVS (RO), Jaipur

PATRON(S)

Shri D R Meena Shri Mukesh Kumar


Assistant Commissioner Assistant Commissioner
KVS(RO), Jaipur KVS(RO), Jaipur

CONTENT COORDINATOR/LEADER

Shri Manoj Kumar Pandey Principal KV Itarana Alwar

CONTENT TEAM

Shri Pankaj Singh PGT(CS) KV Bharatpur


Shri Surendra Kumar Mehra PGT(CS) KV Khetri Nagar
Smt. Nipun Kalra Walia PGT(CS) KV No. 6 Jaipur

0|KVS Regional Office, JAIPUR | Session 2020-21


PYTHON REVISION TOUR (12 Marks)
Python is a widely used high-level programming Arithmetic : +, -, *, /, %, **, //
language for general-purpose programming, Bitwise : &, ^, |
created by Guido Van Rossum and first released in Identity : is, is not
1991. My first program in Python is: Relational : >, >=, <, <=,!=, ==
Logical : and, or
Python shell can be used in two ways, viz., Assignment : =
interactive mode and script mode. Membership : in, not in
TOKENS IN PYTHON (Lexical Unit) Arithmetic assignment: /=, +=, -=, *=, %=, **=, //=
Smallest individual unit in a program. PRECEDENCE OF ARITHMETIC OPERATORS
1. KEYWORDS PE(MD) (AS) = read PEMDAS
Predefined words with special meaning to the P=parenthesis () E=exponential M, D =
language processor; reserved for special multiplication and division A, S=addition and
purpose and must not be used as normal subtraction
identifiers names. Example - True, for, if, else, elif, Ex: 12*(3%4)//2+6 = 24 (Try at your end)
from, is, and, or, break, continue, def, import etc. 5. PUNCTUATORS
2. IDENTIFIERS (1 mark) Punctuators are symbols that are used to organize
Names given to different parts of the program viz. sentence structure. Common punctuators used in
variable, objects, classes, functions, lists, P \()[]{}@,:.
dictionaries and so forth. The naming rules: DATA TYPES
Must only be a non-keyword word with no Means to identify type of data and set of valid
space in between. Example: salary, operations for it. These are
maxmarks 1. NUMBERS
Must be made up of only letters, numbers To store and process different types of numeric
and underscore (_). Ex: _salary, _cs data: Integer, Boolean, Floating-point, Complex no.
Can not start with a number. They can 2. STRING
contain numbers. Ex: exam21 Can hold any type of known characters i.e. letters,
Some valid identifiers are: numbers, and special characters, of any known
Myfile MYFILE Salary2021 _Chk scripted language. It is immutable datatype means
Invalid Identifies are:
My.file break 2021salary if .
3. LITERALS -6 -5 -4 -3 -2 -1
Data items that have a fixed value. S C H O O L
1. String Literals: are sequence of characters 0 1 2 3 4 5
surrounded by quotes (single, double or triple)
3. LISTS (2 marks)
2. Numerical Literals: are numeric values in Represents a group of comma-separated values of
decimal/octal/hexadecimal form. any datatype between square brackets. Examples:
D1=10 D2=0o56 (Octal) D3=0x12 (Hex) L1=list()
3. Floating point literals: real numbers and may L2=[1, 2, 3, 4, 5]
be written in fractional form (0.45) or exponent L3
form (0.17E2). L4=[45, 67, [34, 78, 87], 98]
4. Complex number literal: are of the form a+bJ, In list, the indexes are numbered from 0 to n-1, (n=
where a, b are int/floats and J(or i) represents total number of elements). List also supports
1 i.e. imaginary number. Ex: C1=2+3j forward and backward traversal. List is mutable
5. Boolean Literals: It can have value True or datatype (its value can be changed at place).
False. Ex: b=False 4. TUPLE (1 mark)
6. Special Literal None: The None literal is used Group of comma-separated values of any data type
to indicate absence of value. Ex: c=None within parenthesis. Tuple are immutable i.e. non-
4. OPERATORS (3 marks) changeable; one cannot make change to a tuple.
Tokens that trigger some computation/action t1=tuple()
when applied to variables and other objects in an t2=(1, 2, 3, 4, 5)
expression. These are

1|KVS Regional Office, JAIPUR | Session 2020-21


5. DICTIONARY (1 mark) S[2:6] NDRI From index number 2
The dictionary is an unordered set of comma to (6-1) i.e. 5.
separated key:value pairs, within { }, with the S[1:6:2] EDI From index 1 to 5
requirement that within a dictionary, no two keys every 2nd letter.
can be the same. Following are some examples of S[::2] KNRY
dictionary: every 2nd letter.
d1=dict() S[::3] KDY
every 3rd letter.
S[::-1] AYIRDNEK Will print reverse of
the string.
In dictionary, key is immutable whereas value is S[ : -1] KENDRIY Will print entire string
mutable. except last letter
STRING PROCESSING AND OTHER FUNCTIONS S[ -1] A Will print only last
STRING REPLICATION letter
When a string is multiplied by a number, string is S[-5::] DRIYA From index no -5 to
replicated that number of times. end of the string.
Note: Other datatype list and tuple also show S[-7:-4:] END From index no -7 to -5.
the same behavior when multiplied by an
integer number.
OTHER FUNCTIONS
length() istitle()
>>> print(STR*5) startswith() endswith()
>>>HiHiHiHiHi count(word) isspace()
>>> L=[1, 2] swapcase() find()
>>> print(L*5) lstrip() rstrip()
>>> [1,2,1,2,1,2,1,2,1,2] strip()
>>> t=(1, 2)
>>> print(t*5) LIST PROCESSING AND OTHER OPERATIONS
>>> (1,2,1,2,1,2,1,2,1,2) CREATING LIST
1) Empty List
STRING SLICE (2 marks) >>>L=[] OR >>> L=list()
String Slice refers to part of a string containing 2) From existing sequence
some contiguous characters from the string. The
syntax is str_variable[start:end:step]. >>> L1=list(st) # from a string
start: from which index number to start >>> t=(1, 2, 3)
end: upto (end-1) index number characters will >>> L2=list(t) # from a tuple
be extracted 3) from Keyboard entering element one by one
step: is step value. (optional) By default it is 1 >>> L=[]
Example : Suppose S='KENDRIYA' >>> for i in range(5):
Backward - - - - - - - -
Index no 8 7 6 5 4 3 2 1 L.append(n)
Character K E N D R I Y A
TRAVERSING A LIST
Forward
>>> L=[1, 2, 3, 4, 5]
Index no 0 1 2 3 4 5 6 7
>>> for n in L:
print(n)
Command Output Explanation JOINING LISTS
S KENDRIYA Will print entire string. >>> L1=[1, 2, 3]
S[:] KENDRIYA Will print entire string. >>> L2=[33, 44, 55]
S[::] KENDRIYA Will print entire string. >>> L1 + L2 # output: [1, 2, 3, 33, 44, 55]
SLICING THE LIST (1 mark)
S[2] N Will print element at
>>> L=[10, 11, 12, 13, 14, 15, 16, 18]
index no 2.
>>> seq=L[2:6]
2|KVS Regional Office, JAIPUR | Session 2020-21
# it will take from index no 2 to (6-1) i.e. 5 DELETING ELEMENTS FROM DICTIONARY
>>> seq # output: [12, 13, 14, 15] >>> del d[3]
General syntax for slicing is L[start : end : step] # will delete entire key:value whose key is 3
APPENDING ELEMENT >>> print(d) # op: {1: 'one', 2: 'two', 4: 'four'}
>>> L=[10, 11, 12] OTHER FUNCTIONS
>>>L.append(20) # Will append 20 at last Here is a list of functions to recall them which work
>>> L # output : [10, 11, 12, 20] on dictionaries.
>>>L.append([4,5]) pop(key) len() values()
# Appended data will be treated as a single element items() keys() update()
>>> L # output: [10, 11, 12, 20, [4, 5]]
EXPANDING LIST WORKING WITH FUNCTIONS
>>> L=[10, 11, 12] Block of statement(s) for doing a specific task.
>>>L.extend([44,55]) Advantages of function:
# Will extend given item as separate elements Cope-up with complexity
>>> L # output: [10, 11, 12, 44, 55] Hiding details Abstraction
UPDATING LIST Fewer lines of code - lessor scope for bugs
>>> L=[10, 11, 12] Increase program readability
# Suppose we want to change 11 to 50 Re-usability of the code
>>> L[1]=50 DEFINING AND CALLING FUNCTION
>>> L # output: [10, 50, 12] In python, a function may be declared as:
DELETING ELEMENTS def function_name([Parameter list]) :
del List[index]# Will delete the item at given index -
del List[start : end]# Will delete from index no start Body of the function
to (end-1) return value
>>> L=[x for x in range(1,11)] Remember: Implicitly, Python returns None,
>>> L # list is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
which is also a built-in, immutable data type. Ex:
>>> del L[2:5] >>> def f(a,b):
>>> L # now list is [1, 2, 6, 7, 8, 9, 10] -string
OTHER FUNCTIONS (1 mark) c=a+b
len() clear() sum(List) return c
pop(index) remove() min(List) >>>f(10, 20) # calling of function
insert(pos, value) sort() max(List)
def is a keyword to declare a function
index(value) pop() count()
f is the name of the function
a, b parameter/argument of the function
TUPLE Vs LISTS return is a keyword
Tuples (is immutable) List (Mutable) Functions can be categorized in three types:
We can not change we can change the 1. Built-in function 2. Modules 3. User-defined
value in place. value in place BUILT-IN FUNCTION
Pre-defined functions available in Python.
DICTIONARY Need not import any module (file).
Dictionaries are a collection of some unordered Example of some built-in functions are:
key:value pairs; are indexed by keys (keys must be str(), eval(), input(), min(), max(), abs(),
of any non-mutable type). type(), len(), round(), range(), dir(), help()
TRAVERSING A DICTIONARY MODULES
Module in Python is a file (name.py) which
>>> for key in d: contains the definition of variables and
\ functions. A module may be used in other
1 : one 2 : two 3 : three programs. We can use any module in two ways
ADDING ELEMENT TO DICTIONARY 1. import <module-name>
2. from <module-name> import <func-name>
>>> print(d) Some well-known modules are: math, random,
{1: 'one', 2: 'two', 3: 'three', 4: 'four'} matplotlib, numpy, pandas, datetime

3|KVS Regional Office, JAIPUR | Session 2020-21


USER-DEFINED FUNCTIONS findSum(p,q,r) #output - Sum is 600
UDFs are the functions which are created by findSum(p,q) #output - Sum is 310
the user as per requirement. findSum(r) #output - Sum is 330
After creating them, we can call them in any findSum(q,r) #output - Sum is 510
part of the program. findSum() #output - Sum is 60
U for UDF. 3. KEYWORD ARGUMENTS
ACTUAL AND FORMAL PARAMETER/ ARGUMENT we can pass arguments value by keyword, i.e. by
Formal Parameter appear in function definition passing parameter name to change the sequence of
Actual Parameter appear in function call arguments, instead of their position. Example:
statement. def print_kv(kvnm, ronm):
Example: print(kvname,'comes under',roname,'region')
def findSum(a, b): # a, b formal parameter
#main-program
#main-program print_kv(kvnm='Rly Gandhidham', ronm='Ahmd')
X, Y=10,30 print_kv(ronm='Jaipur', kvnm='Bharatpur')
findSum(X, Y) # X, Y are actual parameter 4. VARIABLE LENGTH ARGUMENTS
VARIABLE SCOPE In certain situations, we can pass variable number
Arguments are local of arguments to a function. Such types of
Variable inside functions are local arguments are called variable length argument.
If variable is not defined , look in parent They are declared with * (asterisk) symbol.
scope def findSum(*n):
Use the global statement to assign to global sm=0
variables for i in n:
TYPES OF ARGUMENTS sm=sm+i
Python supports four types of arguments: print('Sum is ',sm)
1. Positional 2 Default #main-program
3. Keyword 4. Variable Length findSum() #output Sum is 0
1. POSITIONAL ARGUMENTS findSum(10) #output Sum is 10
Arguments passed to function in correct positional findSum(10,20,30) #output Sum is 60
order. If we change the position of their order, then PASSING STRINGS TO FUNCTION
the result will change. def countVowel(s):
>>> def subtract(a, b): vow='AEIOUaeiou'
print(a - b) ctr=0
>>> subtract(25, 10) # output: 15 for ch in s:
>>> subtract(10, 25) # output: - 15 if ch in vow:
2. DEFAULT ARGUMENTS ctr=ctr+1
To provide default values to positional print('Number of vowels in', s ,'are', ctr)
arguments; If value is not passed, then default #main-program
values used. data=input('Enter a word to count vowels :')
Remember - If we are passing default arguments, countVowel(data)
then do not take non-default arguments, otherwise PASSING LIST TO FUNCTION
it will result in an error. def calAverage(L):
sm=0
def findSum(a=30, b=20, c=10): for i in range(len(L)):
print('Sum is ',(a+b+c)) sm=sm+L[i]
''' av=sm/len(L)
def mySum(a=30, b=20, c): return av
print('Sum is ',(a+b+c)) #main-program
#Error that non-default argument follows default marks=[25, 35, 32, 36, 28]
arguments print('Marks are :',marks)
''' avg=calAverage(marks)
#main-program print('The average is', avg)
p, q, r =100, 200, 300
4|KVS Regional Office, JAIPUR | Session 2020-21
PASSING TUPLES TO FUNCTION FUNCTIONS USING LIBRARIES
def midPoint(t1, t2): Math library (import math) (1 mark)
m=((t1[0]+t2[0])/2.0, Function Description Example
(t1[1]+t2[1])/2.0) pi value of pi 3.14159
return m ceil(x) integer >=x ceil(1.2) 2.0
#main-program floor(x) integer <=x floor(1.2) 1.0
p1=(2, 4)
pow(x,y) x raise y pow(3,2) 9
p2=(6, 6)
mp=midPoint(p1,p2) sqrt(n) square root sqrt(2) 1.414
print('The Mid-Point of is', mp)
String library (1 mark)
PASSING DICTIONARY TO FUNCTION capitalize() Convert 1st letter to upper case
def printMe(d): index(ch) Return index-no of 1st occurrence
"""Function to print values of given isalnum() True, if entire string is (a-z, A-Z, 0-9)
dictionary""" isalpha() True, if entire string is (a-z, A-Z)
for key in d: isdigit() True, if entire string is (0-9)
print(d[key]) islower() True, if entire string is in lower
isupper() True, if entire string is in upper
#main-program len() Return length of the string
d={1:'mon', 2:'tue', 3:'wed' }
printMe(d) Random library (import random) (2 Marks)
random() Return floating value between 0
and 1.
randrange(0,N) This generates integer number
from 0 to (N-1).
randint(a, b) Return any number b/w given
number a and b including them
uniform(a, b) Return floating number b/w
given numbers a and b.

EXERCISE TO UNDERSTAND THE CONCEPTS WITH SOLUTION


Sno Question Answer
1 Find the invalid identifier(s) from the following: b) True, as it is a keyword
a) MyName b) True c) 2ndName, Because it is starting
c) 2ndName d) My_Name with a digit.
2 Given the lists L=[1, 3, 6, 82, 5, 7, 11, 92], [6,82,5], as it will start from index no
write the output of print(L[2:5]). 2 to (5-1) i.e. 4.
3 Identify the valid arithmetic operator in Python from c) ** as it is used to find power
the following: a) ? b) < c) ** d) and
4 Suppose tuple T is T = (10, 12, 43, 39), Find incorrect? b) T[2]= -29 (as tuple is immutable
a) print(T[1]) b) T[2] = -29
c) print(max(T)) d) print(len(T))
5 Declare a dictionary Colour, whose keys are 1, 2, 3 Colour={1:'Red', 2:'Green', 3:'Blue'}
and values are Red, Green and Blue respectively.
6 A tuple is declared asT = (2, 5, 6, 9, 8) It will give the sum of all elements of
What will be the value of sum(T)? tuple i.e. 2+5+6+9+8 = 30
7 Name the built-in mathematical function / method abs()
that is used to return an absolute value of a number.
8 d) list, as a list is collection of
a) dictionary b) string c) tuple d) list heterogeneous data.
9 Find the output of the following code? It will print string from index no 3 to
>>>name="ComputerSciencewithPython" (10-1) i.e. 9 means 7 characters. So
>>>print(name[3:10]) outout will be puterSc
5|KVS Regional Office, JAIPUR | Session 2020-21
10 Write the full form of IDLE. Integrated Development Learning
Environment
11 Find the output: A.insert(2,33) will insert 33 at index
>>>A = [17, 24, 15, 30] no 2. Now the list is [17, 24, 33, 15,
>>>A.insert(2, 33) 30]. So print(A[-4)) will start
>>>print (A[-4]) counting from last element starting
from -1, -
12 Name the Python Library modules which need to be (a) math
imported to invoke the following functions: (b) random
(a) ceil() (b) randrange()
13 What will be the result of the following code? (d) Error, because dictionary works
on the principle of key:value. These
>>>print (d1[0]) is no key as 0, so it will produce an
error.
14 It will create a list as
colors=list(STR) colors=['V', 'I', 'B', 'G', 'Y', 'O', 'R']
>>>del colors[4] del colors[4] will delete the element
>>>colors.remove("B") at index no 4 i.e. so list will be ['V', 'I',
>>>colors.pop(3) 'B', 'G', 'O', 'R']. colors.remove("B")
>>>print(colors)
'G', 'O', 'R']. colors.pop(3) will

['V', 'I', 'G', 'R'].


15 Suppose list L is declared as It is List Comprehension.
L = [5 * i for i in range (0,4)], list L is Expression L = [i for i in range (0,4)]
a) [0, 1, 2, 3,] b) [0, 1, 2, 3, 4] will generate [0, 1, 2, 3]. Since here
c) [0, 5, 10, 15] d) [0, 5, 10, 15, 20] we are writing 5*i, so correct
answer will be c) [0, 5, 10, 15]

EXERCISE TO UNDERSTAND THE CONCEPTS WITH SOLUTION (3 Marks)


Sno Question Answer
1 Find possible o/p (s) at the time of execution of the Lower = r.randint(1,3) means Lower will
program from the following code? Also specify the have value 1,2, or 3
maximum values of variables Lower and Upper. Upper =r.randint(2,4) means Upper will
import random as r have value 2, 3, or 4
AR=[20, 30, 40, 50, 60, 70]; So K will be from (1, 2, 3) to (2, 3, 4)
Lower =r.randint(1,3) Means if K=1, then upper limit (2,3,4)
Upper =r.randint(2,4) If K=2, then upper limit (2,3,4)
for K in range(Lower, Upper +1): If K=3, then upper limit (2,3,4)

(i) 10#40#70# (ii) 30#40#50# So correct answer (ii) 30#40#50#


(iii) 50#60#70# (iv) 40#50#70#
2 Write a function LShift(Arr,n), which accepts a list def LShift(Arr, n):
Arr of numbers and n is a numeric value by which L=Arr[n:] + Arr[:n]
all elements of the list are shifted to left. return L
Sample Input Data of the list Arr= [10,20,30,40,12,11]
Arr= [ 10,20,30,40,12,11], n=2 n=2
Output: L1=LShift(Arr,n)
Arr = [30,40,12,11,10,20] print(L1)
3 Write a function in python named def SwapHalfList(Array):
SwapHalfList(Array), which accepts a list Array of mid=len(Array)//2
numbers and swaps the elements of 1st Half of the if sum(Array[:mid]) > sum(Array[mid:]):
print(Array[mid:] + Array[:mid])
6|KVS Regional Office, JAIPUR | Session 2020-21
list with the 2nd Half of the list ONLY if the sum of else:
1st Half is greater than 2nd Half of the list. print(Array)
Sample Input Data of the list: Array= [ 100, 200, 300, 40, 50, 60]
Array= [ 100, 200, 300, 40, 50, 60], SwapHalfList(Array)
Output Arr = [40, 50, 60, 100, 200, 300]
4 Write a function listchange(Arr) in Python, which def listchange(Arr):
accepts a list Arr of numbers, the function will for i in range(len(Arr)):
replace the even number by value 10 and multiply if Arr[i]%2==0:
odd number by 5 . Arr[i]=10
Sample Input Data of the list is: else:
a=[10, 20, 23, 45] Arr[i]=Arr[i]*3
listchange(a) print(Arr)
output : [10, 10, 115, 225] a=[10, 20, 23, 45]
listchange(a)
5 Write a function HowMany(ID, VALUE) to count def HowMany(ID, VALUE):
and display number of times the VALUE is ctr=ID.count(VALUE)
present in the list ID. For example, if the print(VALUE,'found',ctr,'times')
ID contains [115, 25, 65, 59, 74, 25, 110, 250] and List=[115, 25, 65, 59, 74, 25, 110, 250]
the VALUE contains 25, the function should print: Value=25
25 found 2 times. HowMany(List, Value)

DATA FILE HANDLING: 12 MARKS (TEXT FILE-3,CSV-4,BINARY-5)+PRACTICAL-7


1. File: A file is a named location on a secondary storage media like HDD where data are permanently
stored for reusability.
Need of File Handling: To store data in secondary storage for reusability. To access the data fast.
To perform different operations on file likes: open, read, write, search, update, close etc.
2. Types data files: (i) Text File (ii) Binary File (iii) csv file
Text File:A text file consists of human readable characters. Each line of a text file terminated
By a special character called the end of line (EOL). Default EOL used newline (\n).
Binary file: It made up of non-human readable characters and symbols. They represent the actual
content such as image, audio, video, exe file.
CSV File: A CSV (Comma Separated Value) format is one of the simplest and common way to store
tabular data. To represent a csv file, it must be saved with .csv extension. Comma is also a delimiter
which separates two files in a row
3 Modes of files:
Text Binary CSV
file File File Description
mode Mode Mode

By default Read. Opens a file for reading, error if the file does not exist.
Write - Opens a file for writing, creates the file if it does not exist
Append - Opens a file for appending, creates the file if it does not exist

Read and Write-File must exist, otherwise error is raised.


Read and Write-File is created if does not exist.
Read and write-Append new data
Create - Creates the specified file, returns an error if the file exists
Opening and closing a file:To open a file we use open() method and to close file, we use close() method.
Standard syntax for open a file in two way: (i) file_object=open(

7|KVS Regional Office, JAIPUR | Session 2020-21


Close a file: file_object.close()
Example: f = -
book.txt mode-read(by default file op -

Modules required in files:


(i) os module: we used for remove(), rename() and getcwd() methods.
remove(): To delete a file, rename(): To rename a file, getcwd(): To find the current directory
(ii) pickle module: we used in binary file for dump() and load() method respectively to write into a file
and read contents from the file.
Pickle module is used for serializing/pickling and de-serializing/unpickling any python object.
Pickling- It will convert python object into byte stream and unpickling convert byte stream into python
Object.
dump() method: It used to convert(pickling) python objects for writing data in a binary file.
Syntax: module name.dump(dataobject,file object)
load(): It is used to load/read(unpickling) data from a file. Syntax:
storeobject=modulename.load(file object).
(iii) csv module: - we used in csv file for reader(),writer(),writerow(),writerows() methods.
reader(): function is used to read the file, which returns an iterable reader object.
The reader object is then iterated using for loop to print the content of each row.
csv.reader(file object) function in default mode of csv file having comma delimiter.
writer (): The csv.writer(file object) function returns a writer object that converts the data
into delimiter string.
Writerow():The string can later be used to write into CSV File using
storeobeject.writerow( ) function.
Writerows():If we need to write the content of list into csv file, instead
of using writerow() function many times, we can write storeobject.writerows() func.
Note: syntax for accessing modules and methods respectively: import module name and
Objectname=module name.method name()
Text file Methods: write (): writing a single string and returns number of characters being written.
writeline(): writing a sequence of(multiple)strings to a file and does not return the number of characters
written in the file.(Both functions use as fileobject.write(single string/multiple string)
read (): It is used to read a specified number of bytes of data from a data file. fileobject.read(n) where
n-no of bytes read, if we do not pass no argument or a negative number is specified in read () then it read
entire content of file.
readline([n]): It will read one complete line from a file where line terminate with (\n). if we pass as an
argument n then it read a specified number of bytes. If no argument pass or negative number pass it read
complete line. To read the entire file line by line using the readline() we use a for loop.
readlines(): It reads all the lines and returns the lines along with newline as a list of strings.
split (): If we want to display each word of a line separately as an element of a list.
splitlines(): It is used instead of split(), then each line is returned as element of a list.
SETTING OFFSETS IN A FILE: To access the data in random fashion then we use seek () and tell ()
Method. tell (): It returns an integer that specifies the current position of the file object in the file.
fileobject.tell() and seek(): It is used to position the file object at a particular position in a file.
fileobject.seek(offset [, reference point]) where offset is the number of bytes by which the file object is
to be moved and reference point indicating the starting position of the file object. Values of reference point
as 0- beginning of the file, 1- current position of the file, 2- end of file.
Q1. What is full form of csv? Which delimiter used by default?
Ans: CSV- Comma Separated Value and comma delimiter used by default.
Q2.
Ans: Read mode: - Opens a file for reading, error if the file does not exist. Write mode: Opens a file for
writing, creates the file if it does not exist.
Q3. Which modules used in csv and binary file?
Ans: In csv file- csv module and binary file: pickle module.

8|KVS Regional Office, JAIPUR | Session 2020-21


Q4. Which method is used to specify current position and particular position of file object respectively?
Ans: tell ()-specify current position of file object and seek ()- specify the particular position of file object.

NOTE: TEXT FILE SOLUTION STEPS


Def of fun -> Open file -> Use method as per Ques -> Loop -> Condition -> Print -> Close File

BINARY FILE SOLUTION STEPS


Pickle Module -> Def of fun -> Open file -> Inputs -> Store Obj -> dump -> Close File
Q1. Write a method /function countlines_et () Q2. Write a function that counts the
in python to read lines from a text file report.txt, and
COUNT those lines which are starting

count separately. My first book was Me and My Family. It


gave me chance to be known to the
For example: if REPORT.TXT consists of world.
The output of the function should be:
Count of Me/My in file: 4
Then, Output will be: No. of Lines with E: 1 Solution:
No. of Lines with T: 1 def displayMeMy():
Solution: num=0
def countlines_et(): f=open("story1.txt","rt")
f=open("report.txt",'r') N=f.read()
lines=f.readlines() M=N.split()
linee=0 for x in M:
linet=0 if x=="Me" or x== "My":
for i in lines: print(x)
if i[0]=='E': num=num+1
linee+=1 f.close()
elif i[0]=='T': print("Count of Me/My in file:",num)
linet+=1 displayMeMy()
print("No.of Lines with E:",linee) OR
print("No.of Lines with T:",linet) Write a function count_A_M(), which
countlines_et() should read each character of a text file
OR STORY.TXT, should count and display
Write a method/function show_todo():in python to read the occurrence of alphabets A and M
contents from a text file abc.txt and display those lines (including small cases a and m too).
which have occurr Example: If the file content is as follow:
For example: If the content of the file is Updated information As simplified
by official websites.
RESULT OF HARD WORK WE ALL ARE EXPECTED TO DO The count_A_M():function should
HARD WORK. AFTER ALL EXPERIENCE COMES FROM display the output as:
A or a:4 M or m:2
The method/function should displ Solution:
THIS IS IMPORTANT TO NOTE THAT SUCCESS IS THE def count_A_M():
RESULT OF HARD WORK. f=open("story1.txt","r")
WE ALL ARE EXPECTED TO DO HARD WORK. A,M=0,0
Solutions: r=f.read()
def show_todo(): for x in r:
f=open("abc.txt",'r') if x[0]=="A" or x[0]=="a" :
lines=f.readlines() A=A+1
for i in lines: elif x[0]=="M" or x[0]=="m":
if "TO" in i or "DO" in i: M=M+1
print(i) f.close()
show_todo() print("A or a: ",A,"\t M or m: ",M)
9|KVS Regional Office, JAIPUR | Session 2020-21
count_A_M()

Q3. Consider a binary file stock.dat that has the Q4


following data: OrderId, MedicineName,Qty and Price of structure [BookNo, Book_Name,
all the medicines of wellness medicos, write the Author, Price].
following functions: a.Write a user defined function
a)AddOrder() that can input all the medicine orders. CreateFile() to input data for a record
b)DisplayPrice() to display the details of all the and add to Book.dat.
medicine that have Price. b. Write a function CountRec(Author) in
Solution: Python which accepts the Author name
import pickle as parameter and count and retum
def AddOrder(): number of books by the given Author
f=open("Stock.dat",'ab')
OrderId=input("Enter Order Id") import pickle
MedicineName=input("Enter Medicine Name") def CreateFile():
Qty=int(input("Enter Quantity:")) fobj=open("Book.dat","ab")
Price=int(input("Enter Price:")) BookNo=int(input("Book Number :
data=[OrderId,MedicineName,Qty,Price] "))
pickle.dump(data,f) Book_name=input("Name :")
f.close() Author = input("Author: ")
AddOrder() Price = int(input("Price : "))
def DisplayPrice():
f=open("Stock.dat",'rb') rec=[BookNo,Book_Name,Author,Price
try: ]
while True: pickle.dump(rec,fobj)
data=pickle.load(f) fobj.close()
if data[3]>500: def CountRec(Author):
print(data[0],data[1],data[2],data[3],sep="\t") fobj=open("Book.dat","rb")
except: num = 0
f.close() try:
DisplayPrice() while True:
Q5. Create a binary file funandfood.dat that can store rec=pickle.load(fobj)
details of rides such as Ticketno, Ridename, if Author==rec[2]:
No_ofpersons, and price with the help of AddRides() num = num + 1
function and write another python function display except:
Total to display total amount of each ticket. Also count fobj.close()
total number of tickets sold. return num
Solution: Q6
import pickle # to use binary file some records of the structure [TestId,
def AddRides(): Subject, MaxMarks, ScoredMarks]
f=open("funandfood.dat",'ab') Write a function in Python named
Ticketno=input("Enter Ticket Number") DisplayAvgMarks(Sub) that will accept
RideName=input("Enter The Name of Ride") a subject as an argument and read the
No_ofperson=int(input("Enter no of Persons")) contents of TEST.dat. The function will
Price=int(input("Enter Price:")) calculate & display the Average of the
data=[Ticketno,RideName,No_ofperson,Price] ScoredMarks of the passed Subject on
pickle.dump(data,f) screen.
f.close() Solution:
AddRides() def DisplayAvgMarks(sub):
def Display Total(): f=open("TEST.dat","rb")
f=open("funandfood.dat",'rb') count=0
total=0 sum=0
count=0 try:

10 | K V S Regional Office, JAIPUR | Session 2020-21


try: while True:
while True: pos=f.tell()
data=pickle.load(f) rec=pickle.load(f)
total=data[2]*data[3] if rec[1]==sub:
print(data[0],data[1],data[2],data[3],total,sep="\t") sum+=rec[3]
count=count+1 count+=1
except: except:
f.close() f.close()
print("Total number of Tickets sold are:",count) print("AVG Marks:",sum/count)
DisplayTotal() DisplayAvgMarks(sub)
Q7. Abhisar is making a software on & their in which various records
are to be stored/retrieved in CAPITAL.CSV data file. It consists o f some records. He has
written the following code. As a programmer, you have to help him to successfully execute the
program.
import # Statement-1
def AddNewRec(Country,Capital): # Fn. to add a new record in CSV file
_) # Statement-2 fwriter=csv.writer(f)
fwriter.writerow([Country,Capital])
f. # Statement-3
def ShowRec(): # Fn. to display all records from CSV file with as NF:
NewReader=csv. (NF) # Statement-4 for rec in NewReader:
print(rec[0],rec[1])

ShowRec() # Statement-5
1) Name the module to be imported in Statement-1. 1) csv module
2) Write the file mode to be passed to add new record in -append mode.
Statement-2. 3) f.close()
3) Fill in the blank in Statement-3 to close the file. 4) reader()
4) Fill in the blank in Statement-4 to read the data from a csv file. 5) INDIA NEW DELHI
5) Write the output which will come after executing Statement-5. CHINA BEIJING

11 | K V S Regional Office, JAIPUR | Session 2020-21

You might also like