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

CIT 2228 Exam Revision Questions

The document contains a comprehensive set of revision questions for a Computer Programming II course at Multimedia University of Kenya, covering topics such as Python concepts, object-oriented programming, data structures, file handling, exceptions, and advanced Python concepts. Each section includes multiple questions that require explanations, code implementations, and analysis of outputs. The questions are designed to test the understanding and application of programming principles and practices.

Uploaded by

maverickgray37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views21 pages

CIT 2228 Exam Revision Questions

The document contains a comprehensive set of revision questions for a Computer Programming II course at Multimedia University of Kenya, covering topics such as Python concepts, object-oriented programming, data structures, file handling, exceptions, and advanced Python concepts. Each section includes multiple questions that require explanations, code implementations, and analysis of outputs. The questions are designed to test the understanding and application of programming principles and practices.

Uploaded by

maverickgray37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

MULTIMEDIA UNIVERSITY OF KENYA

FACULTY OF ENGINEERING AND TECHNOLOGY


CIT 2228: COMPUTER PROGRAMMING II
REVISION QUESTIONS

QUESTION ONE (COMPREHENSIVE PYTHON CONCEPTS)


(a) (5 marks) Identify and explain any errors in the following Python code snippet. If no errors
exist, state the output and explain the behavior:
1 def modify_list(items=[]):
2 items.append(1)
3 return items
4
5 print(modify_list())
6 print(modify_list())
7 print(modify_list([2]))
8 print(modify_list())
9

(b) (6 marks) Complete the following Python function to implement a Fibonacci sequence gen-
erator using recursion:
1 def fibonacci(n):
2 if _______:
3 return 0
4 elif _______:
5 return 1
6 return ______
7

(c) (4 marks) Explain the difference between shallow and deep copying in Python. Provide
code examples demonstrating each case.

(d) (4 marks) Given the following code snippet, what will be its output? Justify your answer:
1 x = 10
2 def func():
3 global x
4 x = 20
5 print(x)
6
7 func()
8 print(x)
9

(e) (4 marks) Write a Python list comprehension that:

• Generates a list of cubes for odd numbers between 1 and 30


• Filters out all non-alphabetic characters from a given string

(f) (4 marks) What will be the output of the following code and why? Explain dictionary
comprehension:

1
1 numbers = [1, 2, 3, 4, 5]
2 squared = {n: n**2 for n in numbers if n % 2 == 0}
3 print(squared)
4

(g) (5 marks) Given the string ”Hello World”, write Python code to:

• Count the occurrence of each character


• Reverse the string without using built-in reverse functions

QUESTION TWO (OBJECT-ORIENTED PROGRAMMING)


(a) (6 marks) Define encapsulation, inheritance, and polymorphism in Python. Provide a code
example demonstrating each concept.

(b) (6 marks) Given the following class hierarchy, what will be the output? Explain method
resolution order (MRO):
1 class A:
2 def show(self):
3 print("A")
4

5 class B(A):
6 def show(self):
7 print("B")
8
9 class C(A):
10 def show(self):
11 print("C")
12
13 class D(B, C):
14 pass
15
16 d = D()
17 d.show()
18 print(D.__mro__)
19

(c) (4 marks) Write a Python class representing a BankAccount with:

• Private attributes for account number and balance


• Methods for deposit, withdraw, and display balance

(d) (4 marks) What is the difference between @staticmethod and @classmethod? Pro-
vide an example use case for each.

QUESTION THREE (DATA STRUCTURES AND ALGORITHMS)


(a) (6 marks) Implement a stack data structure in Python with the following methods:

• push(item)
• pop()

2
• peek()
• ise mpty()size()

(b)• (6 marks) Write a Python function to sort a list of dictionaries by a specific key:
1 def sort_dict_list(dict_list, key):
2 # Your implementation here
3

(c) (4 marks) What is the time complexity of the following operations? Justify your answers:

• Accessing an element in a Python list by index


• Searching for a value in a Python dictionary
• Inserting an element at the beginning of a Python list

