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

1.

3 1)]
29 conditional when the (Term
Python various andChapter
of
statement.examples
the
in
condition. following statements
lafter
component-book only OTQ5 2021
Pythoncomputer.
In
Progress revising
compound Some ais
statements.
loop
statement
Paper
mark12
(d)
while test the the [CBSE
with of of
header. of loop. _2(d)
at Science the and formend restthe
under and iteration the
XI. loop the the to
aimed practical on action.statementthe if.elif..else. in theof
CONTROL
FLOW Class it >>>*<<< below counting in
loop
over overiteration
1.3 doing
Computer are executed
of passes skipping
STATEMENTS
is in kind unit. body repeatedly the QUESTIONS
CHOICE
MULTIPLE
learnt
session the PriPpractically single
etc. and a in is in.
appearsnext Day_two
(c)
check in any aas indentedif.else is loop entryloop
control
section
(c)
executedstatement
statement, by the
you in there perform
performed over loop
PriP' Progress for a the it of
COncepts Pleaseit an -
forms The control of
clause and loopthebeginning
to empty andwhile
statements ?
variable :following
fill while. immediately of
very iteration
This computer
header manybe
statement, a else
:types to and has the the
of a in instructionsit The
for terminatesto
current (b)
2nd_day
invalid
will wil) break the if as too. control
a a it is, outer thesegrouphas the break
(b)
if statement-
ifbreak
statement loop loop loop
of
example "')
loop to
given a
functions, constructS clause terminateathe
Python
entry-controlled
QUESTIONS
TYPE
OBJECTIVE from
looploop the
inner of
statement transfers an
TOUR
REVISION
Chopter ): the one represeniS of abandons
=
i end very loop, instructions of selection
set else is identifier
break on a looping
: (1,
6) theinner however,
outer statement
: normally. break.
containing
terminates
loop statement immediately following
an range(1,
("",
range theThat inside
in.appears outer terminate.
wiloop
l REVISE
USLET be are
can statementstatements
one
allow have
can breakstatement
is loops, the statements that two an can statement my_day_2
(a) invalid
) following
PYTHON print terminatetheand in compound provides provides is Python a
loops, the
nestedin inj
loop
for
)print(
nested
ed
statement isstatement
is
only
terminate
continue.
If are
Stotements
Compound
compound
statements loop
whilein
continue
It
break nested loop-body. of the
(a)
name
i .Duthon Python Puthon Which
for then .Cuery
The loop.The Loops The Find
The Inwill A In The
A d & d d 1. 2.
30
16. 15. 14. 13. 12. 11. 10. 9. 8. 7. 6. 5. 4. 3.
Which Which Which The What Evaluate What How Which Which Which
(b)
Which Which Which float(12')(a) <<,(a)>> 8/(4/2)(a) (a) 17 0.(a0) (a) 14 x^y(a) eval(a)
(c) (a) @Boolean(a)
print("hello\example\
test.txt")
(a)Selectalofprint("hello\"example\"test.txt") (c) (a) Lists(a)(a)_init,
expression is will Would of of of
Dika Mina Eina two value
of hello\example\test.txt of of among the
\nDika'\nDika'"")
) \nMina
inaDika'"")
print('print('""Eina the the +, the be these the the
the -,
the operators type
valueexpression
the you following following
following following following **, the is
function 8/4/2 of value write not
does %,
following
1, x
can ?
four expressions
statement
int(12)(b) (b)**<<, (8/4)/2(b) wil (b14
) (b) given
(b)27 ofx**y(b) 0 r (b) core a cannot
(b)in assert(b) is
calls (b) % be Stringinput(
(b) the Dictionaryin not
>>, list evaluate X= Python an
as data
code used below expression be a
that ) int keyword?
return | of type a
fragments on prints operators equivalent (13.25 variable
result results if
numeric ? ?
in the + A
= ?
in 4/2) 16 expression ?
this shown has 14 ?
wil values
(c) +
print("hello"\example"\
I(nct) test.txt")(d) () float(12.5')(c) an (c) | to (c15
) 1.(c0) and (c)12 +x^^y(c) Tuples(c) (c) itnonlocal()
output yield the which 13
print("hello\ output error B=
highest %15
in ? 15.
(d) following Python of
below the COMPUTER
Dika') Mina
print('Eina precedence following %B//A A
? \example\
output ?
(d) # Float(d) int(12.5')(d) (d) % (d)23 (d) 1 (d) 0 (d) Class(d) (don
) pass(d) SCIENCE
? ?
expressions none
\test.txt")
of WITH
these
PYTHON
:

X11
double
the loop
corret i)| 1| loop.
31 (Term (Term (Tem language.
by the sets
of
automatically the of
the2021 1202 2021 iteration
following
be Paper Paper Paper programming three
by
will types. go.
(CBSE |CBSE [CBSE next one
(d) followng
and and
(d) done statement
"Three") marks
or
the integer. in
by calledis causes same.same. loops
the ? type the
Python "Two", specified called to quotation
of to and the the
converted nested
are data QUESTIONS
TRUE/FALSE
I'ytho whch ("One")
(d)
("One", is
over
is is
COME
()ECM in BLANKS
a calledtypePython. statements
as placevalue's 4/3*(4-2)
4/3*(2-1) the
"WELCOME", (d) operator as jumps single
of
n ()
or known role in specific is all
operator is name.
? (b)
()
< x (2**2)**3. terminates
Python and changed
a it in and loop variable data.
THE of intervention, and and clause.
Logical is meaning statement
loop variable three
sets
a
conversion for
anthmeic in IN program to the 4/(3*(2-1)
4/(3*(42) clause.
as:
once.placeholder
ass= be operandthe of the else
incorrectTuple FILL
cannot evaluated statement
special of rest as
empty that has else
l'ython a programmer's rest by
valid a in when the used impliesexpressions
only
in not values an the skips expressions surrounded
be statement
have
?(b) an (b) unit having
TOUR
REVISION
YHONis in? Is is of an be
is a
assigned break
print(E||:2|) following a
individual
expression, is skips
conversion cannot 2**2**3 is also
tollowing declaraton following called whose statement statement int(x) variable
word statement a
if can loop,
without the the marks.
quotation
be only
also expression expression
the given WLOE (c) the the3) a typesPython to
take
place. of of string
can can a loops
WEL
(a) 2, (10,
)() smallestis explicit valuevalue Python,Python, nested
is 10.
Python's Variables
of of (a) of (1,
of not token data compiler Python
Whih (a) output
1/ Which Which(a)
a
For The The aIn The The
7. 9.
The The The The The In In
a
In
Ihopter A 3.
A 8.
A 5.A
17. 18. 19. 20. 1. 2. 4. 5. 6. 1. 2. 3. 4. 6. 7. 8. 9. 10.
Chopter I PYTHON KEVISON IOUR
37

GLOSSARY
Blck Agroup of consecutive stolements having same indentaion level.
Ceercien lmplicit Type Conversion.
Constent Adato item that never changes its volue during o progronm run.
Explict ype Conversion Forced dalo type conversion by the user.
Eipty stutement A staBement that appeors in the code but does nothing.
Identiier Nome given by user for a part of the program.
lmplicit Type Conversion Automatic Internol Conversion of dala lype (lower to higher type) by Python.
Aeyword Reserved word having special meaning and purpose.
kevical Unit Other name of loken.
titeral Constont.
Operotor Syrnbol/word that riggers an action or operaBion.
Token The smallest individual unit in a program.
Type Casting Explicit Iype Conversion.
Variable Named stored localion whose value can be manipulated during program run.

Assignments
MULTIPLE CHOICE QUESTIONS

1. The numbered position of aletter in a string is called


(a) position (6) integer position (c) index (d) location
2. The operator tells if an element is present in asequence or not.
(a) exists (b) in (c) into (d) inside
3. The keys of a dictionary must be of types.
(a) integer (b) mutable (c) immutable (d) any of these
4. Following set of commands is executed in shell, what will be the output ?
>>>str= "hello"
>>»str[:2]
>>>

(a) he (b) lo (c) olleh (d) hello


5. What data type is the object below ?
L= [1, 23, 'hello', 1]
(a) list (b) dictionary (c) array () tuple
6. What data type is the object below?
L=1, 23, 'hello',1
(a) list (6) dictionary (c) array (d) tuple
7. To store values in terms of key and value, what core data type does Python provide ?
(a) list (b) tuple (c) class (d) dictionary
8. What is the value of the following expression ? 3+3.00, 3**3.0
(a) (6.0, 27.0) (b) (6.0, 9.00) (c) (6, 27) (d) [6.0, 27.0] (e) (6, 27
9. List AL is defined as follows: AL = [1, 2, 3, 4, 5]
Which of the following statements removes the middle element 3 from it so that the list AL eaualk
[1, 2, 4, 5) ?
(a) del a[2] (b) a[2:3] = |] (c) a(2:2] =| (d) a[2] =[] (e) a.remove(3)
10. Which two lines of code are valid strings in Python ?
(a) This is a string (b) "This is a string' (c) (This is a string) (d) "This is a string"
11. You have the following code segment : String1 = "my"
String2= "work"
print (Stringl + String2)
What is the output of this code ?
(a) my work (b) work (c) mywork (a) my
12. You have the following code segment: String1= "ny"
String2 = "work"
print(String1 +String2.upper())
What is the output of this code ?
(a) mywork (b) MY Work (c) myWORK (d) My Work
Chapter
The15. The14. The13. 18. 17. 16. 15. 14. 13.
12. 1 . The10. The 9.The 8. 5. Operator
Using 7. 6.TheOperator
4. 3. 2. 1.
Which Which What Which 2
Creating
Creating Part Strings Suppose Identify (d) (c) (b) (a) Line3(a) "7(a") (a)
print(T[1)
print(max(T)) (a)
() dictionary(a) PYTHON
of Day Day Day Day "one"
is
is line line
are a in L= (num[3][O]) print
4. 3. 2. 1. >>> the
a the = = = = the
not string Python tuple ('Mon', of output + of
individual tuple a
function (l'monday,
valid (1;Monday'
[1:Monday, , correct
(1:'Monday' (num[o])
print num code int 'two' REVISION
functionmethod
function statement
function operator , (num[5]) print code
function,
mutable = ("3"
from T [5, will of
containing when when store isdeclaration
'23', form + produces TOUR-II
this
returnsreturnsreturnsvalues removes is when declared 4,cause "4")
can
a usedto you while used used their 2'tuesday' ,
2;Tuesday' ,
2:Tuesday', Line
(b) 2 "34"
(6) (b)
set string(b) 3:wednesday'
2:Tuesday' )]
, of 3, code
remove 'hello', [2], 1+ an
all from of can used some with with of declaration an
all all all ists individual as ? error 2
values remove make T L: 1] error
thevalues the a with
contiguous atwo FILL
=(10, 3'wednesday' }
keys
the an
string are. 3;'wednesday'
3:'wednesday'
) )
Key tuple's '60.5'] ? ?
elements
is a a strings, IN of
from in calledindividual antruelist/string letters 12,43,39),
value : item and THE dictionary
elements
a characters (c)34 (c)
Key
dictionary. copy gives in print(len(T))(d) (6) tuple(c) Line(c) 4
of from an "one"
pairs aitem
BLANKS T[2]which
: of and integer Memory
value list/dictionary.
is a ?
as an
or alist. a concatenated = +
called list/dictionary. from -29 of "2"
(key, pair a slice
gives
integer, in the
the
value) of an following
a from
dictionary. replicatesstring erTOr.string.
location. Line(d) 1 (d)24 (d)
a list(d)
equences. list. is '1'
Sample
(CBSE
Paper (CBSE +
called is
incorrect 2
the Sample
list/string.
Paper
?
2020-21] 2020-21) 77
COMPUTER
78 SCIENCE WITH
TRUE/FALSE QUESTIONS
PYTHON - X
1. Do both the following represent the same list".
('a', 'b', 'c']
['c', 'a', 'b']
Z. A list may contain any type of objects except another list.
3. There is no conceptual limit to the size of a list.
4. Allelements in a list must be of the same type.
5. A given object may appear in a list more than once.
6. The keys of a dictionary must be of immutable types.
7. You can combine a numericvalue and astring by using the + symbol.
S. The clear( ) removes all the elements of a dictionary but does not delete the empty
9. The max() and min( ) when used with tuples, can work if elements of the tuple are all of the
10. A list of characters is similar to a string type.
dicsametionartyype..
11. For any index n, sl:n] + s[n:] will give you original string s.
12. A dictionary can contain keys of any valid Python types.
AsSERTIONS AND REASONS

DIRECTIONS
In the following questions, a statement of Assertion (A) is followed by a statement of Reason (R).
Mark the correct choice as :
(a) Both A and R are true and R is the correct explanation of A.
(b) Both Aand Rare true but Ris not the correct explanation of A.
(c) A is true but R is false (or partly true).
(d) A is false (or partly true) but R is true. (e) Both A and R are false or not fully true.

1. Assertion. Lists and Tuples are similar sequence types of Python, yet they are two different datatpes
Reason. List sequences are mutable and Tuple sequences are immutable.
2. Assertion. Modifying a string creates another string internally but modifying a list does not reate a
new list.
Reason. Strings store characters while lists can store any type of data.
3. Assertion. Modifying a string creates another string internally but modifying a list does not create a
new list.
Reason. Strings are immutable types while lists are mutable types of Python.
4. Assertion. Dictionaries are mutable, hence its keys can be easily changed.
Reason. Mutability means avalue can be changed in place without having to create new storage
for the changed value.
5. Assertion. Dictionaries are mutable but their keys are immutable.
Reason. The values of a dictionary can change but keys of dictionary carnot be changed because
through them data is hashed.
6. Assertion. In Insertion Sort, a part of the array is always sorted.
Reason. In insertion sort, each successive element is picked and inserted at an appropriate position
in the sorted part of the array.

NOTE :Answers for 0TOS are given at the end of the book.
arguments).
ambiquity arquments Global to
definition,
arquments), statement.individual
as
known Enclosing,
reverted OTQS explicitly
? list
avoidng call function. parameter
actualformal be
function function environment.
is
accessed cannot
thereby or call of Local, value
null
(d)
or (Required
parameters number its
parameters the the function in declared
itglobal, and
time, in in order: variable any
main defined parameter. parameter equal function. be can global name
aot actual arquments the return
fornmal in or variable) the globalfrom ?
with as as variable in header
passed non-fruitful function. MULTIPLE
CHOICE
QUESTIONS function
dealtprogram)(or arguments default that environments not 1)value
return
(or Positional
arguments for (e.g., the used is
is parameters being tuple identifier doesdouble
(c)
value.program provided program. hides be caller function
(main a value scope. to both
of as values a or variable,
called (i) order known statement. in checks is an in that
a
returns the statenments called arquments. is function. function
received functions. data variable
once (b)
parameters valueassigned local value
of and that function the
part are is None. a or
it global
often statement
are number header coll no be non-voidvoid offunction code or i.e.,
a
code-block
i.e.,
mentioned of in
Smalltop-level naned) if cither fruitful scope rule, change present
and
data definition/header
:arguments only
function with as value
of a afor
a funciion-call the junction considered can arguments known
other piece globalLEGB
of
that
only frame. a empry the the
with (or match
matching. that is asknown values.
affects QUESTIONS
OBJECTIVE
TYPE value are
Keyword the the
on as value. value particular as
FUNCTIONS acts
easiersegment
execution
in values is
valuelegalany be using namethat in (b)
int items
formal must in non-emply either undone
function
in are invoke return
valueskipped
function named
a also name arguments/parameter
multiple
thathandiing athrough return multiple returns only
subprogram
of (1)statement
argument parameters
are
areturn
a can
same
be followingonly
WITH REVISE
USLET the an
namesexeCuted the and
program passed
types
argumentS
de<ault
be
can are
the not
a valuenot internally
return
can which
program scopes
a
of
scope
the a cannot return
tells
having
default namelist
WORKING in three
received
call
positional
having
may returns
for argumentsalso returning does
in
part(s) broadly statement
statenment
alobal
The also
parameter
NG Python function argument
values the the the function
ais being supports or
nay may that that function a resolves variable None
(a)
A make is
Function can ofMutability of
defoult.Function norameter in program 3 What
is
.Enctions vouesvalues Default the default function function
function function function Python,
Functions alobal namespace.function Which(a) ()
Chopter
3 Dthon
the
The .The (i) wWhen .AA The
called
default Kevword
void local
Scope. PythonBuilt-in.
The In The
P A A A A A A A A A 1. 2.
. . d
\xa sniipget (Term (Tern2
PrTHON and
in 2021
scone 2021definition 2021
parameterscode (d)
return
number
parameters val1oe function Paper 25)
Paper Paper =
WITH
given 2
functions Scope. local
scope. Calc(X
(d)
function (d)
an
array call Default function ) 4) [CBSE
the
block
SCIENCE? ICBSE
a [CBSE 4
the d): function a
local in = below =
the
Defaultparameters.
parameters. global d d (d)
in 2, keyword =3,
function
COMPUTER
stores
system
where
of
the
es body: =
2): c to arguments.
parameters.
havevariables? below 3,= the
print("' 1, passing
(c) nc=umber") a in
variable
a 4) c2, invoking 4) c2,
function = in and also in
3,
25)
b, b arguments Positional
Default global the 3, b=
variable 2, = =
1, 1, Positional must 2, b
of = = parameterkeyword Default of invoke1, 1, 1, 1, Calc(Y
beginning
the stack
a(c) the f(a f(a global
a
scope the
without
using = = while = = ?
def
(c) complete order. parameter local scope. test(a
test(a test(a
test(a error
def def
?correct order. of (c)
keyword
of of rightof to
(b) (d) for of a used Error (b)
memory, any and contextright left context of
change
valueof (b) (d) (d) an
25)
true any the the Default value outside
its
cause give
marks
keywords
correctly isheaders
print(number) in in positional
before the be =
area
storage not arguments to to can will Y
arguments in to occur
body is correct
following occur in change
accessed will 15,
() area to occur a usedcalls
define statementswithbe of correct calls calls=
statements
:follows Calc(X
function function must must must right
that to
is
used
positional not must to be function function
4) function
2): function
keyword not
to call?(b) (b) arguments parameters the
parameters usedcan
variables
be cannot d) d) 4)
given
offollowing
=
c is parameters is c, =3, =3, 20): (b)
function f(number):
def Missing
following following
print(f(5))
"number" 1, following to following c,
is
keyword b, c
following b, c as Y= following
name b): =
b passpassacall parameters keyword variablestest(a,2, following
test(a, 2, header
1, 1, 4) = 4) = (X,
the a (a)aheapthe # = = the cancancanPositional Positional
the f(a
Positional 3, 1,b 3, b Calc 25) Calc(15,
(a)
functheof
(a) return f(a the Default the 2, 2, 1, function
Global Global
(c) the = the
Which is
variables one of def def of YouYouYou of functions ?
All of
Local Local def test(1,test(a =
def test(1,
test(a def the
of
(a) (a) (c) Which
What Which of
Pick (a)(0)(c) (d) Which (b) Which Which of
(a) (c) (d)
134
(a) (b) (d) (a) (c) Which (a) (c) a Which
3. 4. 5. 6. For
7. 8. 9. 10. 11. 12,
18. 17. 16. 15 . 13WORKI
ChopteNrG 3
3. 2. 1. 12. The11. 10. 9. 8. 7. A 6. 5. 4. 3. 2. 1.A
The Which What Carefully What What
The
known Non-default A By A
statement. AThe The Pvthon In (L: What (a) ( a)
parameter void parameter Python, arguments
positional
arguments
named(c) (a) BGEL (a) (a) 8 indentation
hello2(c) Error(a)
first default default, valuesvalues Local is A is A is
of is def static static
a a
as function
arguments names the
print_double(x):
print_double (3) the
def >>»function1 ("hello") observe variable variable
function
lin e is
a namespace,
the
Python
argument receivedbeing program order function1(a):
+'1'=aa
arguments
of valuerefers having given print result variable variable
having subprogram the WITH
function also a
for to passed of (2 of = th e defined defined
header. are top a FUNCTIONS
names can
default in
execution argument resolving
E ** this * code
default tahe returns
the level 2
can parameter order the (6) :
Enclosing (b) 6 *) code () (6)
definition be through
and inside outside
the named function L A A
value be a
skipped value segment that global global
placed segment in begins acts types E scope perform
(d) (b)
?cannot give
TRUE/FALSE GB hello2hello2 a
QUESTIONS which arguments a FILL namespace, function all
that in is definition/header in
function-call on can the
variable
in of variable the
before defined value the the with(main data IN a answer.
begins the statements with be name functions
function function function THE
first
program) and skipped referred
or top-level
in to with (c) (c)
with its BLANKS
arguments
arguments keyword
default
(d) (b) GEBL (c) B: in (c) 4
after function statement
statement often Built-In a mathematical A A
header are caller.assigned header local referred
local
keyword a cal l from Python to
default statements
executed are as
returns as
statement. called a
Namespace, variable variable
is values known is are of function program to
defknown
argument called a as
during value. operation
stringson ?
and (main bcing
as segment. call BEG (d) LG: ? (d10 ) (d) (d)
ends as a
a in program) a passed ? Global An An
default a program
withdefinition.
function automaticautomatic
a in namespace)
parameter.
colon run. as th e
function variable variable
(:
), 135
is
also call
any
Questions
Selected withou
accessed. forSolutions Code
QR
Scan
progr
argument.
be
For
QUESTIONS
con
as:")
an
as
it
to

variable)
(e.g.,
QUESTIdesiON
a
than
"goes passed
value
value.
st, was data
:")) statement.
run.whicha
bet
value", returns a
:"))
init+3*step
series
program or
value code
series call often
"&step
AP a the
function of
during and piece
the to
AP
init+2*step,
of theini,
referdata
the statements particular ANSWE
value value", in to on
of st)
tunctionfunction
acts
value a
initial retSeries(ini, which
init+step,
stepinitial
of
a execution
a
thot
subprogram
SHOR
to inside in
(input("Enter
("Enter t4) provided part(s)
with
t3,
of used Parameter
Parameter
Formal
Argument
Argument Parometer
Program A:
init, order
=
print("Series
t4 t2,
int(input value name Named TYPE
return
int
t3,(t1,
t2,
GLOSSARY
The
AA
execution
ofFlow Actual Argument
Argument
Actual Formal
Parameter
Assignment
= print
ini= t1,
st
ArgumentParameter
Function
Scope
Nove
numeric |CBSE
Sample
Paper hs
number
value)
empty a
is other
in
variable
val. n
ana
with in
2
1unbers
nun
along =
n
1],
173
USING PYTHON LIBRARIES

wo forms of import statements


There are <modulenome> las <aliasname>] (i)from <module> import <object>
(0import needs not import any module for them.
buil-in functions of Python are always available ; one
The
random module of Python provides random-number-generation functionality.
The
useful constant strings and a utility function capwords().
string module of Python offers many also has a special
4 The
create Own package, it should be created sothat it has a folder having its name and it
In order
to
current Python installation.
file_init-pyinit. After this, it must be attachedtosite-packoges folder of comnand.
instaled lor attached to site pockages folder of Python instollation can easily be importedusing import
Apackage
*
OBJECTIVE TYPE QUESTIONS OTQs
MULTIPLE CHOICE QUESTIONS
can
particular task and
Fle containing constants/variables, classes, functions etc. related to a
1. A py programs is called
be used in other (d) documentation
(a) module (b) library (c) classes
applications or
The collection of modules and packages that together cater to a specific type of
2. requirements, is called
(c) classes (d) documentation
(a) module (b) library
independent triple quoted string given inside a module, containing documentation related
2 An
information is a
(a) Documentation string (b) docstring
(c) dstring (4) stringdoc
displays from a module.
A The help <module> statement (a) docstrings
(a) constants (b) functions (c) classes
with the imported object name ?
5 Which command(s) modifies the current namespace
(a) import <module> (b) import <modulel>, <module2>
(a) from <module> import *
(c) from <module> import <object>
namespace for each of the imported module ?
6 Which command(s) creates a separate
(a) import <module> (b) import <modulel>, <module2>
(a) from <module> import*
(c) from <module> import <object>
floating point number ?
7. Which of the following random module functions generates a (d) all of these
(a) random( ) (b) randint( ) (c) uniform( )
?
8. Which of the following random module functions generates an integer(d) all of these
(a) random() (b) randint( ) (c) uniform( )
?
9. Which file must be a part of a folder to be used as a Python package
(9) packagepy (b)init -PY ()_package-py (a)module-py
extension.
10. A Python module has
(a) mod (6) imp (c) -py (d) .mpy
in Python ?
11. Which of the following is not a function/method of the random module [CBSE Paper 2021 (Term 1)]

(a) randfloat( ) (b) randint( ) (c) random( ) () randrange( )


d aor 6.
USIt IS
What 5.
4hopter 3.
éa prg
namesa aæ. can defaut :imp current
documeraimporting
th triple-quoled det ue
then program library, program
Pytimpa (, fuly function program's
by the
Reason statement
and full.
not as
displayed the Pythonavailable into
definitin
the importable
or
of current
lalerments
in of Both
R
false statement,
all
its items
of module isby
slatenent in namespace
extension. the <item> standard
COMPUTER
SCIENC of
other type namespace are written made the imported
definitions,
are
an A. do
of
and spectic is a a and
(e)
A that
Reason. part import into book.
it to
in import of
A explanationbe
are
files ile
Python program. the the
init_pyREASONSAND
AsSERTIONS explanation should
current followed of items
library to QUESTIONS
TRUE/FALSE
same..py import
become
<module>modifies of functions the
the
BLANKS calerclass module. samethe uscd
variables, item. part bring
holdingtogether module. module
in
import of
the in
everything (A) correct stringsthrough the notstatement. arename. end
have package.<objccts> Assertioncorrect
the
means i.e., is command
imported
from built-in import
identically.
THE
folder that containing file
thetrue).truc. Python
in
issucd.available
which to
module statements the
module
module special triple-quoted definitionsthrough <modulc>
IN modules of
P'ython
imports import the not is
module <module> the library's
functions, at
FILL the of partly import work given
partpart of a1.
of package. Python awith
Pylhon statement is is R
but for command is made with
imported their
part file) <module> R R
and but (or true) documentation
(-py thethe
collection a
stalement a2. module' from
of
filesalong
is
are are import s along<module> built-in standardtwowhich
specifying are
the importable task. isfunction trueIruefalse program.
offers and
file isfunction aandaand py files
particular aqucstions, partly docstrings etc. it.
to 0TQs
from<module>import,
be
must a program having.py
program<module> from as
are are is <module> constants an is name
having choice lR Imported item
through Python's
fromimported
item
the Python'sPythonimporl
ato is
refers capwords(
uniform() andR
R
andbut (or After module without for
) slatement following truc false The
The
an a
of
astreated a folder correct A A helpAssertion. IfAssertion. The BothAnswers
to
Python
A
3. Pythoninport
Python
2. folder DIRECTIONS Both Bothis is Asserlion. imported
variables, Assertion. namespace
Asserlion.
file
The
| related the AA when Reason. theReason. usedReason. Reason.
le TheThe TheAny The the Mark(a) () (c) (d) use
A A A be :
174 4. 5, 1. 3. 4. 5. 6. In 3. NOTE
4. 5.
179 Assignment
Selective

Solutions
Code
QR
Scan
For

ONO QUESTIO
programs.
files.
objects.
special
other
QUESTI
related
somein
used
of
and
grouping
ond
data. subpackages
included
andlogical
code be
holding
and can
of modules ANSWE
grouping that
environment ?
code Mo
containing
independent
LIBRARIES of SHORT
chunk of
logical
sig
directory
PYTHON
GLOSSARY
Named
Named
reusable A:
TYPE
USING AA
Assignmenthe
4: Namespace
Chopter Module Package
Library
IE HANDING
227

93(h) Wte aprogan to ral and display the contents of


Employee csv created in the previs progra
import csv
Iogram
with open("Employee.csv", "r") as fh: See. we did not specify netine argument in
ereader csv.reader(fh) the open( ) s no FOL trunstarion took
place when the fle was creaied
print ("F1le Employee.csv
for rec in ereader : contains :")
print(rec)
The output producvd by the above Progranm is :
Eile Employee. CSV contains :
r'Empno', 'Name
['1001' "Trupti'
'Designation' , 'Salary']
['1002 *, 'Raziya'
'Manager' 56000']
['1003'. 'simran
'Manager'
55900'] See, no blank lines in bethween the
reconds
'Analyst', '35O00']
r1004, 'silvi ya', 'clerk', 25000 1
this time because the csv file was
with no EOL translation.
created
r1005, 'Suji ', 'PR Oofficer
31000']
Wilh this we have come to
the end of this
chapler.
DATA FiLES IN PYTHON

This PrilP session aims at giving you


practical exposure to file Progress ln Python 5.1
Fill it in PriP 5.1 handling in Python.
in under Chapler 5 of
Computer Science witlh Python afterpractical
component-book
practically doing it on the - Progress
computer.
LET US REVISE
Afle in
A The data itself is a bunch of bytes
files can be stored in stored on some storage
e Atext file three ways : () Text devices like hard-disk,
with a stores
special information
in ASCIl or files (ii) Binary files thumb-drive etc.
character Unicode
place when this EOL known as EOL (End of characters, where each (iii)
line
CSV files,
4 A binary character read or written. character. In text files
file is just a file is Line) of text is
ie.. the file
content that contains some internal terminoted, (delimited)
that is toinformation in
manipulations
is usedreturned
The open( ) the
you is raw (with no same format in take
A function to opena which the
howfilethe
-modefile governs the type of data file in a
program translation or no information
specific is held in
memory,
Atext file
will be used
and acsv file once operations
it's
opened. (e.g., read / write / through a
file-object encoding).
(or a
o A can append) possible file-handle).
" Thebinary file can be opened in opened in these file
be in the
three file these file modes: opened file i.e., it refers to
4 While
read( ) reading funct ions modes : 'rb', 'wb', 'r,w',
of text files a b',
'a', 'r+,
'w+', 'a+'
) reads some are:
readlines{ reads all the lines from the file and readline( ), (rb+),
bytes read( ), 'r+b'
from the file and returns it as a readlines( w+b'('wb+'), 'a+b'('ab+').
returns it in the form string,of readline( )
)
alist. reads a line at a
time and
8. 7. 6. 5. 4. 3.
Which Which The To Which 2. 1.
To To Some
data ?
(b) (a) (a) r infi.read(all)
st(ar) infi.read(all) Information
WeWe readlines(
(a) read (a) read (e) (ie
(0) open Data files(a) array(a)
of of file ife
can can the the the the of
= = = a
remaining open(file
next
open(r"c:\ss.txt", file th e
writefollowing
write following open(c:\\ss.txt", stored
) c:\ss.bxt following
method line
content
content
on
of =
statement (b)mode w returns lines for a
()ist lin es infi.read(
of (b) ) (b) the "c:\ Toxt
files
() dictionary
format storage (0)
into into infi.read( of \ss.txt",)file appending
"a") QUESTIONS
MULTIPLE
CHOICE
will the "a")
from ofdevice
text atext a is refer file files
not "w")
file file a data,
from file can with
correct to
opened
opened binary
a object we be
+ (c) file Vidco
files
( c) a
? (c) infi.readline()(c) () () (d) (b) use created specific
data object
infireadline( )infi, file file file
(Oite
usingusing a
list
we = = name
? of open("c:\res.txt") open(file programmatically
'w' infi, open("c:\\ss.txt",
use
w+ single
we is
mode.mode. called
characters use =
"c:\ss.txt",
jnfi.radlines infi.readlines
()) (d)) tuple(d) a
"rw")
Binary
filesthrough
|CBSE
PaN: N
(d) "w")
a
list ython
cí to
20. 10 18-g
Whi ch 16. Whic1h5. 14 13 12. 10.
(c) (a) (eWhen
) (d) (c) (b) Which
(a) Which exist
not ?
Which 1.
(c) fi(na) = (a)a+ )
fout fout of When When When When (a)abWhich writeline((a)Whi)ch Which W Capter
of fin of the of
(arfite(
feadli)ne( (d()) Which Which () (b) cont(a) ent Whiopench of(d) (b) (a) Which () 5
= =the the = the of file.? of characters
open("c:
open("c: you you
you you youopen("c:\pat.txt", open(file th e the
function function function
function open("Notes.txt',
open('Notes.txt', F F=F=
='A')F'a') into E= F ce of We WeFILE
following =
open open open open open
following following followingfollowing
following open("Notes.txt', Open('Notes.txt') =open("Notes.txt')
open( itthe open( ofthe can can
is following
Python ? open( following
HANDLING
andathe write
is is is text write
\pat.txt",
"w+*)
\pat.txt", a a a = used used used used 'Notes.txt', 'Notes.txt') "Notes.txt')
file
command file file afile afile"c:\pat.txt", file content
statemnents command mode is
content
for for for rw(4) represents (b) w
writelines( (b) ) to (0 )
readlines( to (0) ) to (b) to
for for not notisa "Notes.txt"
writing,reading, writecharacters( write
write readcharacters( read read oplionis
"w") writing, writing, reading, "r") filein into into
is a
used valid list a all single line a all'w+') ;
are "r+") is 'w')correct ; i a a
if if used statement
opening mode characters the the print(F.write(10) print(F.load(10)printprint text
file text
?
to the the if the the if iftrue
the mode of characters
open file (F. correct ile
file to stringsin
of (F.dump(10))
file regarding opento both ) opened
(d) exists, does file file open ) from read(10) openedusing
(d) (b) (w+
C) (c)r+ (wb c) (c) (c) )
file a does does does writestatement( (readstatement(
c) ) (c) 'ython
fout fout W
the not fin fin a writing writeall( ? readall( ? statement
"c:\pat.txt" not not not file a ile mode.
using 'r
the = =file a )
= = existing exist, open("c:\ results file ? ) )
at.txt",
:\\pat.txt", exist, exist,exist,open(file
?
statement
opening "c:\pat.txt" ? and mode.
'rt'
the ) ) to
a an an generatesan or reading
for fileprogram
new =
errorerror \pat.txt", to
writing is modes "c:\
overwritten file in a read
occurs. occurs. (d) (d)w+ (aw+
) inwritechar(
writefullline() (d) ) (d) )
(d) readfullline( (d) text
iswill
\pat.txt",
read-mode
of None binary readchar( )
increated. "r") [CBSE |CBSE file |CBSE
"wb+")"wb")binary open a error "Notes.txt"
file of display
with an "r+") Sample format Paper Paper
? only these the if
format
the empty 2021 2021 the
new ? Paper does file
in
(Term to (Term
only file. first
file. 2023] write 229
? 1)] )] 10
14. 13. The12. 11.10. 9. 8. 7 6. The5. 4 3.
2. 1. 26. 25.
The The The To To To To To The 24. 23. 22 21 230
The Ale The
character read force write read close seek.file_object
seek(offset,
file_object)
(offset)(d) (c) (b) (a) The (d) (c) (b) What (d) (c) (b) Which (d)
conversion two default correct (9)f (ay (b) (a)Which write((a) Whi)ch () bi(a) nary Which
andPython a all an
seek(offset file seeksIt IttellsIt is The The The The tellsIt It It of offout fout ()returns
types
adgoverns places seeks the of returnsplaces
list the dump( lo ad( pickle csv the t he the = format= the of
that
methodmethod write open file file file-open the the the
of in file mode mode of object.seek(offsetsyntax the the significance ) modul
fol l oe wi n g tfollowing
he the followiopen("c: ng open("cfollowing only
to a file, data entire current of
) module details the
separates an of ofinto write contents file, the [, of file absolute of the file ?
the is byt eent ir e lp at
object picklepickle
binary the
will will files type mode reference_point]) seek( pointer \pat.txt",
content byte pickle
of pickle statement isused about
posi ti o n
pointer optiooutput(
con n funct(b)ions) txt", command
in
open open can of
is ) path the used
hierarchy
the modulemodule contents method used. is is: position at module for the tent at is
files, method the operations
a a be fead of a of seek(
module for athe "w+") "w")
values file file FILL [, the fi le . of of do iS
form the
desired reading is the desireda
of reference_point]) ) reading incorrect
is file. correct you Used
reads writes for for mode. IN file. le
offimethod. is file
in in file may of the used and use to
byte write read filles and (eg. THE offset used offset
csv file and inpointer usage to (b) open
modulebuffer belist. a
data data ? to to writing the dump() open("cl
() fout(d)
filesstreamn used. read/write/append)
and and BLANKS pointer read in write fout a
on within write writing objects as a for file
from into context
is of to read write objects. objects an flthe data - "c\pat
the integer. open("|\pat
called is aPython astorage method used. ispurpose.
within objects tell() in COMPt
JIFD
calledbinarybinary purpose. files. of
Gle in the txt"
the in pickled
isfile, the binary ofbinary \pat
for
file. file. used. binary a
possible Al send)
file (d) txt,
files. binary format) txt writing
Or Papet
ICBSE files.
object
"wb
apeCBSE P wh
methodmay Sampe?CRSE files
in > wol
&..
1. DIMarkRECTIOInNS 18. 17
Reason.
andtab are 15. 14.
Assertion. (d) (c) (b) the automatically
Python
Functions
readline(
10. 9. 8. 7 0. 5. 4. 3.
CSV (a) the The The The 4
The ) 2 The1. 0 10
A ABoth Both following Serialisation
cSv csvdump( Conversion When Whe n lfno The relative
The The The
spectively. The and is is correct load( When When When To The The The Je HANDUNG5
files files you you path t y pes relative
Python false true A
absolute you CSr.wrilerspeci( f).
y
appendingfileDfile translation
you you ile tile cmcsv
CSV TSV A ) open is of
(or but
and andquestions,
choice can function
) of open iles
are function
process an amode mode mode suppress
mode
and files is partly Rare Rare R as text only a
operat
given ionsalwayspatfhorpaths paths opern open open different to to to to delimiter are of
said is object file file a fi le
a a a
TSV also. false true true : a files. take of ))wi th .
), are are file file open open open open atually EOL
totrue) sBatement
picklethe of is for flushes readlines(
for withthe and naremains thatona file
relativea fo r for for
are have the hierarchy alappending,
so file topmostfrom reading,
(or but and comma can
delimiter cSv a afor a a
v binary
csbinary tilescsvis
writing, name
writing,writing,
types butpartly R R AsSERTIONS REASONS
AND pickle called the
broadly carriedoutbe to file file uteofil.
R is is of TRUE/FALSE
QUESTIONS
of is not the as
performs
pickling.
module in if if file in the if the if while for for file file
module pickling. th e the exists,filethe filethe iffile is
delimited true. true). the Assertion delimiter. byte th e buffers
before current reading for text
two correct are file
file file writing reading
correct stream essentially level writing file
types performs exists, does open( the
explanation (A) does
not exist,
does
not as
working by
text (e)
explanation is is file same existing
ofthe into as as as
ofBoth the not then
the well giving
files
followved called closing a the even wel l well well
files unpickling. existing exist, dependdirectory. directory exist,an awriling
of same. the reading
csv isreading
writing
only binary - and A Serialisation. a after file,
of A. by file upon
file error an is
a file new file argument
where R A. must changingstructure. iserror 41. is is
and are statement is file th e
overwritten overwritlen ib:
false is
exist file occurs.occurs. 1
the text close( )
created. in
directory.
: the
mode argumernt in
delimiters files, or of the open(
not Reason
even fully withfunction. current file a with
the is the is
).
are when true. (R). opened used
new directory. newfile.
comma file. with 231
there in.
232

) Assertion. The file modes "T, "w, "a" work with text
COMPUTER
Reason. The CSV and TSV are types of delimited text iles,
CSV files and
3. Assertion. The file modes "r", "w", "a" also reveal files only.
the type of
Reason. The binary file modes have 'b' suffix
with regular fle file these are beinhuse
modes
4. Assertion. Pickling' is the process whereby aPython object
Reason. A binary file works with byte-streams.
5. Assertion. Tickling' isthe process whereby aPython object
hie ra rchy is
converted
hie nto
,ararchy is converted in
Reason. Pickling process is used to work with binary files as a
6. Assertion. Every open file maintains a file-pointer
and
Reason. Every read and write operation takes place keeps
binary file worionks
at track of its posit
the
7. Assertion. CSV (Comma Separated Values) is a file format
for current position ofter
Reason. The information is organized with one record on data
cOmMa. storage which
each line
evey
and each
NOTE : Answers for 0T0s are given at the end of the book

Solved Problems
1 What is tlhe difference between a text file and a binany file ?
Solution, A text file is a file that stores information in the
characters. In text files, each line of text is terminated form
of a
System) known as EOL (End of Line) character. with a stream of
special character
Abinary file is afile that stores the
is no delimiter for a line and no information the forrn of a
in (as per the O
character translations occur here of stream bytes. In
2. What is the difference between read( ) and
readlines( ) function?
Solution. The read( ) reads from afile in read mode, and
stores itscontents
nabinany fle
The readlines( ) function, reads from a file in read in a
mode and
3. Diferentiate betwen the following :
() f= open(" diary.txt','r') (i) f=
retuns a list
stringlyinpeesvinate
ofall
Solution. () File has been opened in read mode with file open('
handle f diary.txt',
'w')
(i) File has been opened in write mode with
file handle f.
A What is the difference between readline( ) and
readlines( ) function?
Solution. The readline()function reads from afile in read
or a blank string if there mode and returns
are no more lines. (The the
The readlines() function, also reads from a ile in
returned data is
read mode and
of
stringatype) next line in
(The returned data is of list type). returns list of all
lines in,
5 What is the difference between writel ) and writelines( )
functions ?
Soluion Both write( ) and writelines() work on text files. The
string type and writes it to the file. The writelines() function, on write( ) function takes ar
the other hand. tkes
(tuple/list/string/a python sequence) as argument and writes it to the file.
6 Write asingle loop to display all the contents of atext file poem.tbxt after
removing leading and trailng
Solution. for line in file("poem.txt") :
print (line.strip())
Assertions True/False
Reasonsand Questions Fil QuestionsMultiple
Choice Assertions
Reasonsand Questions Fil Questions
MulChoitiplcee
) (41.
)
True/False keyword10.
items(15.clear(
)contiguous 1. (a)1. 6.F 1.T casting
type6.Token 1. in (109). 13(.b) (b7.
(a) 1. 7.F 1.F 10. ) 6. 1. in 13.(d) (d)7. ()
Tuples the the
Blonks Blanks
or
Strings lexical
unit 2. 20.(d) 14.(6) (b)8. (d)2.
7.F 2.T
packing11. 2 14.(c) (a)8. (b)2. (c)2.
(c) 2. 8.T 2.F
+

CHAPTER CHAPTER

(b),(13.c) Answers
) 3.+ 15.(c) 9. (c) 3. (d)3. 8.F 3.F keyword
pass 7. 3. (c)9. (a) 3.
(a)3. 9.T 3. unpacking 12. list( 7. 2: 1:
T (a),
(b), PYTHON PYTHON
(e)
o
16.(a) (b),(d10.) 9.T 4.F Immutable
break 8. 4. 16.(c) 10.(b) (b) 4.
10. F 4.F ) string
keys(13.pop( 8.
)slice 4. (a)4.
REVISION (a) 4. Objecive
(d)4. REVISION

TOUR-I| Type
11. T 17.(d) (c)11. (a) 5. 10. F 5.T continue 9. 5. (17.a) (11.b) (d)5.
ToUR
(a)5. 5.T
values(14. ) del 9. 5.* (a)5.
implicit
Questions
type
12. F (d)18. 12.() (h) 6.
(a)6. 6.T 18.(b) (12.c) (d)6. (b)6. conversion

(oT0sl
Questions
Multiple
Choice Assertions
Reasons
andTrue/False
Questions
25.(c) 19. 13.(a) Multiple
Choice
Fil Questions Assertions
Reasons
and True/False
(d) 7. (c)1. Questions Questions
Mult1ple
Choice
(a)1. 1.F _init Fil
(a),
-py 1. in (a),(c) 7. (a)1. (a)7. (a)1. 7.T 1.FKeyword 8.Function
5. 1. 13.() (a)7. (a)1.
in
(d), the the
parameters/formal
(e) Blanks Blanks
26.(a) 20.(b) 14.(b) (c)8. (b),(d)2. (b)2. 2.T library 2. ()8. (b)2. (c)8. (b)2. 8.T 2.T None 9. 14.(c)
2 (b)8. (b)2.

CHAPTER parameters/formal main_ CHAPTER

(21.d) 15.(a)
CHAPTER
FiLE5:
(c)9.(a),(c) 3. (a)3. 3.F module 3. () 3.
9. () (b)3. 10._main__
9.
T 3.T 15.(a)
(b)9. (c)3. 3:
4 3._main
: arguments WORKING
UsING

()
22.(c) 16.(b) 10.(c) 10. F 4.F 11. 16.(a) (a),10.(d) (c)4.
(c)4. (a)4. 4.F random 4. 10.(c) (d)4.PYTHON (a)4. parameter
default 6. 4.
WITH
HANDLING Flow
arguments/actual
of
LIBRARIES Execution FUNCTIONS
11. T 5.T 17.(b) (b),11.(c) (d) 5.
23.(c) 17.(b) 11.(a) (e) 5. 5.T string 5. 11.(a) (c),(d) 5. (a)5.
(d)5. parameters/actual
arguments

12.
headerdefault 7. 18.(d) (d)12. (c)6.
(b) 6. 6.F
24.(a) 18.(b) 12.(a) 6.F (a),(6) 6.
(b)6.
(u)
6. 6. (0)
(c) 12, rec
nfi
F F T 18,
6. 12.
at 14,
delimiler
10.
pickle
or wb+t
19, 5.
(0) (c)
5. 11.
(c)
wt 5. T F
T 17.
11,
5.
RECURSION
6:
CHAPTER
9.
flush(0
13. rb+
18.
serialisation
pickling, ()
4. 4. 10.
(0) ()
N T T10. 16.
F
4. 4.
)writelines(
3.text,
binary delimiter
22.
newline (d)
(6),
3.
(a)
3. (d)
9. 15.
(C)
3. F F
T
8. 17. 9. 15.
2. )readlines(
mode
file 7. Questions
Choice
Multiple
load(
)12.
text
16.
at
21.
True/False Reasons
Questions
2. 8.
F T
and
Assertions
T (a)
2. (b) (d) (d)
2. 8.
14. 14.
Blanks
close()
6. )dump(
11. comma
15. 2
the read
1.
r+
20. 1.(@) (a)
7. 1. 7. 13.
(c) (a) (a)
in 7. T
1.T T 13.
Fill

You might also like