Class 12 CS Chapter 2 Python Revision Tour II Solutions

Contents show

Python Revision Tour II Solutions

Python Revision Tour II Solutions
Class 12 CS Chapter 2 Python Revision Tour II Solutions

Q 1. What is indexing in context to Python strings ? Why is it also called two-way indexing ?


Ans. In Python strings, each individual character is given a location number, called index and this process is called indexing.
Python allocates indices in two direction :

  • in forward direction, the indexes are numbered as 0, 1, 2,…. length-1
  • in backward direction, the indexes are numbered as -1, -2. -3…. length.
    This is known as two-way indexing.

Q 2. What is a string slice ? How is it useful ?


Ans. A sub-part or a slice of a string, say s, can be obtained using s[n:m] where n and m are integers. Python returns all the character at indices n, n+1, n+2…m-1 e.g.,
‘Well done’ [1:4] will give ‘ell’

Q 3. Figure out the problem with following code fragment. Correct the code and then print the output.

1. s1 = 'must'
2. s2 = 'try'
3. n1 = 10
4. n2 = 3
5. print(s1+s2)
6. print(s2*n2)
7. print(s1+n1)
8. print(s2*s1)

Ans. The problem is wih lines 7 and 8.

  • Line 7 – print(s1+n1) will cause error because s1 being a string cannot be concatenated with a number n1.

This problem can be solved either by changing the operator or operand e.g., all the following statements will work :

(a) print(s1*n1)
(b) print(s1+str(n1))
(c) print(s1+s2)

Line 8 – print(s2*s1) will cause error because two strings cannot be used for replication. The corrected statement will be :

print(s2+s1)

Q 4. Consider the following code : [Python Revision Tour II]

string = input("Enter a string")
count = 3
while True :
           if string[0] == 'a' :
                string = string[2:]
            elif string[-1] == 'b' :
                   string = string[:2]
            else :
                 count += 1
                 break
print(string)
print(count)

What will be the output produced, if the input is :


(i) aabbcc
(ii) aaccbb
(iii) abcc

Ans.

(a) bbcc            (b) cc               (c) cc
    4                   4                     4

Q 5. Consider the following code :

Inp = input("Please enter a string :")
while len(Inp) <= 4 :
      if Inp[-1] == 'z' :                  #condition 1
            Inp = Inp[0:3] + 'c'
       elif 'a' in Inp :                     #condition 2
              Inp = Inp[0] + 'bb'
       elif not int(Inp[0]) :            #condition 3
               Inp = '1' + Inp[1:] + 'z;
        else :
               Inp = Inp + '*'
print(Inp)

What will be the output produced if the input is (i) 1bzz, (ii) ‘1a’ (iii) ‘abc’ (iv) ‘0xy’, (v) ‘xyz’.

Ans.
(i) 1bzc*
(ii) 1bb**
(iii) endless loop because ‘a’ will always remain in index 0 and condition 3 will be repeated endlessly.
(iv) 1Xyc*
(v) Raises an error as Inp[0] cannot be converted to int.

Q 6. Write a program that takes a string with multiple words and then capitalizes the first letter of each word and forms a new string out of it. (Python Revision Tour II)


Ans.

string = input("Enter a string :")
length = len(string)
a = 0
end = length
string2 = ' '                      #empty string
while a<length :
         if a == 0 :
                  string2 += string[0].upper( )
                  a += 1
          elif (string[a] == ' ' and string[a+1] != ' ') :
               string2 += string[a]
               string2 += string[a+1].upper( )
               a += 2
           else :
                string2 += string[a]
                a += 1
print("Original String :", string)
print("Captilized words String :", string2)

Q 7. Write a program that reads a string and checks whether it is a palindrome string or not.


Ans.

sting = input("Enter a string :")
length = len(string)
mid = length/2
rev = -1 
for a in range(mid) :
       if string[a] == string[rev] :
              a += 1
              rev -+ 1
        else :
               print(string, "is not a palindrome")
               break
else :              #loop else
       print(string, "is a palindrome")

Q 8. How are lists different from strings when both are sequences ?


Ans. The lists and strings are different in following ways :


(i) The lists are mutable sequences while strings are immutable.
(ii) In consecutive locations, a string stores the individual characters while a list stores the references of its elements.
(iii) String store single type of elements – all characters while lists can store elements belonging to different types.

Q 9. What are nested lists ?


Ans. When a list is contained in another list as a member-element, it is called nested list, e.g.,

a = [2, 3, [4, 5]]

The above list a has three elements – an integer 2, an integer 3 and a list [4, 5], hence it is nested list.

Q 10. What is output produced by the following code snippet ?

aLst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(aLst[::3])

Ans.

Ans. [1, 4, 7]

Q 11. What will be the output of the following code snippet ?

Lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Lst[::2] = 10, 20, 30, 40, 50, 60
print(Lst)

(a) ValueError : attempt to assign sequence of size 6 to extended slice of size 5
(b) [10, 2, 20, 4, 30, 6, 40, 8, 50, 60]
(c) [1, 2, 10, 30, 40, 50, 60]
(d) [1, 10, 3, 20, 5, 30, 7, 40, 9, 50, 60]

Ans. (a)

Q 12 What will be the output of the following code ?

values = [ ]
for i in range (1, 4) :
        values.append(i)
        print(values)

Ans.

[1]
[1, 2]
[1, 2, 3]

Q 13. What will be the output of the following code ?

rec = {"Name" : "Python", "Age" : "20"}
r = rec.copy( )
print(id(r) == id(rec))

(a) True (b) False (c) 0 (d) 1

Ans. (b)

Q 14. What will be the output of the following code snippet ?

dc1 = {}
dc1[1] = 1
dc1['1'] = 2
dc1[1.0] = 4
sum = 0
for k in dc1 :
       sum += dc1[k]
