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

STUDY MATERIAL FOR TERM – 1

Class XII
COMPUTER SCIENCE (083)

Session 2021-22

KENDRIYA VIDYALAYA SANGATHAN


Regional Office AGRA
OUR MENTORS

Sh. C.S. Azad


Deputy Commissioner
KVS RO Agra Region

Sh. M.L.Mishra
Assistant Commissioner
KVS RO Agra Region

Co-ordinator
Mrs. Neetu Verma
Principal
K.V. NO. 3 Agra
TERM – 1

Syllabus

Computer Science (Code No. 083)

CLASS XII

Session : 2021-22

Distribution of Theory Marks:

Unit No Unit Name Marks

01 Computational Thinking and 35

Programming - 2

Total 35

Unit I: Computational Thinking and Programming – 2

 Revision of Python topics covered in Class XI.

 Functions: types of function (built-in functions, functions defined in module, user defined
functions), creating user defined function, arguments and parameters, default
parameters, positional parameters, function returning value(s), flow of execution, scope
of a variable (global scope, local scope)

 Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute
paths

 Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file,
opening a file using with clause, writing/appending data to a text file using write() and
writelines(), reading from a text file using read(), readline() and readlines(), seek and tell
methods, manipulation of data in a text file

 Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+,
ab, ab+), close a binary file, import pickle module, dump() and load() method, read,
write/create, search, append and update operations in a binary file CSV file: import csv
module, open / close csv file, write into a csv file using csv.writerow() and read from a csv
file using csv.reader( )

Unit I: Computational Thinking and Programming – 2

Revision of Python

Token : Smallest Individual unit in a program is known as Token. Python has following tokens:

 Keywords

 Identifiers

 Literals

 Operators

Keywords : Keywords are the words that have special meaning reserved by programming
language. They are reserved for special purpose and cannot be used for normal identifier names.
E.g. in, if, break, class, and, continue, True, False.

Identifiers : Dentifiers are fundamental building block of a program. They are names given to
variable, functions, objects classes etc. Python is case sensitive i.e. it treats upper case and lower
case letter differently.

Naming Conventions:

• Contain A-Z, a-z, _

• Name should not start with digit

• It can start with alphabet or ( _ ) underscore

Literals : Literals are data items that have fixed value. Python allows several kinds of literals:

• String literals
• Numeric literals

• Boolean literals

• Special Literal None

• The text enclosed in single or double quotes.

• There is no character literal.

• Example „a‟, „anant‟, “HelloWorld”

• Python allows non-graphic characters in string values.

• Non-graphic characters are represented using escape sequence.\n for newline, \t


tab space, \r carriage return

• Integer: positive negative numbers without decimal

• Floating Point: Real numbers with decimal points

• Complex Number: are in form a+bj, where a and b are floating point numbers and
j is
√-1. Where a is real part and b is imaginary part.

• True and False are the two Boolean Literals

• Special literal None represent absence of value

• None also indicates end of List

• They are built-in constant literals of Python

Operators:

Operators are the symbol, which triggers some computation when applied on operand.

Unary Operator: those operators that require only one operand.

• Unary Plus +

• Unary Minus –

• Bitwise ~ Complement

• Logical Negation not


Binary Operator: those operators that require only two operand.

• Arithmetic Operator (+,-,*,/,%)

• Bitwise Operator (&, ^, |)

• Shift Operator (>> ,<<)

• Identity Operator (is , is not)

• Relational operator (<,>,<=,>=,==,!=)

• Logical operator (and ,or)

• Whether variable in sequence(in)

• Whether variable not in sequence (not in)

Punctuators : are the symbols used in programming language to organise the statements of the
program.

• Common Punctuators are „ “ # \ ( ) [ ] { } @ , : . =

Identifier :

Named Label whose value can be changed and processed during the program run

• Creating Variable :

Name=„Anant‟

Age=30

• Python do not have fixed memory locations, when the value changes they change
their location

• lvalue: expression that can come on lhs of an assignment.

• Rvalue: expression that can come on rhs of anvaraible

• The process in which the variable pointing to a value of certain type,can be made to
point to the value of other type.

age=10 print(age)

age=“ten”
print(age)

type( ) function is used to determine the type of object.

Dynamic Typing:

In Dynamic Typing the datatype attached with the variable can change during the program run
whereas in Static Typing the data type defined for the first time is fixed for the variable.

• Python Support Dynamic Typing

• Python allows Multiple assignments.

• Assign same value to multiple variables.

x = y = z = 20

here x, y, z has same value 20

• Assign multiple values to multiple variables.

x , y , z = 20, 40, 60

• Variable is created or defined when the first value is assigned to it.

• Variable is not created until some value is assigned to it.

• input( ): function is used for taking value for a variable during runtime.

• To overcome the above error we need to convert the string type object to integer or
any desired numeric type.

• input( ) function always returns a value of string type.

• Use int( ) or float( ) function to convert the type string to int and float respectively.

• When converting variable to int/float we need to make sure that the value entered is
of int/float type.

• If we enter rashmi for age then rashmi cannot be converted to int.print statement has
number of features

Automatic conversion of items to string type. Inserting space between items automatically as
default value of sep (separator) is space. It appends a newline at the end of the each print
Data Types : Python offers five built-in core data types

• Numbers(int, float, complex)

• String

• List

• Tuples

• Dictionary

Integers

• Integers Signed: positive and negative integers(Whole Numbers)

• Boolean: Truth Values False(0)/bool(0) and True(1) /bool(1)

• Floating Point Numbers: precision of 15 digits possible in Python

• Fractional Form: Normal Decimal Form, e.g. 325.89, 300.845

• Exponent Notation: Represents real numbers for measurable quantities. E.g.


3.500789E05, 1.568789E09, 0.254E-07

Complex Numbers: Python represents complex numbers as a pair of floating point numbers. E.g.
A+Bj. J is used as the imaginary part which has value √-1.

• a=1.6+4j real part=1.6 imaginary component=4

• b=0+5.2j real part=0 imaginary component=5.2

a.real and b.real gives the real part

a.imag and b.imag gives the imaginary part

String:

• Any number of valid characters within quotation marks.

• It can hold any type of known characters like alphabets, numbers, special characters
etc.

• Legal String in Python are “Raman”, „rocket‟, “we2345@”,”%&$#”

• String as a sequence of Characters


– String is stored as individual characters in contiguous location

Forward Indexing

– Length of the string can be determined using len(string)

Backward Indexing

– Individual letter of a string cannot be changed beca.use the String is immutable.

name=„hello‟

name*2+=„g‟ name=„Computer‟

# Not Possible

#Possible , we can assign string to another string

List: List in Python represents a list of comma-separated values of any data type between square
brackets. Mutable Data Type [1,2,3,4,5]

Tuples:In Python represents a list of comma-separated values of any data type between round
brackets. Immutable Data Type

T=(1,2,3,4,5) A=(„a‟, „b‟,‟c‟,‟d‟)

B=(„rat‟, „bat‟, „cat‟, ‟dog‟)

Dictionary: in Python represents unordered set of comma-separated key : value pair within { },
with the requirement that within a dictionary, no two keys can be the same.

A={a‟:1, „b‟:2,‟c‟:3,‟d‟:4}

The immutable types: are those that can never change their value inplace.Immutable Data Types
are

– Integer

– Floating Point Number

– Boolean

– String

– Tuples

Mutable types : are those whose values can be changed in place. Mutable Data Types are :

– List
– Dictionary

– Sets

Thus Mutability means that in the same memory address, new value can be stored as and when
you want.

Expression:

• Expression is the valid combination of operators, literals and variables.

• Expression is formed by atoms and operators.

• Atoms are something which has value. E.g. Literals, identifier, string, list, tuples, sets
and dictionary etc.

• Types of Expression

o Arithmetic Expression: a+5-6

o Relational Expression: x>90

o Logical Expression: a>b or 6<p

o String Expression: “computer” + “science”, “web” *3


Type conversion:

During evaluation if the operands are of same data type then the resultant will be of the data
type which is common.

• Incase, during evaluation if the operand are of different data type then the resultant
will be of the data type of the largest operand. We need to promote all the operand
to the largest type through type promotion.

Implicit Type Conversion:

Implicit conversion is performed by the compiler without programmer’s intervention.

• Division operator will result in floating point number, even if both operands are
integer type.

• Python internally changes the data type of some oper and, so that all oper and have
same data type. This is called Implicit Type Conversion.

Explicit Type Conversion/Type Casting : user defined conversion that forces an expression to be
of specific type.

Type casting is done by <datatype> (expression)

• Amt= int(amount)

• Different data types are int(), float(), complex(), str(), bool()

Statement : Smallest executable unit of the program. These are instructions given to the
computer to perform any kind of action, data movement, decision making, repeating actions etc.
They are of three types

• Empty Statement : Statement which does nothing. In Python empty statement is a


pass statement.

• Simple Statement : Any single executable statement is a simple statement.

• Compound Statement : Group of Statement executed as a unit. It has a headerline


and a body.

o Header line : It begins with the keyword and ends with a colon.

o Body : consist of one or more Python statements, indented inside header line. All
Statement are at same level of indentation.
In Python, if Statement is used for decision making. It will run the body of code only when IF
statement is true. When you want to justify one condition while the other condition is not true,
then you use "if statement".

Syntax:

if expression

Statement

Example:

a = 33

b = 200

if b > a:

print("b is greater than a")

Example:

