0% found this document useful (0 votes)
888 views

WS 2 Python

This document contains a worksheet with 42 questions on Python programming. The questions cover topics like loops, functions, methods, lists, classes, modules, files, and more. Example code is provided to demonstrate various Python concepts like break and continue statements, selection sort, postfix notation, and more. Students are asked to write Python code, find outputs, differentiate between error types, and more.

Uploaded by

Nandhini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
888 views

WS 2 Python

This document contains a worksheet with 42 questions on Python programming. The questions cover topics like loops, functions, methods, lists, classes, modules, files, and more. Example code is provided to demonstrate various Python concepts like break and continue statements, selection sort, postfix notation, and more. Students are asked to write Python code, find outputs, differentiate between error types, and more.

Uploaded by

Nandhini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

XII- Computer Science New (083)

Worksheet 2- Python

1(17- Differentiate between break and continue statement with the help of an example.
18)
Ans break statement is used to terminate the execution of the loop.
For example:

The output of the above code will be:


0
1
2
The loop terminates when i becomes 3 due to break statement
Whereas,
continue statement is used to force the next iteration while skipping the statements in
the present iteration.

The output of the above code will be:


0
1
2
4
5
continue statement forces next iteration when i becomes 3 , bypassing the print
statement .Thus ,in the output 3 is missing.
2 Identify and write the name of the module to which the following functions belong:
i. ceil( ) ii. findall()
Ans i. ceil( ) - math module
ii. findall( ) – re module
3 Observe the following Python code very carefully and rewrite it after removing all
syntactical errors with each correction underlined.
XII- Computer Science New (083)
Worksheet 2- Python

Ans

4 Write the output of the following Python code:

Ans 14 : 7
8 : 49
5 Write the output of the following Python program code:
XII- Computer Science New (083)
Worksheet 2- Python

Ans ['d', 'o', 'I', 'i', 't', '@', '@', '1', '1', '2', '3', '!', '!']
6 Study the following program and select the possible output(s) from the options (i) to
(iv) 2
Page No. 20
following it. Also, write the maximum and the minimum values that can be assigned to
the variable Y.

i) 0 : 0
ii) 1 : 6
iii) 2 : 4
iv) 0 : 3
Ans i) and iv) are the possible output(s)
Minimum value that can be assigned to Y = 0
Maximum value assigned to Y = 3
7 Write the definition of a function Reverse(X) in Python, to display the elements in
reverse order such that each displayed element is the twice of the original element
(element * 2) of the List X in the following manner:
Example:

Ans

8 Consider the following unsorted list :


[22, 54, 12, 90, 55, 78]
Write the passes of selection sort for sorting the list in ascending order till the 3rd
XII- Computer Science New (083)
Worksheet 2- Python

iteration.
Ans Pass 1: [12, 54, 22, 90, 55, 78]
Pass 2 : [12, 22, 54, 90, 55, 78]
Pass 3 : [12, 22, 54, 90, 55, 78]
9 Evaluate the following postfix expression using a stack. Show the contents of stack
after
execution of each operation:
10,40,25,-,*,15,4,*,+
Ans

10 Nancy intends to position the file pointer to the beginning of a text file.Write Python
statement for the same assuming F is the Fileobject.
Ans F.seek(0)
11 Write a function countmy( )in Python to read the text file “DATA.TXT” and count the
number of times “my” occurs in the file.
For example if the file “DATA.TXT” contains:
“This is my website. I have displayed my preferences in the CHOICE section.”
The countmy( ) function should display the output as:
“my occurs 2 times”.
XII- Computer Science New (083)
Worksheet 2- Python

Ans

12 Evaluate the following POSTFIX expression. Show the status of Stack after execution
of each operation separately: TRUE, FALSE, OR, NOT, TRUE, FALSE, AND, OR
Ans

The result is False


13(18) Differentiate between Syntax Error and Run-Time Error? Also, write a suitable
example in Python to illustrate both.
XII- Computer Science New (083)
Worksheet 2- Python

Ans

14

Ans
15 Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.

Ans
XII- Computer Science New (083)
Worksheet 2- Python

16

Ans

17 What possible outputs(s) are expected to be displayed on screen at the time of


execution of the program from the following code? Also specify the maximum
values that can be assigned to each of the variables BEGIN and LAST.

Ans

18

Ans
XII- Computer Science New (083)
Worksheet 2- Python

