CH 1
CH 1
Python Basics
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.
          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.
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,
e.g.,
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 Outside
Delhi2016]
Answer:
Question 2.
Name the Python Library modules which need to be imported to invoke the follwing
functions :
          1. sqrt()
          2. dump() (CBSE Outside Delhi2016)
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]
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.
Answer:
          1. find
          2. index
Question 6.
Answer:
          1. len(str)
          2.   str.capitalize()
          3.   ch.isalnum()
          4.   str.upper()
          5.   str.replace(old,new)
Question 7.
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 enduser, and raw_input when
you are expecting a string.
Question 8.
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:
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 = i+1
Answer:
0 times.
Question 11.
How many times will Python execute the code inside the following while loop?
 i=1
  while i < 10000 and i > 0 and 1:
  print “ Hello ...”
  i=2*i
Answer:
14.
Question 12.
Convert the following for loop into while loop, for i in range (1,100):
 if i % 4 == 2 :
  print i, “mod”, 4 , “= 2”
Answer:
 i=1
  while i < 100:
  if i % 4 == 2:
  print i, “mod”, 4 , “= 2”
  i = i +1
Question 13.
 for i in range(10):
  for j in range(i):
  print '$',
  print"
Answer:
 i=0
  while i < 10:
  j=0
  while j < i:
  print '$’
  print"
Question 14.
Rewrite the following for loop into while loop: [CBSE Text Book]
 for a in range(25,500,25):
  print a
Answer:
 a=25
  while a < 500:
  print a
  a = a + 25
Question 15.
Rewrite the following for loop into while loop: [CBSE Text Book]
 a = 90
  while a > 9:
  print a
  a = a9
Question 16.
 i=0
  while i < 100:
  if i % 2 == 0:
  print i, “is even”
  else:
  print i, “is odd”
  i=i+1
Answer:
 for i in range(100):
  if i % 2 == 0:
  print i, “is even”
  else :
  print i, “is odd”
Question 17.
 char = ""
  print “Press Tab Enter to stop ...”
  iteration = 0
  while not char == “\t” and not iteration > 99:
  print “Continue?”
  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.
 i = 10
  while i<250:
  print i
  i = i+50
Answer:
 i=88
  while(i>=8): print i
  i = 8