a = 33
b = 200
if b > a:
print("b is greater than a")
else:
print(“a is greater than b")

By using "elif" : condition, you are telling the program to print out the third condition or
possibility when the other condition goes wrong or incorrect.

x,y =8,8

if(x < y):

st= "x is less than y"

elif (x == y):

st= "x is same as y"

else:

print(st)

st="x is greater than y"


There are many situations when we need to repeat certain task or functions some given number
of times or based on certain condition.

Loop:

• Loops can execute a block of code number of times until a certain condition is met.
Their usage is fairly common in programming. Unlike other programming language
that have For Loop, while loop, do while, etc.

To carry out repetitive task python provides following looping/iterative statements:

• Conditional Loop while

• Counting Loop for

o The range( ) function of Python generates a list which is special sequence type.

o Range function works in three forms:

• range( lower limit, upper limit)

range( l, u) will give l, l+1, l+2 u-1

range(3,7) will give 3,4,5,6 range(13,7) will give empty list

Default step value is +1

– range( lower limit, upper limit, step value) range( l, u, s) will give l, l+s, l+2s………….u-1
range(3,17,3) will give 3,6,9,12,15 range(13,7,2) will give 13,11,9,7

– Range(number)

range( n) will give 0,1,2………….n-1 range(7) will give 0,1,2,3,4,5,6

in operator tests if a given value is contained in a sequence or not and return True or False.

Syntax:

for<variable> in <sequence>:

statements to repeat

Example:

Syntax:
while <logical expression> :

loop body

Anatomy of a while loop

1. Initialization

2. Test Expression

3. The Body of loop

4. Update Expression

Both the loops of Python has else clause. The else of a loop executes only when the loop end
normally( i.e. only when the loop is ending because the while loop’s test condition has become
false and for loop has executed the last sequence)

Jump Satement:

break and continue

• The break statement in Python terminates the current loop and resumes execution at
the next.

• The continue statement in Python returns the control to the beginning of the while
loop. The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.

Nested Loop: One loop inside another loop

Case - Based MCQ


Q1. Renuka is looking for her admission in B.Tech in a Govt. college but has some restrictions.
She loves Delhi and would take admission there if course fess is less than Rs. 40,000. She does
not want to go Meerut and She will join there if course fees is less than Rs. 10,000. In any another
location she is willing to take admission if fees is Rs. 25,000. The following code shows her basic
strategy for admission in B.Tech:

fees=__________________________

location=__________________________

if location == "Noida":
print ("I’ll take it!") #Statement 1

elif location == "Meerut":

if fees > 10000:

print ("No way") #Statement 2

else:

print ("I am willing!") #Statement 3

elif location == "Delhi" and fees <40000:

print("I am happy to join") #Statement 4

elif fees<=25000:

print("I will take admission ") #Statement 5

else:

print("No thanks, I can find something better") #Statement 6

On the basis of the above code, choose the right statement which will be executed when different
inputs for pay and location are given.

(i) Input : location = "Meerut” and fees = 20000

a. Statement 1

b. Statement 2

c. Statement 3

d. Statement 4

Correct Ans: Statement 2

(ii) Input : location = "Muzaffernagar", fees = 60000

a. Statement 2

b. Statement 4

c. Statement 5

d. Statement 6
Correct Ans: Statement 6

(iii) Input : location = "Any Other City", fees = 100000

a. Statement 1

b. Statement 2

c. Statement 4

d. Statement 6

Correct Ans: Statement 6

(iv) Input : location = "Delhi", fees= 35000

a. Statement 6

b. Statement 5

c. Statement 4

d. Statement 3

Correct Ans: Statement 4

(v) Input : location = "Lucknow", fees = 20000

a. Statement 2

b. Statement 3

c. Statement 4

d. Statement 5

Correct Ans: Statement 5

Q2. Reema write the following program for generating the random number by writing the
following program but the program is not executed. Help her to correct the program:

AR=[20,30,40,50,60,70];

Lower =random.randint(1,3) # Statement 1

Upper =random.randint(2,4) # Statement 2


for K in range(Lower, Upper +1): # Statement 3

print (AR[K],end=”#“) # Statement 4

On the basis of the above code, choose the right option which will be executed when program
executed:
(i) She is getting the error “NameError: name 'random' is not defined”, while executing the
program to remove the above error she must use the option:

a. import random

b. random.h

c. import.random

d. random.random

Correct Ans: a. import random

(ii) What possible outputs(s) are expected to be displayed on screen at the time of execution of
the program.

10#40#70#

30#40#50#

50#60#70#

40#50#70#

Correct Ans: b. 30#40#50#

(iii) What are the maximum values that can be assigned to each of the variables Lower and
Upper?

1,4

3,4

2,3

1,2

Correct Ans: b. 3,4

(iv) The value of variable Lower variable is 1 or 2 or 3?

True

False

Correct Ans: a.True


(v) If we use randomrange() in place of randomint() what are the maximum values that can be
assigned to each of the variables Lower and Upper?

1,4

3,4

2,3

1,2

Correct Ans: c. 2,3

Q3. Priyank is a software developer with a reputed firm. He has been given the task to
computerize the operations for which he is developing a form which will accept customer data
as follows:The DATA TO BE ENTERED IS :

a. Name

b. Age

c. Items bought (all the items that the customer bought)

d. Bill amount

(i) Choose the most appropriate data type to store the above information in the given sequence.

string, tuple, float, integer

string, integer, dictionary,float

string, integer, integer,float

string, integer, list,float

Correct Ans: (d) string, integer, list,float

(ii) Choose the correct varaible names to store the above information in the given sequence.

a. 2name,age,_items,bill amount

b. Name,_age,items,bill_amount

c. Name,4age,.items, bill@amount
d. Name,age,items,bill.amount

Correct Ans: (b) Name,_age,items,bill_amount

(iii) Now the data of each customer needs to be organized such that the customer can be
identified by name followed by the age, item list and bill amount. Choose the appropriate data
type that will help Priyank accomplish this task.

a. List

b. Dictionary

c. Nested Dictionary

d. Tuple

Correct Ans: (b) Dictionary

(iv) What is the maximum possible length of above identifiers?

a. 16

b. 32

c. 64

d. None of these above

Correct Ans: d. None of these above

(v) After completing the code Priyank want to save the program in which extension he will save
the Python file?

a. .py

b. .python

c. .p

d. None of these

Correct Ans: a. .py

Q4. Rohan create a Password validation program in Python. He has following conditions for a
valid password are:

Should have at least one number.

Should have at least one uppercase and one lowercase character.


Should have at least one special symbol.

Should be between 6 to 20 characters long.


Rohan writes the following code for above statements:

passwd =input("Enter password")

SpecialSym=['$','@','#','%']

val = True

if len(passwd) < 6:

print('length should be at least 6') # Statement 1

val = False

if len(passwd) > 20:

print('length should be not be greater than 8') # Statement 2

val = False

if not any(char.isdigit() for char in passwd):

print('Password should have at least one numeral') # Statement 3

val = False

if not any(char.isupper() for char in passwd):

print('Password should have at least one uppercase letter') # Statement 4

val = False

if not any(char.islower() for char in passwd):

print('Password should have at least one lowercase letter') # Statement 5

val = False

if not any(char in SpecialSym for char in passwd):

print('Password should have at least one of the symbols $@#') # Statement 6

val = False

if (val==True):

print("Password is valid") # Statement 7

else:
print("Invalid Password !!") # Statement 8

On the basis of the above code, answer the following questions.

(i) If input is “zkau @123, which statements are executed

a. Only Statement 8

b. Statement 5, Statement 2

c. Statement 7, Statement 4, Statement 5

d. Statement 4, Statement 8

Correct Ans: d. Statement 4, Statement 8

(ii) If input is “Abc@123, which statements are executed:

a. Only Statement 7

b. Statement 7, Statement 4, Statement 5

c. Statement 4, Statement 8

d. Statement 5, Statement 7

Correct Ans: a. Only Statement 7

(iii) If Rohan wants to give three chances for the valid password to the user:

Statement 1: may use a loop to enter the password three times

Statement 2: may repeat the same code three times.

a. Both statements are correct.

b. Statement 1 is correct, but statement 2 is not.

c. Both statements are incorrect.

d. Statement 1 is incorrect but statement 2 is correct.

Correct Ans: Both statements are correct.

(iv) If input is “kVs@123” what is the final value of identifier val

a. True

b. False
Correct Ans : a. True

Q5. Kritiks write a Python program which iterates the integers from 1 to 50. For multiples of three
print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which
are multiples of both three and five print "FizzBuzz". Help her to complete the following code

Code:

forfizzbuzzinrange(___): # Statement 1

if____________________________________://statement2

print("fizzbuzz")

continue

elif fizzbuzz%3==0:

print("fizz")

continue

elif fizzbuzz%5==0:

print("buzz")

continue

print(fizzbuzz)

(i) Which of the following command id used to generate the integer from 1 to 50 in statement 1?

a. range(1,51)

b. range(50)

c. range(1,50)

d. range(52)

Correct Ans: a. range(1,51)

(ii) Use of continue statement in the above code

a. Terminate the loop


b. Instructs a loop to continue to the next iteration

c. Nothing

Correct Ans: b. instructs a loop to continue to the next iteration

(iii) Which of the following command used to check the number is divisible by 3 and 5 in
statement 2

a. fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0

b. fizzbuzz % 3 == 0 or fizzbuzz % 5 == 0

c. fizzbuzz / 3 == 0 and fizzbuzz % 5 == 0

d. fizzbuzz// 3 == 0 and fizzbuzz // 5 == 0

Correct Ans: a. fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0

(iv) How many times this loop will be executed

a. 50

b. 51

c. 52

d. 27

Correct Ans: a. 50

String:-

String is a sequence of characters, which is enclosed between either single (' ') or double

quotes (" "), python treats both single and double quotes same.

Creating string:-

Creation of string in python is very easy.

e.g. a=‘Computer Science'

b=input(“Enter string”)

String slicing:

It refers to part of string containing some contiguous character from the string.
e.g.

code='Computer Science‘ OUTPUT

print(‘code-', code) ('code-', 'Computer Science')

print('code[0]-', code[0]) ('code[0]-', 'C')

Iterating/Traversing through string

Each character of the string can be accessed one character at a time using for loop.

Eg :

code='Computer Science‘

for i in code:

print(i, end=” “)  c o m p u t e r

Operations in String

Operators Description Example

+ Concatenation–toaddtwostrings a+b = compsc

* Replicate same codeingmultipletimes a*2=compcomp


(Repetition)

[] Characterofthestring a[1] willgiveo

[:] RangeSlice–Rangestring a[1:4] willgiveomp

in Membershipcheck pinawillgive1

notin Membershipcheckfornonavailability M not in awillgive1

LIST-

The list is a collection of items of different data types. It is an ordered sequence of items

Features of Python List


Lists are mutable ie values in the list can be modified or changed.

Each element of a sequence is assigned a number - its position or index. The first index is zero,
the second index is one, and so forth.

The values that make up a list are called its elements. Elements are separated by comma and
enclosed in square brackets [].

Syntax of List

list = [value1, value2, value3,...valueN]

names=[“Naman", “Anu", “Nikhil", "Mohan"]

Lists

Declaring/Creating Lists

Accessing List Elements

Traversing a List

Aliasing

Comparing Lists

Slicing

Code Result Exp’computlanation

Val[1:4] ‘omp’ Items 1 to 3

Val[1:6:2] ‘opt’ Items 1,3,5

Val[3:] ‘puter’ Items 3 to end

Val[:5] ‘compu’ Items 0 to 4

Val[-3:] ‘ter’ Last 3 items

Val[:-2] ‘comput’ All except last 2 items

Opeartion on Lists-
Python Expression Results Exp’computlanation

len([1, 2, 3]) 3 Items 1 to 3

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Items 1,3,5

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Items 3 to end

2 in [1, 2, 3] True Items 0 to 4

for x in [1, 2, 3]: 123 Last 3 items

print x,

Nested Lists:-

L3=3,4,[5,6,7],8]

A list can have an element in it, which itself is a list. Such a list is called a nested list

Built in Functions:

Python includes following list methods

Sr.No. Methods with Description

1 list.append(obj) Appends object obj to list

2 list.count(obj) Returns count of how many times obj occurs in list

3 list.extend(seq) Appends the contents of seq to list

4 list.index(obj) Returns the lowest index in list that obj appears

5 list.insert(index, obj) Inserts object obj into list at offset index

6 list.pop(obj=list[-1]) Removes and returns last object or obj from list

7 list.remove(obj) Removes object obj from list


8 list.reverse() Reverses objects of list in place

9 list.sort([func]) Sorts objects of list, use compare func if given


Python includes the following list functions:

Sr.No. Function with Description

1 cmp(list1, list2) Compares elements of both lists.

2 len(list) Gives the total length of the list.

3 max(list) Returns item from the list with max value.

4 min(list) Returns item from the list with min value.

5 list(seq) Converts a tuple into list.

Tuple:- Tuple is a collection of values separated by comma and enclosed in parenthesis. Unlike
lists, tuples are immutable

Creation of Tuple:

Accessing a Tuple

Tuple Operations

Tuple Slicing

Dictionary:

A dictionary in Python is an unordered set of key: value pairs.

Unlike lists, dictionaries are inherently order less. The key: value pairs appear to be in a certain
order but it is irrelevant.

Each KEY must be unique, but the VALUES may be the same for two or more keys.

If you assign a value to a key then later in the same dictionary have the same key assigned to a
new value, the previous value will be overwritten.

Instead of using a number to index the items (as you would in a list), you must use the specific
key.
CASE - BASED MCQ

Question1 : Naman prepare a code for different conditions and take different inputs in variable
str1. What will be the output for the different inputs given below:

str1="PT1"
str2=" "
I=0
while I<len(str1):
if str1[I]>="A" and str1[I]<="M":
str2=str2+str1[I+1]
elif str1[I]>="0" and str1[I]<="9":
str2=str2+str1[I-1]
else:
str2=str2+"*"
I=I+1
print(str2)

(i)If input will be str1= “Exam2021” then output will be

a. X***M202 b. X**M2021

c. x***m201 d. x***m202

Ans d:- . x***m202

(ii)If input will be str1= “CBSE-Exam” then output will be

a. Bs*-*x*** b. BS*-*x***

c. BS*-*x** d. BS**-*x**

Ans:- b. BS*-*x***

(iii) If input will be str1= “PT1” then output will be

a. **T b. *T*

c. T** d. **

Ans- c. T**

(iv) If input will be str1= “xyzA” then output will be

a. **A b. ***A
c. *xyz d. Error : String index out of range

Ans:- d. Error : String index out of range

Question 2 : Assume, you are given two lists: a = [1,2,3,4,5] b = [6,7,8,9] The task is to create a
list which has all the elements of a and b in one dimension.

(i) If Output : a = [1,2,3,4,5,6,7,8,9] , Which of the following option would you choose?

a. a.append(b) b. a.extend(b)

c. Any of the above d. None of these

Ans:-b. a.extend(b)

(ii) If Output : a = [1,2,3,4,5,[6,7,8,9]] , Which of the following option would you choose?

a). a.append(b) b. a.extend(b)

c. Any of the above d. None of these

Ans:-. a.append(b)

(iii)You want to update the value of this lista = [1,2,3,4,5] at 4th index to 10. Which of the
following option will you choose?

a. a(4) = 10 b. a[4] = 10

c. a{4} = 10 d. None of these

Ans:-b. tup[4] = 10

(iv)You want to insert the value 100 at 2nd index. Which of the following option will you choose?

a. a.insert(2, 100) b. a.insert(100,2)

c. a.append(2, 100) d. None of these

Ans:-a.insert(2, 100)

Question3: Suppose you are defining a tuple given below: tup = (1, 2, 3, 4, 5 )

(i) You want to update the value of this tuple at 2nd index to 10. Which of the following option
will you choose?
a. tup(2) = 10 b. tup[2] = 10

c. tup{2} = 10 d. None of these

Ans:- d. None of these

(ii) You want to check the index of value 5. Which of the following option will you choose?

a. tup.index(5) b. tup=index(5)

c. tup.index(4) d. tup=index(4)

Ans:-tup.index(5)

(iii) You want to check the minimum value of tup. Which of the following option will you choose?

a. min=tup() b. tup=min(1)

c. tup=min() d. min(tup)

Ans:- d. min(tup)

(iv) You want to check the length of tup. Which of the following option will you choose?

a. len.tup b. len(tup)

c. len=tup d. None of these

Ans:- b. len(tup)

(v) You want to delete tup. Which of the following option will you choose?

a. delete(tup) b. remove(tup)

c. del tup d. tup.remove()

Ans:-del tup
FUNCTION

Functions are the most important building blocks for any application in python and work on the
divide and conquer approach.

A function is a sub program of a large program/application that accept some data and return a
value, where each function performing a specific tasks.

A function is a group of statements to perform a specific task.

The use of functions makes a program easy to Read, Write, Understand, Manage and Debug.

Functions are line of codes that executed sequentially from top to bottom by the python
interpreter.

A Python function is written once but can be called any number of times.

Functions are also called routines, sub-routines, procedures or methods.

Types of Functions in python

Functions can be divided in following three categories in Python:

Built-in Functions:

Functions in Modules:

User-defined Functions:

User Defined Functions:

User Defined Functions are the functions created or defined by the user using “def” (keyword)
statement followed by Function name and Parenthesis.

A UDF can be called any number of times in a program whenever required.

Syntax to define a user defined function:

def <function_name> ( [ parameters] ): # def is a keyword

statement1 # parameters are optional

statement2 # function name is an identifier

-----------------------------------
return <value> # here return is a keyword

Example:

def area_of_circle( radius ):

print(“Area of circle = “, 3.1416*radius*radius)

r=int(input(“Enter radius of circle”))

area_of_circle(r)

output:

Enter radius of circle 10

Area of circle = 314.16

Points about User Defined Functions:

Every User Defined Function start with the Keyword def.

The first line of the function is called Function Definition.

Function name must follow norms of valid identifier.

Every function header end with parenthesis and colon sign followed by function name

We can provide parameters inside parenthesis, which is optional.

The return statement is used to return a value from function. The return statement is also
optional. The function should return a value only at the place from where it get’s called.

To use a function, it must be called or invoked in main program.

Type of user defined functions:

The user defined functions can be categorized in following 4 categories:

1.Function which accept arguments and return some value

2.Function which accept arguments but return no value

3.Functions which do not accept any argument but return some value

4.Functions which do not accept any argument and even not return any value

Parameters/Arguments passed to functions: These are the values passed to user defined
functions from the calling function.
If you are passing values of immutable types (i.e., numbers, strings,etc) to the Called function,
then the called function cannot alter their values.

If you are passing values of mutable types (i.e., List, Dictionary, etc) to the Called function, then
the called function can make changes to them.

They are categorized in following two types:

Formal Parameters or Formal Arguments: These are the values provided in Parenthesis when we
write a function Header.

Actual Parameters or Actual Arguments: These are the values passed to the function when it is
called/invoked.

Example:

def area_of_circle( radius ): # here radius is the Formal Parameter or Formal Argument

print(“Area of circle = “,3.1416*radius*radius)

r=int(input(“Enter radius of circle”))

ar=area_of_circle(r) # here r is the Actual Parameter or Actual Argument

output:

Enter radius of circle 10

Area of circle = 314.16

Types of Arguments:

In Python following four types of arguments allowed:

Positional Arguments

Default Arguments

Keyword Arguments

Variable length Arguments

FUNCTIONS RETURNING VALUES:

The return statement in python specifies what value to be returned back to the calling function.
The Functions can take input values as parameters, process them and return output to the calling
function.

In python the return statement can return one or more values at a time.

The “return” is a keyword in python.

If the return statement is without an expression, the special value None is returned.

The function will return None in case we don’t explicitly give a return statement in function.

Example:

def Max_Two(X, Y):

if X>Y:

return X

else:

return Y

print(“Maximum value = “, Max_Two(25, 56))

Output:

Maximum value = 56

CASE BASED MCQ

1. Mohit class XII student has designed following code, which showing no error but gives no
output after executing the code. Suggest the correct solutions to his problem out of the
following.
A program to calculate simple interest:
def simple_int(p,r,t):
si=(p*r*t)/100
print(“Simple interest = “, simple_int(5000,10.5,2))
(a) function should print the value of simple interest no need to return
(b) function should return the value of si
(c) the formula used in function gives no output
(d) both (a) & (b)
ANSWER: (b) function should return the value of si
2. Assertion (A): All the functions are called user defined functions to perform a particular
task.
Reason (R): Functions are defined by the user to perform a particular task.
(a) Both A and R are true and R is the Correct reason of A
(b) Both A and R are false
(c) A is true but R is false
(d) A is false but R is true
ANSWER: (b) Both A and R is false

3. Rohan is solving a sample question paper provided by board, the sample question paper
contain a code having blank lines and options for the user to complete the code. Kindly
go through the following code and choose correct option for the statement1, 2 & 3.
----------------------------------- # statement1
def area_of_circle(radius):
area=pi*radius**2
-------------------------------- # statement2

R=int(input("Enter radius of circle"))


------------------------------------- # statement3
print("Area of circle = ",area)

(i) The statement 1 must be………..


(a) import math
(b) import math *
(c) from math import pi
(d) import pi from math
(ii) The statement 2 can be ………………..
(a) return area
(b) return (area)
(c) return 1*area
(d) Any of the above
(iii) The statement 3 should be………………
(a) area=pi*radius*radius
(b) area=Math.pi*R*R
(c) area=area_of_circle(R)
(d) area=area_of_circle(Radius)
BUILT IN FUNCTIONS
FUNCTIONS

STANDARD
USER DEFINED
LIBRARY
FUNCTIONS
FUNCTIONS

BUILT IN
MODULES
FUNCTIONS

The Python has a number of built-in functions. They are loaded automatically as a shell starts
and are always available, such as

input() , print(), int(), float(), complex(),list(), tuple(), set() etc.

A categorized list of some of the frequently used built-in functions in Python:

I/O Functions: input(), print()


Datatype Conversion: bool(), chr(), dict(), float(), int(), list(), ord(), set(), str(), tuple()
Mathematical Functions : abs(), divmod(), max(), min(), pow(), sum()
Other Functions: __import__(), len(), range(), type()
We have already used some of the built-in functions. Let us get familiar with some of them as
explained in following Table:

Name of the Description Example


function

abs (x) It returns distance between x and >>>abs(-45) 45 >>>abs(119L)


zero, where x is a numeric 119
expression.

max( x, y, z, .... ) It returns the largest of its >>>max(80, 100, 1000) 1000
arguments: where x, y and z are >>>max(-80, -20, -10) -10
numeric variable/expression.

min( x, y, z, .... ) It returns the smallest of its >>> min(80, 100, 1000) 80 >>>
arguments; where x, y, and z are min(-80, -20, -10) -80
numeric variable/expression.
cmp( x, y ) It returns the sign of the difference >>>cmp(80, 100) -1
of two numbers: -1 if x < y, 0 if x == >>>cmp(180, 100) 1
y, or 1 if x > y, where x and y are
numeric variable/expression.

divmod (x,y ) Returns both quotient and >>> divmod (14,5) (2,4) >>>
remainder by division through a divmod (2.7, 1.5) (1.0,
tuple, when x is divided by y; where 1.20000)
x & y are variable/expression.

len (s) Return the length (the number of >>> a= [1,2,3] >>>len (a) 3 >>>
items) of an object. The argument b= „Hello‟ >>> len (b) 5
may be a sequence (string, tuple or
list) or a mapping (dictionary).

range (start, This is a versatile function to create >>> range(10) [0, 1, 2, 3, 4, 5,


stop[, step]) lists containing arithmetic 6, 7, 8, 9] >>> range(1, 11) [1,
progressions. It is most often used 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>
in for loops. The arguments must range(0, 30, 5) [0, 5, 10, 15,
be plain integers. If the step 20, 25] >>> range(0, 10, 3) [0,
argument is omitted, it defaults to 3, 6, 9] >>> range(0, -10, -1) [0,
1. If the start argument is omitted, -1, -2, -3, -4, -5, -6, -7, -8, -9]
it defaults to 0. The full form >>> range(0) [] >>> range(1, 0)
returns a list of plain integers [start, []
start + step, start + 2 * step, ...]. If
step is positive, the last element is
the largest start + i * step less than
stop; if step is negative, the last
element is the smallest start + i *
step greater than stop. step must
not be zero (or else Value Error is
raised).

round( x [, n] ) It returns float x rounded to n digits >>>round(80.23456, 2) 80.23


from the decimal point, where x >>>round(-100.000056, 3) -
and n are numeric expressions. If n 100.0 >>> round (80.23456)
is not provided then x is rounded to 80.0
0 decimal digits.

Apart from these functions, you have already seen the use of the following functions:

bool ( ), chr ( ), float ( ), int ( ), long (), str ( ), type ( ), id ( ), tuple ( )

Module
In addition to built-in functions, a large number of pre-defined functions are also available as a
part of libraries bundled with Python distributions. These functions are defined in modules. While
a function is a grouping of instructions, a module is a grouping of functions. A module is created
as a python (.py) file containing a collection of function definitions.

There are two ways to import a module in our program, they are

Import: It is simplest and most common way to use modules in our code.

Syntax:

import modulename1 [, module name 2, ---------]

Example: Input any number and to find square and square root.

import math

x = input ("Enter any number")

y = math.sqrt(x)

a = math.pow(x,2)

print "Square Root value=",y

print "square value=",a

output:

Enter any number25

Square Root value= 5.0

square value= 625.0

From statement: It is used to get a specific function instead of complete file. If we know
beforehand which function(s), we will need, then we may use 'from'. For modules having large
number of functions, it is recommended to use from instead of import.

Syntax

>>> from modulename import functionname [, functionname…..]

from modulename import * will import everything from the file.

Example: Input any number and to find square and square root.

from math import sqrt,pow


x=input("Enter any number")

y=sqrt(x) #without using math

a=pow(x,2) #without using math

print( "Square Root value =",y)

print ("square value =",a)

Enter any number100

Square Root value = 10.0

square value = 10000.0

The functions available in math module are:

Name of the function Description Example

ceil( x ) It returns the smallest math.ceil(-45.17) -45.0


integer not less than x, math.ceil(100.12) 101.0
where x is a numeric math.ceil(100.72) 101.0
expression.

floor( x ) It returns the largest math.floor(-45.17) -46.0


integer not greater than x, math.floor(100.12) 100.0
where x is a numeric math.floor(100.72) 100.0
expression.

fabs( x ) It returns the absolute math.fabs(-45.17) 45.17


value of x, where x is a math.fabs(100.12) 100.12
numeric value. math.fabs(100.72) 100.72

exp( x ) It returns exponential of x: math.exp(-45.17)


e x, where x is a numeric 2.41500621326e-20
expression. math.exp(100.12)
3.03084361407e+43
math.exp(100.72)
5.52255713025e+43
log( x ) It returns natural logarithm math.log(100.12)
of x, for x > 0, where x is a 4.60636946656
numeric expression. math.log(100.72)
4.61234438974

log10( x ) It returns base-10 math.log10(100.12)


logarithm of x for x > 0, 2.00052084094
where x is a numeric math.log10(100.72)
expression. 2.0031157171

pow( x, y ) It returns the value of xy, math.pow(100, 2) 10000.0


where x and y are numeric math.pow(100, -2)
expressions.
0.0001 math.pow(2, 4) 16.0
math.pow(3, 0) 1.0

sqrt (x ) It returns the square root math.sqrt(100) 10.0


of x for x > 0, where x is a math.sqrt(7)
numeric expression. 2.64575131106

cos (x) It returns the cosine of x in math.cos(3) -0.9899924966


radians, where x is a math.cos(-3) -
numeric expression 0.9899924966 math.cos(0)
1.0 math.cos(math.pi) -1.0

sin (x) It returns the sine of x, in math.sin(3) 0.14112000806


radians, where x must be a math.sin(-3) -
numeric value. 0.14112000806 math.sin(0)
0.0

tan (x) It returns the tangent of x math.tan(3) -


in radians, where x must be 0.142546543074
a numeric value. math.tan(-3)
0.142546543074
math.tan(0) 0.0

degrees (x) It converts angle x from math.degrees(3)


radians to degrees, where 171.887338539
x must be a numeric value. math.degrees(-3) -
171.887338539
math.degrees(0) 0.0

radians(x) It converts angle x from math.radians(3)


degrees to radians, where 0.0523598775598
x must be a numeric value. math.radians(-3) -
0.0523598775598
math.radians(0) 0.0

Some functions from random module are:

Name of the function Description Example

random ( ) It returns a random float x, >>random.random ( )


such that 0 ≤ x 0.281954791393
>>>random.random ( )
0.309090465205

randint (a, b) It returns a int x between a >>> random.randint (1,10) 5


& b such that a ≤ x ≤ b >>> random.randint (- 2,20)
-1

uniform (a,b) It returns a floating point >>>random.uniform (5, 10)


number x, such that a <= x 5.52615217015
<b

randrange ([start,] stop It returns a random item >>>random.randrange(100


[,step]) from the given range ,1000,3) 150

Some functions from statistics module are:

Name of the function Description Example

mean(x) It returns arithmetic mean >>> statistics.


mean([11,24,32,45,51]) 32.6

median(x) It returns median (middle >>>statistics.


value) of x median([11,24,32,45,51]) 32

mode(x) It returns mode (the most ) >>> statistics.


repeated value mode([11,24,11,45,11]) 11
>>> statistics.
mode(("red","blue","red"))
'red'

Some of the other modules, which you can explore, are: string, time, date.

Note:
• import statement can be written anywhere in the program

• Module must be imported only once

• In order to get a list of modules available in Python, we can use the following statement: >>>
help("module")

Flow of Execution of program containing Function call

Execution always begins at the first statement of the program. Statements are executed one at a
time, in order from top to bottom. Function definition does not alter the flow of execution of
program, as the statement inside the function is not executed until the function is called.

On a function call, instead of going to the next statement of program, the control jumps
to the body of the function; executes all statements of the function in the order from top to
bottom and then comes back to the point where it left off. This remains simple, till a function
does not call another function. Simillarly, in the middle of a function, program might have to
execute statements of the other function and so on.

It is also important to note that a function must be defined before its call within a program.

Below example program explains the flow of execution for a programs. The number in square
brackets shows the order of execution of the statements.

Example 1:

[2] def Greetings(Name): #Function Header

[3] print("Hello "+Name)

[1] Greetings("John") #Function Call

[4] print("Thanks")

Example 2:

[4] def RectangleArea(l,b):

[5] return l*b

[1] l = input("Length: ")


[2] b = input("Breadth: ")

[3] [6] Area = RectangleArea(l,b)

[7] print(Area)

[8] print("thanks")

Scope of Variables

VARIABLE
SCOPE

LOCAL GLOBAL
SCOPE SCOPE

Scope of variable refers to the part of the program, where it is visible, i.e., area where you can
refer (use) it.

We will study two types of scope of variables- global scope or local scope.

Global Scope

A variable, with global scope can be used anywhere in the program. It can be created by defining
a variable outside the scope of any function/block.

Example

x=40

def func ( ):

print (“Inside func x is” , x )

print( “Value of x is” , x )

On execution the above code will produce

Inside func x is 40
Value of x is 40

Any modification to global is permanent and visible to all the functions written in the file.

Example

x=40

def func ( ):

x+= 10

print (“Inside func x is”, x)

print (“Value of x is”, x)

will produce

Inside func x is 50

Value of x is 50

Local Scope

A variable with local scope can be accessed only within the function/block that it is created in.
When a variable is created inside the function/block, the variable becomes local to it. A local
variable only exists while the function is executing.

Example

X=40

def func ( ):

y = 20

print (“Value of x is ‟, X, “; y is ‟ , y )

print (“Value of x is ‟, X, “ y is “ , y)

On executing the code we will get

Value of x is 40; y is 20
The next print statement will produce an error, because the variable y is not accessible outside
the function body.

A global variable remains global, till it is not recreated inside the function/block.

Example

x=40

def func ( ):

x=4

y=2

print(“Value of x & y inside the function are “ , x , y)

print (“Value of x outside the function is “ , x)

This code will produce following output:

Value of x & y inside the function are 4 2

Value of x outside the function is 40

If we want to refer to global variable inside the function then keyword global will be

prefixed with it.

Example :

x=40

def test ( ):

global x

x =2

y=2

print (“Value of x & y inside the function are “ , x , y)


print (“Value of x outside function is “ , x)

This code will produce following output:

Value of x & y inside the function are 2 2

Value of x outside the function is 2

CASE BASE MCQs

Q1. A variable created or defined within a function body is classified as:


(a) local
(b) global
(c) built-in
(d) instance

Answer.a

Q2. A local variable having the same name as that of a global variable, hides the global variable
in its function.

(a) True
(b) False

Answer.a

Q3. The _____ refers to the order in which statements are executed during a program run.

(a) Flow of Execution


(b) Flow of Program
(c) Sequential Flow
(d) None of these

Answer.a
Q4. A _____ is a file containing Python definitions and statements intended for use in other
Python programs.

(a) Function

(b) Module
(c) File
(d) Package

Answer.b

Q5. Assertion (A): A variable can be used anywhere in the program.

Reason(R): Declare with global scope.

A - Both A and R are true and R is the correct explanation of A.

B - Both A and R are true but R is not the correct explanation of A.

C - A is true but R is false.

D - A is false but R is true.

E - Both A and R are false.

Answer : A

Q6. Assertion (A): sqrt() is used to calculate square root but can not directly used in Python codes.

Reason(R): Defined under math module, need to import math module.

A - Both A and R are true and R is the correct explanation of A.

B - Both A and R are true but R is not the correct explanation of A.

C - A is true but R is false.

D - A is false but R is true.

E - Both A and R are false.

Answer. A
Q7 . Assertion (A): len() can be directly accessed in Python codes.

Reason(R): It is a built in function built into Python language.

A - Both A and R are true and R is the correct explanation of A.

B - Both A and R are true but R is not the correct explanation of A.

C - A is true but R is false.

D - A is false but R is true.

E - Both A and R are false.

Answer. A

Q8. Assertion (A): Function definition does not alter the flow of execution of program.

Reason(R): Statement inside the function is not executed until the function is called.

A - Both A and R are true and R is the correct explanation of A.

B - Both A and R are true but R is not the correct explanation of A.

C - A is true but R is false.

D - A is false but R is true.

E - Both A and R are false.

Answer. A

Q9. What are the two main types of functions?

a) Custom function

b) Built-in function & User defined function

c) User function

