1 ITT205 ---------2021--------
2 Here is a detailed answer to all questions, including optional ones, from the
2021 December ITT205 Python problem-solving question paper.
3
4
5 ---
6
7 PART A (Answer all questions; each carries 3 marks)
8
9 1. Explain the use of break statement in Python with an example.
10 The break statement terminates the nearest enclosing loop prematurely.
11 Example:
12
13 for i in range(1, 10):
14 if i == 5:
15 break
16 print(i)
17 # Output: 1, 2, 3, 4
18
19
20 ---
21
22 2. Write a Python program to find the average of n numbers entered by the
user.
23
24 n = int(input("Enter the number of elements: "))
25 nums = [float(input(f"Enter number {i+1}: ")) for i in range(n)]
26 average = sum(nums) / n
27 print("Average:", average)
28
29
30 ---
31
32 3. Write a Python program that takes two strings entered by the user and
prints True if the first string appears as a substring in the second.
33
34 str1 = input("Enter the first string: ")
35 str2 = input("Enter the second string: ")
36 print(str1 in str2)
37
38
39 ---
40
41 4. Write a Python program that takes a list of numbers and copies only odd
numbers to a new list.
42
43 numbers = list(map(int, input("Enter numbers separated by spaces:
").split()))
44 odd_numbers = [num for num in numbers if num % 2 != 0]
45 print("Odd numbers:", odd_numbers)
46
47
48 ---
49
50 5. Explain parameters and arguments in a function with an example.
51
52 Parameters: Variables in a function definition.
53
54 Arguments: Values passed to the function when called.
55 Example:
56
57
58 def greet(name): # name is the parameter
59 print(f"Hello, {name}")
60
61 greet("Alice") # "Alice" is the argument
62
63
64 ---
65
66 6. What is a recursive function? Explain with an example.
67 A recursive function calls itself to solve smaller subproblems of the
original problem.
68 Example:
69
70 def factorial(n):
71 if n == 1:
72 return 1
73 return n * factorial(n - 1)
74
75 print(factorial(5)) # Output: 120
76
77
78 ---
79
80 7. Write a function ls() for printing all files in the current working
directory.
81
82 import os
83
84 def ls():
85 for file in os.listdir('.'):
86 if os.path.isfile(file):
87 print(file)
88
89 ls()
90
91
92 ---
93
94 8. Explain the pickle module in Python with an example.
95 The pickle module is used to serialize and deserialize Python objects.
96 Example:
97
98 import pickle
99
100 data = {"name": "Alice", "age": 25}
101 with open("data.pkl", "wb") as file:
102 pickle.dump(data, file)
103
104 with open("data.pkl", "rb") as file:
105 loaded_data = pickle.load(file)
106 print(loaded_data)
107
108
109 ---
110
111 9. Define the terms class and attributes with the help of an example.
112
113 Class: A blueprint for creating objects.
114
115 Attributes: Variables associated with an object.
116 Example:
117
118
119 class Dog:
120 def __init__(self, name):
121 self.name = name # Attribute
122
123 my_dog = Dog("Buddy")
124 print(my_dog.name) # Accessing attribute
125
126
127 ---
128
129 10. Explain the concept of inheritance in Python with an example.
130 Inheritance allows one class to derive properties from another.
131 Example:
132
133 class Animal:
134 def speak(self):
135 print("Animal speaks")
136
137 class Dog(Animal):
138 def speak(self):
139 print("Dog barks")
140
141 dog = Dog()
142 dog.speak() # Output: Dog barks
143
144
145 ---
146
147 PART B (Answer one full question from each module; each carries 14 marks)
148
149
150 ---
151
152 Module 1
153
154 11a. Write a Python program to find the sum of all prime numbers in a group
of n numbers entered by the user.
155
156 def is_prime(num):
157 if num < 2:
158 return False
159 for i in range(2, int(num**0.5) + 1):
160 if num % i == 0:
161 return False
162 return True
163
164 n = int(input("Enter the number of elements: "))
165 numbers = [int(input(f"Enter number {i+1}: ")) for i in range(n)]
166 prime_sum = sum(num for num in numbers if is_prime(num))
167 print("Sum of primes:", prime_sum)
168
169 11b. Define the terms expression and statement with the help of an example.
170
171 Expression: A combination of values and operators that evaluates to a value.
172 Example: 2 + 3 → evaluates to 5.
173
174 Statement: An instruction that performs an action.
175 Example: x = 5 assigns 5 to x.
176
177
178
179 ---
180
181 12a. Write a Python program to find the sum of all odd numbers divisible by
three in a group of n numbers entered by the user.
182
183 n = int(input("Enter the number of elements: "))
184 numbers = [int(input(f"Enter number {i+1}: ")) for i in range(n)]
185 odd_sum = sum(num for num in numbers if num % 2 != 0 and num % 3 == 0)
186 print("Sum of odd numbers divisible by 3:", odd_sum)
187
188 12b. What is the use of the continue statement in Python?
189 The continue statement skips the current iteration and moves to the next.
190 Example:
191
192 for i in range(5):
193 if i == 2:
194 continue
195 print(i) # Output: 0, 1, 3, 4
196
197
198 ---
199
200 Module 2
201
202 13a. Write a Python program to remove duplicate elements from a list and
print the count of elements removed.
203
204 numbers = list(map(int, input("Enter numbers separated by spaces:
").split()))
205 unique_numbers = list(set(numbers))
206 print("Unique list:", unique_numbers)
207 print("Duplicates removed:", len(numbers) - len(unique_numbers))
208
209 13b. Write a Python program to reverse elements in a tuple.
210
211 tpl = tuple(map(int, input("Enter numbers separated by spaces: ").split()))
212 reversed_tpl = tpl[::-1]
213 print("Reversed tuple:", reversed_tpl)
214
215 14a. Write a Python program to create a dictionary of subjects as keys and
marks as values, then print a report card with total marks.
216
217 subjects = {}
218 n = int(input("Enter the number of subjects: "))
219 for _ in range(n):
220 subject = input("Enter subject name: ")
221 marks = int(input(f"Enter marks for {subject}: "))
222 subjects[subject] = marks
223
224 print("Report Card:")
225 for subject, marks in subjects.items():
226 print(f"{subject}: {marks}")
227 print("Total Marks:", sum(subjects.values()))
228
229 14b. Write a Python program to count the number of times a character appears
in a string.
230
231 string = input("Enter a string: ")
232 char = input("Enter the character to count: ")
233 print(f"'{char}' appears {string.count(char)} times in the string.")
234
235 Continuing with a detailed solution for Modules 3, 4, and 5, including all
optional questions:
236
237
238 ---
239
240 Module 3
241
242 15a. Write a lambda function in Python to calculate the area of a circle.
243
244 import math
245 area_circle = lambda r: math.pi * r ** 2
246 radius = float(input("Enter radius of the circle: "))
247 print("Area of the circle:", area_circle(radius))
248
249
250 ---
251
252 15b. Write a recursive function to find the nth Fibonacci number.
253
254 def fibonacci(n):
255 if n <= 1:
256 return n
257 else:
258 return fibonacci(n - 1) + fibonacci(n - 2)
259
260 n = int(input("Enter the position of Fibonacci number: "))
261 print(f"The {n}th Fibonacci number is:", fibonacci(n))
262
263
264 ---
265
266 16a. Write a Python function to calculate the least common multiple (LCM) of
two numbers.
267
268 def gcd(a, b):
269 while b:
270 a, b = b, a % b
271 return a
272
273 def lcm(a, b):
274 return a * b // gcd(a, b)
275
276 num1 = int(input("Enter first number: "))
277 num2 = int(input("Enter second number: "))
278 print(f"LCM of {num1} and {num2} is:", lcm(num1, num2))
279
280
281 ---
282
283 16b. Explain package imports in Python with the help of an example.
284 Packages are collections of modules organized in a directory structure.
Importing allows you to use their functionalities.
285 Example:
286
287 # Directory Structure:
288 # my_package/
289 # __init__.py
290 # module1.py
291
292 # module1.py
293 def greet(name):
294 print(f"Hello, {name}")
295
296 # main.py
297 from my_package import module1
298 module1.greet("Alice")
299
300
301 ---
302
303 Module 4
304
305 17a. Write a Python function to copy the contents of one file to another
file, omitting lines that begin with # or !.
306
307 def copy_file(input_file, output_file):
308 with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
309 for line in infile:
310 if not (line.startswith('#') or line.startswith('!')):
311 outfile.write(line)
312
313 input_file = "source.txt"
314 output_file = "destination.txt"
315 copy_file(input_file, output_file)
316 print("File copied successfully!")
317
318
319 ---
320
321 17b. Write a function in Python that takes a directory name as an argument
and prints the list of complete paths for all files in the directory.
322
323 import os
324
325 def list_files(directory):
326 for root, dirs, files in os.walk(directory):
327 for file in files:
328 print(os.path.join(root, file))
329
330 directory = input("Enter directory name: ")
331 list_files(directory)
332
333
334 ---
335
336 18a. Explain how exceptions are handled using try and except statements in
Python with the help of an example.
337 Exceptions are handled using try and except to prevent program crashes.
338 Example:
339
340 try:
341 num = int(input("Enter a number: "))
342 result = 10 / num
343 print("Result:", result)
344 except ZeroDivisionError:
345 print("Cannot divide by zero!")
346 except ValueError:
347 print("Invalid input! Please enter a number.")
348
349
350 ---
351
352 18b. Write a function in Python that takes a filename and returns True if the
file exists, False otherwise.
353
354 import os
355
356 def file_exists(filename):
357 return os.path.isfile(filename)
358
359 filename = input("Enter filename: ")
360 if file_exists(filename):
361 print("File exists.")
362 else:
363 print("File does not exist.")
364
365
366 ---
367
368 Module 5
369
370 19a. Create a class Person with attributes name, age, and department. Two
classes, Student and Faculty, inherit from Person. Add specific attributes
and methods for these classes.
371
372 class Person:
373 def __init__(self, name, age, department):
374 self.name = name
375 self.age = age
376 self.department = department
377
378 class Student(Person):
379 def __init__(self, name, age, department, marks):
380 super().__init__(name, age, department)
381 self.marks = marks
382
383 def display(self):
384 print(f"Student: {self.name}, Age: {self.age}, Department:
{self.department}, Marks: {self.marks}")
385
386 class Faculty(Person):
387 def __init__(self, name, age, department, salary):
388 super().__init__(name, age, department)
389 self.salary = salary
390
391 def display(self):
392 print(f"Faculty: {self.name}, Age: {self.age}, Department:
{self.department}, Salary: {self.salary}")
393
394 student = Student("Alice", 20, "CS", 85)
395 faculty = Faculty("Dr. Smith", 45, "CS", 80000)
396
397 student.display()
398 faculty.display()
399
400
401 ---
402
403 19b. Write the __init__ method for the Date class that takes year, month, and
day as optional parameters and assigns them to attributes.
404
405 class Date:
406 def __init__(self, year=1970, month=1, day=1):
407 self.year = year
408 self.month = month
409 self.day = day
410
411 date = Date(2023, 12, 2)
412 print(f"Date: {date.year}-{date.month:02}-{date.day:02}")
413
414
415 ---
416
417 20a. Write a Python program to display details of a Team Leader using
multiple inheritance.
418
419 class Employee:
420 def __init__(self, employee_id, salary):
421 self.employee_id = employee_id
422 self.salary = salary
423
424 class TeamMember:
425 def __init__(self, name, age, project_code):
426 self.name = name
427 self.age = age
428 self.project_code = project_code
429
430 class TeamLeader(Employee, TeamMember):
431 def __init__(self, employee_id, salary, name, age, project_code,
team_size):
432 Employee.__init__(self, employee_id, salary)
433 TeamMember.__init__(self, name, age, project_code)
434 self.team_size = team_size
435
436 def display(self):
437 print(f"Team Leader: {self.name}, Age: {self.age}, Employee ID:
{self.employee_id}, "
438 f"Salary: {self.salary}, Project Code: {self.project_code},
Team Size: {self.team_size}")
439
440 team_leader = TeamLeader(101, 75000, "John", 35, "P123", 5)
441 team_leader.display()
442
443
444 ---
445
446 20b. Create a class Square with attributes number and output, and methods
calculate and display.
447
448 class Square:
449 def __init__(self, number):
450 self.number = number
451 self.output = None
452
453 def calculate(self):
454 self.output = self.number ** 2
455
456 def display(self):
457 print(f"The square of {self.number} is {self.output}")
458
459 square = Square(7)
460 square.calculate()
461 square.display()
462
463
464 ---
465
466 This provides a comprehensive and detailed answer to every question in the
problem set. Let me know if you need further clarifications or additional
explanations!
467
468
469
470