Part A: Multiple Choice Questions (MCQs)
1. Main purpose of the programming paradigm is __.
a. Increase code length
b. Complexity reduction
c. Eliminate bugs
d. Improve hardware performance
Answer: b. Complexity reduction
Explanation: Programming paradigms provide structured approaches to solving problems, which helps in managing and reducing the complexity of software development.
2. __ programming paradigm emphasizes the use of functions without changing state.
a. Procedural
b. Functional
c. Object-oriented
d. Structural
Answer: b. Functional
Explanation: Functional programming is based on the concept of pure functions that do not have side effects (do not change state). It emphasizes immutability and avoiding shared state.
3. Object-Oriented Programming primarily revolves around __ of the following.
a. Data structures
b. Functions
c. Objects
d. Variables
Answer: c. Objects
Explanation: Object-Oriented Programming (OOP) is centered around "objects," which are instances of classes that encapsulate data (attributes) and behavior (methods).
4. In Python __ data structure is used to store a collection of items.
a. List
b. Dictionary
c. Tuple
d. Set
Answer: a. List (Note: While dictionaries, tuples, and sets also store collections, "List" is the most general and commonly cited answer for a general collection of items in introductory contexts.)
5. Adictionary stores __ in Python.
a. Keys only
b. Values only
c. Key-value pairs
d. Sequential data
Answer: c. Key-value pairs
Explanation: A dictionary in Python is an unordered collection of data values used to store data values like a map. It holds key-value pairs.
6. An example of disk IO is _____.
a. Storing a variable in memory
b. Reading a file from the hard disk
c. Defining a function
d. Looping through a list
Answer: b. Reading a file from the hard disk
Explanation: Disk IO (Input/Output) refers to operations that read from or write to a disk (hard drive). Reading a file is a classic example.
7. To write content to a file in Python __ method is used.
a. file.write()
b. file.insert()
c. file.add()
d. file.modify()
Answer: a. file.write()
Explanation: The write() method is used to write a string to a file object in Python.
8. A primary key in a database is __.
a. A key that has a default value
b. A unique identifier for records
c. A key for linking multiple databases
d. A key used for temporary tables
Answer: b. A unique identifier for records
Explanation: A primary key is a column or a set of columns that uniquely identifies each row in a table. It must contain unique values and cannot contain NULLs.
9. A common database normalization goal is __.
a. Reducing redundancy
b. Maximizing data size
c. Increasing the number of tables
d. Storing duplicate records
Answer: a. Reducing redundancy
Explanation: Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity.
10. __ key is used to uniquely identify a record in a related table.
a. Primary
b. Secondary
c. Foreign
d. Unique
Answer: c. Foreign (Note: A foreign key is used to link tables. It refers to the primary key of another table. The question is slightly
ambiguous; "Foreign" is the best fit for linking to another table.)
11. To create a simple GUI in Python, __ library is used.
a. Pygame
b. OS
c. Sys
d. math
Answer: a. Pygame (Note: While Tkinter is the standard GUI library, Pygame is used for creating games with graphical interfaces. Among the options, Pygame is the only one related to graphics/GUI.)
12. Anested list in Python is referred as __.
a. A list containing another list
b. A list of dictionaries
c. A dictionary of lists
d. A set containing multiple lists
Answer: a. A list containing another list
Explanation: A nested list is simply a list that contains other lists as its elements.
13. The purpose of unit testing in Python is __.
a. Test individual units of code
b. Test the entire program
c. Debug the entire program
d. Optimize the code for speed
Answer: a. Test individual units of code
Explanation: Unit testing involves testing individual components (units) of a program, such as functions or methods, in isolation to ensure they work correctly.
14. The primary goal of debugging is __.
a. Writing new code
b. Fixing errors in the code
c. Increasing program speed
d. Creating a graphical interface
Answer: b. Fixing errors in the code
Explanation: Debugging is the process of finding and fixing errors (bugs) in a program.
15. Python function used to print debugging messages to the console __.
a. print()
b. debug()
c. trace()
d. log()
Answer: a. print()
Explanation: The print() function is commonly used to output messages to the console for debugging purposes.
16. Output of the following code will be:
python
| my_dict | = | {"a": | [1, | 2], | "b": | [3, | 4]} |
| print(my_dict["a"][ | 1]) |
a. 1
b. 2
c. [1, 2]
d. [3, 4]
Answer: b. 2
Explanation: my_dict["a"] returns the list [1, 2]. Indexing [1] on this list returns the second element, which is 2.
17. The code will print "inner" __ times.
python
| for | i | in | range(3): | |||
| for | j | in | range(2): | |||
| print("inner") |
a. 2
b. 3
c. 5
d. 6
Answer: d. 6
Explanation: The outer loop runs 3 times, and the inner loop runs 2 times for each outer iteration. Total iterations = 3 × 2 = 6.
Part B: Short Answer Questions
1. Elaborate programming language paradigm and why is it important for software development?
Answer: A programming paradigm is a fundamental style or approach to programming. It provides a framework for how programs are structured and how problems are solved. Common paradigms include Procedural, Object-Oriented, Functional, and Logical. It is important for software development because it helps in:
Structuring Code: Provides a clear and organized way to write code. Managing Complexity: Different paradigms are suited to different types of problems (e.g., OOP for large, complex systems). Team Collaboration: Provides a common vocabulary and approach for developers. Maintainability: Code written in a consistent paradigm is easier to maintain and extend.
2. How do you interpret the concept of complexity reduction in programming? How does dividing code into modules help manage complexity?
Answer: Complexity reduction in programming refers to the practice of breaking down a large, complex problem into smaller, more manageable sub-problems. Dividing code into modules (functions, classes, files) helps manage complexity by:
Abstraction: Hiding implementation details and exposing only what is necessary. Encapsulation: Grouping related data and behavior together. Modularity: Allowing independent development and testing of components. Reusability: Modules can be reused in different parts of the program or in other programs. Easier Debugging: Isolating errors to specific modules.
3. Compare Functional Programming and Object-Oriented Programming (OOP) paradigms. Enlist main differences in their approach to problem-solving.
Answer:
| Feature | Functional Programming | Object-Oriented Programming |
| Core Concept | Functions and immutable data. | Objects (instances of classes). |
| State | Avoids shared state and side effects. | Encapsulates state within objects. |
| Approach | Decomposes problem into functions. | Decomposes problem into objects. |
| Data & Behavior | Separated. | Combined in objects. |
| Example | Haskell, Lisp, Python (partial). | Java, C++, Python. |
Functional programming focuses on what to solve, while OOP focuses on how to model the problem.
4. What is Disk IO and why is it important for system performance?
Answer: Disk IO (Input/Output) refers to the processes of reading data from and writing data to a disk (hard drive or SSD). It is important for system performance because disk operations are much slower than memory (RAM) operations. If a program is disk IO bound, it spends a significant amount of time waiting for the disk, which can slow down the entire system. Efficient disk IO is crucial for databases, file servers, and any application that handles large amounts of data.
5. Describe the difference modes in file handling in Python.
Answer: File handling modes in Python determine how a file is opened and used:
'r' (Read): Opens a file for reading. Error if file does not exist. 'w' (Write): Opens a file for writing. Creates a new file or overwrites an existing one. 'a' (Append): Opens a file for appending. Creates a new file or adds to the end of an existing one. 'r+' (Read/Write): Opens for both reading and writing. 'b' (Binary): Used for binary files (e.g., images). 'x' (Exclusive Creation): Creates a new file, fails if it exists.
6. What is the benefit of using the 'with' keyword while working with files in Python?
Answer: The with keyword in Python is used with file operations to ensure that the file is properly closed after its suite finishes, even if an exception is raised. This is known as a context manager. Benefits include:
Automatic Resource Management: No need to explicitly call file.close(). Exception Safety: The file is closed even if errors occur. Cleaner Code: Reduces boilerplate code.
Example: with open('file.txt', 'r') as f: data = f.read()
7. How can you create a simple GUI application using Pygame? Enlist the steps involved.
Answer: Pygame is a library for making games, but it can be used for simple GUI applications. Steps:
1. Install Pygame: pip install pygame.
2. Import Pygame: import pygame.
3. Initialize: pygame.init().
4. Set up the display: screen = pygame.display.set_mode((width, height)).
5. Main Loop: Create a loop that runs until the user quits.
Handle events (e.g., pygame.QUIT, mouse clicks). Update game state. Draw everything to the screen (screen.fill(), pygame.draw.rect(), etc.). Update the display: pygame.display.flip().
6. Quit: pygame.quit().
8. Describe the use of a nested list in Python and how can it be used to represent a matrix?
Answer: A nested list in Python is a list that contains other lists as elements. It can be used to represent a matrix (a 2D array) where each inner list represents a row.
Example:
python
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Accessing elements: matrix[row][col]. For example, matrix[0][1] is 2. Iterating: Nested loops can be used to iterate over rows and columns.
9. What is data normalization and why is it used in database management?
Answer: Data normalization is the process of organizing data in a database to minimize redundancy and dependency. It involves dividing large tables into smaller, related tables and defining relationships between them. It is used to:
Eliminate Redundant Data: Saves storage space and avoids inconsistencies. Ensure Data Integrity: Updates are made in one place, reducing the risk of errors. Simplify Queries: Well-structured tables are easier to query. Improve Performance: In some cases, normalization can improve query performance.
10. What is debugging and why is it important in software development?
Answer: Debugging is the process of identifying, analyzing, and removing errors (bugs) from a software program. It is important because:
Correctness: Ensures the program works as intended. Reliability: Reduces crashes and unexpected behavior. User Experience: Provides a smooth and error-free experience. Security: Fixes vulnerabilities that could be exploited. Cost-Effective: Fixing bugs early in development is cheaper than after release.
11. What seems to be the problem in: sampledict = {"a": 1, "b": 2} then print(sampledict["c"])
Answer: The problem is that the key "c" does not exist in sampledict. Attempting to access a non-existent key using square brackets raises a KeyError. To avoid this, you can use the get() method: print(sampledict.get("c")), which returns None instead of raising an error.
12. Final value of my_list after the following lines would be:
python
| own_list | = | [1, | 2, | 3] | |
| own_list.append(4, | 5) |
Answer: The code will raise a TypeError. The append() method takes exactly one argument. To add multiple elements, you should use the extend() method: ownlist.extend([4, 5]) which would result in [1, 2, 3, 4, 5]. If append() were used with a single list argument, e.g., ownlist.append([4, 5]), the result would be [1, 2, 3, [4, 5]].
Part C: Long Answer Questions
1. Write a Python function that calculates the factorial of a given number. Test the function with 5 different inputs.
Answer:
python
def factorial(n): if n < 0: return "Factorial not defined for negative numbers"
elif n == 0 or n == 1: return 1 else:
result = 1 for i in range(2, n + 1):
result *= i return result
| # | Testing | with | 5 | different | inputs | ||
| print(factorial(0)) | # | 1 | |||||
| print(factorial(1)) | # | 1 |
| print(factorial(5)) | # | 120 | |||||
| print(factorial(10 | )) # | 3628800 | |||||
| print(factorial(-3) | ) # | Factorial | not | defined | for | negative | numbers |
2. Implement a Python class Rectangle with methods to calculate the area and perimeter of a rectangle. Create instances of the class and print the perimeter of rectangle.
Answer:
python
class Rectangle: def init(self, length, width):
self.length = length
self.width = width
def area(self): return self.length * self.width
| def | perimeter(self): | |||||||
| return | 2 | * | (self.length | + | self.width) |
| # | Creating | instances | ||||
| rect1 | = | Rectangle(5, | 3) | |||
| rect2 | = | Rectangle(10, | 4) |
| # | Printing | perimeter | |||||
| print("Perimeter | of r | ect1:", | rect1.perimeter()) | # | 16 | ||
| print("Perimeter | of r | ect2:", | rect2.perimeter()) | # | 28 |
3. Write a program highlighting the use of functions to simplify a problem. For example, create a program that calculates the average
of a list of numbers and by using separate functions to add all numbers, marking repeated values and calculate the average of the list with and without repeating values.
Answer:
python
| def a | dd_numbers(numbers): | ||
| return | sum(numbers) |
def mark_repeated(numbers):
seen = set()
repeated = set() for num in numbers: if num in seen: repeated.add(num) seen.add(num) return repeated
| def ca | lculate_average(numbers): | |||
| if n | ot numbers: | |||
| r | eturn 0 | |||
| return | sum(numbers) / l | en(numbers) |
# Main program
data = [1, 2, 2, 3, 4, 4, 4, 5]
total = add_numbers(data)
repeated = mark_repeated(data)
avgwith = calculateaverage(data)
unique_data = list(set(data))
avgwithout = calculateaverage(unique_data)
print("Total:", total)
| print("Repeated | values:", | repeated) | |||||
| print("Average | with | repeats:", | avg_with) | ||||
| print("Average | withou | t repeats:", | avg_without) |
4. Create a Python dictionary to store student names as keys and their grades as values. Write a program to add new students, update existing students' grades, and remove students from the dictionary.
Answer:
python
students = {"Alice": 85, "Bob": 90, "Charlie": 78}
| # | Add | new | student | ||
| students["David"] = | 88 | ||||
| print("After | adding | David:", | students) |
| # | Update | existing s | tudent's | grade | ||||
| students["Alice"] | = | 92 | ||||||
| print("After | updating A | lice:", | students) |
# Remove a student del students["Charlie"] print("After removing Charlie:", students)
5. Write a Python program to create a file named data.txt, write a string to it and then read the content of the file and display the output.
Answer:
python
| # | Writing t | o | file | |||||||||
| with | open("data.txt", | "w") | as | file: | ||||||||
| file.write("Hello, | this | is | a | test | file.") |
| # | Reading | from | file | ||||||
| with | open("data.txt", | "r") | as | file: | |||||
| content | = | file.read() | |||||||
| print("File | content:", | content) |
6. Create a Python program that appends a new line of text to an existing file. If the file does not exist, it should create a new file.
Answer:
python
def appendtofile(filename, text): with open(filename, "a") as file: file.write(text + "\n")
| appendtofile("data.txt", | "This | is | a | new | line.") | |||
| appendtofile("new_file.txt", | "This | file | was | created.") |
7. Write Python code using Pygame that creates a simple window with a button. When the button is clicked, it should display a message on the window.
Answer:
python
import pygame
pygame.init()
| screen | = | pygame.display.set_mode((400, | 300)) | |
| pygame.display.set_caption("Button | Example") |
button_rect = pygame.Rect(150, 120, 100, 50)
font = pygame.font.Font(None, 36)
message = ""
| running | = | True | ||||||||
| while r | unning: | |||||||||
| for e | vent | in | pygame.event.get(): | |||||||
| if | event.type | == | pygame.QUIT: | |||||||
| running | = F | alse | ||||||||
| if | event.type | == | pygame.MOUSEBUTTONDOWN: | |||||||
| if | button_rect.collidepoint(event.pos): | |||||||||
| message | = | "Button | Clicked!" |
| screen.fill((255, | 255, | 255)) | |||||||||||
| pygame.draw.rect(screen, | (0, | 128, | 255), | button_rect) | |||||||||
| text | = f | ont.render("Click | Me", | True, | (255, | 255, | 255)) | ||||||
| screen.blit(text, | (155, | 130)) |
if message:
msgtext = font.render(message, True, (0, 0, 0)) screen.blit(msgtext, (100, 200))
pygame.display.flip()
pygame.quit()
8. Develop a Python program that calculates and prints the transpose of a 3x3 matrix represented using a nested list.
Answer:
python
| matrix | = | [ | ||
| [1, | 2, | 3], | ||
| [4, | 5, | 6], | ||
| [7, | 8, | 9] | ||
| ] |
transpose = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
| print("Original | Matrix:") | ||||
| for r | ow | in | matrix: | ||
| print(row) |
| print("Transpose | Matrix:") | ||||
| for r | ow | in | transpose: | ||
| print(row) |
9. Write a Python function that counts the number of occurrences of each letter in a text file and prints the results.
Answer:
python
| def | count_letters(filename): | ||||||||||
| letter_count | = | } | |||||||||
| with | open(filename, | "r") | as | file: | |||||||
| text | = | file.read().lower() | |||||||||
| for | char | in | text: |
if char.isalpha():
lettercount[char] = lettercount.get(char, 0) + 1 for letter, count in sorted(letter_count.items()): print(f"{letter}: {count}")
| # | Example | usage | (assuming ' | data.txt' | exists) |
| # | count_letters("data.txt") |
10. Write a Python program to connect to a database and demonstrate how to insert, update and retrieve data from the database. Explain the importance of database connectivity in Python applications.
Answer:
python
import sqlite3
| # | Connect | to | database | (creates | file | if | not | exists) | |||
| conn | = | sqlite3.connect("example.db") | |||||||||
| cursor | = | conn.cursor() |
| # | Create | table | ||||||||||||
| cursor.execute("""CREATE | TABLE | IF | NOT | EXISTS | students | |||||||||
| (id I | NTEGER | PRIMARY | KEY, | name | TEXT, | grade | INTEGER)""") |
# Insert data cursor.execute("INSERT INTO students (name, grade) VALUES (?, ?)", ("Alice", 85)) conn.commit()
# Update data
cursor.execute("UPDATE students SET grade = ? WHERE name = ?", (90, "Alice")) conn.commit()
# Retrieve data cursor.execute("SELECT * FROM students")
rows = cursor.fetchall() for row in rows: print(row)
conn.close()
Importance: Database connectivity allows Python applications to store, retrieve, and manipulate persistent data. This is essential for web applications, data analysis, and enterprise software.
11. Explain unit testing and its Importance in Python programming. How does it help in catching errors early during the development process? Include an example of a unit test for a simple Python function.
Answer: Unit testing is the practice of testing individual units of source code (e.g., functions, methods) to determine if they are fit for use. It is important because:
Early Bug Detection: Catches errors early in development. Refactoring Safety: Ensures changes don't break existing functionality. Documentation: Serves as documentation for how code should work. Design Improvement: Encourages modular and testable code.
Example:
python
import unittest
def add(a, b):
return a + b
| class | TestAdd(unittest.TestCase): | |||||||
| def | testaddpositive(self): | |||||||
| self.assertEqual(add(2, | 3), | 5) | ||||||
| def | testaddnegative(self): | |||||||
| self.assertEqual(add(-1, | -1), | -2) |
| if | name | == | 'main': |
| unittest.main() |
12. Write a Python code that selects a number between 1 and 10 and the player will try to guess the number in 5 tries. For each incorrect guess, the program provides a hint whether the guess was higher or lower side. If the number is successfully guessed then a Congratulating message should be displayed along with in how many attempts the number was guessed correctly. Otherwise another message should be displayed along with the chosen number. The outputs should look like: Hello, what's your name?Abrar okay! Abrar I am guessing a number between 1 and 100: 50 Your guess is too low 75 Your guess is too high 85 Your guess is too high 88 Your guess is too high 78 You guessed the number in 5 tries!!
Answer:
python
import random
| name = | input("Hello, | what's | your | name?") | |||||||||
| print(f"okay | ! {name} | I | am | guessing | a | number | between | 1 | and | 100:") |
number = random.randint(1, 100)
tries = 0
maxtries = 5
| while tr | ies < | max_tries: | |
| gues | s = in | t(input()) | |
| tries | += 1 |
if guess < number: print("Your guess is too low") elif guess > number: print("Your guess is too high") else: print(f"You guessed the number in {tries} tries!!") break else: print(f"You did not guess the number. The number was {number}")
13. The following code is supposed to open a file 'abc.txt' and counts the number of occurrences of the character 's' and displays output like:
text
line 1: file_name = 'abc.txt'
line 2: target_letter = 's' line 3:
line 4: try:
line 5: file = open(file_name, "r")
line 6: text = file.read() line 7: file.close() line 8: except FileNotFoundError: line 9: print("Error: File 'file_name' not found.") line 10: exit() line 11:
line 12: count = 0 line 13: for char in text:
line 14: if char == target_letter:
line 15: count += 1 line 16: print("The letter 'targetletter' appears count + times in the file 'filename'.")
>Sample text in file 'abc.txt': I scream, you scream, we all scream for ice cream. >Sample Output: The letter 's' appears 3 times in the file 'abc.txt'. However, the code does not execute. Debug and remove any bug(s) from the code.
Answer: The bugs in the code are:
1. Line 9: The variable filename is inside a string literal, so it prints the literal text "filename" instead of the variable's value. It should be an f-string or concatenated.
2. Line 16: The variables targetletter, count, and filename are inside string literals. The + sign is also incorrectly placed inside the string. It should be an f-string.
Debugged Code:
python
| file_name | = ' | abc.txt' | |
| target_letter | = ' | s' |
try:
file = open(file_name, "r")
text = file.read() file.close() except FileNotFoundError: print(f"Error: File '{file_name}' not found.") exit()
count = 0 for char in text:
if char == target_letter:
count += 1 print(f"The letter '{targetletter}' appears {count} times in the file '{filename}'.")