d) System function

Answer: b

Explanation: Built-in functions and user defined ones. The built-in functions are part of the
Python language. Examples are: dir(), len() or abs(). The user defined functions are functions
created with the def keyword.

Q10. Where is function defined?


a) Module

b) Class

c) Another function

d) All of the mentioned

Answer: d

Explanation: Functions can be defined inside a module, a class or another function.

Q11. Where is function defined?

a) Module

b) Class

c) Another function

d) All of the mentioned

Answer: d

Explanation: Functions can be defined inside a module, a class or another function.

DATA FILE HANDLING

Introduction to file:
A file is a packet in which any information or logically related data is stored with a unique identity
name. A file can have the information like textual, audio, video, image etc.

Classification of file:

A file classification scheme (also known as a file plan) is a tool that allows for identifying, titling,
accessing and retrieving records of a file by the help of file extension.

Type of file Contain Data/Information Extension of file

Characters (upper case, lower case,


Text file /Rich
digits and special symbols) including .txt, .rtf
document file
ASCII code

Audio file Analog / digital waveform data .mp3,.mpa,.aif,.wav,.wma

Image file Contain information of a picture format .bmp,.gif,.png,.jpeg,.jpg

Video Contain Audio and video data format .3gp,.m4v,.mkv,.mov,.mp4