19

Ans

20 Write AddClient(Client) and DeleteCleint(Client) methods in python to add a new


Client and delete a Client from a List of Client Names, considering them to act as
insert and delete operations of the queue data structure.
Ans

21

Ans
XII- Computer Science New (083)
Worksheet 2- Python

22

Ans

23

Ans

24
XII- Computer Science New (083)
Worksheet 2- Python

Ans

25 Write a method in python to search and display all the content in the file
CINEMA.DAT where MTYPE is matching with „Comedy‟.

26(18 Differentiate between Run-Time Error and Logical Error ? Also, write a suitable
) example in Python to illustrate both.
27 Name the Python Library modules which need to be imported to invoke the
following functions
(i) log() (ii) match()
28 Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
Num = int(rawinput("Number:"))
Sum = 0
XII- Computer Science New (083)
Worksheet 2- Python

for i in range(10,Num,3)
Sum+=i
if i%2=0:
print i*2
Else:
print i*3
print Sum
29 Find and write the output of the following python code :
Val = [20,"A",40,"K",10,"H"]
Freq = 0
Sum = 0
Cat = ""
For I in range(1,6,2):
Freq = Freq + I
Sum = Sum + Val[I-1]
Cat = Cat + Val[I] + "*"
print Freq,Sum,Cat
30 What possible outputs(s) are expected to be displayed on screen at the time of
execution of the program from the following code ? Also specify the maximum
values that can be assigned to each of the variables START and END.
import random
SCORE=[20,40,10,30,15];
START=random.randint(1,3)
END=random.randint(2,4)
for I in range(START,END+1):
print SCORE[I],"&",
(i) 10&40&20& (ii) 10&30&15&
(iii) 40&10&30& (iv) 20&40&10&
31 Consider the following randomly ordered numbers stored in a list
806, 304, 506, 102, 405, 607
Show the content of list after the First, Second and Third pass of the bubble sort
method used for arranging in ascending order ?
Note: Show the status of all the elements after each pass very clearly underlining
the changes.
32 Write definition of a method Endingwith5(SCORES) to add all those values in the
list of SCORES, which are ending with 5 and display the sum.
For example,
If the SCORES contain [205,506,365,100,230,335]
The sum should be displayed as 905
XII- Computer Science New (083)
Worksheet 2- Python

33 Write AddCustomer(Customer) and DeleteCustomer(Customer) methods in Python


to add a new Customer and delete a Customer from a List of Customer Names,
considering them to act as insert and delete operations of the queue data structure.
34 Write definition of a Method COUNTNOW(REGIONS) to find and display names
of those REGIONS, in which there are less than or equal to 5 characters.
For example :
If the list REGIONS contains
["GOA","NEW DELHI","DAMAN","CHENNAI","BANGALORE"]
The following should get displayed
GOA
DAMAN
35 Evaluate the following Postfix notation of expression :
12,3,/,9,2,*,+,11,-
36 Write a statement in Python to open a text file NOTES.TXT so that new contents
can be written in it.
37 Write a method in python to read lines from a text file INDIA.TXT, to find and
display the occurrence of the word “INDIA” or “India”.
For example:
If the content of the file is
__________________________________________________________________
INDIA is a famous country all over the world.
Geographically, India is located to the
south of Asia continent. India is a high
population country and well protected
from all directions naturally.
India is a famous country for
its great cultural and traditional
values all across the world.
__________________________________________________________________
The output should be 4
38 Which of the following can be used as valid variable identifier(s) in
Python ?
(i) 4thSum
(ii) Total
(iii) Number#
(iv) _Data
39 Name the Python Library modules which need to be imported to
invoke the following functions :
(i) floor()
XII- Computer Science New (083)
Worksheet 2- Python

(ii) randint()
40 Rewrite the following code in Python after removing all syntax
error(s). Underline each correction done in the code.
STRING=""WELCOME
NOTE""
for S in range[0,8]:
print STRING(S)
print S+STRING
41 Find and write the output of the following Python code :
TXT = ["20","50","30","40"]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print TOTAL
CNT-=1
42 Find and write the output of the following Python code :
class INVENTORY:
def __init__(self,C=101,N="Pad",Q=100): #constructor
self.Code=C
self.IName=N
self.Qty=int(Q);
def Procure(self,Q):
self.Qty = self.Qty + Q
def Issue(self,Q):
self.Qty -= Q
def Status(self):
print self.Code,":",self.IName,"#",self.Qty
91 13 P.T.O.
I1=INVENTORY()
I2=INVENTORY(105,"Thumb Pin",50)
I3=INVENTORY(102,"U Clip")
I1.Procure(25)
I2.Issue(15)
I3.Procure(50)
I1.Status()
I3.Status()
I2.Status()
XII- Computer Science New (083)
Worksheet 2- Python

