CIT 2228 Exam Revision Questions
CIT 2228 Exam Revision Questions
(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
(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:
(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
(d) (4 marks) What is the difference between @staticmethod and @classmethod? Pro-
vide an example use case for each.
• 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:
(d) (4 marks) Implement a binary search algorithm in Python both recursively and iteratively.
(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:
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
• Context managers
• Descriptors
• Metaclasses
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
(f) (6 marks) Implement a function that returns the first n Fibonacci numbers using a generator.
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
6
SECTION E: ADVANCED CONCEPTS (20 Questions)
(a) (6 marks) Implement a memoization decorator for recursive functions.
(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
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
(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
(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
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.
(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()‘.
(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.
11
(56) (4 marks) Write a function that accepts variable number of arguments and returns their sum.
(58) (6 marks) Create a class ‘Vector2D‘ and implement vector addition using ‘a dd‘ .
(62) (6 marks) Create a class ‘Matrix2x2‘ with ‘add()‘ and ‘multiply()‘ methods for 2x2 matrices.
(64) (6 marks) Build a ‘StudentRecord‘ class that maintains a list of scores and calculates GPA.
(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
(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
(78) (6 marks) Build a class ‘LoginSystem‘ that checks username and password, using a dictionary.
(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.
(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
(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
14
(102) (6 marks) Write a class ‘ATM‘ that handles balance inquiry, deposit, and withdrawal.
(104) (6 marks) Create a class ‘Counter‘ with an internal counter that can be incremented and reset.
(106) (6 marks) Define a class ‘BankAccount‘ with methods to deposit, withdraw, and display balance.
Ensure balance doesn’t go negative.
(109) (6 marks) Write a class ‘Circle‘ that takes radius and computes area and circumference.
(111) (4 marks) Differentiate between shallow copy and deep copy in Python with an example.
(113) (6 marks) Write a class ‘Employee‘ that stores name, salary, and tax rate. Add method to compute
net salary.
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()‘.
(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
(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
(125) (6 marks) Write a class ‘Account‘ with methods to transfer money between two accounts.
11. What are Python context managers? How are they implemented?
13. What are Python generators? How do they differ from lists?
18. What are Python metaclasses? When would you use them?
17
22. Explain the difference between append() and extend() for lists.
29. What are Python’s built-in functions for working with numbers?
32. What are Python’s built-in functions for working with sequences?
35. What are Python’s built-in modules for working with dates and times?
38. What are Python’s built-in functions for working with iterators?
18
50. Explain the concept of mixins in Python.
51. What is the difference between instance, class, and static methods?
70. Write Python code for bubble sort and explain its complexity.
72. Write Python code for quick sort and explain its advantages.
19
78. Implement a priority queue using Python’s heapq module.
83. Write Python code to find the shortest path in an unweighted graph.
84. Implement dynamic programming solutions for Fibonacci and knapsack problems.
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?
111. What are Python’s memoryview objects? When would you use them?
117. What are Python’s data classes? When would you use them?
21