Zip file Contain compressed data .zip,.rar

Advantages of computerized files:

(i) Computer can perform calculations quickly and efficiently.

(ii) Data can be retrieved quickly and easily.

(iii) Lost documents can be retrieved.

(iv)Security is tight and hard to break into.

(v) Makes work easier.

Types of files (Text file, Binary file, CSV file)

Text files:

(i) All the information in text files are saved in the format of ASCII codes.

(ii) A text file consists of a sequence of lines.

(iii) All the lines in the text files terminated by a special syntax classed "\n" (new line).It is also
known as End of Line (EOL).

(iv)The text file has the extension (.txt)


(v) The text files are slow in excess.

(vi)All the data of text file is displayed in the same fashion as it is stored in the memory.

Binary files:

(i) All the information is stored in binary format directly.

(ii) No delimiter is used to terminate each line of binary files.

(iii) The binary file has the extension (.dat).

(iv) The binary files are fast to excess.

(v) All the data of binary file is displayed in the different fashion, while it is stored in the binary
format in the memory.

(vi) The Image, Audio and Video files are the example of Binary files.

CSV (Comma Separated Values) file:

(i) A CSV file stores the in tabular data (numbers and text) in plain text.

(ii) Each line of the file is known as data record.

(iii) It stores the data in tabular format, also known as a spreadsheet or database.

(iv)The CSV File has the extension (.csv).

(v) No need to close the CSV file.

(vi)We can use the CSV file by import csv library.

Case based MCQs

Q.1Avni is a class XII Computer Science student studying Data File Handling chapter. She has gone
through the basics of file systems. She is having some questions after reading the book contents.
Help het to find the correct answers.

(a) A file may have the data in the format of ………..?

(i) Text (ii) Audio format

(iii) Wave forms (iv) All of the above


(b) To identify the different file name and application of a file system, we use the ……..

(i) File Extensions (ii) Logically related data

(iii) Only file name (iv) None of these

(c) Avni makes a lesson note using an application and stored with the file extension (.docx), On
which application she has made her lesson note.

(i)Notepad (ii) MS Word

(iii)WordPad (iv) All of these

(d)Avni is taking some pictures of her notes, which extension will the files be used to store?

(i)JPG (ii)JPEG/JPG

(iii)TXT (iv)MP4

(e)Kindly tell to Avni ? What is the strongest feature of a file?

(i) Storage/Retrieval (ii) Share

(iii)Read/Write (iv)None of these

Answer Keys:- (a) (iv) All of the above (b) (i) File Extensions (c) (ii) MS Word

(d) (ii)JPEG/JPG (e) (i) Storage/Retrieval

Q.2 Rajat, a class XII computer science student is working on text file. Help him to find the answers
of his some questions/doubts…

(a) What does the “I” letters stand in ASCII?

(i) Interpreted Interrelated (ii) Interchange Information

(iii) Interrupted information (iv) Information Interchange

(b)What is memory size of ASCII code?

(i) 1- Byte (8-bits) (ii) 2-Bits

(iii) 1 Kilo Bytes (iv) None of these


(c) In which applications/app, Rajat can view his file data?

(i) Notepad (ii) WordPad

(iii) Option (i) & (ii) (iv) In all applications

(d)Each line of a text file is terminated with a special name and symbol…….

(i)New line (ii)EOL

(iii)\n (iv)All of these

(e) Files having information related audio & video comes under the categories of ……

(i) Binary files (ii) Text file

(iii)AV file (iv)None of these

(f) Which file system stores data in tabular format,in Data file handling?

(i) Binary files (ii) Text file

(iii)CSV files (iv)All of these