Answer:
Answer:
Answer:
Answer:
 i=5
 while i <= 100:
 print i
 i=i+5
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]
 i = 100
  while (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,
Question 26.
Answer:
Question 27.
Answer:
 // is Integer or Floor division whereas / is normal division
  (eg) 7.0 // 2   →3.0
  7.0/2   → 3.5
Question 28.
Answer:
1. using import
 Syntax:
   import[,,...]
   Example:
   import math, cmath
2. using from
 Syntax:
  fromimport[, ,.. ,]
  Example: .
  from fib. import fib, fib2.
Question 29.
Answer:
                            header
       2                (eg) def area (r):         (eg) def main() radius = 5.0 area
(radius)
Question 30.
Answer:
Python allowes function arguments to have default values; if the function is called
without the argument, the argument gets its default value
Question 31.
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.
Answer:
It is 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.
Question 33.
Answer:
Answer:
Answer:
The slice[n:m] operator extracts subparts from a string. It doesn’t include the
character at index m.
Python counts from the end (right) if negative indices are given.
 (eg) S = “Hello”
  print S[:3] >> He
  print S[3:] >> llo
Question 37.
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.
Answer:
An array holds values of a single type. List in Python can hold values of mixed data
type.
Question 39.
Answer:
A tuple uses parenthess (()) whereas a list uses square brackets ([]).
Question 40.
Carefully observe the following python code and answer the question that follows:
x=5
def func2():
x=3
global x
x=x+1
print x
print x
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:
TOPIC – 2
Question 1.
Rewrite the following code in Python after removing all syntax errors(s). Underline
each correction done in the code. [CBSE Delhi2016]
for Name in [Amar, Shveta, Parag]
Print (Name)
Answer:
Rewrite the following code is Python after removing all syntax errors(s). Underline
each correction done in the code. [CBSE Outside Delhi2016]
Print (Name)
Answer:
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:
break
Print (start)
Answer:
Output:
Question 4.
 x=3
  x+ = xx
  print x
Answer:
Output: 3
Working:
 x=3
 x = (x+ xx ):x = 3 + 3  3 = 3
Question 5.
What will be printed, when following Python code is executed? [CBSE SQP 2015]
 class person:
  def init (self,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
Question 6.
print 4+9
print “4+9”
Answer:
13 (addition), 49 (concatenation).
Question 7.
 a=3
  b='1'
  c=a2
  d=ac
  e=“Kathy”
  f=‘went to party.’
  g=‘with Sathy’
  print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f
Answer:
a, c,d = 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.
Answer:
4 + (4/2) + 2 = 8.
Question 9.
Write the output from the following code: [CBSE Text Book]
 x= 10
  y = 20
  if (x>y):
  print x+y
  else:
  print xy
Answer:
– 10
Question 10.
Answer:
Question 11.
 s=0
  for I in range(10,2,2):
  s+=I
  print “sum= ",s
Answer:
sum= 28
Question 12.
 n = 50
  i=5
  s=0
  while i<n:
  s+ = i
  i+ = 10
  print “i=”,i
  print “sum=”,s
Answer:
 i= 15
  i= 25
  i= 35
  i= 45
 i= 55
 sum= 125
Question 13.
 n = 50
  i=5
  s=0
  while i<n:
  s+ = i
  i+ = 10
  print “i=”,i
  print “sum=”,s
Answer:
 i= 15
  i= 25
  i= 35
  i= 45
  i= 55
  sum= 125
Question 14.
Observe the following program and answer the question that follows:
import random
x=3
print 1, ‘#’, 1 + 1
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
Answer:
a. Minimum Number = 1
Maximum number = 3
Question 15.
Observe the following Python code carefully and obtain the output, which will appear
on the screen after execution of it. [CBSE SQP 2016]
EA3n
Question 16.
1# 0 0
1# (1#) (1#)
2# (1#) (1#2#)
1# (2#) (1#2#3#)
2# (1#) 1#
3# (2#) 1#2#
(3#) 1#2#3#
Question 17.
What are the possible outcome(s) executed from the following code? Also, specify
the maximum and import random. [CBSE Delhi 2016]
 PICK=random.randint (0,3)
  CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"];
  for I in CITY :
  for J in range (1, PICK)
  print (I, end = " ")
  Print ()
               (i)                                     (ii)
DELHIDELHI DELHI
MUMBAIMUMBAI DELHIMUMBAI
CHENNAICHENNAI DELHIMUMBAICEHNNAI
KOLKATAKOLKATA
(iii) (iv)
DELHI DELHI
            MUMBAI                              MUMBAIMUMBAI
              CHENNAI                               KOLKATAKOLKATAKOLKATA
KOLKATA
Answer:
Question 18.
Find and write the output of the following Python code : [CBSE Outside Delhi2016]
 Values = [10,20,30,40]
  for val in Values:
  for I in range (1, Val%9):
  print (I," * ", end= " ")
  print ()
Answer:
1* 0 0
         1*                         (1.*)                           (1*)
        2*                         0         (1*2*)
1* (1,*) (1*2*3*)
2* (2.*) 1*
3* 0 1*2*
(1.*) 1*2*3*
(2,* )
(3,* )
Question 19.
 y = 2000
  if (y%4==0):
  print “Leap Year”
  else:
  print “Not leap year”
Answer:
Leap Year.
Question 20.
123456789
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
Question 21.
What will be the output of the following statement? Also, justify the answer.
Question 22.
Question 23.
True.
Question 24.
Hello Python
Question 25.
 A={10:1000,20:2000,30:3000,40:4000,50:5000}
  print A.items()
  print A.keys()
  print A.values()
Answer:
Question 26.
 t=(10,20,30,40,50)
  print len(t)
Answer:
Question 27.
 t=(‘a’,‘b’,‘c’,‘A’,‘B’)
  print max(t)
  print min(t)
Answer:
‘c’
A’
Question 28.
 T=(10,30,2,50,5,6,100,65)
  print max(T)
  print min(T)
Answer:
100
2
Question 29.
 T1=(10,20,30,40,50)
  T2 =(10,20,30,40,50)
  T3 =(100,200,300)
  cmp(T1, T2)
  cmp(T2,T3)
  cmp(T3,T1)
Answer:
1
Question 30.
 T1=(10,20,30,40,50)
  T2=(100,200,300)
  T3=T1+T2
 print T3
Answer:
(10,20,30,40,50,100,200,300)
Question 31.
 t=tuple()
  t = t +(‘Python’,)
  print t
  print len(t)
  t1=(10,20,30)
  print len(t1)
Answer:
(‘Python’,)
Question 32.
Rewrite the following code in Python after remo¬ving all syntax error(s). Underline
each correction done in the code.
print (student)
Question 33.
1, 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)
COW GAROO
KANGAROOKANG KANGA
AROO ROO
Answer:
Monkey Monkey
TOPIC3
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 Delhi2016]
 import random
  PICKER = random randint (0, 3)
  COLOR = ["BLUE", "PINK", "GREEN", "RED"]:
  for I in COLOR :
  for J in range (1, PICKER):
  Print (I, end = " ")
  Print ()
          (i)                       (ii)                (iii)        (iv)
ED
Answer:
OR
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 p[i] != ‘R’:
    l = random.randint(0,3) + 5
    print p[l],’’,
    i += 1
(i) R – P – O – R –
(ii) P – O – R – Y –
(iii) O R – A – G –
(iv) A G – R – M –
Answer:
Minimum value=5
Maximum value=8
TOPIC4
Question 1.
Rewrite the following Python code after removing all syntax error(s). Underline the
corrections done. [CBSE SQP 2015]
 def main():
  r = rawinput(‘enter any radius : ’)
  a = pi * math.pow(r,2)
  print “ Area = ” + a
Answer:
 str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment.
  str.replace(str[6],‘S’).
Question 3.
T=[a,b,c]
print T
Answer:
T=[‘a’,‘b’,‘c’]
Question 4.
for i in 1 to 100:
print I
Answer:
print i
Question 5.
 i=10 ;
  while [i<=n]:
  print i
  i+=10
Answer:
 i=10
  n=100
  while (i<=n):
  print i
  i+=10
Question 6.
 c=dict()
  n=input(Enter total number)
  i=1
  while i<=n:
  a=raw_input(“enter place”)
  b=raw_input(“enter number”)
  c[a]=b
  i=i+1
  print “place”,“\t”,“number”
  for i in c:
  print i,“\t”,c[a[i]]
Answer:
 c=dict()
  n=input(‘‘Enter total number”)
  i=1
  while i<=n :
  a=raw_input(“enter place”)
  b=raw_inputf enter number”)
  c[a]=b
  i=i+1
  print “place”,“\t”,“number”
  for i in c:
  print i,“\t”,c[i]