(d) (4 marks) Implement a binary search algorithm in Python both recursively and iteratively.

QUESTION FOUR (FILE HANDLING AND EXCEPTIONS)


(a) (5 marks) Write a Python program that reads a CSV file and:

• Calculates the average of a specified numeric column


• Handles potential file-related exceptions
• Uses context managers for file operations

(b) (6 marks) Create a Python script that:

• Takes a directory path as input


• Recursively counts all files with specific extensions (.txt, .csv, .py)
• Generates a summary report in JSON format

(c) (4 marks) Explain the difference between the following exception handling approaches:
1 try:
2 # code
3 except Exception as e:
4 # handling
5
6 try:
7 # code
8 except (ValueError, TypeError) as e:
9 # handling
10

(d) (5 marks) Write a Python function that validates user input for:

• Email address format


• Password strength (minimum 8 chars, 1 uppercase, 1 digit)
• Age (positive integer between 18-120)

3
QUESTION FIVE (ADVANCED PYTHON CONCEPTS)
(a) (5 marks) What will be the output of this asynchronous Python code? Explain the event
loop:
1 import asyncio
2
3 async def task(name, delay):
4 print(f"Start {name}")
5 await asyncio.sleep(delay)
6 print(f"End {name}")
7
8 async def main():
9 await asyncio.gather(
10 task("A", 2),
11 task("B", 1),
12 task("C", 3)
13 )
14
15 asyncio.run(main())
16

(b) (6 marks) Implement a Python decorator that:

• Logs function execution time


• Caches results for expensive computations
• Handles exceptions gracefully

(c) (4 marks) Explain the following Python concepts with examples:

• Context managers
• Descriptors
• Metaclasses

(d) (5 marks) Write a multithreaded Python program that:

• Downloads multiple files concurrently


• Implements a thread-safe progress counter
• Uses synchronization primitives

1 PYTHON FUNDAMENTALS
(a) (4 marks) Analyze the output of this code and explain the behavior of mutable default
arguments:
1 def append_to(element, collection=[]):
2 collection.append(element)
3 return collection
4
5 print(append_to(1))
6 print(append_to(2))
7

(b) (5 marks) Implement a function that converts between Celsius and Fahrenheit:

4
1 def convert_temp(temp, unit):
2 # Your implementation
3

(c) (6 marks) Given the code:


1 a = [1, 2, 3]
2 b = a
3 c = a[:]
4 b[0] = 10
5 c[1] = 20
6 print(a, b, c)
7

Explain the output and the concepts of reference vs value copying.

(d) (5 marks) Write a list comprehension that:

• Generates squares of even numbers between 1-50


• Filters prime numbers from a given list

(e) (4 marks) Explain the output and the concept of unpacking:


1 first, *middle, last = range(10)
2 print(middle)
3

(f) (6 marks) Implement a function that returns the first n Fibonacci numbers using a generator.

(g) (5 marks) Analyze the scope in this code:


1 x = 5
2 def outer():
3 x = 10
4 def inner():
5 nonlocal x
6 x += 5
7 print(x)
8 inner()
9 print(x)
10 outer()
11 print(x)
12

SECTION B: OOP CONCEPTS (25 Questions)


(a) (6 marks) Implement a Rectangle class with:

• Private width and height attributes


• Properties with validation
• Methods for area and perimeter

(b) (5 marks) Explain the output and MRO:

5
1 class A: pass
2 class B(A): pass
3 class C(A): pass
4 class D(B, C): pass
5 print(D.__mro__)
6

(c) (6 marks) Create an abstract base class ’Shape’ with:


• Abstract methods area() and perimeter()
• Concrete subclass Circle
(d) (4 marks) Differentiate between @classmethod, @staticmethod, and instance methods.
(e) (4 marks) Implement the str and repr methods for a Student class.

SECTION C: DATA STRUCTURES (25 Questions)