(g) In which applications, the information of CSV files can be access/display?

(i) MS Access (ii) Text file

(iii)MS Excel/Spreadsheet (iv) All of these

(h) What is Data Record in CSV file?

(i) A Row (Each line of data) (ii) All data

(iii)Any information (iv) None of these

Answer Keys:- (a) (ii) Interchange Information (b) (i) 1- Byte (8-bits) (c) (iii) Option (i)
& (ii)

(d) (iv)All of these (e) (i) Binary files (f) (iii)CSV files

(g) (iv) All of these (h) (i) A Row (Each line of data)
TEXT FILE HANDLING

A file is a named location on a secondary storage media where data is stored temporary or
permanently for later use. A text file can be understood as a sequence of characters consisting
of alphabets, numbers and other special symbols. Each line of a text file is terminated by a special
character, called the End of Line (EOL).

OPENING AND CLOSING FILES:

To open a text file in Python, we use the open() function. The syntax of open() is as follows:

file_object= open(file_name, access_mode)

(This function returns a file object called file handle which is stored in the variable file_object. If
the file does not exist, the above statement creates a new empty file and assigns it the name we
specify in the statement.)

The file_object has certain attributes that tells us basic information about the file, such

as:

<file.closed> returns true if the file is closed and false otherwise.

<file.mode> returns the access mode in which the file was opened.

<file.name> returns the name of the file.

The access_mode is an optional argument that represents the mode in which the file has to be
accessed by the program. The default is the read mode.

close() function : Once we are done with the read/write operations on a file, it is a good practice
to close the file.

The syntax of using close() function is:

file_object.close()

Here, file_object is the object that was returned while opening the file. Python makes sure that
any unwritten or unsaved data is flushed off (written) to the file before it is closed.
FILES MODE: It defines how the file will be accessed:-

File Mode Description File Offset position

<r> Opens the file in read-only mode. Beginning of the file

<rb> Opens the file in binary and read-only mode. Beginning of the file

<r+> or <+r> Opens the file in both read and write mode. Beginning of the file

Opens the file in write mode. If the file already exists, all
<w> the contents will be overwritten. If the file doesn’t exist, Beginning of the file
then a new file will be created.

<wb+> or Opens the file in read,write and binary mode. If the file
already exists, the contents will be overwritten. If the Beginning of the file
<+wb> file doesn’t exist, then a new file will be created.

Opens the file in append mode. If the file doesn’t exist,


<a> End of the file
then a new file will be created.

Opens the file in append and read mode. If the file


<a+> or <+a> End of the file
doesn’t exist, then it will create a new file.

Opening a file using with clause:

In Python, we can also open a file using with clause. The syntax of with clause is:

with open (file_name, access_mode) as file_ object:

The advantage of using with clause is that any file that is opened using this clause is closed
automatically, once the control comes outside the with clause.

Example:

with open(“myfile.txt”,”r+”) as myObject:

content = myObject.read()

Writing to a text File:-


For writing to a file, we first need to open it in write or append mode. If we open an existing file
in write mode, the previous data will be erased, and the file object will be positioned at the
beginning of the file. On the other hand, in append mode, new data will be added at the end of
the previous data as the file object is at the end of the file.
We can use the following methods to write data in the file.

Method Syntax Significance Example

write() <filehandle>.write(str1) for writing a Consider the following piece of code:


single string
myobject=open("myfile.txt",'w')

myobject.write("Hey I have started #using


files in Python\n")

writelines() <filehandle>.writelines for writing a myobject=open("myfile.txt",'w')


(L) sequence of
strings lines =["Hello everyone\n", "Writing
#multiline strings\n", "This is the #third
line"]

myobject.writelines(lines)

myobject.close()

Reading from a text File:

We can write a program to read the contents of a file. Before reading a file, we must make sure
that the file is opened in “r”, “r+”, “w+” or “a+” mode.

Methods to read data from files

Method Syntax Description Example

read() <filehandle>.read( [n] ) This method is used to read a myobject=open("myfile.txt",'r')


specified number of bytes of
data from a data file. print(myobject.read())

Hello everyone

If no argument or a negative
number is specified in read(),
the entire file content is read. myobject=open("myfile.txt",'r')
print(myobject.read())
Hello everyone

Writing multiline strings

This is the third line

myobject.close()

Readline( ) <filehandle>.readline([n]) This method reads one myobject=open("myfile.txt",'r')


complete line from a file
where each line terminates myobject.readline(10)
with a newline (\n) character.
It can also be used to read a 'Hello ever'
specified number (n) of bytes
of data from a file but
maximum up to the newline
character (\n).

If no argument or a negative
number is specified, it reads a myobject=open("myfile.txt",'r')
complete line and returns
string. print(myobject.readline())

'Hello everyone\n'

readlines() <filehandle>.readlines() The method reads all the lines myobject=open("myfile.txt", 'r')
and returns the lines along
with newline as a list of print(myobject.readlines())['Hello
strings. everyone\n', 'Writing multiline
strings\n', 'This is the third line']

myobject.close()
Setting offsets In a File:

The functions that we have learnt till now are used to access the data sequentially from a file.
But if we want to access data in a random fashion, then Python gives us seek() and tell() functions
to do so.

Method Syntax Description Example

tell() file_object.tell() This function returns an There is “GfG.txt” which


integer that specifies contains the following
the current position of text:
the file object in the file.

"Code is like humor.


seek() Syntax: f.seek(offset, from_what), This method is used to When you have to
where f is file pointer position the file object explain it, it’s bad."
Parameters: at a particular position
Offset: Number of positions to in a file.
move forward
from_what: It defines point of f = open("GfG.txt", "r")
reference.
f.seek(20)
Returns: Does not return any value
print(f.tell())

print(f.readline())
The reference point is selected by
the from_what argument. It f.close()
accepts three values:

0: sets the reference point at the


beginning of the file
Output:

1: sets the reference point at the 20


current file position
When you have to
explain it, it’s bad.
2: sets the reference point at the
end of the file

By default from_what argument is


set to 0.

CASE BASED MCQs

Q.1 Considering the content stored in file “PLEDGE.TXT”

“ India is my country

And all Indians are my brothers and sisters,

I love my country,

And I am proud of its rich and varied heritage.

I shall always strive to be worthy of it.

I shall give respect to my parents, teachers, and all the elders,

And treat everyone with courtesy.”

Write the output of following statements – f = open("PLEDGE.TXT")

sr1 = # to read first line of file

str2 = # to read next line of file

str3 =_____________ # to read remaining lines of file

a. f.read() b. f.readline()

f.readline() f.read()

f.readlines() f.readlines()

c. f.readline() d. f.readlines()

f.readline() f.readline()
f.readlines() f.readline()

Ans: c. f.readline()

f.readline()

f.readlines()

Q.2 Considering the content stored in file “PLEDGE.TXT”, write the output

f = open(“PLEDGE.TXT”)

print(f.read(2))

print(f.read(2))

print(f.read(4))

a. India b. In
is di
my a is
c. Ind d. India is my country
ia And all Indians are my brothers and sisters,
is I love my country,

Ans: b. In
di
a is

Q.3 Which of the following commands is used to write the list L into the text, POEM.TXTwith
file handle F ?

a. F.write(L) b.F.writeline(L)

c. F.writelines( ) d. F=write(L)

Ans c. F.writelines( )
Q.4 Which of the following statements correctly explain the function of tell() method?

a. tells the current position within the file.

b. determines if you can move the file position or not.

c. indicates that the next read or write occurs from that position in a file.

d. moves the current file position to a given specified position.

Ans a. tells the current position within the file.

Q.5 In which of the following file modes the existing data of the file will not be lost?

i) rb

ii) w

iii) a+b

iv) wb+

v) r+

vi) ab

vii) w+b

viii)wb

ix) w+

Ans ab and a+b mode

BINARY FILES
BINARY FILES
FOR READING/ WRITING
DATA IN THE FORM OF
BYTES FROM/TO FILE

Writing Data to a Reading data from the


binary file is done binary file is done
through process through process called
called
PICKLING UNPICKLING

Method used: Method used:


dump(object, load(fileObject)
fileObject)

Binary files use strings of type bytes. This means when reading binary data from a file, an object
of type bytes is returned.

Binary files are also stored (written) in terms of bytes (0s and 1s), but unlike text files, these bytes
do not represent the ASCII values of character.

Rather, they represent the actual content such as image, audio, video, compressed versions of
other files, executable files, etc.

Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents. Thus, trying to open a binary file using a text editor will show
some garbage values.

To work on a binary file an external module named pickle is used.

Pickle module converts Python object to byte stream so that it can be stored on disk. This process
is called Pickling.

While retrieving data from file Pickle module converts stream of bytes to original structure. This
process is called Unpickling.

STEPS to Read/ Search data from Binary File

import pickle module


Open binary file for reading ie using ‘rb’ mode.

Process the data in a loop ie repeat the step 4 and step 5 for all records

Read data from the file (in a variable say d) using load( fileobject) method

Apply appropriate search function / method on the variable read from the file.

Close file

STEPS to Write data to Binary File

import pickle module

Open binary file for writing is ‘wb’ mode.

Read data from the user (in variables)

Assemble data in the form of list/tuple/ dictionary say t

Write data to the file using dump(t, fileobject) method

Close file .

STEPS for updating a binary file

1 import pickle module

2. Open binary file for reading

3. Read data from the file (in a variable) using load() method

4. Close the file.

5. Make changes in the variable read from the file

6. Open binary file in writing mode

7. Write updated variable in the file using dump() method

8. Close the file.

Example 1: #Create a binary file "emp.dat" that writes n employee records in the file with details-
[empno, ename, sal] and then read the contents from the file

import pickle
f=open("emp.dat", "wb")

c='Y'

while c=='Y' or c=='y':

n=int(input("Enter the employee no::"))

nm=input("Enter the employee name::")

s=int(input("Enter the employee sal::"))

r=[n,nm,s]

pickle.dump(r,f)

c=input("Do you want to continue(y/n)::")

f.close()

Example 2 :: Write a function search_cd(n) that takes a parameter ie name of cd and searches for
the quantity of it in the file "Audio.dat" containing records of the format- [CdNo, CD name, Qty]

import pickle

def search_cd(n):

f=open("Audio.dat","rb")

fl=0

while True:

try:

r=pickle.load(f)

if(r[1].lower()==n.lower()):

fl=-99

print("Item found, Quantity is::\n ", r[2],"of item\t",r[1])

except EOFError:

break
if fl==0:

print("CD Not found")

f.close()

return

Example 3: Consider file "Items.dat". Write a menu driven program to:

1. add a record to the file having the record in the format - [Itemno, item name, price]

2. Search a record with a given item name

3. Display the records

4. Update the price for a particular item name input by the user.

5. To delete the record of a given itemno.

import pickle

def ins_rec():

f=open("item.dat","ab")

ino=input("Input Itemno::")

nam=input("Enter item name::")

pr=float(input("Enter item price::"))

d=[ino,nam,pr]

pickle.dump(d,f)

f.close()

return

def search_rec():

f=open("item.dat","rb")

fl=0
n=input("Enter item name to b searched::")

while True:

try:

r=pickle.load(f)

if(r[1]==n):

fl=-99

print("Item found Details are::\n ", r)

except EOFError:

break

if fl==0:

print("Item Not found")

f.close()

return

def disp():

f=open("item.dat","rb")

i=0

while True:

try:

r=pickle.load(f)

i=i+1

print("Item ",i," Details are::\n ", r)

except EOFError:

break

f.close()

return
def update_rec():

f=open("item.dat","rb+")

fd=0

fl=[]

n=input("Enter item name to b updated::")

while True:

try:

r=pickle.load(f)

fl.append(r)

except EOFError:

break

f.close()

for x in fl:

if n.lower()==x[1].lower(): #Biscuits / biscuits bisCuits, biscuits,

#biscUITS

fd=1

p=float(input("enter the price to be updated::"))

x[2]=p

f=open("item.dat","wb")

for x in fl:

pickle.dump(x,f)

if fd==0:

print("Item Not found")

f.close()

return
def del_rec(n):

f=open("item.dat","rb")

fd=0

fl=[]

while True:

try:

r=pickle.load(f)

fl.append(r)

except EOFError:

break

f.close()

f=open("item.dat","wb+")

for x in fl:

if n==x[0]:

fd=1

print("Item being deleted", x)

continue

pickle.dump(x,f)

if fd==0:

print("Item Not found")


f.close()
return

ch='Y'

while ch=='Y'or ch=='y':

print("Items DATA")

print("1. Insert Records")


print("2.Searching records")

print("3. Display Records")

print("4. Update Records")

print("5. Delete records")

print("6. Exit")

c=int(input("Enter the choice(1-6)"))

if c==1:

ins_rec()

elif c==2:

search_rec()

elif c==3:

disp()

elif c==4:

update_rec()

elif c==5:

n=input("Enter item no to be deleted::")

del_rec(n)

else:

break

ch=input("Do You want continue(Y/N)")

CASE BASED MCQs

Q1) Rashmi is eager to learn Python, and has learnt Python so far through videos, websites etc.
Now, she is writing her first program using binary files in which she is trying to record the
observation of various plants in her surrounding in the following format:

(P_Id, Plant_Name, type, useful_part, medicinal_value)


She has written the following code with the help of user defined function addPlant() to create a
binary file called MyPlants.DAT containing plants information.

She has succeeded in writing partial code and is confused in certain statements, so she has left
certain queries in comment lines. You as an expert of Python have to provide the missing
statements and other related queries based on the following code of Rashmi.

___________ # Statement 1

def addPlants():

t=tuple()

f= _______ #Statement 2

while True:

pid = input("Plant ID :")

pame = input("Plant Name : ")

ptype = input("Plant Type: ")

med_benefits= input("Plant Medicinal Benefits : ")

____________ #Statement 3

____________ #Statement 4

Choice = input("enter more (y/n): ")

if Choice not in "Yy":

break

f.close()

Answer any four questions (out of five) from the below mentioned questions.

i) Which of the following statement is correct to mention the module to be used for creating
binary file? ( Statement 1)

import csv

import files

import pickle

import binary
Correct Answer : c. import pickle

ii) Which of the following commands is used to open the file “MyPlants.DAT” for adding records
in binary format to previously existing plant data? (Statement 2)?

a. open("MyPlants.DAT",'wb')

b. open("MyPlants.DAT",'ab')

c. open("STUDENT.DAT",'a')

d. open("STUDENT.DAT",'r+')

Correct Answer : b. open("MyPlants.DAT",'ab')

iii) Which of the following commands is used to populate the tuple t for writing records into the
binary file, MyPlants.DAT? (marked as Statement 3)

a) t= pid, pname, ptype, med_benefits

b) t= t +(pid, pname, ptype, med_benefits)

c) t= [pid, pname, ptype, med_benefits]

d) t= pid +pname+ ptype+ med_benefits

Correct Answer : a. t= pid, pname, ptype, med_benefits

iv) Which of the following commands is correct to write the tuple t into the binary file,
MyPlants.DAT? (Statement 4)

a. pickle.write(t,f)

b. pickle.load(t, f)

c. pickle.dump(t,f)

d. f=pickle.dump(t)

Correct Answer : c. pickle.dump(t,f)

v) Read both the statements carefully and choose the correct alternative from the following :

Assertion(A): Conversion of data at the time of reading and writing is required.


Reason(R) : Binary files store the data in binary format

A and R are both correct, also R is the correct explanation of A.

b)A and R are both correct, but R is not the correct explanation of A.

A is correct, but R is wrong

A is wrong, but R is correct.

Correct Answer : a. A and R are both correct, also R is the correct explanation of A.

Q 2) Ranjeet, is newly recruited in a Software Firm that designs software for Aerospace
manufacturers. He has been assigned a program for searching a record in a binary file
‘AircraftForces.dat’ that stores the data in the format given below :

[Pid, climb_angle,lift, thrust, weight, drag]

And writes the following record format in another file ‘ForceEffect.dat’

[PID, Effect] on the basis of following criteria:

Flight Condition Effect

Lift > Weight Plane Rises

Weight> Lift Plane Falls

He is successful in writing the partial code and has missed out certain statements, so he has left
queries in comment lines. You as an expert TeamLeader have to provide the missing statements:

def write_effect():

af=open("AircraftForces.dat","___") # Statement 1 to open file for reading

f=open("ForceEffect.dat","____") # Statement 2 to open file for writing

_____: # Statement 3 to prevent an infinite loop

while True:

r=pickle.load(af)

if ____: # Statement 4 for comparing lift and weight


pickle._______ # Statement 5 to write records in file where

# lift > weight

else:

pickle._______ # Statement 6 to write records in file

# where weight > lift

except EOFError:

break

f.close()

af.close()

return

#main program

___________ # Statement 7 to invoke the function write_effect

In which mode Ranjeet should open the files Aircraft.dat in Statement 1 and ForceEffect.dat in
Statement-2?

a) wb and rb

b) rb and wb

c) ab and wb

d) r and w

Correct Answer: b) rb and wb

ii) What will be the suitable code to be used in Statement 3 to avoid getting into an infinite loop?

for i in range(20):

try

if (af):

Break

Correct Answer: b) try


iii) Identify the suitable code to be used at blank space in line marked as Statement- 4

a. ) if r[3]>r[5]

b) if(r[2]>r[4])

c) try

d) True

Correct Answer: b) if(r[2]>r[4])

iv) Identify the correct statement among the following to write the data in file ‘ForceEffect.dat’
in the blank marked as Statement 5 and Statement 6?

dump([af, r[0],"Plane Falls"]) and dump(af, [r[0],"PlaneRises"])

dump([ r[0],"Plane Falls"],f) and dump( [r[0],"PlaneRises"],f)

dump([r[0],"Plane Rises"],af) and load([r[0],"Plane Falls"],af)

dump([r[0],"Plane Rises"],f) and dump([r[0],"Plane Falls"],f)

Correct Answer: d) dump([r[0],"Plane Rises"],f) and dump([r[0],"Plane Falls"],f)

v) Which statement among the following should be used in blank space in line marked Statement
7?

def write_rec()

func write_rec( )

call write_rec()

write_rec()

Correct Answer : d) write_rec()

Q 3) Kaustubh is given an opportunity to work in a firm that designs software for stock market
analysis during internship on stipend. Now, he has been assigned a task to work on python binary
files on which he has little expertise.

He has tried to write a program that has 2 functions:

ins_rec() : to add the records at the end of file stock.dat in the following format

{"Comp_name" :"Abc", "date":"3/09/2021",'open':56, 'high':78, 'low':45, 'close':76}


update_rec() : that searches and updates the high index at the end of day for a given company
name input by the user

He was successful in writing the program but after many attempts. He marked those statements
with blanks in which he tried various options to try again and again for practice. The options with
which he tried the code are listed as options with only one correct code statement using which
he was successful at last. Identify the correct option in questions given below

import pickle

def ins_rec(cid,d,o,h,l,c):

file_obj=___________ # statement 1

rec={}

rec["Comp_name"]=cid

rec["date"]=d

rec["open"]=o

rec["high"]=h

rec["low"]=l

rec["close"]=c

_________________ #Satement 2

file_obj.close()

return

def update_rec():

f=open("stock.dat","rb+")

fd=0

fl=[]

n=input("Enter Company name to b updated::")

try:

while True:
r=________ # Statement 3

fl.append(r)

except EOFError:

pass

f.close()

print(fl)

for x in fl:

_________ # Statement 4

fd=1

p=int(input("enter the high to be updated::"))

x['high']=p

print(fl)

f=_________ # Statement 5

for x in fl:

pickle.dump(x,f)

if fd==0:

print("Item Not found")

f.close()

return

i) In statement 1, he wanted to open the file ‘stock.dat’ to add records at the end of file. The
possibilities with which he tried the code are listed below and only one is correct with which the
code worked.

a) open("stock.dat","a")

b) open("stock.dat","ab")

c) open("stock.dat","a+")

d) open("stock.dat","wb")
Correct Answer : b) open("stock.dat","ab")

ii) Which option is correct among the following to be written as statement 2 to write the records
into the file stock.dat?

dump(rec,file_obj)

pickle.dump(file_obj, rec)

pickle.dump(rec,file_obj)

pickle.write(rec,file_obj)

Correct Answer : c) pickle.dump(rec,file_obj)

iii) In statement 3, he wants to read a record from the file and tried with following statements.
Choose the one with which Kaustubh was successful.

pickle.load(f)

load(f)

read(f)

pickle.read(f)

Correct Answer : a) pickle.load(f)

iv) In Statement 4, he wants to compare the company name of the record read and the
company’s name entered by the user whose high is to be updated.

for k in x.values():

for k in x.keys():

if k in x.keys():

if x['Comp_name'].lower()==n.lower():

Correct Answer : d) if x['Comp_name'].lower()==n.lower():

v) What will be the correct code for Statement 5 to open the file for writing the updated records
in the binary file after making all updations in list fl .

open("stock.dat","ab")

open("stock.dat","wb+")
open("stock.dat","wb")

open("stock.dat","w")

Correct Answer : c) open("stock.dat","wb")

Q 4) Akhtar is a student and is assigned a program by his teacher to store the details of all his
classmates in a binary file ‘ClassXII_A.dat’ with the following record format:

[ Adm_no, StudentName, Fathers Name, PhoneNo]

He has written 2 functions :

add_rec(): to add record for a new admission in the above format

delete_tc() :to search and delete the record with given admn no for TC students

The code is given below with few errors and blanks due to which he is unable to run the program
successfully. You, as an expert, help him run the program successfully by choosing the correct
option.

1 import pickle

2 def add_rec():

3 with open("ClassXII_A.dat","ab") as file_obj:

4 adm=input("Input Admission No::")

5 sname=input("Input Student Name::")

6 fname=input("Input Father's name::")

7 phno =input("Input Phone No::")

8 rec=[adm,sname,fname,phno]

9 pickle.dump(rec,file_obj)

10 return

11 def del_tc(n):

12 f=open("ClassXII_A.dat") # Statement 1

13 fd=0

14 fl=[]
15 try :

16 while True:

17 r=pickle.load(f)

18 fl.append(r)

19 except EOFError:

20 pass

21 f.close()

22 with open("ClassXII_A.dat","wb+") as f:

23 for x in fl:

24 ____________ #Statement 2

25 fd=1

26 print("Student being deleted", x)

27 pickle.dump(x,f)

28 if fd==0:

29 print("Item Not found")

30 return

i) Akhtar has not closed the file in the function add_rec(). Identify the suitable option to close the
file.

file_ob.close()

pickle.close()

close(file_obj)

There is no need to close the file in this case as python will automatically close the file.

Correct Answer : d) There is no need to close the file in this case as python will automatically
close the file.

ii) In Statement 1 he wants to open the already existing file to read all the records and store
them in a list. When he is executing the program he is getting an error in statement1. Help him
diagnose the reason of error and correct code, by selecting the correct option below::
He is opening in reading mode, while he was supposed to open in writing mode to delete it,
f=open(“ClassXII_A.dat”,”wb”),

He is opening in reading mode, while he was supposed to open in writing mode to delete it,
pickle.open(“ClassXII_A.dat”,”wb”)

He has not mentioned the binary mode, so he must write, f=open(“pickle.dat”,”rb”)

He has not mentioned the binary mode, so he must write, f=open(“pickle.dat”,”b”)

Correct Answer : c) He has not mentioned the binary mode, so he must write,
f=open(“pickle.dat”,”rb”)

iii) What should be written in Statement 2, line no 24 to compare the admission no sent as an
argument to function del_tc() with admission no present in list fl?

a) if n==x[0]:

b) while n==x[0]:

c) if n==x :

d) while n in x:

Correct Answer : a) if n==x[0]:

iv) In the block between line no 22 to 30, he is trying to skip the record from writing into the file
matched with admission no passed as an argument to del_tc() but is not successful in it. Identify
the correct statement and its position which could help him skip the record to be deleted from
writing into the file.

break, after line no 27

continue , before line no 27 at same indentation level of ‘for’ body

continue, before line no 27 at same indentation level of body of statement 2

pass, before line no 27

Correct Answer : c) continue, before line no 27 at same indentation level of body of


statement 2

v) Which of the following statements correctly explain the operation performed by following
statement:

File_object. seek(35,1)

a) moves the current file position to 35 bytes forward from the end of file.
b) moves the current file position to 35 bytes backward from the end of file.

