0 ratings0% found this document useful (0 votes) 64 views39 pagesChapter 1 Review of Python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Review of Python
Very Short Answer Type Questions (1 mark)
Question 1.
Name the Python Library modules which need to be imported to invoke the following
functions:
1. load ()
2. pow () [CBSE Delhi 2016]
Answer:
1. pickle
2. math
Question 2.
Name the modules to which the following func-tions belong:
1. Uniform ()
2. fabs () [CBSE SQP 2016]
Answer:
1. random ()
2. math ()
Question 3.
Differentiate between the round() and floor() functions with the help of suitable example.
[CBSE Comptt. 2016]
Answer:
The function round() is used to convert a fractional number into whole as the nearest
next whereas the function floor() is used convert to the nearest lower whole number,
eg.
round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5
Short Answer Type Questions (2 marks)
Question 1.
Out of the following, find those identifiers, which cannot be used for naming Variables or
functions in a Python program:
Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE OutsideDethi-2016]
Answer:
Total * Tax, class, 3rd Row, finally
Question 2.
Name the Python Library modules which need to be imported to invoke the follwing
functions :
1. sqrt()
2. dump() (CBSE Outside Delhi-2016)
Answer:
1. math
2. pickle
Question 3.
Out of the following, find the identifiers, which cannot be used for naming Variable or
Functions in a Python program: [CBSE Delhi 2016]
_Cost, Price*Aty, float, switch, Address one, Delete, Number12, do
Answer:
Price *Qty, float, Address one, do
Question 4.
Out of the following find those identifiers, which can not be used for naming Variable or
Functions in a Python Program
Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My city
Answer:
Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and
Grant Total Because of being either keyword or including space or operator or starting
with integar.
Question 5.
Name the function / method required for [CBSE SQP 2015]
1. Finding second occurrence of m in madam.
2. get the position of an item in the list.
Answer:
1. find2. index
Question 6.
Which string method is used to implement the following
1, To count the number of characters in the string.
2. To change the first character of the string in capital letter.
3. To check whether given character is letter or a number.
4. To change lowercase to uppercase letter.
5, Change one character into another character. [CBSE Text800k]
Answer:
1. len(str)
2. str.capitalize()
3. chisalnum()
4. str.upper()
5. str.replace(old,new)
Question 7.
What is the difference between input() and raw_input()?
Answer:
raw_input() takes the input as a string whereas input() basically looks at what the user
enters, and automatically determines the correct type. We use the inputQ function when
you are expecting an integer from the end-user, and raw_input when you are expecting
a string.
Question 8.
What are the two ways of output using print()?
Answer:
Ordinarily, each print statement produces one line of output. You can end the print
statement with a trailing ' to combine the results of multiple print statements into a single
line
Question 9.
Why does the expression 2 + 3*4 result in the value 14 and not the value 24?
Answer:
Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence
the result is 14.Question 10.
How many times will Python execute the code inside the following while loop? You
should answer the question without using the interpreter! Justify your answers.
i-0
while i <0 and i > 2
print “Hello ...”
i= itl
Answer:
O times.
Question 11.
How many
es will Python execute the code inside the following while loop?
“Hello ...”
is2*i
Answer:
14,
Question 12.
Convert the following for loop into while loop, for iin range (1,100):
ified :
print i, “mod”, 4, “= 2"
Answer:
while i < 101
if ie 4-52:
print i, “mod”, 4, “=
ieidvl
Question 13.
Convert the following for loop into while loop.
for i in range (10):
for } in range (i):
print '$',
print"Question 14.
Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range (25,500,253):
Question 15.
Rewrite the following for loop into while loop: [CBSE Text Book]
for a in range(90, 9, -9):
print a
Answer:
a= 90
while a > 9:
print a
aay
Question 16.
Convert the following while loop into for loop:
while i <1
if is 2 ==
print i, “is even”
else:
print i, “is odd”
isitl
Answer:for i in range(100):
if ie 2-=-=0:
print i, “is even”
else
print i, “is odd”
Question 17.
Convert the following while loop into for loop
ess Tab Enter to stop ...
iteration = 0
while not char
print “Continu
“\t" and not iteration > 99:
char = raw_input ()
iteration+ = 1
Answer:
char = "
print “Press Tab Enter to stop ...”
for iteration in range (99):
if not char == ‘\t’
print “Continue?”
char = raw_input ()
Question 18.
Rewrite the following while loop into for loop:
Answer:
for i in range (10,
print i
Question 19.
Rewrite the following while loop into for loop:
=38
hile(i>=8): print i
i-=8Answer:
for i in range(88, 9, -8)
print i
Question 20.
Write for statement to print the series 10,20,30, 300
Answer:
for i in range (10
print i
Question 21.
Write for statement to print the series 105,98,91,....7
Answer:
for i in range(105, 8, -7):
print i
Question 22.
Write the while loop to print the series: 5,10,15,100
Answer:
while i <= 100:
i
isits
Question 23.
How many times is the following loop executed? [CBSE Text Book]
for a in range(100,10,-10):
print a
Answer:
9 times.
Question 24.
How many times is the following loop executed? [CBSE Text Book]
le (i<=200):print i
i + =20
Answer:
6 times
Question 25.
State whether the statement is True or False? No matter the underlying data type if
values are equal returns true,
char chl, ch2;
if (chl==ch2)
print “Equal”
Answer:
True. Two values of same data types can be equal.
Question 26.
What are the logical operators of Python?
Answer:
or, and, not
Question 27.
What is the difference between ‘/’ and ‘//' 2
Answer:
// is Integer or Floor division whereas / is normal division
(eg) 7.0 // 2 + 3.0
7.0/2 + 3.5
Question 28.
How can we import a module in Python?
Answer:
1. using import
Syntax:
import [), ++
Example:
import math, cm:
2. using fromsyntax:
fromimport[, +--+]
Exampli
£
; import fib, fib2.
Question 29.
What is the difference between parameters and arguments?
Answer:
S.No. Parameters ‘Arguments
1 Values provided in function header | Values provided in function call.
2 (eg) def area (r): (eg) def main() radius = 5.0 area
—> ris the parameter (radius)
=> radius is the argument
What are default arguments?
Answer:
Python allowes function arguments to have default values; if the function is called
without the argument, the argument gets its default value
What are keyword arguments?
Answer:
If there is a function with many parameters and we want to specify only some of them in
function call, then value for such parameters can be provided by using their names
instead of the positions. These are called keyword argument.
(eg) def simpleinterest (p, n=2, r=0.6)
‘def simpleinterest (p, 2, n=3)
Question 32.
What are the advantages of keyword arguments?
Answer:
Itis easier to use since we need not remember the order of the arguments.
We can specify the values for only those parameters which we want, and others have
default values,
What does “in” do?Answer:
in’ is a membership operator. It evaluates to true if it finds a variable/string in the
specified sequence : Otherwise itevaluates to false.
(eg) lo World"
if” nS:
print “True”
will true
Question 34.
What does “not in” do?
Answer:
“not in” is a membership operator. It evaluates to true if it does not finds a variable/string
in the specified sequence. Otherwise it evaluates to false,
ello World”
1” not in s:
print “False”
will print False.
Question 35.
What does “slice” do?
Answer:
The slice[n:m] operator extracts subparts from a string. It doesn't include the character
at index m.
(eg)
Question 36.
What is the use of negative indices in slicing?
Answer:
Python counts from the end (right) if negative indices are given.
ello”
3] >> He
>> lo
(eg) $
print $
Question 37.
Explain find() function?
Answer:find (sub{,start{,end]])
This function is used to search the first occurrence of the substring in the given string. It
returns the index at which the substring starts. It returns -1 if the substring doesn’t occur
in the string.
(eg) str = “compu
str.findf("om”) +
Question 38.
What are the differences between arrays and lists?
Answer:
An array holds fixed number of values. List is of variable-length — elements can be
dynamically added or removed
An array holds values of a single type. List in Python can hold values of mixed data
type.
Question 39.
What is the difference between a tuple and a list?
Answer:
A tuple is immutable whereas a list is a mutable.
A tuple cannot be changed whereas a list can be changed internally,
A tuple uses parenthess (()) whereas a list uses square brackets ({)).
tuple initialization: a = (2, 4, 5)
list initialization: a = [2, 4, 5]
Question 40.
Carefully observe the following python code and answer the question that follows:
x5
def func2():
x3
global x
XEX+!
print x
print x
On execution the above code produces the following output.
6
3
Explain the output with respect to the scope of the variables.
Answer:
Names declared with global keyword have to be referred at the file level. This is
because 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 reassingned with the value 3 the local x hides the global x and hence 3
printed
(2 marks for explaning the output) (Only 1 mark for explaining global and local
namespace.)
Question 41.
Explain the two strategies employed by Python for memory allocation.
[CBSE SQP 2016]
Answer:
Pythonuses two strategies for memory allocation-
(i) Reference counting
{ii) Automatic garbage collection
Reference Counting: works by counting the number of times an object is referenced by
other 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 that the threshold number, the garbage
collector is run and the unused blocks of memory is reclaimed.
TOPIC -2
Writing Python Programs
Question 1.
Rewrite the following code in Python after removing all syntax errors(s). Underline each
correction done in the code. [CBSE Delhi-2016]
for Name in [Amar, Shveta, Parag]
if Name [0] ='s’
Print (Name)
Answer:
for Name in [* Amar”,
if Name [0] E "
Print (Name)
" shveta_” , "_Parag_"]
Question 2.
Rewrite the following code is Python after removing all syntax errors(s). Underline each
correction done in the code. [CBSE Outside Delhi-2016]
for Name in [Ramesh, Suraj, Priya]
if Name [0] = ‘S’Print (Name)
Answer:
, “_Suraj_” , “_Priya_"]
Name in [*_Rame
me [0] =_="S'
(Name)
Question 3.
What will be the output of the following python code considering the following set of
inputs?
AMAR
THREE
A123
1200
Also, explain the try and except used in the code.
Start = 0
while True
Try:
Number = int (raw input (“Enter Number’)
break
except valueError : start=start+2
print (“Re-enter an integer’)
Print (start)
Answer:
Output
Enter Number AMAR
Re-enter an integer
Enter Number THREE
Re-enter an integer
Enter Number A123
Re-enter an integer
Ent Number 12006
Explanation : The code inside try makes sure that the valid number is entered by the
user. When any input other an integer is entered, a value error is thrown and it prompts
the user to enter another value.
Question 4.
Give the output of following with justification,
[CBSE SaP 2015]
x=3
xt = xoxprint x
Answer:
Output: 3
Working:
(ct xox )ix = 343-353
Question 5.
What will be printed, when following Python code is executed? [CBSE SQP 2015]
class person
def init f, id):
self.id = id arjun = person(150)
arjun. diet [‘age’ 50
print arjun.age + len(arjun. diet )
Justify your answer.
Answer:
52
arjun.age = 50
arjun.dict has 2 attributes so length of itis 2. So total = 52
Question 6,
What would be the output of the following code snippets?
print 4+9
print “4+9"
Answer:
13 (addition), 49 (concatenation)
Question 7.
Highlight the literals in the following program
and also predict the output. Mention the types of
variables in the program
g Sathy’
print a,g,e,f,a,g,",",d/9,*,",C,g, "and his”,e,fAnswer:
a, od = integer
b, e,f,g = string
Output: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and
his Kathy, went to party.
Question 8.
What is the result of 4+4/2+2?7
Answer:
4+ (a/2)+2=8,
Question 9.
Write the output from the following code:
[CBSE Text Book]
x= 10
y = 20
(x>y) =
xty
Answer:
10
Question 10,
Write the output of the following code:
print “Python is an \n interpreted \t Language”
Answer:
Python is an interpreted Language
Question 11.
Write the output from the following code:
s-0
for I in range(10,2,-2):
s+=1Question 12.
Write the output from the following code:
[CBSE TextBook]
print “is”,i
print “sum=",s
Answer:
is 15
is 25
Question 13.
Write the output from the following code: [CBSE TextBook]
n = 50
s=0
while i>> str=‘Honesty is the best policy’
>>> str.replace(‘o’, **/)
Answer:
‘Htnesty is the best p'licy’
Question 23.
Give the output of the following statements :
>> str=‘Hello Python’
>>> str.istitle()Answer:
True.
Question 24.
Give the output of the following statements:
>> str='Hello Python’
>>> print -Istrip("Hel”)
Answer:
Hello Python
Question 25.
Write the output for the following codes:
000, 20:2000, 30:3000, 40:4000,50:500
Av items ()
A. keys ()
t A.values()
pri
Answer:
[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000,
2000, 5000, 3000]
Question 26.
Write the output from the following code:
(10, 20, 30, 40,50)
rint len(t)
Answer:
5
Question 27.
Write the output from the following code:
te(ta’, "bl, *o", ‘AY, SBI)
max (t)
min(t)
Answer:
‘e
xQuestion 28.
Find the output from the following code:
T= (10, 30,2,50,5, 6,100, 65)
print max (1)
print min(T)
Answer:
100
2
Question 29.
Write the output from the following code:
120,30, 40,50)
20, 30,40, 50)
Answer:
0
A
}
Question 30.
Write the output from the following code:
0,20, 30, 40,50)
00,200, 300)
Answer:
(10,20,30,40,50, 100,200,300)
Question 31.
Find the output from the following code:
t=tuple()
t = t +(*Python’,)
print t
print len(t)= (10,20, 30)
nt len (t1)
Rewrite the following code in Python after removing all syntax error(s). Underline each
correction done in the code.
for student in [
I£ Student [0]
print (student)
a, Priya, Gagan]
a
Answer
for studednt in values [“Jaya’, “Priya”, “Gagan"):
if student [0] = = “Ss”
print (student)
Question 33.
Find and write the output of the following Python code:
Values = [11, 22, 33, 44] for V in Value!
for NV in range (1, V#10):
print (NV, V)
Answer:
4,11
2,22
3,33
4,44
Question 34,
What are the possible outcome(s) executed from the following code? Also, specify the
maximum and minimum values that can be assigned to variable SEL.
import random
SEL=random. randint (0, 3)
ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”];
for A in ANIMAL:
for AAin range (1, SEL):
print (A, end ="”)print _()
(i) (ii) (iii) (iv)
DEERDEER DEER DEER DEER
MONKEYMONKEY DELHIMONKEY MONKEY | MONKEYMONKEY
cowcow DELHIMONKEYCOW | COW KANGAROOKANGAROOKANGAROO
KANGAROOKANGAROO KANGAROO
Answer:
Maximum value of SEL is 3
The possible output is below
DEER
Monkey Monkey
Kangaroo Kangaroo Kangaroo
Thus (iv) is the correct option.
TOPIC-3
Random Functions
Question 1,
What are the possible outcome(s) executed from the following code ? Also specify the
maximum and minimum values that can be assigned to variable PICKER. [CBSE
Outside Delhi-2016]
import random
KER = random randii
COLOR = ["BLUE", "PINK "RED"):
COLOR
in range (1, PICKER):
(i, end =" ")
0
@ 0) i) (wy
BLUE BLUE PINK SUUEBLUE
PINK BLUEPINK PINKGREEN | PINKPINK
GREEN BLUEPINKGREEN | GREENRED | GREENGREEN
RED BLUEPINKGREENRED REDREDAnswer:
Option (i) and (iv) are possible
OR
option (i) only
PICKER maxval = 3 minval = 0
Question 2.
What are the possible outcome(s) expected from the following python code? Also
specify maximum and minimum value, which we can have. [CBSE SQP 2015]
def main():
p = ‘MY PROGRAM!
i=0
while pli] != ‘R's
1 = random. randint (0,3) + 5
print p[l),’-",
its
()R-P-0-R-
(i) P-O-R-Y-
(iii) O-R-A-G—
(iv) A-G-R-M—
Answer:
Minimum valu
Maximum valu
So the only possible values are O, G, R, A
Only option (ii) is possible.
TOPIC-4
Correcting The Errors
Question 1.
Rewrite the following Python code after removing all syntax error(s). Underline the
corrections done. [CBSE SQP 2015]
def main(
r = raw-input (‘enter any radius : ’)
a = pi * math.pow(r,2)
print “ Area =" + aAnswer:
def main ():
r = raw_input (‘enter any radius : ’)
a = pi * math.pow(r,2)
print “ Area =", a
Question 2.
Reotify the error (if any) in the given statements.
>> str=“Hello Python”
>>> str[6]='s!
Answer:
str[6] = ‘S’ is incorrect ‘str’ object does not support item
assignment.
str.replace(str[6], ‘S’
Question 3.
Find the errors from the following code:
T=[a,b.c]
print T
Answer:
Name Error: name ‘a’ is not defined
T=fal-be]
Question 4.
Find the errors from the following code:
for iin 4 to 100:
print |
Answer:
for i in range (1,100):
print i
Question 5.
Find the errors from the following code:
[is-nl:n=100
while (i<=n):
print i
its10
Question 6,
Find the errors from the following code:
if (a>b)
print a:
else if (ab) // missing colon
print a:
else if (a 0:
print “Roots are real and distinct”
root] = (- b + math.sqrt(d)) / (2*a)
root2 = (-b - math.sqrt(a)) / (2*a)
else
print “Roots are imaginary”
print “Roots of the quadr
© equation are”, rootl, “and”, root2
Question 3,
Write a program to input any number and to print all the factors of that number.
Answer:
n = inputfEn
if ngi
print i,“is a factor off
Question 4.
Write a program to input ,.any number and to check whether given number is Armstrong
or not.
(Armstrong 1,153,ete. 13,
» 13453 +33
53)Answer:
n = inputfEnter the number”)
savedn =n
sum:
while n > 0:
a = ng10
sum = sum + avata
n = n/10
if savedn == sum:
print savedn,“is an Armstrong Number”
else:
print savedn,”is not an Armstrong Number”
Question 5.
Write a program to find all the prime numbers up to a given number
Answer:
n = input ("Enter the number”)
i-2
flag = 0
while (i 0:
rem=dec$2
+ (i*rem)
print “The binary of the given number is:”,s raw_input ()Question 7.
Write a program to convert binary to decimal
Answer:
binary = raw_input ("Enter the binary string”)
decimal=0
for i in range(Len(str(binary))):
power-len (str (binary)) - (i
decimal+=int (str (binary) [i]) *(2**power)
print decima
Question 8.
Write a program to input two complex numbers and to find sum of the given complex
numbers.
Answer:
= input ("Enter real part of first complex number”)
input ("Enter imaginary part of first complex number”)
= input ("Enter real part of second complex number”)
= input ("Enter imaginary part of second complex number”)
al - areal + breal
totimg = aimg + bimg
print “Sum of the complex numbers
totreal, “+i”, totimg
Question 9.
Write a program to input two complex numbers and to implement multiplication of the
given complex numbers.
Answer:
input ("Enter real part of first complex number”)
b = input ("Enter imaginary part of first complex number”)
¢ = input ("Enter real part of second complex number”)
d = input ("Enter imaginary part of second complex number”)
Question 10.
Write a program to find the sum of all digits of the given number.Answer:
a
nputfinter
rev=0
while (n>0):
a=n%10
number”)
sum = sum + a
n=n/10
print “Sum of digits
"sum
Question 11.
Write a program to find the reverse of a number.
Answer:
n = input ("Enter the number”)
while (n>0):
a=n%10
rev=(rev*10) +a
n=n/10
print “Reversed number=", rev
Question 12.
Write a program to print the pyramid
1
22
333
4444
55555
Answer:
for } in range (1,
print i,
print
Question 13.
Write a program to input username and password and to check whether the given
username and password are correct or not.Answer:
import st:
usemame
J
input (“Enter username”)
password = raw input (“Enter password”)
£ omp (username. strip () , "XXX"
if cmp (password, 123”) == 0:
print “Login successful”
“password Incorrect”
“Username Incorrect”
Question 14.
Write a generator function generatesq () that displays the squareroots of numbers from
100 to n where n is passed as an argument.
Answer:
import math
def generatesq (n)
for i in range (100, n)
yield (math, sqrt (i))
Question 15.
Write a method in Python to find and display the prime number between 2 to n. Pass n
as argument to the method
Answer:
def prime (N)
for a in range (2, N.
for I in range (2, a
if Nei =-0 :
break print a
OR
def prime (N
rain ge (2, N):
for I in range (2, a)
f a’l==0:
break
else
print a
Question 16.
Write a program to input username and password and to check whether the givenusername and password are correct or not.
Answei
import string
ame= raw input (“Enter username”)
sword = raw_input (“Enter password”)
pas
cmp (usemame strip () ,“XXX”)== 0:
if cmp (password, 123”) 0:
print “Login successful”
else:
print “Password Incorrect”
else:
print “Username Incorrect
Question 17.
Which string method is used to implement the following: [CBSE Text Book]
To count the number of characters in the string
To change the first character of the string in capital letter.
To check whether given character is letter or a number.
To change lowercase to uppercase letter.
Change one character into another character.
DaONa
Answer:
len(str)
str.title() or str.capitalize()
str.isalpha and str.isdigit()
lower(str{i])
str.replace(char, newchar)
ARONA
Question 18.
Write a program to input any string and to find the number of words in the string.
Answer:
str = “Honesty is the best policy”
words = str.split()
print len (words)
Question 19.
Write a program to input n numbers and to insert any number in a particular position.Answer:
n=input (“Enter no, of values")
]
for i in range (n):
number=input (“Enter the number") num.append (number)
newno = input ("Enter the number to be inserted”)
pos = input ("Enter position”) num. insert (newno, pos)
print num
Question 20.
Write a program to input n numbers and to search any number from the list.
Answer:
n=input (“Enter no. of values”)
num=[]
flag-0
for i in range (n):
number=input (“Enter the number”)
num, append (number)
search = input ("Enter number to be searched")
for 4 in range(n)
if num[i]==search:
print search,“found at position”,
flag=1
if flag==0:
print search, “not found in list”
Question 21.
Write a program to search input any customer name and display customer phone
number if the customer name is exist in the list
Answer:
def printlist(s):
i=0
for i in range(len(s)):
print i,s[i]
i= 0
phonenumbers = ['9840012345’, ‘9840011111,’
9845622222" , *9850012345", ‘98844123457 }
flag=0
number = raw input ("Enter the phone number to be searched")
number = number.strip()dex (number)
flag=1
except ValueError:
pass
if(flag <>0):
print “\nphone number found in Phonebook at index”, i
else:
print'\iphonenumbernot foundin phonebook”
print “\nPHONEBOOK”
print list (phonenumbers)
Question 22.
Write a program to input n numbers and to reverse the set of numbers without using
functions.
Answer:
(“Enter no. of values”)
for i in range (n):
number=input (“Enter the number”)
(number
num. ap)
jen-
for i in range(
] = num[j],num[i]
break
print num
Question 23.
Find and write the output of the following Python code: [CBSE Complementry-2016]
class Clie
def init (s
constructor
self.CID = ID
self. Name = NM
def Allocate (self, cl
self.CID = self.CID +
self.Name = Title + s
def Display (self) :
f, ID = 1, NM="Noname”) #
hangelD, Title) +
ngeld
» Name
ang}
chacD).
0
(102)
(205, *’Fedrick”)
Display ()
Display ()
isplay ()
+ Allocate (4, "Ms.”)
-Alloc: (2, "
Allocate (1,
Display ()
. play ()
3 . Display ()
Answer:
CID Name
— Fedrick
102 Mr. Fedrick
205 Mrs. Fedrick
— Mr. & Mrs. Fedrick
Question 24,
What will be the output of the following Python code considering the following set of
inputs?
MAYA
Your 5 Apples
Mine2
2
Also, explain the try and except used in the code.
Count = 0
while True
try:
Numbe (raw input ("Input a Number :"))
break
Except valueError :
Count=Count + 2
# For later versions of py
# Should be consider as inp’
mehtods:
— DenCal () # Method to calcualte Density as People/Area
— Add () # Method to allow user to enter values Deode, DName, People, Area and Call
DenCal () Mehtod
— View () # Method to display all the data members also display a message “High
Population” if the Density is more than 8000
ny, xaw_inputAnswer:
Output is below
2 Re Enter Number
10 Re Enter Number
5 Input = Number
3 Input = number
Try and except are used for handling exception in the Pythan code
Question 25,
Write a method in Python and display the prime numbers between 2 to N. Pass as
argument to the methods.
Answer:
def prime (N) +
for a in range (2, N)
for I in range (2, a):
if ati= = 0
Prime = 0
if Prime = = 1:
print a
oR
def prime (N) :
or a in range (2, N):
Tin range (2, a)
OR
Any other correct code performing the same
Long Answer Type Questions (6 marks)
Question 1.
Aastha wnats to create a program that accepts a string and display the characters in the
reverse 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:[CBSE SQP 2016]
Class mystack :
def inin (self):selfe. mystr= # Accept a string
self.mylist= # Convert mystr to a list
# Write code to display while removing element from the stack.
def display (self)
Answer:
class mystack :
def _init_ (self)
self.myster= rawjnput ("Enter the string”)
self.mylist = list (self.mystr)
def display (self)
x = len (self. mylist)
Lf (x > 0)
for i in range (x)
self.mylist.pop (),
"Stack is empty”