(a) (6 marks) Implement a queue using:
• Python lists
• collections.deque
(b) (5 marks) Write a function to reverse a linked list.
(c) (6 marks) Implement binary search tree operations:
• Insertion
• In-order traversal
(d) (4 marks) Analyze time complexity of:
• Dictionary lookups
• List concatenation
(e) (4 marks) Implement a graph using adjacency lists.

SECTION D: FILE I/O AND EXCEPTIONS (20 Questions)


(a) (6 marks) Write a program that:
• Reads a CSV file
• Calculates column statistics
• Handles file exceptions
(b) (5 marks) Implement a JSON configuration file handler with:
• Reading/writing
• Validation
(c) (4 marks) Create a custom exception hierarchy for a banking application.
(d) (5 marks) Write a context manager for timing code blocks.

6
SECTION E: ADVANCED CONCEPTS (20 Questions)
(a) (6 marks) Implement a memoization decorator for recursive functions.

(b) (5 marks) Analyze this async code:


1 async def fetch_data():
2 print("Start fetching")
3 await asyncio.sleep(2)
4 print("Done fetching")
5 return {’data’: 1}
6

(c) (4 marks) Explain GIL and its impact on multithreading.

(d) (5 marks) Implement a simple WSGI application.

(1) (4 marks) Explain the difference between ‘is‘ and ‘==‘ in Python. Provide code examples
to illustrate.

(2) (6 marks) Define a class ‘Car‘ with attributes ‘make‘ and ‘year‘. Add a method ‘display()‘
that prints them.

(3) (4 marks) Complete the following function to compute the sum of a list of numbers using a
loop.
1 def compute_sum(lst):
2 total = 0
3 for num in ______:
4 total += num
5 return total
6

(4) (6 marks) Define a class ‘Car‘ with attributes ‘make‘ and ‘year‘. Add a method ‘display()‘
that prints them.

(5) (5 marks) What is the output of the following Python code? Explain your reasoning.
1 def greet(name):
2 return f"Hello, {name}!"
3
4 print(greet("World"))
5

(6) (4 marks) Complete the following function to compute the sum of a list of numbers using a
loop.
1 def compute_sum(lst):
2 total = 0
3 for num in ______:
4 total += num
5 return total
6

(7) (4 marks) Explain the difference between ‘is‘ and ‘==‘ in Python. Provide code examples
to illustrate.

7
(8) (6 marks) Define a class ‘Car‘ with attributes ‘make‘ and ‘year‘. Add a method ‘display()‘
that prints them.
(9) (4 marks) Complete the following function to compute the sum of a list of numbers using a
loop.
1 def compute_sum(lst):
2 total = 0
3 for num in ______:
4 total += num
5 return total
6

(10) (5 marks) What is the output of the following Python code? Explain your reasoning.
1 def greet(name):
2 return f"Hello, {name}!"
3
4 print(greet("World"))
5

(11) (4 marks) Explain the difference between mutable and immutable data types in Python.
Provide code examples.
(12) (6 marks) Create a class ‘Student‘ with attributes ‘name‘ and ‘marks‘. Include a method
‘isp ass()‘thatreturns‘T rue‘if ‘marks ¿= 50‘
.

(13) (4 marks) Complete this function to return the maximum value from a list without using ‘max()‘:
1 def find_max(lst):
2 max_val = lst[0]
3 for num in ______:
4 if num > max_val:
5 max_val = num
6 return max_val
7

(14) (6 marks) Define a class ‘Rectangle‘ with ‘length‘ and ‘width‘. Include methods to compute area
and perimeter.
(15) (5 marks) What is the output of this code? Explain why.
1 def append_number(num, lst=[]):
2 lst.append(num)
3 return lst
4
5 print(append_number(1))
6 print(append_number(2))
7

(16) (4 marks) Complete the function to reverse a string using a loop:


1 def reverse_string(s):
2 result = ’’
3 for char in ______:
4 result = char + result
5 return result
6