43 What are the possible outcome(s) executed from the following code ?
Also specify the maximum and minimum values that can be
assigned to the variable N.
import random
NAV = ["LEFT","FRONT","RIGHT","BACK"];
NUM = random.randint(1,3)
NAVG = ""
for C in range (NUM,1,-1):
NAVG = NAVG+NAV[I]
print NAVG
(i) BACKRIGHT (ii) BACKRIGHTFRONT
(iii) BACK (iv) LEFTFRONTRIGHT
44 What will be the status of the following list after the First, Second
and Third pass of the bubble sort method used for arranging the
following elements in ascending order ?
Note : Show the status of all the elements after each pass very
clearly underlining the changes.
52, 42, –10, 60, 90, 20
45 Write definition of a method EvenSum(NUMBERS) to add those
values in the list of NUMBERS, which are odd.
46 Write Addnew(Member) and Remove(Member) methods in Python to
Add a new Member and Remove a Member from a list of Members,
considering them to act as INSERT and DELETE operations of the
data structure Queue.
47 Write definition of a method MSEARCH(STATES) to display all the
state names from a list of STATES, which are starting with
alphabet M.
For example :
If the list STATES contains
["MP","UP","WB","TN","MH","MZ","DL","BH","RJ","HR"]
The following should get displayed :
MP
MH
MZ
48 Evaluate the following Postfix notation of expression :
4,2,*,22,5,6,+,/,-
49 Differentiate between file modes r+ and rb+ with respect to Python.
50 Write a method in Python to read lines from a text file
MYNOTES.TXT, and display those lines, which are starting with
XII- Computer Science New (083)
Worksheet 2- Python

the alphabet ―K.


51(dh) Which of the following can be used as valid variable identifier(s) in Python ?
(i) total
(ii) 7Salute
(iii) Que$tion
(iv) global
52 Name the Python Library modules which need to be imported to invoke the
following functions :
(i) ceil()
(ii) randint()
53 Rewrite the following code in Python after removing all syntax error(s). Underline
each correction done in the code.
TEXT=""GREAT
DAY""
for T in range[0,7]:
print TEXT(T)
print T+TEXT
54 Find and write the output of the following Python code :
STR = ["90","10","30","40"]
COUNT = 3
SUM = 0
for I in [1,2,5,4]:
S = STR[COUNT]
SUM = float (S)+I
print SUM
COUNT–=1
55 What are the possible outcome(s) executed from the following code ? Also specify
the maximum and minimum values that can be assigned to variable N. 2
import random
SIDES=["EAST","WEST","NORTH","SOUTH"];
N=random.randint(1,3)
OUT=""
for I in range(N,1,–1):
OUT=OUT+SIDES[I]
print OUT
(i) SOUTHNORTH (ii) SOUTHNORTHWEST
(iii) SOUTH (iv) EASTWESTNORTH
56 What will be the status of the following list after the First, Second and Third pass
of the bubble sort method used for arranging the following elements in descending
XII- Computer Science New (083)
Worksheet 2- Python

order ? 3
Note : Show the status of all the elements after each pass very clearly underlining
the changes.
152, 104, –100, 604, 190, 204
57 Write definition of a method OddSum(NUMBERS) to add those values in the list
of NUMBERS, which are odd.
58 Write Addnew(Book) and Remove(Book) methods in Python to Add a new Book
and Remove a Book from a List of Books, considering them to act as PUSH and
POP operations of the data structure Stack.
59 Write definition of a Method AFIND(CITIES) to display all the city names from a
list of CITIES, which are starting with alphabet A. 2
For example :
If the list CITIES contains
["AHMEDABAD","CHENNAI","NEW DELHI","AMRITSAR","AGRA"]
The following should get displayed
AHMEDABAD
AMRITSAR
AGRA
60 Evaluate the following Postfix notation of expression : 2
2,3,*,24,2,6,+,/,–
61 Differentiate between file modes r+ and w+ with respect to Python.
62 Write a method in Phyton to read lines from a text file DIARY.TXT, and display
those lines, which are starting with an alphabet „P‟.
63 Carefully observe the following python code and answer the
questions that follow:

On execution the above code produces the following output.


6
3
Explain the output with respect to the scope of the variables.
Ans Names declared with global keyword have to be referred at the file
level. This is because the global statement indicates that the particular
XII- Computer Science New (083)
Worksheet 2- Python

variable lives in the global scope. If no global statement is being


used, the variable with the local scope is accessed.
Hence, in the above code the statement succeeding the statement
global x informs python to increment the global variable x
Hence the output is 6 i.e 5+1 which is also the value for global x.
When x is reassigned with the value 3 the local x hides the global x
and hence 3 is printed.
64 Name the modules to which the following functions belong:
a. uniform() b. fabs()
Ans a. random()
b. math()
65 Rewrite the following code after removing the syntactical errors (if
any). Underline each correction.

Ans def chksum():


x= input("Enter a number")
if (x%2 == 0):
for i in range(2*x):
print i
else:
print "#"
66 Observe the following Python code carefully and obtain the output,
which will appear on the screen after execution of it.

Ans EA3n
XII- Computer Science New (083)
Worksheet 2- Python

67 What output will be generated when the following Python code is


executed?

Ans [11, 10, 9, 8, 7, 4]


68 Observe the following program and answer the questions that follow:

a. What is the minimum and maximum number of times the loop


will execute?
b. Find out, which line of output(s) out of (i) to (iv) will not be
expected from the program?
I. 0#1
ii. 1#2
iii. 2#3
iv. 3#4
Ans a. Minimum Number = 1
Maximum Number = 3
b. Line iv is not expected to be a part of the output.
69 Explain the two strategies employed by Python for memory
allocation.
Ans Python uses two strategies for memory allocationi.
Reference counting
ii. Automatic garbage collection.
Reference Counting: works by counting the number of times an
object is referenced by other objects in the system. When an object's
reference count reaches zero, Python collects it automatically.
Automatic Garbage Collection: Python schedules garbage
collection based upon a threshold of object allocations and object deallocations.
When the number of allocations minus the number of
deallocations are greater than the threshold number, the garbage
XII- Computer Science New (083)
Worksheet 2- Python

collector is run and the unused block of memory is reclaimed.


70 Consider the following unsorted list
95 79 19 43 52 3
Write the passes of bubble sort for sorting the list in ascending order
till the 3rd iteration.
Ans [79, 19, 43, 52, 3, 95]
[19, 43, 52, 3, 79, 95]
[19, 43, 3, 52, 79, 95]
71 Kritika was asked to accept a list of even numbers but she did not put
the relevant condition while accepting the list of numbers. You are
required to write a user defined function oddtoeven(L) that accepts the
List L as an argument and convert all the odd numbers into even by
multiplying them by 2 .
Ans

72 Aastha wants to create a program that accepts a string and display the
characters in the reverse order in the same line using a Stack. She
has created the following code , help her by completing the
definitions on the basis of requirements given below :
class mystack:
def __init__(self):
self.mystr= ________________ # Accept a string
self.mylist =________________ # Convert mystr to a list
# Write code to display while removing element from the stack.
def display(self):
:
:
Ans

73 Write a generator function generatesq() that displays the squareroots of


numbers from 100 to n where n is passed as an argument .
XII- Computer Science New (083)
Worksheet 2- Python

Ans

74 Evaluate the following Postfix expression:


20,10,-,15,3,/,+,5,*
Ans

75 Observe the following code and answer the questions that follow:
File = open("Mydata","a")
_____________________ #Blank1
File.close()
i. What type (Text/Binary) of file is Mydata?
ii. Fill the Blank 1 with statement to write “ABC” in the file “Mydata”
Ans i. Text File
ii. File.write("ABC")
76 A text file “Quotes.Txt” has the following data written in it:
Living a life you can be proud of
Doing your best
Spending your time with people and activities that are important to you
XII- Computer Science New (083)
Worksheet 2- Python

Standing up for things that are right even when it‟s hard
Becoming the best version of you
Write a user defined function to display the total number of words

present in the file.


Ans