Question 8.
Observe the following class definition and answer the question that follows : [CBSE
SQP 2016]
   class info:
    ips=0
    def _str_(self): #Function 1
    return "Welcome to the Info Systems"
    def _init_(Self):
    self. _ Sstemdate= " "
    self. SystemTime = " "
    def getinput (self):
    self . Systemdate = raw_input ("enter data")
    self , SystemTime = raw_Input ("enter data")
    Info, incrips ()
    Estaiomethod # Statement 1
    def incrips ():
    Info, ips, "times"
    I = Info ()
    I. getinput ()
    Print I. SystemTime
    Print I. _Systemdate # Statement 2
i. Write statement to invoke Function 1.
Answer:
i. print I
ii. The statement 2 is giving an error because _Systemdate is a private variable and
hence cannot to be printed outside the class.
TOPIC – 5
Short Programs
Question 1.
Write a program to calculate the area of a rectangle. The program should get the
length and breadth ; values from the user and print the area.
Answer:
 length = input(“Enter length”)
  breadth = input(“Enter breadth”)
  print “Area of rectangle =”,length*breadth
Question 2.
Answer:
 import math
  a = input(“Enter coefficient of x^2”)
  b = input(“Enter coefficient of x”)
  c = inputfEnter constant term”)
  d = b*b  4*a*c
  if d == 0:
  print “Roots are real and equal”
  root1 = root2 = b / (2*a)
  elif d > 0:
  print “Roots are real and distinct”
  root1 = ( b + math.sqrt(d)) / (2*a)
  root2 = (b  math.sqrt(d)) / (2*a)
  else:
  print “Roots are imaginary”
  print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.