print(sum)

Ans.

6

Q 15. Predict the output of following code fragment :

fruit = {}
f1 = ['Apple', 'Banana', 'apple', 'Banana']
for index in f1 :
        if index in fruit :
             fruit[index] += 1
        else :
             fruit[index] = 1
        print(fruit)
print(len(fruit))

Ans.

{'Apple' : 1}
{'Apple' : 1, 'Banana' : 1}
{'Apple' : 1, 'Banana' : 1, 'apple' : 1}
{'Apple' : 1, 'Banana' : 2, 'apple' : 1}
3

Q 16. Find the error in following code. State the reason of the error.

aLst = {'a' : 1, 'b' : 2, 'c' : 3}
print(aLst['a', 'b'])

Ans. The above code will produce KeyError, the reason being that there is no key same as the list [‘a’, ‘b’] in dictionary aLst.
It seems that the above code intends to print the values of two keys ‘a’ and ‘b’, thus we can modify the above code to perform this as :

aLst = {'a' : 1, 'b' : 2, 'c' : 3}
print(aLst['a'], aLst['b'])

Now it will give the result as :

1 2

Q 17. Find the error in the following code fragment. State the reason behind the error.

box = { }
jars = { }
crates = { }
box['biscuit'] = 1
box['cake'] = 3
jars['jam'] = 4 
crates['box'] = box
crates['jars'] = jars
print[crates[box])

Ans. The above code will produce error with print( 0 because it is trying to print the value from dictionary crates by specify a key which is of a mutable type dictionary(box is a dictionary). There can never be a key of mutable type in a dictionary, hence the error.
The above code can be corrected by changing the print( ) as :

print(crates['box'])

Q 18. Write the most appropriate list method to perform the following tasks.


(a) Delete a given element from the list.
(b) Delete 3rd element from the list.
(c) Add an element in the end of the list.
(d) Add an element in the beginning of the list.
(e) Add elements of a list in the end of a list.


Ans. (a) remove( )
(b) pop( )
(c) append( )
(d) insert( )
(e) extend( )

Q 19. How are tuples different from lists when both are sequences ?
Ans. The tuples and lists are different in following ways :

  • The tuples are immutable sequences while lists are mutable.
  • List can grow or shrink while tuples cannot.

Q 20. How can you say that a tuple is an ordered list of objects ?


Ans. A tuple is an ordered list of objects. This is evidenced by the fact that the objects can be accessed through the use of an ordinal index and for a given index, same element is returned everytime.

Q 21. Following code is trying to create a tuple with a single item. But when we try to obtain the length of the tuple is, Python gives error. Why? What is the solution ?

>>> t = (6)
>>> len(t)
Trackback(most recent call last) :
File "<pyshell#8>", line 1, in <module>
    len(t)
TypeError : object to type 'int' has no len( )

Ans. The syntax for a tuple with a single item requires the item to be followed by a comma as shown below

t = ("a", )

Thus, above code is not creating a tuple in t but an integer, on which len( ) cannot be applied. To create a tuple in t with single element, the code should be modified as :

>>> t = (6, )
>>> len(t)

Q 22. What is the length of tuple shown below ?

t = (((('a', 1), 'b', 'c'), 'd', 2), 'e', 3)

Ans. The length of this tuple is 3 because there are just three elements in the given tuple. Because a careful look at the given tuple yields that tuple t is made up of :

t1 = "a", 1
t2 = t1, "b2", "c"
t3 = t2, "d", 2
t = (t3, "e", 3)

Q 23. Can tuples be nested ? [Python Revision Tour II]


Ans. Tuples can contain other compound objects, including lists, dictionaries, and other tuples. Hence, tuples can be nested.

Q 24. How are dictionaries different from lists ?


Ans. THe dictionary is similar to lists in the sense that it is also a collection of dat-items just like lists BUT it is different from lists in the sense that lists are sequential collections (ordered) and dictionaries are non-sequential collections (unordered).
In lists, where there is an order associated with the data-items because they act as storage units for other objects or variables you’ve creatd. Dictionaries are different from lists and tuples because the group of objects they hold aren’t in any particular order, but rather each object has its own unique name, commonly known as a key.

Q 25. How are objects stored in lists and dictionaries different ?


Ans. The objects or values stored in a dictionary can basically be anything(even the nothing type defined as None), but keys can only be immutable type-objects. e.g., strings, tuples, integers, etc.

Q 26. When are dictionaries more useful than lists ?


Ans. Dictionaries can be much more useful than lists. For example, suppose we wanted to store all our friends’ cell-phone numbers. We could create a list of pairs (name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get time-consuming. Better would be if we could index the list by our friend’s name. This is precisely what a dictionary does.

Q 27. Can sequence operations such as slicing and concatenation be applied to dictionaries ? Why ?


Ans. No, sequence operations like slicing and concatenation cannot be applied on dictionaries. The reason being, a dictionary is not a sequence. Because it is not maintained in any specific order, operations that depend on a specific order cannot be used.

Q 28. Why can’t Lists be used as keys ?


Ans. Lists cannot be used as keys in a dictionary because they are mutable. And a Python dictionary can have only keys of immutable types.

Q 29. If the addition of a new key:value pair causes the size of the dictionary to grow beyond its original size, an error occurs. True or false?


Ans. False. There cannot occur an error because Dictionaries being the mutable types, they can grow or shrink on an as-needed basis.

Python Revision Tour II

Hope, you that these questions helps you in your preparation for computer science with python class 12 Board Exams.

Read More :

Python Revision Tour I Solutions

CBSE Class 12 Computer Science Notes

Python Revision Tour II

In this content your chapter 2 Python Revision Tour II important questions and answers based on latest cbse examination pattern is covered.

Python Revision Tour II