c) moves the current file position to 35 bytes forward from the current position in the file.

d) moves the current file position to 35 bytes forward from the beginning of file.

Correct Answer : c) moves the current file position to 35 bytes forward from the current
position in the file.

Q 5) Priyanka’s father owns a pharmacy shop. She is studying python in class XII. She decided to
computerize the data for her father’s shop with the help of binary files and storing the data in
the given format:

{“name”: ‘Combiflam’, ‘qty’: 4}

She has written the following code but is having difficulty in some statements. Help her solve the
errors:

import pickle

def ins_rec():

with open("med_lab.dat","ab") as file_obj:

rec={ }

mid=input("Input Medicine name::")

rec['Name']=mid

d=input("Enter Quantity::")

8. rec['Qty']=d

9. pickle.dump(rec,file_obj)

10. return

11. def sell_med(nm, n):

12. fd=0

13 lst=[]

14 with open("med_lab.dat","____") as file_rw:

15 try:

16 while True:
17 r=pickle.load(file_rw)

18 lst.append(r)

19 except EOFError:

20 pass

21 print(lst)

22 for i in range(0, len(lst)):

23 if ( lst[i]['Name']==nm):

24 fd=1

25 lst[i]['Qty']-=n

26 print(lst)

27 ________________

28 for x in lst:

29 ___________________

30 if fd==0:

31 print("Medicine Not found")

32 return

33 def disp():

34 f=open("med_lab.dat","rb")

35 i=0

36 print(n, "File Data")

37 while True:

38 try:

39 r=pickle.load(f)

40 i=i+1

41 print("Item ",i," Details are::\n ", r)


42 except EOFError:

43 break

44 f.close()

45 return

46 ins_rec()

47 disp()

48 n=input("Medicine being sold::")

49 q=input("Quantity being sold::")

50 sell_med(n,q)

51 disp()

i) In line 14, she wants to open file for both reading and writing, help her right the correct
file access mode?

a) ‘w+’
b) ‘rb+
c) ‘ab+’
d) ‘rw’
Correct Answer : b) ‘rb+’

ii) She is trying to search medicine ‘Combiflam’, though it exists in file but

still it is showing, “Medicine not found”. Which line needs to be modified?

a) Line 23 as if ( lst[i]['Name'].lower()==nm.lower()):

b) Line 22 as for i in lst:

c) Line 23 as if ( lst[i][0].lower()==nm.lower()):

d) Line 23 as if ( lst[i].lower()==nm.lower()):

Correct Answer : a) Line 23 as if ( lst[i]['Name'].lower()==nm.lower()):

iii) In line 25, she doubts there is an error, as when she is trying to subtract the required quantity
it shows typeError. Suggest a possible reason for it to her?

a) Quantity must be integer


b) Line no 7 needs to be rectified as, d=int(input("Enter Quantity::"))

c) Line no 49 needs to be rectified as q=int(input("Quantity being sold::"))

d) All of the above

Correct Answer : d) All of the above

iv) In line 27, she is trying to reposition the file object to the beginning of the file to start writing
the modified records. Identify the correct option that will help Priyanka accomplish the task.

a) file_rw.open(‘ med_lab.dat’,”wb”)

b) file_rw.open(‘ med_lab.dat’,”wb”)

c) file_rw.tell(0)

d) file_rw.seek(0)

Correct Answer : d) file_rw.seek(0)

v) What should be the correct statement to be written in line no 29 to write the updated record
in the file?

a) file_rw.dump(x)

b) pickle.dump(x,file_rw)

c) pickle.dump(lst, file_rw)

d) file_rw.writelines(x)

Correct Answer : b) pickle.dump(x,file_rw)

Q6) Amritya Seth is a programmer, who has recently been given a task to write a python code to
perform the following binary file operations with the help of two user defined
functions/modules:

AddStudents() to create a binary file called STUDENT.DAT containing student information – roll
number, name and marks (out of 100) of each student.

GetStudents() to display the name and percentage of those students who have a percentage
greater than 75. In case there is no student having percentage > 75 the function displays an
appropriate message. The function should also display the average percent.
He has succeeded in writing partial code and has missed out certain statements, so he has left
certain queries in comment lines. You as an expert of Python have to provide the missing
statements and other related queries based on the following code of Amritya.

Answer any four questions (out of five) from the below mentioned questions.

import pickle

def AddStudents():

____ #1 statement to open the binary file to write data

while True:

Rno = int(input("Rno :"))

Name = input("Name : ")

Percent = float(input("Percent :"))

L = [Rno, Name, Percent]

__________ #2 statement to write the list L into the file

Choice = input("enter more (y/n): ")

if Choice in "nN":

break

F.close()

def GetStudents():

Total=0

Countrec=0

Countabove75=0

with open("STUDENT.DAT","rb") as F:

while True:

try:

__________ #3 statement to read from the file

Countrec+=1
Total +=R[2]

if R[2] > 75:

print(R[1], " has percent =",R[2])

Countabove75+=1

except:

break

if Countabove75==0:

print(“There is no student who has percentage more than


75")

average=Total/Countrec

print(“Average percent of class=”, average)

Addstudents()

GetStudents()

i) Which of the following commands is used to open the file “STUDENT.DAT”

for writing only in binary format? (marked as #1 in the Python code)

a. F= open("STUDENT.DAT",'wb')

b. F= open("STUDENT.DAT",'w')

c. F= open("STUDENT.DAT",'wb+')

d. F= open("STUDENT.DAT",'w+')

Correct Answer : a. F= open("STUDENT.DAT",'wb')

ii) Which of the following commands is used to write the list L into the binary file, STUDENT.DAT?
(marked as #2 in the Python code)

a. pickle.write(L,f)

b. pickle.write(f, L)

c. pickle.dump(L,F)

d. f=pickle.dump(L)
Correct Answer : c. pickle.dump(L,F)

iii) Which of the following commands is used to read each record from the binary file
STUDENT.DAT? (marked as #3 in the Python code)

a. R = pickle.load(F)

b. pickle.read(r,f)

c. r= pickle.read(f)

d. pickle.load(r,f)

Correct Answer : a.R = pickle.load(F)

iv) Which of the following statement(s) are correct regarding the file access Modes?

a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.

b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists and
creates a new one if it does not exist.

c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and
creates a new one if it does not exist.

d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists.

Correct Answer : a

v) Which of the following statements correctly explain the function of seek()

method?

a. tells the current position within the file.

b. determines if you can move the file position or not.

c. indicates that the next read or write occurs from that position in a file.

d. moves the current file position to a given specified position

Correct Answer : d
Q 7) Arun, during Practical Examination of Computer Science, has been assigned an incomplete
search() function to search in a pickled file student.dat. The File student.dat is created by his
Teacher and the following information is known about the file.

File contains details of students in [roll_no,name,marks] format.

File contains details of 10 students (i.e. from roll_no 1 to 10) and

separate list of each student is written in the binary file using dump().

Arun has been assigned the task to complete the code and print details of roll number 1.

def search():

f = open("student.dat",____ ) #Statement-1

……….. : #Statement-2

while True:

rec = pickle.___ #Statement-3

if(____): #Statement-4

print(rec)

except:

pass

____________ #Statement-5

In which mode Arun should open the file in Statement-1?

a) r
b) r+
c) rb
d) wb
Correct Answer: c) rb

ii) Identify the suitable code to be used at blank space in line marked as Statement- 2
a. ) if(rec[0]==1)

b) for i in range(10)

c) try

d) pass

Correct Answer: c) try

iii) Identify the function (with argument), to be used at blank space in line marked as Statement-
3.

a) load()

b) load(student.dat)

c) load(f)

d) load(fin)

Correct Answer: c) load(f)

IV ) What will be the suitable code for blank space in line marked as Statement-4.

a) rec[0]==2

b) rec[1]==2

c) rec[2]==2

d) rec[0]==1

Correct Answer: d) rec[0]==1

V) Which statement Arun should use at blank space in line marked as Statement-4 to close the
file.

a) file.close()

b) close(file)

c) f.close()
d) close()

Correct Answer: c) f.close()

What is CSV file or Characteristics of CSV files :

A CSV (Comma Separated Values) file is a simple plain text file having extension .csv.

Because it is a text file it only contains text data means ASCII / Unicode characters.

In CSV file data is stored in rows and columns form (tabular form).

The character that separates values is known as delimiter. Normally CSV files uses a comma to
separate each value but comma is not the only delimiter. We can also use tab ( ‘\t’ ), colon ( : ),
semi-colon ( ; ) or any other character.

The format of CSV file is as follows

OR

Here first row is the header holding the name of the columns and after that each row have a
separate record. We can easily notice that each piece of data is separated by a comma.

CSV files can be opened in spreadsheet as well as in any text editor.


To work with CSV files we need to import CSV library

How CSV file is different from text file.

Text files CSV files

Text files have plain text without any format CSV files also have plain text but in a tabular
format ( rows / columns)

There is no concept of delimiter In csv file each row is considered as a record having
many fields. Fields are the values separated by
delimiter.

Text file can be opened in any text editor Csv files can be opened in any text editor as well
as in any spreadsheet.

Format of Text file Format of CSV file

Writing into CSV file

There are two functions required to write into a csv file.

csv.writer( ) : This function accepts the file object and returns a writer object that can be used to
write into a csv file.

writer_object.writerow( ) : This function is used to insert the record into the csv file. It requires
the record in the form of list or tuple.

for example :
The above program will create a file student.csv at e drive. A glimpse of the file is

Note : There is an empty line (or newline in terms of programming) after each row in the
student.csv file. To avoid this empty line we can override the newline as empty by adding a new
argument newline=’’ in the open ( ) function as follows

The output of the above program


Now the file doesn’t have empty rows after each record.

Sometimes while executing the file creation program again and again we encounter the following
error of Permission denied

The error may have occurred because the csv file is already open and we can’t write in an open
file. To avoid it just close the csv file and try again.

Writing multiple rows with writerows( )

To write multiple rows or two dimensional list we can use writerows( ) function instead of
writerow( ) as follows
The content of the student.csv file will be the same as the above program. The only difference
here is that we are using writerows( ) function which can write multiple rows at a time.

To write a CSV file with any other delimiter like colon ( ‘:’ )

If we want to use any delimiter other than default delimiter that is comma ( , ) we simply have
to mention delimiter argument while creating the writer object using the writer( ) function as
shown below:

Output in student.csv file

We can easily notice that here each field is separated by colon ( ‘:’ ) instead of comma ( ‘,’ ).
Making program Interactive and inserting multiple records in csv file.

Till now we are writing fixed records in the file. The program is not interacting with the user and
always writes two same records whenever we run it. If we want to make our program interactive
it should accept values from the user as well as it should be able to write as many records in the
file as the user wants. To accept multiple records from the user, loops can be used. For example,

The above program will accept the values till the user wants. For this purpose we have taken a
variable choice and accepted the response from the user in ‘y’ or ‘n’ form. Now on the basis of
choice the flow of the program is decided. If the user presses ‘N’ or ‘n’ the if condition becomes
True and break is encountered, which will terminate the while loop for any other value it will
again move to the beginning of the loop and accept values again.

Reading a csv file

csv.reader( ) function is used to read the csv file. It returns an iterable reader object that can be
iterated using a for loop to print the content of each row. The records are read in the form of a
list of lists. The default delimiter is comma ( ‘,’ )

For example :
Note : The file ‘e://student.csv’ must exist in the e: drive of system for successful execution of
above program.

Output :

Reading file with any other delimiter like colon (‘:’)

If we have some other delimiter in place of comma we can still read that file by tweaking the

csv.reader( ) function.

For example :

Suppose we want to read a file having format shown above. In the above file the delimiter used
is colon(‘:’) not comma(‘,’). To read a file having a delimiter different from comma (‘,’) we just
have to pass an additional argument delimiter in the csv.reader( ) function.

reader_obj=csv.reader(file, delimiter=’:’) #here the delimiter is colon (‘:’)

For example :
Searching in CSV files

Suppose we have a student file having records shown above.

Example 1 : In this csv file we are going to search a particular record according to name. so, the
program of that would be look like

The above program looks like reading program except three changes that are

name=input(‘Enter the name of the student you want to search : ‘)

This statement is asking for the name of the student that we want to search in the csv file and
storing that in the name variable.
i[1] == name