8
(17) (4 marks) Explain the purpose and use of the ‘i nit‘ methodinP ythonclasses.P rovideanexample.
(18) (6 marks) Create a ‘Book‘ class with ‘title‘, ‘author‘, and ‘price‘. Add a method ‘discount()‘ that
applies a 10
(19) (4 marks) Fill in the blanks to count the number of vowels in a string:
1 def count_vowels(s):
2 vowels = ’aeiouAEIOU’
3 count = 0
4 for char in ______:
5 if char in ______:
6 count += 1
7 return count
8

(20) (5 marks) Predict the output and explain object references:


1 a = [1, 2]
2 b = a
3 b.append(3)
4 print(a)
5

(21) (4 marks) Write a list comprehension that extracts all numbers divisible by 3 from a list.
(22) (6 marks) Create a class ‘Circle‘ with ‘radius‘ and a method to compute the area.
(23) (4 marks) Complete the function that checks if a string is a palindrome:
1 def is_palindrome(s):
2 return ______ == ______
3

(24) (6 marks) Create a class ‘Temperature‘ with Celsius to Fahrenheit conversion.


(25) (5 marks) What is the output of this unpacking? Explain why.
1 a, *b, c = [10, 20, 30, 40, 50]
2 print(b)
3

(26) (4 marks) Write a list comprehension that squares all even numbers between 1 and 20.
(27) (4 marks) Describe the ‘try-except‘ block in Python. Provide an example that handles division by
zero.
(28) (6 marks) Define a class ‘Employee‘ with name, salary, and a raise method to increase salary by
10
(29) (4 marks) Complete this function to count how many times a word appears in a string:
1 def count_word(text, word):
2 words = text.split()
3 count = 0
4 for w in ______:
5 if w == ______:
6 count += 1
7 return count
8

9
(30) (5 marks) What will this print and why?
1 x = "hello"
2 y = x
3 x = x.upper()
4 print(y)
5

(31) (4 marks) Explain the concept of list slicing in Python. Show how to reverse a list using slicing.
(32) (6 marks) Define a class ‘BankAccount‘ with ‘deposit()‘ and ‘withdraw()‘ methods. Track the
balance.
(33) (4 marks) Complete the function to check if an integer is prime:
1 def is_prime(n):
2 if n <= 1:
3 return False
4 for i in range(2, int(n**0.5) + 1):
5 if n % i == 0:
6 return False
7 return ______
8

(34) (6 marks) Create a class ‘Person‘ that includes a greeting method and stores age, name, and
gender.
(35) (5 marks) What will be printed by the following code? Explain list mutability.
1 x = [1, 2, 3]
2 y = x[:]
3 y[0] = 99
4 print(x)
5

(36) (4 marks) Write a one-liner using a dictionary comprehension to square each number in the list
‘[1, 2, 3]‘.
(37) (4 marks) Describe the use of ‘break‘ and ‘continue‘ in Python loops with short examples.
(38) (6 marks) Design a class ‘ComplexNumber‘ with real and imaginary parts. Add a method to
display it in ‘a + bi‘ format.
(39) (4 marks) Fill in the blanks to find the sum of numbers divisible by 5 in a list:
1 def sum_div5(lst):
2 total = 0
3 for num in lst:
4 if ______:
5 total += num
6 return total
7

(40) (5 marks) What is the output and why?


1 x = (1, 2, 3)
2 y = x
3 x += (4,)
4 print(y)
5

10
(41) (4 marks) Write a list comprehension to extract all uppercase letters from a string.

(42) (6 marks) Define a class ‘ShoppingCart‘ to add items with name and price. Include method to
calculate total.

(43) (4 marks) Complete this function to convert all elements of a list to lowercase:
1 def to_lower(lst):
2 return [____ for s in lst]
3

(44) (6 marks) Create a class ‘Timer‘ with start and stop methods using ‘time‘ module.

(45) (5 marks) Predict output and explain slicing:


1 a = [10, 20, 30, 40, 50]
2 print(a[1:4])
3

(46) (4 marks) Explain how ‘range()‘ works with examples of ‘range(5)‘, ‘range(1,5)‘, ‘range(1,10,2)‘.