77 List one similarity and one difference between List and Dictionary datatype
Ans Similarity : Both List and Dictionary are mutable datatypes.
Dissimilarity: List is a sequential data type i.e. they are indexed.
Dictionary is a mapping datatype. It consists of key: value pair.
Eg: L =[1,2,3,4,5] is a list
D= {1:”Ajay”,2:”Prashant,4:”Himani”} is a dictionary where 1,2,4 are keys and
“Ajay”,Prashant,”Himani” are their corresponding values.
78 Observe the following Python functions and write the name(s) of the module(s) to
which they
belong:
a. uniform() b. findall()
Ans a. random b.re
79 Rewrite the following Python program after removing all the syntactical errors (if
any),underlining each correction.:
XII- Computer Science New (083)
Worksheet 2- Python

Ans

80 Find the output of the following Python program:

Ans The new string is: S1U3E5Ts


81 Find the output of the following program
XII- Computer Science New (083)
Worksheet 2- Python

Ans

82 Observe the following Python code and find out , which out of the given options i) to
iv) are
the expected correct output(s).Also assign the maximum and minimum value that can
be
assigned to the variable „Go‟.
import random
X =[100,75,10,125]
Go = random.randint(0,3)
for i in range(Go):
print X[i],"$$",

i. 100$$75$$10 ii. 75$$10$$125$$iii. 75$$10$$ iv.10$$125$$100


Ans 100 $$ 75 $$ 10 $$
Minimum Value that can be assigned to Go is 0
Maximum Value that can be assigned to Go is 3
83 Discuss the strategies employed by python for memory allocation?
XII- Computer Science New (083)
Worksheet 2- Python

Ans Python uses two strategies for memory allocation- Reference counting and Automatic
garbage collection:
Reference Counting: works by counting the number of times an object is referenced
by other
objects inthe system. When an object's reference count reaches zero, Python collects it
automatically.
Automatic Garbage Collection: Python schedules garbage collection based upon a
threshold of
objectallocations and object de-allocations. When the number of allocations minus the
number of
deallocations are greater than the threshold number, the garbage collector is run and the
unused
block ofmemory is reclaimed.
84 Write a user defined function findname(name) where name is an argument in Python to
delete
phone number from a dictionary phonebook on the basis of the name ,where name is
the
key.
Ans

85 Explain try..except…else … with the help of user defined function def divide(x,
y)which
raises an error when the denominator is zero while dividing x by y and displays the
quotient
otherwise.
XII- Computer Science New (083)
Worksheet 2- Python

Ans

In the above example:


try block consists of code that can raise an error.When y(denominator) gets a 0 value,
ZeroDivisionError is raised which is handled by except clause.In case of no exception
else
statement is executed.
In case there is no error the statement(s) in else clause are executed .
86 Write a user defined function arrangelements(X),that accepts a list X of integers and
sets all
the negative elements to the left and all positive elements to the right of the list.
Eg: if L =[1,-2,3,4,-5,7] , the output should be: [-2,-5,3,4,7]
Ans

87 Write a python function generatefibo(n) where n is the limit, using a generator function
Fibonacci (max)( where max is the limit n) that produces Fibonacci series..
XII- Computer Science New (083)
Worksheet 2- Python

Ans

88 Evaluate the following postfix using stack & show the content of the stack after the
execution
of each:
20, 4, +, 3, -, 7, 1
Ans

89 Consider the following code : 1


f = open ("mytry", "w+")
f.write ("0123456789abcdef")
XII- Computer Science New (083)
Worksheet 2- Python

f.seek (-3,2) //1


printf.read(2) //2
Explain statement 1 and give output of 2
Ans Statement 1 uses seek()method can be used to position the file object at particular place
in
the file. It's syntax is :fileobject.seek(offset [, from_what]).
So,f.seek(-3,2) positions the fileobject to 3 bytes before end of file.
Output of 2 is :de (It reads 2 bytes from where the file object is placed.)
90 Write a user defined function in Python that displays the number of lines starting with
„H‟ in
the file Para.txt.Eg: if the file contains:
Whose woods these are I think I know.
His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.
Then the line count should be 2.
Ans

91 Consider a binary file Employee.dat containing details such as empno:ename:salary


(separator
„ :‟). Write a python function to display details of those employees who are earning
between
20000 and 40000.(both values inclusive)
XII- Computer Science New (083)
Worksheet 2- Python

Ans

You might also like