In this statement we are matching name with the i[1] value. If we look carefully the student file
has three fields in the sequence Rollno, Name, Percentage.

i [ 0 ] = holding the Rollno of the student.

i [ 1 ] = holding the name of the student.

i [ 2 ] = holding the percentage of the student.

So here name is at the position of i[1] so we are comparing i[1] with name.

If we have to search according the rollno so we can use i[0] = rollno

Or if we are going to search according to percentage we can use i[2]=percentage

else:

print(‘Record not found’)

this else statement will execute if the break is not encountered or we can say if the loop is not
terminated prematurely.

Example 2 :

Now we want to write a program to search and display records of those students who secured
marks greater than 60.

Some of the important points to note in this program are

next ( reader_obj ) : The next( ) function moves the reader_obj to the next record. We are using
this function here because the first row of the student.csv file has column names which should
not be compared with 60. Therefore next(reader_obj) will skip the header row of the student.csv
file.
int ( i [ 2 ] ) > 60 : In this statement we are converting the percentage from string to integer by
type conversion. As we all know csv file stores data in text format therefore to compare two
values we need to convert it into numbers.

flag is simply a boolean variable to keep the status of records (i.e found or not found).

CASE BASED MCQs

Question No. 1

Neha is a student of class XII working on a project ‘student management system’ developed in
python and uses a csv file ‘student.csv’ to store data. Now Neha wants to add a new function
first_division ( ) in this project that will display the name of all those students whose percentage
is greater than 60. The format of the csv file ‘student.csv’ and the definition of first_division ( )
function are as follows.

Rollno,Name,Percentage

1,vikas,80

2,abhinav,40

3,parvez,75

4,sandeep,51

import csv

def first_division( ) :

with open('student.csv') as file: #statement1

reader_obj=csv.reader(file)

______________________ #statement2
flag=False

for row in reader_obj :

if _______________ > 60: #statement3

print ( row )

flag=True

if flag==False:

print('Record not found')

In statement 1 Neha didn’t mention the mode of the file to be opened. Identify the correct mode
in which the file will be open (if we skip the mode) from the options given below.

The file will be opened in ‘w’ mode.

The file will be opened in ‘r’ mode.

The file will be opened in ‘a’ mode.

The program will throw an error because it is mandatory to mention the mode of the file in the
open function.

Ans : B

From the data of the student.csv file shown above it is clearly visible that the first row of the file
has the name of the columns. To find out the records having percentage more than 60 Neha has
to skip the first row because it doesn’t have any record. Identify the correct option for
statement2.

csv.next( )

csv.skip( )

next(reader_obj)

skip(reader_obj)

Ans : C

In statement3 Neha wants to compare the percentage of students with 60. Identify the suitable
option for statement 3.

row > 60

row [ 0 ] > 60
row [ 2 ] > 60

int ( row [ 2] ) > 60

Ans : D

To keep all csv files at one place Neha moved the student.csv file from its default location to d:/
drive. What will be the effect of changing the location of student.csv file.

Moving of csv file doesn’t have any effect on this program.

The above function will create a new student.csv file.

In open function we can only mention the name of the file, not location.

We can change location by statement “with open(‘d:/student.csv’) as file”

Ans : D

In this first_division( ) function Neha has not closed the file. Identify the correct statement

The file is automatically closed when open with ‘with statement’.

The program will throw an error because the file is not closed.

reader_obj.close( ) function can be used to close the file.

csv.close( ) function( ) can be used to close the file.

Ans : A

Question No. 2

Sandeep is writing a program in python to store data of employees working in ACE Infotech in
‘employee.csv’ file. While writing the program he is facing some problems. Help Sandeep to sort
out the difficulties.

def create_file( ) :

file = open ( ‘ employee.csv’, ‘w’ )

writer_obj = csv.writer(file)

writer_obj._______________ #statement 1

employee_id=input(‘Enter employee id : ‘)

employee_name=input(‘Enter employee name : ‘)


employee_dept= input(‘Enter employee dept : ‘)

contact_no=input(‘Enter employee contact no : ‘)

record=__________________________ #statement 2

writer_obj.writerow(record)

After successfully executing the code, when sandeep opened the ‘employee.csv’ file he noted
that there are empty lines after each row. Identify the suitable options to avoid these empty
lines.

file = open ( ‘employee.csv’, ‘w’, newline=’’ )

writer_obj = csv. newline=’‘)

writer_obj= csv.writer(newline=’’)

writer_obj=csv.writer(file,newline=’’)

Ans : A

Before writing the actual data in the file Sandeep wants to add a row that should have the header
or column names of the field. Identify the suitable statement for blank space in statement 1

writeheader ( [ ‘Employee_code’ , ’Name’ , ’Department’ , ’contact_no’ ] )

header ( [ ‘Employee_code’ , ’Name’ , ’Department’ , ’contact_no’ ] )

writecaption ( [ ‘Employee_code’ , ’Name’ , ’Department’ , ’contact_no’ ] )

writerow( [ ‘Employee_code’ , ’Name’ , ’Department’ , ’contact_no’ ] )

Ans : D

After executing the code successfully Sandeep noticed that every time when he runs the program
the previous data stored in the ‘employee.csv’ file disappears. How he can preserve the previous
data from disappearing.

By using mode ‘a’

By using mode ‘b’

By using mode ‘w’

Sandeep has to manually copy the data from ‘employee.csv’ to some other file because in python
every time we run a program to write on a file python creates a new file.

Ans : A
In statement 2 what should be the data type of variable record to write data successfully in
employee.csv file.

List

Tuple

Both A & B can be used

None of them

Ans : C

Sandeep didn’t close the file. Identify the suitable option to close the file.

writer_obj.close( )

csv.close( )

file.close( )

There is no need to close the file in this case as python will automatically close the file and doesn’t
have any impact on student.csv file.

Ans : C
Question No 3

Parvez is a class XII student working on a program to read and write on student.csv file. The
format of the student.csv file is as follows. (note the fields in the file are separated by hash(‘#’) )

Rollno#Name#percentage

1#vanshika#82

2#abhishek#48

3#tanishq#58

The program is

import ___________________ #statement 1

def create_file( ) :

with open ( ‘student.csv’, ‘w’ ) as file :

writer_obj = ________________ #statement 2

writer_obj.writerows(____________) #statement 3

def display_file( ) :

with open ( ‘student.csv’, ‘r’ ) as file :

reader_obj = _____________________ #statement 4

for row in reader_obj :

_________________ #statement 5

Identify the suitable code for blank space of statement 1

csv (comma separated values)

hsv (hash separated values)

#sv (#separated values)

We can’t use any other separator except comma( ‘,’ ) in csv file.

Ans : A
To create a file in which values are separated by ‘#’. Identify the correct option for statement 2

csv.writer(separator=’#’, file)

csv.writer(delimiter=’#’,file)

csv.writer( file, separator=’#’)

csv.writer(file, delimiter=’#’)

Ans : D

Identify the correct option for blank space of statement 3

[ [ ‘1’ , ‘vanshika’ , ‘82’ ] , [ ‘2’ , ‘abhishek’ , ‘48’ ] , [ ‘3’ , ‘tanishq’ , ‘58’ ] ]

[ [ ‘1’ # ‘vanshika’ # ‘82’ ] , [ ‘2’ # ‘abhishek’ # ‘48’ ] , [ ‘3’ # ‘tanishq’ # ‘58’ ] ]

[ ‘1’ , ‘vanshika’ , ‘82’ ] , [ ‘2’ , ‘abhishek’ , ‘48’ ] , [ ‘3’ , ‘tanishq’ , ‘58’ ]

[ ‘1’ # ‘vanshika’ # ‘82’ ] , [ ‘2’ # ‘abhishek’ # ‘48’ ] , [ ‘3’ # ‘tanishq’ # ‘58’ ]

Ans : A

Choose the suitable option to read a file having values separated by ‘#’ for blank line in statement
4

csv.reader(file)

csv.reader(file, separator=’’)

csv.reader(file, delimiter=’#’)

csv.reader(separator=’’, file )

Ans : C

Now Parvez wants to display only the names of all students from the ‘student.csv’ file. Identify
the correct option for statement 5

print (‘Name’)

print ( row [ ‘name ‘ ] )

print ( row [1] )

print ( row [2] )


Ans : C
Question No 4

Tata Technical Services is hiring students for their new project. To shortlist the candidates they
have provided the following incomplete code related to csv files and written in python to all the
candidates. On the basis of this code they have some questions for candidates

1. ________ csv #statement 1

2. def create_file( ):

3. ________ open( 'e:/student.csv' , 'w' , newline='' ) as file: #statement 2

4. write_obj = csv.writer( file )

5. lst = [ ]

6. while True:

7. rollno = input ( 'Enter rollno : ' ) #statement 3

8. name = input ( 'Enter name : ' )

9. marks = input ( 'Enter marks :' )

10. record = [ rollno , name , marks ]

11. lst.append ( record )

12. choice = input ( 'Do you have more records (y/n) : ' )

13. if choice == 'n' :

14. break

Write suitable option for blank space in statement 1

add

include

import

from

Ans : C
Write suitable code for blank space in statement 2

file =

with =

file

with

Ans : D

Identify the correct position of write_obj.writerows ( lst ) function.

after line no. 11

after line no. 14 inside while loop

after line no. 14 outside while loop

after line no. 14 outside with open block

Ans : C

If we replace the statement 3 written in the above program by the statement given below

rollno = int ( input ( 'Enter rollno : ' ) )

what will be its effect on the program and the file.

The statement rollno = int ( input ( ‘Enter rollno : ‘ ) ) will throw error because we can't accept
rollno as integer.

The statement record = [ rollno , name , marks ] will throw an error because we can't mix numbers
with strings in a list ( all values should be of same data type)

C. It will write rollno into the student.csv file in integer format.

D. It will not have any effect on the file.

Ans : D

5. Identify the keyword which is used here to terminate the loop prematurely.

append
choice

True

break

Ans : D

Question No. 5

Shubham of class 12 is writing a program to create a CSV file “user.csv” which will contain user
name and password of all the users. He has written the following code. As a programmer, help
him to successfully execute the given task.

import ________________________ # statement 1

def addUser ( username , password ) :

file = open ( 'user.csv' , ' _______' ) # statement 2

file_writer = csv.writer ( file )

file_writer.writerow ( [ username , password ] )

file.____________( ) #statement 3

def displayUser( ):

with open ( 'user.csv' ,'r' ) as file:

file_reader = csv. _____________( file ) #statement 4

for row in file_reader :

if row[0]== ‘man#22’ :

print ( row )

addUser ( “vikash” , ”vikas@123” )

addUser ( “manoj” , “man#2022” )

displayUser ( ) # statement 5

1. Identify the module required for blank space of statement 1.

a) CSV

b) Csv
c) csv

d) All three are correct

Ans : C

2. Write mode of opening the file in statement 2

a) r

b) w

c) both A & B can be used

d) both are incorrect.

Ans : B

3. Identify the correct option to close the file for statement 3

a) quit( )

b) exit ( )

c) break ( )

d) close ( )

Ans : D

4. Fill the blank in statement 4 to the read the data from csv file

a) read

b) reader

c) readline

d) readlines

Ans : B

5. Identify the output after execution of statement 5

a) [ ‘manoj’, ‘man#2022’]
b) [ ‘man#2022’, ‘manoj’]

c) ‘manoj ‘, ‘man#2022’

d) Nothing

Ans : D
CONTENT DEVELOPMENT TEAM

SNo Name of the Teacher Name of the KV Content to be developed

1 Ms. Sarita Yadav DL Meerut Revision of Python I

2 Ms Minu Singh Hindon No 1 AFS Revision of Python II

3 Ms. Kirti Gupta NTPC Dadri Functions : Buit in functions defined in


module

Flow of execution Scope of a variable

4 Mr. Roopnaryan Muradnagar Functions: user defined functions,


arguments and parameters, function
returning values

5 Mr. Hargovind Jhansi No 2 Introduction to File,

Types of files

6 Ms. Namrata Gokhale Bulandshahr Text File

7 Mr. Naveen Yadav PL Meerut Binary File

8 Mr. Huma Naqvi Greater Noida CSV File

Content Compilation by:

Ms. Meetu Singhal


PGT (Computer Science)
KV No 3 Agra

You might also like