(47) (4 marks) Describe exception chaining in Python. Give a small example using ‘raise from‘.

(48) (6 marks) Create a class ‘Contact‘ with name, phone, email. Include a method ‘displayc ontact()‘.

(49) (4 marks) Complete this function to return a dictionary of character frequencies:


1 def char_freq(s):
2 d = {}
3 for char in s:
4 if char in d:
5 d[char] += 1
6 else:
7 ______
8 return d
9

(50) (5 marks) What will be the output?


1 print("abc" * 3)
2

(51) (4 marks) Explain the difference between ‘pass‘, ‘continue‘, and ‘break‘ in loops.

(52) (6 marks) Create a class ‘Polynomial‘ with a method to evaluate ‘ax2 + bx + c‘f orgiven‘x‘.

(53) (4 marks) Complete this function to check if a number is even using a lambda:
1 is_even = lambda x: ______
2

(54) (6 marks) Write a class ‘User‘ with username, email, and password. Add a method to change
password securely.

(55) (5 marks) What will the following print?


1 print(list(map(lambda x: x*x, [1, 2, 3])))
2

11
(56) (4 marks) Write a function that accepts variable number of arguments and returns their sum.

(57) (4 marks) Describe shallow copy vs deep copy with examples.

(58) (6 marks) Create a class ‘Vector2D‘ and implement vector addition using ‘a dd‘ .

(59) (4 marks) Complete a function that removes duplicates from a list:


1 def remove_duplicates(lst):
2 return list(______)
3

(60) (5 marks) Explain the output of:


1 a = set([1, 2, 3])
2 b = set([2, 3, 4])
3 print(a & b)
4

(61) (4 marks) Explain the role of ‘self‘ in class methods.

(62) (6 marks) Create a class ‘Matrix2x2‘ with ‘add()‘ and ‘multiply()‘ methods for 2x2 matrices.

(63) (4 marks) Write a lambda expression to reverse a string.

(64) (6 marks) Build a ‘StudentRecord‘ class that maintains a list of scores and calculates GPA.

(65) (5 marks) What is the output and why?


1 print("".join(["a", "b", "c"]))
2

(66) (4 marks) Write a function to count all numeric characters in a string.

(67) (4 marks) Describe the role of ‘super()‘ in class inheritance.

(68) (6 marks) Write a class ‘Stack‘ with push, pop, and display methods.

(69) (4 marks) Fill the blanks to use ‘enumerate()‘ for printing index and value:
1 for index, value in ______(my_list):
2 print(index, value)
3

(70) (5 marks) What is the output?