Write a program to input any number and to print all the factors of that number.
Answer:
Write a program to input ,.any number and to check whether given number is
Armstrong or not.
Answer:
 n = inputfEnter the number”)
  savedn = n
  sum=0
  while n > 0:
  a = n%10
  sum = sum + a*a*a
  n = n/10
  if savedn == sum:
  print savedn,“is an Armstrong Number”
  else:
  print savedn,”is not an Armstrong Number”
Question 5.
Answer:
Answer:
 i=1
  s=0
  dec = int ( raw_input(“Enter the decimal to be converted:”))
  while dec>0:
  rem=dec%2
  s=s + (i*rem)
  dec=dec/2
  i=i*10
  print “The binary of the given number is:”,s raw_input()
Question 7.
Write a program to convert binary to decimal
Answer:
Write a program to input two complex numbers and to find sum of the given complex
numbers.
Answer:
Write a program to input two complex numbers and to implement multiplication of the
given complex numbers.
Answer:
Write a program to find the sum of all digits of the given number.
Answer:
Answer:
22
333
4444
55555
Answer:
    for i in range(1,6):
     for j in range(1,i+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 string
  usemame= raw_input(“Enter username”)
  password = raw_input(“Enter password”)
  if cmp(username.strip(),“XXX”)== 0:
  if cmp(password,”123”) == 0:
  print “Login successful”
  else:
  print “Password Incorrect”
  else:
  print “Username Incorrect”
Question 14.
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:
Write a program to input username and password and to check whether the given
username and password are correct or not.
Answer:
 import string
  usemame= raw_input(“Enter username”)
  password = raw_input(“Enter password”)
  if 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]
Answer:
          1.   len(str)
          2.   str.title() or str.capitalize()
          3.   str.isalpha and str.isdigit()
          4.   lower(str[i])
          5.   str.replace(char, newchar)
Question 18.
Write a program to input any string and to find the number of words in the string.
Answer:
Write a program to input n numbers and to insert any number in a particular position.
Answer:
Write a program to input n numbers and to search any number from the list.
Answer:
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’,‘9884412345’]
  flag=0
  number = raw_input(“Enter the phone number to be searched")
  number = number.strip()
  try:
  i = phonenumbers.index(number)
  if i >= 0:
  flag=1
  except ValueError:
  pass
  if(flag <>0):
  print “\nphone number found in Phonebook at index”, i
  else:
  print'\iphonenumbernotfoundin phonebook”
  print “\nPHONEBOOK”
  printlist(phonenumbers)
Question 22.
Write a program to input n numbers and to reverse the set of numbers without using
functions.
Answer:
 class Client:
  def init (self, ID = 1, NM=”Noname”) #
  constructor
  self.CID = ID
  self. Name = NM
  def Allocate (self, changelD, Title) :
  self.CID = self.CID + Changeld
  self.Name = Title + self. Name
  def Display (self) :
  print (self. CID). "#”, self. Name)
  C1 = Client ()
  C2 = Client (102)
  C3 = Client (205, ‘’Fedrick”)
  C1 . Display ()
  C2 . Display ()
  C3 . Display ()
  C2 . Allocate (4, "Ms.”)
  C3 .Allocate (2, "Mr.”)
  C1. Allocate (1, "Mrs.”)
  C1. Display ()
  C2 . Display ()
  C3 . 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
 412
 Also, explain the try and except used in the code.
 Count = 0
 while True :
 try:
 Number=int (raw input ("Input a Number :"))
 break
 Except valueError :
 Count=Count + 2
 # For later versions of python, raw_input
 # Should be consider as input
mehtods:
– Add () # Method to allow user to enter values Dcode, 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.
Answer:
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:
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)
  if (x > 0) :
  for i in range (x) :
  print self.mylist.pop (),
  else :
  print "Stack is empty”