0% found this document useful (0 votes)
4 views21 pages

3

The document contains various Python programming exercises and concepts, including list manipulation, tuple indexing, dictionary key-value pairs, and string operations. It also includes multiple-choice questions and assertions related to Python's data types and their properties. Additionally, it provides solutions to specific coding problems and explanations of concepts like indexing and slicing in Python.

Uploaded by

enggpranjal9
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
0% found this document useful (0 votes)
4 views21 pages

3

The document contains various Python programming exercises and concepts, including list manipulation, tuple indexing, dictionary key-value pairs, and string operations. It also includes multiple-choice questions and assertions related to Python's data types and their properties. Additionally, it provides solutions to specific coding problems and explanations of concepts like indexing and slicing in Python.

Uploaded by

enggpranjal9
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
You are on page 1/ 21
2.3 Given three lists as listl = ['a’,*b’,c"] list2 = ['h’,4?, ] and list3 = [‘0",'1’,*2"]. Write a program that adds lists 2 and 3 to listl as single element each. The i resultant list should be in the order of list3, rogram elements of listt, list2, list =['a','b','c*] list2=['h',"i',"t'] list3 "er,'1', '2°] print ("Originally :") print("List1=", list1) print("List2=", list2) print("List3 =", 1ist3) # adding 1ist2 as single element at the end of list1 Hstt.append(list2) _#1ist2 gets added as one element at the end of List! # adding list3 as single element at the start of list list1.insert(@,list3) #1ist3 gets added as one print("After adding two lists as individual e. print (list1) element at the beginning of List! ‘lements, list now is :") 7. PYTHON REVISION TOUR. ee? ‘The output produced by above program is as follows : peter adding two Tists as individual elements, list now is : (rote Te 2De a TB Me he] 4 Given three lists as list! = ('a°,"b’,'c"),list2 = [*h’,*7,1°] and list = ['0",'1''2"]. Write a program that adds individual elements of lists 2 and 3 to listl. The resultant list should be in the order of p. elements of list3, elements of list1, elements of list2. list =['a',"b','c'] List2=([‘h',‘i','t"] List3=('0", "2", '2"] print("Originally :*) print("List1 =", listz) print("List2=", list) print("List3 =", list3) # adding elements of list at the end of list3 List3.extend(list1) # adding elements of List2 at the end of list3 List3.extend(1ist2) print( “After adding elenents of two lists individually, list now is print (1ist3) The output produced by above program is as follows : original List = ['a', 'b', 'c'] List2= (tht, i", 't'] List3 = ['0", '1', '2°] After adding elements of two lists individually, list now is : (tor, ‘1", "2, ta, bt, tet, the, t,t!) 2.5. Write a program that finds an element’s index/position in a tuple WITHOUT using index(). tuplet=(‘a','p','p'y‘1',"e"s) char = input ("Enter a single letter without quotes if char in tuple: count = @ for ain tuple1 if'a l= char: count += 1 rogram ™~ 2 COMPUTER SCIENCE wiTy Poy else: break print(char, "is at index", count, "in", tuple1) else: print(char, "is NOT in", tuple1) Enter a single letter without quotes : 1 Lis at position 3 in ('a', 'p', 'p', "7 ee ee Enter a single letter : p p is at position 1 in ('a’, 'p’, ‘pt, "7 2.6 Write a program that checks for presence of a value inside a dictionary and prints its key. P info = {"Riya’:'CSc.", 'Mark':'Eco", ‘Ishpreet’ — inp = input(“Enter value to be searched for :") if inp in info. values(): for a in info: if infofa] == inp: print (“The key of given value is break m Eng’, 'Kamaal': "Env. sey a) else: print(“Given value does not exist in dictionary") Enter value to be searched for : Env.sc The key of given value is kamaal Enter value to be searched for : eng Given value does not exist in dictionary P 2.7 The code of previous will not work if the cases of the given ‘ifferent. That is, the resule (of previous program) will be Enter value to be searched for : eng Given value does not exist in dictionary Make changes in above program so that the Program returns the key, ‘match the two values ignoring their cases value and value inside dictionary are e: Program even if the cases differ, ie, info = {'Riya':'CSc.*, “Mark': inp = input (“Enter value t for ain info: if info[a] .upper() == in print ("The key of, break “Eco, 'Ishpreet': ‘Eng’, "Kamal": 'Env.sc*} ‘0 be searched for :") iP-upper() ; given value is”, a) else: Print ("Given value does not Enter value to be searched for : en The key of given value is Ishpreet exist in dictionary") 9 OTQs CU 1>> 4nt("3" 4 "4") (a) “7” (b) “34” (4 (dy 24 Which line of code will cause an error ? print(num[3][@]) int (num[5]) (b) Line 2 (0 Line 4 (@) Line 1 Which is the correct form of declaration of dictionary ? (@) Day = {1'Monday’, 2:Tuesday’, 3:‘wednesday') (b) Day = {1/Monday’, (©) Day = [1:’Monday’, 2:"Tuesday’, 3:';wednesday’] (@) Day = {1'monday’, 2'tuesday’, 3'wednesday') Identify the valid declaration of L: L=[‘Mon', '23", ‘hello’, '60.5'] [se Pe (2) dictionary (©) string (0 tuple (@) list Suppose a tuple T is declared as T=(10, 12, 43,39), which of the following is incorrect ? (a) print(T(1)) (® T[2] = -29 (© print(max(T)) (@) print(len()) [CBSE SP 238-21) Given the following Tuple: Tup = (18, 20, 30, 50} Which of the following statements will result in an error ? [CBSE D 233) (a) print(tup[o]) (b) Tup-insert(2, 3) (c) print(Tup[1:2]) —(d) print(1en(Tup)) + Which of the following statement(s) would give an error after executing the following cose ? ae el ve COMPUTER SCIENCE WITH PYTHON . ) Statement 2 (h) Statement 3 0 seument 4 (a) Statements 2 and 4 [CBSE D amy ieee ste nal of the following will delete key-value pair for key = “Red” from a dictionary D1 ? (@) delete D1("Red") () del D1["Red"} (©) del.01["Red"} (a) D1.del["Red"] [CBSE SP nes. What does the listremove(x) method do in Python ? (c) Removes the element at index x m the list (}) Removes the first occurrence of value x from the list (©) Removes all occurrences of value x from the list (@) Removes the last occurrence of value x from the list [CBSE SP 224-251 FILL IN THE BLANKS Strings in Python store their individual letters in Memory in location. Operator when used with two strings, gives a concatenated string. Operator when used with a string and an integer gives an error. Part of a string containing some contiguous characters from the string is called The operator when used with a list/string and an integer, replicates the list/string. are not mutable while lists are. Using function, you can make a true copy of a list. The The The function is used to remove an item from a list/dictionary. statement can remove an individual item or a slice from a list, function removes all the elements of a list/dictionary. Creating a tuple from a set of values is called Creating individual values from a tuple’s elements is called The method returns all the keys in a dictionary. The The function retums all values from Key : value pair of function returns all the Key : value pairs as (key, TRUE/FALSE QUESTIONS present the same list”, a dictionary. value) sequences. Do both the following re ['a', ‘bY, te") {'c', ‘a’, ‘by A list may contain any type of objects excey pt another list. ‘There is no conceptual limit to the size of a list, All elements in a list must be of th same type, | A given object may appear in a list The keys of a dictionary must be of in You can combine a numeric value The clear( ) removes alll the ele: wore than one mutable types. and a string by using the + symbol. “ments Of a dictionary but does not delete the empty dictionary. The max() and min() when used with tuples, can work if elements of the tuple are all ofthe same type THON REVISION TOUR. noe i jn, AList of characters 8 Similar ta 9 eteing type ti. Por any index m, sE:0} + sin] will give year on ginal ateing, 4 12. A dictionary can contain keys of any valid : iython Fypoa Assertions AND REASONS. piRECTIONS In the following questions, a statement © Mark the correct choice as : (@) Both A and R are true andl R is the cortect explanation of A (0) Both A and R are true but K fs not the cortect explanation of A (¢) Ais true but R is false (or partly true). (@ A's false (or partly true) but R is true, (€) Both A and Rave falee oF nor fully tse of Assertion (A) Is folloroed by a statement of Racor (i). 1. Assertion. Lists and Tuples are similar sequence types of Python, yet they are tars differen Reason. List sequences are mutable and Tuple sequences are immutable, 2 deste Modifying, a string creates another string internally but modifying a list does nor crmate # new lis 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 dows nor croato + 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 a value can be changed in place without having to create new storage for the changed value, 5. Assertion (A), The expression “HELLO” .sort() in Python will give an error. Reason (R), sort () does not exist as a method/function for strings in Python. 6. Assertion. Dictionaries are mutable but their keys are immutable. Reason, The values of a dictionary can change but keys of dictionary cannot be changed because through them data is hashed. 7. 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. Batty NOTE : Answers for OTQs are given at the end of the book. Solved Problems |. What is indexing in context to Python strings ? Why is it also called two-roay indexing ? Solution. In Python strings, each individual character is given a location number, called inde ance this process is called indexing. Python allocates indices in two directions : * in forward direction, the indexes are numbered as 0, 1, 2... lengthel. Bue length, * in backward direction, the indexes are numbered as ~1, -2, This is known as two-way indexing. COMPUTER SCIENCE WITH PYTHON ti) 2, What isa string slice ? How is it usefil ? of a string, say 8, can sub-part or a stice ‘ eger ae srume all the characters at indices 1 w+ 1, w+ 2.M—T OR» intege on re *well done’ [1:4] re out the problem with following code fragmte be obtained using s Im ml where and m ay willgive ‘ell’ Fi ent, Correct the code and then print the output. 3. Figu *must* 4, n2=3 5. print(si+s2) 6. print(s2*n2) 7. print(si+n1) 8. print(s2* s1) Solution. The problem is with lines 7 and 8. ¢ Line 7 - print(s1 + n1) will cause error because s1 being a string cannot be concatenated with a number nl. This problem can be solved either by changing the operator or operand ¢.g,, all the following statements will work : (@) print (s1*n1) (®) print (s1+str(n1)) (© 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) If we replace the Line 7 with its suggested solution (b), the output will be : must try . try try try i must 10 try must 4. Find and write the output of the following python code : [CBSE Sample Paper 2019-2] x= “abcdef” iste" while $ in x: print(i, en Solution. aaaaaa—- keeps printing a's endlessly OR infinite loop 5. Write the output on execution of the following Python code (CBSE D 2024) S = “Racecar Car Radar" L=S.split() for Win xe upper ) 1): for Tinx : print(I, end = Copter 2: PTHON REVSION TOUR! else: for I inw: print(I, end ="#") print() Solution. R*ASC*E*C#ASR® chatr# RAA*D*APRY & Consider the following code : string = input( "Enter a string :") count = 3 while True : if string[@] =='a : string = string[2 :] elif string[-1] =='b : string = string [: 2] else: count += break print(string) print(count) What will be the output produced, if the input is : (i) aabbec (ii) aaccbb (iii) abce Solution. (a) bbee (B) ce () ee 4 4 4 7. Consider the following code : Inp = input ("Please enter a string : while len(Inp) <=4: if Inp[-1] condition 1 Iny :3)eic elif ‘a’ in Inp: condition 2 Inp = Inp[@] +06 elif not int(Inp[@]) = condition 3 Inp ='1' + Inp[1 :] +'2 else: Inp = Inp+'* print(Inp) What will be the output produced if the input is (i) 1bzz, (ii)' 1a" (iti) abe" iv)" Oxy’, (0) xy Solution. (i) 1bzc+ (ii) 1bb+* (ii). endless loop because d will always remain at index 0 and condition 3 will be repeated endlessly. (iv) Ixyew (») Raises an error as Inp[0] cannot be converted to int. ich word and 8 Write a program that takes a string with muiltiple words and then capitalizes the first letter of forms a new string out of it. Solution. string = input( “Enter a string :") length = len(string) a=0 end = length COMPUTER SCIENCE WITH PrTHy, - oot string? =" tempty string while ac length : ifassO: string2 += string[®].upper() ated elif (string[a] =="' and stringlata] string2 += string[a] string2 += string[a+1].upper() at=2 else: string2 += stringla] ats1 print ("Original String :", string) Print (Captilized words String", string2) S. Write a program that reads a string and checks whether it is a palindrone string or not. Solution. string = input ("Enter a string : length = len(string) forainrange(mid) : if string[a] == string[rev] : ata rev-=1 . else: print(string, “is not a palindrome") break else: #loop else print(string, “isa palindrome") 10. How are lists different from strings when both are sequences ? Solution. The lists and strings are different in following ways : (© The lists are mutable sequences while strings are immutable. (i) In consecutive locations, a string stores the individual characters while references of its elements. (iii) Strings store single a list stores the to different types, ‘ype of elements ~ all characters while lists can store elements belonging 11. What are nested lists 7 Solution. When a list is contained in another list as a member-element, it is called nested list, ¢. a=(2,3, 14, 5] The above list a has three elements — 12. ‘an integer 2, an integer 3 and a list [4, 5], How is a mutable object different from an immutabl hence it is nested list immutable object from the following : le object in Python ? Identify one mutable object and one (1,2), [2,2], (1:2, 2:2}, "123" [case sp 202425), - NP HON REVISION TOURAI 4 83 owe? anc A mutable object can be gqtution A updated in place whereas an immutable object cannot be updated inp uuatieobiects®—— Cs2] or (122,222) Famarat cect? (192) 0" 223" what does cach of the following expressions evaluate to? 15 J gation. Suppose that L is the list [rThese”, ["are”, “a”], ["few", “words"], “that”, “we", “will”, “use”. @ upsea] + L222] () "Few" in t[2:3] (0 “few in 2] @ ust) (@) Ufa} +t[2] solution. (@ Usa] = Cthat’] upa:2] = (Lares ‘a]] ~ [3:4] + L[2:2] = that’, [are’, ‘a]] () False. The string “few” is not an element of this range. L{2:3] returns a list of elements from L-> [Cfew’, ‘words'}], this is a list with one element, a list. (0 True. L{2] returns the list [‘few’, ‘words'], “few” is an element of this list. (@ U2] = (few, words'] (© Ula)= [are] U[2][4:] = [words'} L[2] = (few, ‘words'] L[1] +L [2] = Care’, ‘a’, ‘few, ‘words'] 1A. Given the lists L=[1,3,6,82,5,7,11,92], write the output of print(L{2:5). (case sP 202 Solution. [6, 82, 5] 15. What will be the output of the following code ? (ses tuple = (1, 2, 3) tuple2 = tuple tuplel += (4,) print (tuple1 == tuple2) (@) True ( False (© tuplel (@ Error Solution. (b) False 16. What is the output produced by the following code snippet ? alst =[1,2,3,4,516,7,829] print(aLst[::3]) Solution. [1,4,7] Write the output displayed on execution ofthe following Python code : Ls = ["HIMALAYA", "NILGIRI", "ALASKA", “ALPS"] D={} for Sin Ls + if len(S)*4 ==: D[s] = len(5) = v, for KinD: es print(K, D[K], sep = “#") ution, — HIMALAYA#B ALPS#A | COMPUTER SCIENCE WITH PYIHioy, What will be the output of the folli 1g code snippet ? Ust =[1,2,3,4,5,6,7,8,9] Lst[1:2]=16, 20, 30,40, 50,60 print(Lst) (a) ValueError : attempt to assign sequence of size 6 to extended slice of size 5 (b) 110, 2, 20, 4, 30, 6, 40, 8, 50, 60) © _[1, 10, 3, 20, 5, 30, 7, 40, 9, 50, 60] Solution. @ (©) [1, 2, 10, 20, 30, 40, 50, 60] 19. What will be the output of the following code snippet 2 values = [] fori in range (1,4): values. append(i) print (values) es) G, 2] (, 2,3] What will be the output of the following code ? rec = {"Name" r=rec.copy() print(id(r) == id(rec)) p (@) True Solution. Python", "Ag 20"} (®) False (oo @1 Solution. @) Given the following dictionaric dict_exam = {"Exar [CBSE sP as ‘AISSCE", "Year" :2023} dict_result = {"Total":500, "Pass_Marks":165} Which statement will merge the contents of both dictionaries ? (@)_ dict_exam.update(dict_result) (&) dict_exam+ dict_result (© dict_exam.add(dict_result) (4) dict_exam.merge(dict_result) Solution. (a) dict_exam.update(dict_result) What will be the output of the following code snippet? ded = {} de1[a] =2 dei['1'}=2 de1[1.0} =4 ‘sum = @ fork indci: sum += de1[k] print (sum) Solution, pyTHON REVISION TOUR. oot! ct the output of following code fragment Myst =O i = [’Apple’, ‘Banana’, * 4 in apple’, ‘Banana’ } 4 index in fruit: fruit[index) += 1 else: fruit[index] = 1 print(fruit) print (len(fruit)) {*Apple' : 1} {‘Apple': 1, 'Banana’: 1) {'Apple’: 1, "Banana': 1, ‘apple’: 1) {‘Apple": 1, 'Banana': 2, ‘apple’: 1} 3 gatution. Predict the output of the Python code given below : leas tuplet = (11, 22, 33, 44, 55 ,66) List1 =List(tuple1) new_list = [] for iin listi: if i%2 new_list.append(i) new_tuple = tuple(new_list) print(new_tuple) Solution, (22,44,66) Find the error in following code. State the reason of the error. alst={'a':1,'b* print (alst[‘a’,b"]) Solution, The above code will produce KeyE: ['a’,’b']in dictionary aLst. It seems that the above co “vy, thus we can modify the above code to perform this as : alst = {'a":1,'b':2,'c':3} print (aLst{‘a‘J, aLst['b"]) Now it will give the result as: 12 2, Find the error in the following code fragment. State the reason behind the error. box = (} Jars = {} crates = {} box{ 'biscuit"] =1 box['cake"] = 3 ror, the reason being that there is no key same as the list .de intends to print the values of two keys ‘a’ and ) COMPUTER SCIENCE WITH PTO = jars(‘jam']=4 crates{ box’ ] = box crates[‘jars'] = jars print (crates[box]) The above code will produce error with print) because its trying to Print the valy dictionary crates by specify a key which is of a mutable type dictionary(box is a dictionary) ee 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" }) 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. (©) Add an element in the end of the list. (@) Add an element in the beginning of the list. (©) Add elements of a list in the end of a list. (2) remove() (6) pop() (c) append() (d) insert() (©) extend() How are tuples different from lists when both are sequences ? Soluson. The tuples and lists are different in following ways : * The tuples are immutable sequences while lists are mutable. ‘+ Lists can grow or shrink while tuples cannot. How can you say that a tuple is an ordered list of objects 2 Sowsson. A tuple is an ordered list of objects. This is evidenced by the fact that the objects can accessed through the use of an ordinal index and for a given index, same element fe reams everytime. Following code is trying to create a tuple with a single item. But when we try to obtain the length of the tare is, Python gives error. Why? What is the solution ? >>> t= (6) >>> len(t) Traceback (most recent call last): File“", line 1, in len(t) TypeError: object of type ‘int has no len() jaion. Tne syntax for a tuple with a single item requires the item to be followed by a commas shown below : tec) Thus, above code is not creating a tuy ple in t but an integer, on which len( ) cannot be applic! To create a tuple in t with single element, the code should be modified wen >>> t=(6,) >>> len(t) 31. What is the length of the tuple shunwn below ? b= (CCCat, 1), 0s), 8, 2), 'e, 3) _— aa Yr x 36, “37. peIHOH PEMBION TOU 4 sptutions The length OF his tuple is Vheenise there are ss fare Tok atthe given tuple yield that tuple tb - aaae ne Oe tera" nade 1p ttl, “b’, “ec” paet2,"d",2 te ( 13,6", 3) can tuples be nested ? galution. Tuples can contain other compound objects, ineuding, liste, dieters ged Set open Hence, tuples can be nested, . sma How ar dictionaries different from lists? Solution, ‘The dictionary in similar to liste in the serise that it is alors a ceMlecticn of Gata tomes pot 8 ists BUT it is different fram liste in the serie that lists ate wequential cltzctions (cxdeonts) #08 dictionaries are non sequential collections (unordered) aap ee lon coca Oe In lists, where there is an order associated with the data-tterns becauye they act 7 © other objects or variables you've created, Dictionaries are different fre sad group of objects they hold aren't in any particular order, but rather wack: ame, commonly known as a key. How are objects stored int lists and dictionaries different ? Golution. The objects or values stored in a dictionary can basically te anepthing (1m he ro defined as None), but Keys can only be immutable type-ckjects. «7, sete, e=ple = When are dictionaries more useful than lists ? Solution, Dictionaries can be much more useful than lists. For example, sup si our friends’ cell-phone numbers. We could create a list of pairs (nazne off aa eonee this list becomes long enough searching this list for a specific prone a econsuming, Better would be if we could index the list by our frienc’s ra Tr what a dictionary does. Can sequence operations such as slicing and concatenation be applied to dictionaries ? Wey solution. No, sequence operations like slicing and concatenation cannot be applied on dictionaries The reason being, a dictionary is not a sequence. Because itis not maintained in any spec - operations that depend on a specific order cannot be used. Why can’t Lists be used as keys ? solution, Lists cannot be used as keys in a dictionary because they are mutable. And 2 dictionary can have only keys of immutable types. Ifthe addition of anew key-value pair causes the size of the dictionary to grow beyond its original size, a error occurs. True or false ? Solution, False. There cannot occur an error because grow or shrink on an as-needed basis. (A) Write the Python statement for each of the following tasks using built-in functions/methods only ionary named Students. m whose key is “NISHA” from a the dictionary Students contains (“ANITA” : 90, “NISHA” : 76, “ASHA® = atthe dictionary should contain (“ANITA” : 90, “ASHAY = 2) s” in string named message. Dictionaries being the mutable types. they can () To remove th For example, 92), then after remov. (i) To display the number of occurrences of the substring “is For example, ifthe string message contains “This i his book”, then the output will be 3. CANIS AOR HI PTH Ag ny on AB) A tip named subject stares the wanes of different aulierte, Witte the Vyslin commande MW HOMOH hg glen tuple 0-0 Hot aul hereafter sltete the aot eament af the Hab fom rig lution (A) 0) de} Student s| "NISHA" ] (ii) message, count ("1s") fi Or ubjects = ("Mathe”, "Computer sesance”, "English", "Phystes") ublist = 1st (subjects) ublist, pop() idera dictionary amy. points with slngle-tetter keys, each falnoed by a 2-element tuple representing the iniates of a point in an x-y eoordinale plane, 4,3), Ws (1,2), 4,1) ) Write a program to calculate the marlon vad from with all of the valnes tuples at same inde. For example, maximem for 0 index will he computed from value 4, Land fi~ all the entrles ut 0 index in the value-tuple, Print the result in following format 1 Maximum Value at index(my points, 6) = Maximum Value at index(my points, 1) = 3 Solution, — my_podnts = ("a's (4, 3), "Ws (1,9), "es (5,1) ) highest = [@, 6] init =0 for a An range(2) : b init = for b in my_points.keys(): val = ny_points[b][a] AP init == 0: highest [a] » val init += 1 Af val > highest{a] : highest[a] « val print "Maximum Value at {ndex(my points, ", a,") «", highest[a}) ny points = GLOSSARY — Dletlonary ‘A mutable, unordered collaction with elements In the form of a koy:value pairs that associate keys to valve Index ‘Ax integer varlable thot Is used to Identify the Position of an element and accoss the element. Ust A tutoble sxquencn of Pylhon that can store objec of any typo. Lookup 4 dicionary operation that takes 4 kay and finds tho corresponding valve Mapping Linking of a boy vith «value trough some Internal lunetin (hash function), ‘Nesting —Hving an olarnant of similar typu Inside another element, Packing §— Creating « Wple from individual valugs, Tuple ‘An tmunusabla voquence of elomonts. Unpacking — Craving individual valves from a tuple’s wlemants, Sorting —_ Arranging alemante of saquenca in some order (axcanding/doxcending) pap gsignment un 12, 13, 44 2: PYTHON REVISION TOUR«I EA: TREAT SHORT ANSWER QUESTIONS/CONCEPTUAL QUESTIONS What is the intemal structure of Python strings ? wae on eat ea traverses through an input string and prints its characters in different lines ~ piscuss the utility and significance of Lists, briefly. What do you understand by mutability 7 What does “in place’ start with the list [8, 9, 10}. Do the following : (a) Set the second entry (index 1) to 17 (o) Remove the first entry from the list (0) Double the list task mean ? (b) Add 4, 5 and 6 to the end of the list (@) Sott the list () Insert 25 at index 3 What's a]1 1] if a is a string of at least two characters ? And what if string is shorter ? What are the two ways to add something to a list ? How are they different ? ‘What are the two ways to remove something from a list? How are they different ? What is the difference between a list and a tuple ? In the Python shell, do the following : () Define a variable named states that is an empty list. _(if) Add ‘Delhi to the list. (il), Now add ‘Punjab’ to the end of the list. (io) Define a variable states? that is initialized with ‘Rajasthan’, ‘Gujarat’, and ‘Kerala’. (@) Add ‘Odisha’ to the beginning of the list states2. (vi) Add ‘Tripura’ so that it is the third state in the list states2. (vi) Add ‘Haryana’ to the list states2 so that it appears before ‘Gujarat’. Do this as if yor DO NOT KNOW where ‘Gujarat’ is in the list. Hint, See what states2.index(“Rajasthan”) does. What can you conclude about what listname.index(item) does ? (viii) Remove the 5th state from the list states2 and print that state’s name. Discuss the utility and significance of Tuples, briefly. If ais (1, 2, 3) (@) what is the difference (if any) between a * 3 and (a, a, a) ? (6) is a*3 equivalent toa+a+a? (c) what is the meaning of a[1:1] ? (4) what's the difference between a[1:2] and a[1:1] ? What is the difference between (30) and (30,) ? Write a Python statement to declare a Dictionary named ClassRoll with Keys as 1, 2, 3 and corres- ponding values as ‘Reena’, ‘Rakesh’, ‘Zareen’ respectively. ese 20] [int ClassRoll = {1:"Reena", 2:"Rakesh”, 3:"Zareen"} | Why is a dictionary termed as an unordered collection of objects ? What type of objects can be used as keys in dictionaries ? Though tuples are immutable type, yet they cannot always be used as keys in a dictionary, What is the condition to use tuples as a key in a dictionary ? . Dictionary ig a mutable type, which means you can modify its contents ? What all is modifiable in a dictionary ? Can you modify the keys of a dictionary ? all Pr 0 a 4 6 CATA REITER HETIL Vaan te ate 1) anal te Fyfetion of TTEIann teaey ctae aredlid HEP Eta etal ‘vette abettonuany tnnnyent atte Tareas wie ie ha Bega a Wane AFM eg peetie ICY Hi Hig ‘a woestetvayt Re (VYPAED) 4 UN Tak afanae F81Tun otTE yae Te Fee oy Mee caaietaderd Bey Ad Ceca, BENE Ye! apa!) f Wun fe montane Noni eusnns faspnear eae tag Hee H Ab Asievaven Botte unt anatase any ova tec Ht yt Vie Ne ABPLICATION DARED QUES HOHE Wat with te tle cnntpnah gunned fy Flletyy eae: Hygiene f (ye Hed Laan i (a) ye stra’) (eet ny xe Mholty" #9 Lo by thant 1\, WMA AE AL A ay, printer, y) “wor tl wedlnbefed, ALD so "hel to" world" tor chan Lit WHA AL AE AL) y= len(x) y= chat peint(yy x) pred (yy SE onthe") Write a short Python ene seyanent Ut atl cp Hee legis Ga al thee were IAL Hak An it fit tha average (mean) length, Predict the output of the following code sntyypel a= [1,2,3,4,5) print(a[3:0:-1]) Predict the output of the following code ulppel? (a) arr = [4, 2, 3, 4) 5, 6) for 4 An range(1, 6): are <4) =aneti] for iin range(0, 6): print(arr[i], end =" ") (H) Numbers = [9, 18, 27, 36] for Num in Numbers + for Nin range(1, Numi) : print(N, "Wy end ="") fos amie print() Find the errors, State reasons, (a) t= (A, "a", 9.2) (i) t= "helte t[0] = 6 t(0] =" () te U4, "9", 9.2) tle) 6 (0) for Name In [Anar, Shveta, Parag) TE Name[O] = 68" (t=, "2", 9.24 print (Name) t[4] =6 fone bane Assuming, words isa valld Hat of words, the Progrant below (le to print the fist in reverse, Does It have an error? If so, why ? (Hint ‘There are two problenie with the cade.) for 4 in range(len(words), 0, <1)+ print(words[4], ond =" ') 1: PYTHON REVSION TOUR chapter 1d be the output of foll nat woul lowing code if ntpl = (“Hello”, “Nita”, “How's”, 2 wi vee, d) «tpl ntpl = (“Hello”, “Nita”, “How's”, “life 7”) ? a) 7 print("e 152") €) print("d is:", d) ntple (@ bs cd) print (ntp1[6][0]+ntpl[1}[1], ntpi[a}) What will be the output of the following code ? tuple_a= ‘a’, "b’ tuple_b=(‘a", 'b') print (tuple_a == tuple_b) @o i (0) False (d) True «a, What will be the output of the following code snippet ? rec = {"Name" : "Python", “Age":"20", "Addr" : "NJ", “Country” : "USA"} idi = id(rec) del rec rec = ("Name id2 = id(rec) print(idi == id2) : "Python", “Age":"20", "Addr" : "NI", “Country” : "USA"} (a) True (b) False @1 (@) Exception 10. Write the output of the code given below : [CBSE Sample Paper my_dict = {"name": "Aman", “age’ my_dict[‘age’] = 27 my_dict['address'] = "Delhi" print (my_dict .items()) 11. Write a method in python to display the elements of list thrice if it is a number and display the element terminated with ‘#” if it is not a number. [CBSE D 2015} For example, if the content of list is as follows : List = [(41’, ‘DROND’, “GIRTRAI’, ‘137, “ZARA J The output should be 414141 ‘DROND# GIRIRAJ# 131313 ZARAH Name the function/method required to () check if a string contains only uppercase letters i) gives the total length of the list. 2, {CBSE D 2015}, COMPUTER SCIENCE WITH PYTHON ~ xy, What will be the output of the following code snippet ? my_dict = {} my_dict[(1,2.4)]=8 my_dict[(4,2,1)] = 10 my_dict[(1,2)] = 12 sum =@ fork inmy_dict: sum += my_dict[k] print (sum) print(my_dict) TYPE C : PROGRAMMING PRACTICE/KNOWLEDGE BASED QUESTIONS 1. Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input. Display if the phone number entered is valid format or not and display if the phone number is valid or not (i¢,, contains just the digits and dash at specific places). Write a program that should prompt the user to type some sentence(s) followed by “enter”. It should then print the original sentence(s) and the following statistics relating to the sentence(s) : Number of words Number of characters (including white-space and punctuation) Percentage of characters that are alpha numeric Hi = Assume any consecutive sequence of non-blank characters in a word. Write a program that takes any two lists L and M of the same size and adds their elements together to form a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L=[3,1,4] and M=[1,5,9} then N should equal [4, 6, 13]. 4, Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc, and the element in the last index moves to the first index. Write a short Python code segment that prints the longest word in a list of words. Write a program that creates a list of all the integers less than 100 that are multiples of 3 or 5. Define two variables first and second so that first = “Jimmy” and second = “Johny”. Write a short Python code segment that swaps the values assigned to these two variables and prints the results, Write a Python program that creates a tuple storing first 9 terms of Fibonacci series. 9, Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months. (a) Ask the user to enter a month name and use the di month. ; (0) Printout all of the keys in alphabetical order. _(¢) Print out all of the months with 31 days. (@) Print out the (key-value) pairs sorted by the number of days in each month. : 30, Write a function called addDiet(dictl, dict2) which computes the union of two dicti return a new dictionary, with all the items in both its arguments (assumed to be di same key appears in both arguments, feel free to pick a value from either. 11, Write a program to sort a dictionary’s keys using Bubble sort and produce the sorted keys as a list. 12, Write a program to sort a dictionary’s values using Bubble sort and produce the sorted values as a list. nary to tell them how many days are in the naries. It should ynaries). If the

You might also like