2020 Itt205
2020 Itt205
2
3 Here is a detailed response to all questions from the provided ITT205
December 2020 Python question paper, including those from the modules.
4
5
6 ---
7
8 PART A (Answer all questions; each carries 3 marks)
9
10 1. What are keywords? Give examples.
11 Keywords are reserved words in Python with specific meanings and purposes.
They cannot be used as variable names or identifiers.
12 Examples: if, else, while, for, def, class, return.
13
14
15 ---
16
17 2. When should we use nested if statements? Explain with an example.
18 Nested if statements are used when one condition depends on another condition
being true.
19 Example:
20
21 num = int(input("Enter a number: "))
22 if num > 0:
23 if num % 2 == 0:
24 print("The number is positive and even.")
25 else:
26 print("The number is positive and odd.")
27 else:
28 print("The number is not positive.")
29
30
31 ---
32
33 3. Write a program that converts a sentence entered by the user into a list
of words.
34
35 sentence = input("Enter a sentence: ")
36 word_list = sentence.split()
37 print("List of words:", word_list)
38
39
40 ---
41
42 4. Illustrate when to use list, tuple, and dictionary with an example.
43
44 List: Use when the data is ordered and can change.
45 Example: fruits = ["apple", "banana", "cherry"]
46
47 Tuple: Use for ordered data that should not change.
48 Example: dimensions = (1920, 1080)
49
50 Dictionary: Use for key-value pairs.
51 Example: student = {"name": "John", "age": 20}
52
53
54
55 ---
56
57 5. What are packages in Python?
58 Packages are a way of organizing Python modules into directories with a
hierarchy. They help manage code by grouping related functionalities. For
example, the numpy package is used for numerical computations.
59
60
61 ---
62
63 6. Write a Python function that accepts three arguments x, y, and z. Find x +
y, and if the sum is greater than z, return the square root of (x² + y²).
Otherwise, return 0.
64
65 import math
66
67 def calculate(x, y, z):
68 total = x + y
69 if total > z:
70 return math.sqrt(x**2 + y**2)
71 else:
72 return 0
73
74
75 ---
76
77 7. What is the advantage of using pickling? Explain the dump and load
methods.
78 Pickling is used to serialize and save Python objects for later use. It
allows easy storage and retrieval of complex data structures.
79
80 dump: Writes a serialized object to a file.
81
82 load: Reads a serialized object from a file.
83
84
85
86 ---
87
88 8. Explain the utility of the open() function.
89 The open() function is used to open files in Python for reading, writing, or
appending. Syntax: open(filename, mode) where mode can be 'r', 'w', 'a', etc.
90
91
92 ---
93
94 9. What is the significance of the __init__() method?
95 The __init__() method is the constructor in Python classes. It initializes
the object’s attributes when an object is created.
96
97
98 ---
99
100 10. What is class instantiation? How is it done?
101 Class instantiation is the process of creating an object from a class. It is
done by calling the class name as if it were a function.
102 Example:
103
104 class Dog:
105 def __init__(self, name):
106 self.name = name
107
108 my_dog = Dog("Buddy") # Instantiation
109
110
111 ---
112
113 PART B (Answer one full question from each module)
114
115
116 ---
117
118 Module 1
119
120 11a. List the rules to name an identifier in Python.
121
122 1. Identifiers can only contain letters (a-z, A-Z), digits (0-9), and
underscores (_).
123
124
125 2. They cannot begin with a digit.
126
127
128 3. Keywords cannot be used as identifiers.
129
130
131 4. Identifiers are case-sensitive.
132
133
134
135 11b. Write a program to generate all prime numbers in a given range.
136
137 def find_primes(start, end):
138 for num in range(start, end + 1):
139 if num > 1: # Prime numbers are greater than 1
140 for i in range(2, int(num**0.5) + 1):
141 if num % i == 0:
142 break
143 else:
144 print(num, end=" ")
145
146 start = int(input("Enter start of range: "))
147 end = int(input("Enter end of range: "))
148 find_primes(start, end)
149
150
151 ---
152
153 12a. Write a program to read a number and then calculate the sum of its
digits.
154
155 num = int(input("Enter a number: "))
156 digit_sum = sum(int(digit) for digit in str(num))
157 print("Sum of digits:", digit_sum)
158
159 12b. What are the different operators used in Python? Briefly explain.
160
161 1. Arithmetic operators: +, -, *, /, %, **, //
162
163
164 2. Comparison operators: ==, !=, <, >, <=, >=
165
166
167 3. Logical operators: and, or, not
168
169
170 4. Bitwise operators: &, |, ^, ~, <<, >>
171
172
173 5. Assignment operators: =, +=, -=, etc.
174
175
176
177
178 ---
179
180 Module 2
181
182 13a. Write a Python program to add 'ing' at the end of a string. If it
already ends with 'ing', then add 'ly'.
183
184 word = input("Enter a word: ")
185 if word.endswith("ing"):
186 word += "ly"
187 else:
188 word += "ing"
189 print("Modified word:", word)
190
191 13b. What is meant by mutability of a data structure? Explain with lists and
tuples.
192
193 Mutable: Data that can be modified (e.g., lists).
194
195 Immutable: Data that cannot be modified (e.g., tuples).
196 Example:
197
198
199 # Mutable
200 lst = [1, 2, 3]
201 lst[0] = 10 # Allowed
202
203 # Immutable
204 tup = (1, 2, 3)
205 # tup[0] = 10 # Error
206
207
208 ---
209
210 14a. Write a program to print all indices of a particular value in a list.
211
212 lst = [1, 2, 3, 2, 4, 2]
213 val = int(input("Enter value: "))
214 indices = [i for i, x in enumerate(lst) if x == val]
215 print("Indices:", indices)
216
217 14b. Write a Python program to create a dictionary of roll numbers and names
of five students, and display contents in alphabetical order of names.
218
219 students = {
220 101: "Alice",
221 102: "Bob",
222 103: "Charlie",
223 104: "Dave",
224 105: "Eve"
225 }
226 sorted_students = sorted(students.items(), key=lambda x: x[1])
227 print("Sorted students:", sorted_students)
228
229
230 ---
231
232 Continuing from the earlier response, here's a detailed answer to all
remaining questions from Modules 3, 4, and 5.
233
234
235 ---
236
237 Module 3
238
239 15a. Differentiate between global and local variables.
240
241 Global Variables: Defined outside of any function and accessible throughout
the program.
242
243 Local Variables: Defined inside a function and accessible only within that
function.
244 Example:
245
246
247 x = 10 # Global variable
248
249 def my_function():
250 x = 5 # Local variable
251 print("Local x:", x)
252
253 my_function()
254 print("Global x:", x)
255
256
257 ---
258
259 15b. Write a program to read an integer number. Print the reverse of this
number using recursion.
260
261 def reverse_number(num, rev=0):
262 if num == 0:
263 return rev
264 else:
265 return reverse_number(num // 10, rev * 10 + num % 10)
266
267 num = int(input("Enter a number: "))
268 reversed_num = reverse_number(num)
269 print("Reversed number:", reversed_num)
270
271
272 ---
273
274 16a. Write a function that accepts two positive numbers n and m, where m <=
n, and returns numbers between 1 and n that are divisible by m.
275
276 def divisible_numbers(n, m):
277 return [i for i in range(1, n + 1) if i % m == 0]
278
279 n = int(input("Enter n: "))
280 m = int(input("Enter m: "))
281 if m <= n:
282 print("Numbers divisible by", m, ":", divisible_numbers(n, m))
283 else:
284 print("m must be less than or equal to n")
285
286
287 ---
288
289 16b. Compare the built-in functions int() and str() with examples. What are
they used for?
290
291 int(): Converts a value to an integer.
292 Example: int("42") → 42
293
294 str(): Converts a value to a string.
295 Example: str(42) → "42"
296
297
298
299 ---
300
301 Module 4
302
303 17a. Write a program that infinitely prints natural numbers. Raise the
StopIteration exception after displaying the first 20 numbers to exit the
program.
304
305 class NaturalNumbers:
306 def __init__(self, limit):
307 self.num = 1
308 self.limit = limit
309
310 def __iter__(self):
311 return self
312
313 def __next__(self):
314 if self.num > self.limit:
315 raise StopIteration
316 current = self.num
317 self.num += 1
318 return current
319
320 numbers = NaturalNumbers(20)
321 for number in numbers:
322 print(number)
323
324
325 ---
326
327 17b. Write a program that reads a file and prints only those lines that have
the word "python" in it.
328
329 filename = input("Enter the file name: ")
330 with open(filename, 'r') as file:
331 for line in file:
332 if "python" in line.lower():
333 print(line.strip())
334
335
336 ---
337
338 18a. How are exceptions handled in Python? Illustrate with an example.
339 Exceptions in Python are handled using try and except blocks.
340 Example:
341
342 try:
343 num = int(input("Enter a number: "))
344 result = 10 / num
345 print("Result:", result)
346 except ZeroDivisionError:
347 print("Cannot divide by zero!")
348 except ValueError:
349 print("Invalid input! Please enter a number.")
350
351
352 ---
353
354 18b. Write a program that reads a file and copies its contents into another
file. While copying, replace all full stops with commas.
355
356 input_file = input("Enter input file name: ")
357 output_file = input("Enter output file name: ")
358
359 with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
360 for line in infile:
361 modified_line = line.replace('.', ',')
362 outfile.write(modified_line)
363 print("File copied successfully with replacements.")
364
365
366 ---
367
368 Module 5
369
370 19a. Make a class Book with members title, author, publisher, and ISBN
number. Write functions for the class that will read and display the data.
371
372 class Book:
373 def __init__(self, title, author, publisher, isbn):
374 self.title = title
375 self.author = author
376 self.publisher = publisher
377 self.isbn = isbn
378
379 def display(self):
380 print(f"Title: {self.title}")
381 print(f"Author: {self.author}")
382 print(f"Publisher: {self.publisher}")
383 print(f"ISBN: {self.isbn}")
384
385 book = Book("Python Basics", "John Doe", "Tech Books", "123456789")
386 book.display()
387
388
389 ---
390
391 19b. Create a class Student with attributes name and roll_no, and a method
dataprint() for displaying them. Create two instances of the class and call
the method for each instance.
392
393 class Student:
394 def __init__(self, name, roll_no):
395 self.name = name
396 self.roll_no = roll_no
397
398 def dataprint(self):
399 print(f"Name: {self.name}, Roll No: {self.roll_no}")
400
401 student1 = Student("Alice", 101)
402 student2 = Student("Bob", 102)
403
404 student1.dataprint()
405 student2.dataprint()
406
407
408 ---
409
410 20a. Explain the term class, object, and attributes.
411
412 Class: A blueprint for creating objects. It defines attributes and methods.
413
414 Object: An instance of a class.
415
416 Attributes: Variables that hold data associated with an object.
417 Example:
418
419
420 class Car:
421 def __init__(self, make, model):
422 self.make = make
423 self.model = model
424
425 my_car = Car("Toyota", "Corolla") # Object
426 print(my_car.make, my_car.model) # Attributes
427
428
429 ---
430
431 20b. Create a class Employee with attributes name, age, and salary. Write a
method briefdetails() for displaying them. Create instances and use the
method.
432
433 class Employee:
434 def __init__(self, name, age, salary):
435 self.name = name
436 self.age = age
437 self.salary = salary
438
439 def briefdetails(self):
440 print(f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}")
441
442 emp1 = Employee("John", 30, 50000)
443 emp2 = Employee("Jane", 25, 45000)
444
445 emp1.briefdetails()
446 emp2.briefdetails()
447
448
449 ---
450
451 This completes the detailed answers for all questions in the provided Python
problem-solving question paper. Let me know if you need further
clarification!
452
453