1 print(5 // 2)
2 print(5 / 2)
3

(71) (4 marks) Explain what a generator is. Write a simple generator for squares of numbers.

(72) (6 marks) Design a class ‘FileHandler‘ that reads content from a file, counts words, and handles
exceptions.

(73) (4 marks) Write a one-liner to remove whitespace from both ends of a string.

(74) (6 marks) Create a class ‘Inventory‘ with methods to add items, remove items, and print stock.

12
(75) (5 marks) Predict output and explain scope:
1 x = 10
2 def foo():
3 x = 5
4 foo()
5 print(x)
6

(76) (4 marks) Write a comprehension to flatten a list of lists: ‘[[1,2],[3,4]] → [1,2,3,4]‘.

(77) (4 marks) Explain the purpose of ‘s tr( )‘methodinP ythonclasses.

(78) (6 marks) Build a class ‘LoginSystem‘ that checks username and password, using a dictionary.

(79) (4 marks) Complete this function to check if a word is in a file:


1 def word_in_file(filename, word):
2 with open(filename) as f:
3 for line in f:
4 if ______:
5 return True
6 return False
7

(80) (5 marks) Output and reason:


1 x = [1, 2, 3]
2 print(x * 2)
3

(81) (4 marks) Explain the difference between ‘is‘ and ‘==‘ in Python. Use a code example to demon-
strate.

(82) (6 marks) Create a class ‘Rectangle‘ that accepts width and height, and has methods ‘area()‘ and
‘perimeter()‘.

(83) (4 marks) Fill in the blanks to get even numbers from a list:
1 def get_even(lst):
2 return [x for x in lst if ______]
3

(84) (6 marks) Define a class ‘Temperature‘ with methods to convert from Celsius to Fahrenheit and
vice versa.

(85) (5 marks) Predict the output and explain:


1 def modify_list(lst):
2 lst.append(4)
3 x = [1, 2, 3]
4 modify_list(x)
5 print(x)
6

(86) (4 marks) Write a function that returns the longest word in a given string.

(87) (4 marks) Describe the difference between ‘input()‘ and ‘rawi nput()‘inP ython2vsP ython3.

13
(88) (6 marks) Write a class ‘Book‘ with attributes ‘title‘, ‘author‘, and a method ‘displayi nf o()‘.
(89) (4 marks) Complete this snippet to filter out non-numeric strings:
1 lst = ["23", "hi", "7", "bye"]
2 numbers = list(filter(lambda x: x.isdigit(), ______))
3

(90) (5 marks) What does this print? Explain list aliasing.


1 a = [1, 2, 3]
2 b = a
3 b[0] = 10
4 print(a)
5

(91) (4 marks) Write a one-liner to remove duplicates from a list while preserving order.
(92) (6 marks) Design a class ‘Student‘ with attributes name and a list of marks. Include a method to
return average marks.
(93) (4 marks) Fill in the blanks to use ‘zip()‘ for summing elements from two lists:
1 a = [1, 2, 3]
2 b = [4, 5, 6]
3 sums = [x + y for x, y in ______]
4

(94) (6 marks) Write a class ‘Clock‘ that stores hours and minutes and prints time in HH:MM format.
(95) (5 marks) What is the result of the following?
1 print(sorted("banana"))
2

(96) (4 marks) Explain how ‘with open(...) as f:‘ works. Show with an example that reads a file and
prints each line.
(97) (4 marks) Write a function that counts how many times each word appears in a list.
(98) (6 marks) Build a class ‘Car‘ with methods to start, stop, and display status.
(99) (4 marks) Fill in the blanks to get list of squares using ‘map()‘:
1 lst = [1, 2, 3, 4]
2 squares = list(map(______, lst))
3

(100) (5 marks) What is the output? Explain:


1 print("Python"[::-1])
2

(101) (4 marks) Describe list comprehension. Convert this loop to a comprehension:


1 result = []
2 for i in range(5):
3 result.append(i*i)
4

14
(102) (6 marks) Write a class ‘ATM‘ that handles balance inquiry, deposit, and withdrawal.

(103) (4 marks) Write a generator that yields even numbers up to ‘n‘.

(104) (6 marks) Create a class ‘Counter‘ with an internal counter that can be incremented and reset.

(105) (5 marks) What is the output and why?


1 a = [0] * 3
2 b = [a] * 3
3 b[0][0] = 1
4 print(b)
5

(106) (6 marks) Define a class ‘BankAccount‘ with methods to deposit, withdraw, and display balance.
Ensure balance doesn’t go negative.

(107) (5 marks) What is printed and why?


1 x = 5
2 def func():
3 global x
4 x = 10
5 func()
6 print(x)
7

(108) (4 marks) Convert this function into a lambda:


1 def add(x, y):
2 return x + y
3

(109) (6 marks) Write a class ‘Circle‘ that takes radius and computes area and circumference.

(110) (4 marks) Complete this function to reverse all words in a sentence:


1 def reverse_words(sentence):
2 words = ______
3 return ’ ’.join(______)
4

(111) (4 marks) Differentiate between shallow copy and deep copy in Python with an example.

(112) (5 marks) Predict the output:


1 a = [[1, 2], [3, 4]]
2 b = a[:]
3 b[0][0] = 99
4 print(a)
5

(113) (6 marks) Write a class ‘Employee‘ that stores name, salary, and tax rate. Add method to compute
net salary.

(114) (4 marks) Modify this to handle file-not-found error:

15
1 f = open(’data.txt’, ’r’)
2 print(f.read())
3 f.close()
4

(115) (4 marks) Describe the role of ‘super()‘ in inheritance. Provide a short code example using ‘su-
per()‘.

(116) (5 marks) What is the result and why?


1 print(bool([]), bool({}), bool(0), bool(’False’))
2

(117) (4 marks) Complete this to count occurrences of each character in a string:


1 def count_chars(s):
2 d = {}
3 for c in s:
4 d[c] = d.get(c, ____) + 1
5 return d
6

(118) (6 marks) Write a class ‘Timer‘ that records start and stop times using ‘datetime.now()‘ and com-
putes duration.

(119) (4 marks) Fill in to print 10 random integers between 1 and 100 (inclusive):
1 import random
2 print([random.randint(_____, _____) for _ in range(10)])
3

(120) (5 marks) Predict output and explain:


1 def foo(bar=[]):
2 bar.append("baz")
3 return bar
4
5 print(foo())
6 print(foo())
7

(121) (6 marks) Define a class ‘Inventory‘ to store item names and quantities using a dictionary. Add
methods to add and remove items.

(122) (4 marks) Explain what ‘enumerate()‘ does. Modify this code to use ‘enumerate‘:
1 i = 0
2 for fruit in [’apple’, ’banana’, ’cherry’]:
3 print(i, fruit)
4 i += 1
5

(123) (5 marks) Fill in the blanks to find common elements in two sets:

16
1 set1 = {1, 2, 3}
2 set2 = {2, 3, 4}
3 common = ________
4 print(common)
5

(124) (4 marks) What is the output and why?


1 print("5" + "5")
2 print(int("5") + int("5"))
3

(125) (6 marks) Write a class ‘Account‘ with methods to transfer money between two accounts.

Python Fundamentals (40 Questions)


1. Explain the difference between Python 2 and Python 3.

2. What are Python’s built-in data types? Provide examples of each.

3. Explain how Python handles memory management.

4. What is the difference between is and == in Python?

5. Explain the purpose of init in Python classes.

6. What are Python decorators? Provide an example.

7. Explain the Global Interpreter Lock (GIL) in Python.

8. How does Python’s garbage collection work?

9. What are Python’s magic methods? Provide three examples.

10. Explain the difference between deepcopy and copy.

11. What are Python context managers? How are they implemented?

12. Explain the purpose of if name == " main ":.

13. What are Python generators? How do they differ from lists?

14. Explain the purpose of *args and **kwargs.

15. What is the difference between @staticmethod and @classmethod?

16. How does Python implement multithreading and multiprocessing?

17. Explain Python’s name mangling mechanism.

18. What are Python metaclasses? When would you use them?

19. Explain the purpose of slots in Python classes.

20. How does Python’s super() function work?

21. What are Python descriptors? Provide an example.

17
22. Explain the difference between append() and extend() for lists.

23. What is the purpose of Python’s with statement?

24. How do you create a virtual environment in Python?

25. Explain Python’s module search path.

26. What are Python’s naming conventions (PEP 8)?

27. How do you handle circular imports in Python?

28. Explain the difference between break, continue, and pass.

29. What are Python’s built-in functions for working with numbers?

30. How do you implement operator overloading in Python?

31. Explain Python’s string formatting methods (f-strings, format(), %).

32. What are Python’s built-in functions for working with sequences?

33. How do you implement a singleton pattern in Python?

34. Explain Python’s property decorator and its uses.

35. What are Python’s built-in modules for working with dates and times?

36. How do you implement memoization in Python?

37. Explain Python’s enumerate() function and its benefits.

38. What are Python’s built-in functions for working with iterators?

39. How do you implement a custom iterator in Python?

40. Explain Python’s zip() function and its uses.

Object-Oriented Programming (25 Questions)


41. Explain the four pillars of OOP with Python examples.

42. What is method resolution order (MRO) in Python?

43. How does Python implement multiple inheritance?

44. Explain the difference between abstraction and encapsulation.

45. What is the Liskov Substitution Principle? Provide an example.

46. How do you implement an abstract base class in Python?

47. Explain the difference between composition and inheritance.

48. What is the dependency inversion principle? Provide an example.

49. How do you implement interfaces in Python?

18
50. Explain the concept of mixins in Python.

51. What is the difference between instance, class, and static methods?

52. How do you implement the factory pattern in Python?

53. Explain the observer pattern with a Python implementation.

54. What is the strategy pattern? Provide a Python example.

55. How do you implement the decorator pattern in Python?

56. Explain the adapter pattern with a Python example.

57. What is the singleton pattern? How is it implemented in Python?

58. How do you implement the command pattern in Python?

59. Explain the prototype pattern with a Python example.

60. What is the facade pattern? Provide a Python implementation.

61. How do you implement the state pattern in Python?

62. Explain the template method pattern with a Python example.

63. What is the builder pattern? Provide a Python implementation.

64. How do you implement the chain of responsibility pattern?

65. Explain the visitor pattern with a Python example.

Data Structures and Algorithms (20 Questions)


66. Implement a stack using Python lists.

67. Implement a queue using Python’s collections.deque.

68. Explain and implement a linked list in Python.

69. Implement a binary search tree in Python.

70. Write Python code for bubble sort and explain its complexity.

71. Implement merge sort in Python and analyze its performance.

72. Write Python code for quick sort and explain its advantages.

73. Implement binary search in Python (iterative and recursive).

74. Explain and implement a hash table in Python.

75. Write Python code for breadth-first search (BFS).

76. Implement depth-first search (DFS) in Python.

77. Explain Dijkstra’s algorithm and provide a Python implementation.

19
78. Implement a priority queue using Python’s heapq module.

79. Write Python code to reverse a linked list.

80. Implement a graph using adjacency lists in Python.

81. Write Python code to detect cycles in a directed graph.

82. Implement topological sorting in Python.

83. Write Python code to find the shortest path in an unweighted graph.

84. Implement dynamic programming solutions for Fibonacci and knapsack problems.

85. Write Python code to implement the A* search algorithm.

File Handling and Exception Handling (15 Questions)


86. How do you read and write text files in Python?

87. Explain the different file opening modes in Python.

88. How do you handle CSV files in Python?

89. What is JSON serialization? How is it done in Python?

90. How do you handle binary files in Python?

91. Explain Python’s pickle module and its uses.

92. What is the difference between read(), readline(), and readlines()?

93. How do you handle file paths in a cross-platform way?

94. Explain Python’s with statement for file handling.

95. What are Python’s built-in exceptions? List 10 common ones.

96. How do you create custom exceptions in Python?

97. Explain the try-except-else-finally blocks.

98. How do you raise exceptions in Python?

99. What is exception chaining in Python?

100. How do you implement retry logic with exponential backoff?

20
Advanced Python Concepts (20 Questions)
101. Explain Python’s Global Interpreter Lock (GIL) and its implications.

102. What are Python coroutines? How do they differ from generators?

103. Explain Python’s asyncio module and its uses.

104. How do you implement parallel processing in Python?

105. What are Python’s multiprocessing and multithreading modules?

106. Explain Python’s concurrent.futures module.

107. How do you implement a thread pool in Python?

108. What are Python’s synchronization primitives?

109. Explain Python’s queue module and its thread-safe implementations.

110. How do you implement a producer-consumer pattern in Python?

111. What are Python’s memoryview objects? When would you use them?

112. Explain Python’s buffer protocol.

113. How do you interface Python with C code?

114. What is Cython? How does it differ from regular Python?

115. Explain Python’s type hinting system.

116. How do you use Python’s typing module?

117. What are Python’s data classes? When would you use them?

118. Explain Python’s enum module and its benefits.

119. How do you implement pattern matching in Python 3.10+?

120. What are Python’s walrus operator and positional-only parameters?

End of Revision Questions

End of Revision Questions

21

You might also like