Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Questions with solution

The document provides an overview of Python programming concepts, including definitions of Python, its features, data types, memory management, and identifiers. It also covers lists, dictionaries, loops, classes, and file operations, along with examples and comparisons to other programming languages. The content is structured into short and long questions categorized by Bloom's Taxonomy, focusing on key concepts and practical applications in Python.

Uploaded by

king.gamer.20k02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Questions with solution

The document provides an overview of Python programming concepts, including definitions of Python, its features, data types, memory management, and identifiers. It also covers lists, dictionaries, loops, classes, and file operations, along with examples and comparisons to other programming languages. The content is structured into short and long questions categorized by Bloom's Taxonomy, focusing on key concepts and practical applications in Python.

Uploaded by

king.gamer.20k02
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit 1: Introduction and Overview – Questions & Solutions

Short Questions (2 Marks Each)

Q1. Define Python and mention its key features. (K1, CO1, PO1)

Solution:
Python is a high-level, interpreted programming language known for its simplicity, readability, and
flexibility.
Key features:

1. Easy to learn and read (clear syntax)

2. Interpreted language (executed line-by-line)

3. Dynamically typed (no need to declare variable types)

4. Cross-platform (runs on Windows, Mac, and Linux)

5. Supports OOP and functional programming

Q2. How are variables assigned in Python? Give an example. (K1, CO1, PO1)

Solution:
Variables in Python do not need an explicit declaration. The assignment happens using the =
operator.
Example:

x = 10 # Integer variable

y = 3.14 # Float variable

name = "Python" # String variable

print(x, y, name)

Q3. What are Python’s standard data types? (K1, CO1, PO1)

Solution:
Python has the following standard data types:

1. Numeric types – int, float, complex

2. Sequence types – list, tuple, range

3. Text type – str

4. Set types – set, frozenset

5. Mapping type – dict


6. Boolean type – bool (True, False)

Q4. Differentiate between mutable and immutable types in Python. (K2, CO1, PO2)

Solution:

 Mutable objects: Can be changed after creation (e.g., list, dict, set).

 Immutable objects: Cannot be changed after creation (e.g., int, float, str, tuple).

Example:

# Mutable Example

lst = [1, 2, 3]

lst.append(4) # List is modified

print(lst) # Output: [1, 2, 3, 4]

# Immutable Example

name = "Python"

name[0] = 'J' # This will raise an error

Q5. Explain Python's memory management. (K2, CO1, PO2)

Solution:
Python manages memory using:

1. Reference Counting – Objects are deleted when no references exist.

2. Garbage Collection (GC) – Automatically frees memory occupied by unused objects.

3. Memory Pools – Manages memory allocation efficiently through PyMalloc.

Example of garbage collection:

import gc

gc.collect() # Forces garbage collection

Q6. What are Python Identifiers? Give examples. (K1, CO1, PO1)

Solution:
Identifiers are variable, function, class, and module names in Python.
Rules:

 Must start with a letter (A-Z or a-z) or an underscore _.

 Followed by letters, digits (0-9), or underscores.


 Cannot use Python keywords.

Example:

_myVar = 10 # Valid

123name = "John" # Invalid (cannot start with a number)

Q7. Write a Python program to demonstrate the use of comments. (K2, CO1, PO2)

Solution:

# This is a single-line comment

"""

This is a multi-line comment.

Python ignores these while execution.

"""

x = 5 # Assigning value to x

print(x)

Q8. Explain different types of operators in Python. (K2, CO1, PO2)

Solution:
Python supports:

1. Arithmetic Operators (+, -, *, /, %, **, //)

2. Comparison Operators (==, !=, >, <, >=, <=)

3. Logical Operators (and, or, not)

4. Bitwise Operators (&, |, ^, ~, <<, >>)

5. Assignment Operators (=, +=, -=, *=, %=, etc.)

Example:

a = 10

b=5

print(a + b) # Output: 15 (Arithmetic)

print(a > b) # Output: True (Comparison)

print(a and b) # Output: 5 (Logical)

Long Questions (4 Marks Each)


Q9. Compare Python with other programming languages in terms of usability and performance.
(K3, CO1, PO3)

Solution:

Feature Python Java C++

Syntax Simple Verbose Complex

Typing Dynamic Static Static

Performance Slower (interpreted) Faster Fastest

Memory Management Automatic GC GC Manual

Use Cases Web, AI, ML, Scripting Enterprise apps Games, OS

Python is preferred for ease of use, while Java and C++ are faster but complex.

Q10. Explain string operations in Python with examples. (K3, CO1, PO3)

Solution:
Python provides various string operations:

1. Concatenation (+)

2. Repetition (*)

3. Slicing ([start:end])

4. Built-in Methods (upper(), lower(), replace(), split(), strip())

Example:

s = "Hello"

print(s.upper()) # HELLO

print(s[1:4]) # ell (Slicing)

print(s + " World") # Hello World (Concatenation)

Q11. Discuss the built-in functions available in Python for numbers and strings. (K3, CO1, PO3)

Solution:

 For Numbers: abs(), round(), max(), min(), pow(), int(), float()

 For Strings: len(), ord(), chr(), str(), capitalize(), join(), find()

Example:

print(abs(-10)) # 10

print(len("Python")) # 6
Q12. Write a Python program to illustrate the use of different data types. (K4, CO1, PO4)

Solution:

x = 10 # Integer

y = 3.14 # Float

z = "Hello" # String

lst = [1, 2, 3] # List

tup = (4, 5, 6) # Tuple

d = {'a': 1, 'b': 2} # Dictionary

print(type(x), type(y), type(z), type(lst), type(tup), type(d))

Output:

<class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> <class 'dict'>

Alright! Let’s move on to Unit 2: Lists, Dictionaries, Conditionals, and Loops with short and long
questions along with their solutions, categorized based on Bloom's Taxonomy (K1-K6), COs, and
POs.

Unit 2: Lists, Dictionaries, Conditionals, and Loops – Questions & Solutions

Short Questions (2 Marks Each)

Q1. What are lists in Python? Explain with an example. (K1, CO1, PO1)

Solution:
A list is an ordered, mutable collection of items. Lists can hold elements of different types.

Example:

my_list = [1, 2, 3, "Python", 4.5]

print(my_list) # Output: [1, 2, 3, 'Python', 4.5]

Q2. What is a dictionary in Python? How is it different from a list? (K1, CO1, PO1)

Solution:
A dictionary is an unordered collection of key-value pairs. Unlike lists, dictionaries are accessed using
keys rather than indices.

Example:
my_dict = {"name": "John", "age": 25}

print(my_dict["name"]) # Output: John

Difference:

 Lists use indexing (list[0]), dictionaries use keys (dict["key"]).

 Lists are ordered, dictionaries (before Python 3.7) were unordered.

Q3. What are the built-in methods available for lists? (K2, CO1, PO2)

Solution:
Some important list methods:

 append(x) → Adds an item at the end.

 insert(i, x) → Inserts at index i.

 remove(x) → Removes first occurrence of x.

 pop(i) → Removes item at index i.

 sort() → Sorts in ascending order.

Example:

lst = [3, 1, 2]

lst.append(4)

lst.sort()

print(lst) # Output: [1, 2, 3, 4]

Q4. Explain the difference between a tuple and a list. (K2, CO1, PO2)

Solution:

Feature List Tuple

Mutability Mutable (can change) Immutable (cannot change)

Performance Slower Faster

Syntax [] (square brackets) () (parentheses)

Example:

lst = [1, 2, 3] # List

tup = (1, 2, 3) # Tuple

Q5. How does the for loop work in Python? (K2, CO1, PO2)
Solution:
A for loop iterates over a sequence (list, tuple, string, etc.).

Example:

for i in range(1, 6):

print(i)

Output:

Q6. What is the use of the break statement in loops? (K2, CO1, PO2)

Solution:
The break statement is used to exit a loop when a condition is met.

Example:

for num in range(1, 10):

if num == 5:

break

print(num)

Output:

The loop stops when num == 5.

Q7. Explain the use of continue and pass statements. (K2, CO1, PO2)

Solution:

 continue: Skips the current iteration and moves to the next.

 pass: Does nothing (used as a placeholder).

Example:
for i in range(5):

if i == 3:

continue # Skips 3

print(i)

Output:

Long Questions (4 Marks Each)

Q8. Write a Python program to demonstrate list operations (append, remove, sort). (K3, CO2, PO3)

Solution:

# List operations

numbers = [4, 1, 3, 2]

numbers.append(5) # Append 5

numbers.remove(3) # Remove 3

numbers.sort() # Sort in ascending order

print(numbers) # Output: [1, 2, 4, 5]

Q9. Explain dictionary operations with a Python program. (K3, CO2, PO3)

Solution:

# Creating a dictionary

student = {"name": "Alice", "age": 22, "grade": "A"}

# Adding a new key-value pair

student["course"] = "Computer Science"

# Modifying a value

student["age"] = 23
# Deleting a key

del student["grade"]

print(student)

# Output: {'name': 'Alice', 'age': 23, 'course': 'Computer Science'}

Q10. Write a Python program using conditional statements (if, elif, else). (K3, CO2, PO3)

Solution:

num = int(input("Enter a number: "))

if num > 0:

print("Positive Number")

elif num < 0:

print("Negative Number")

else:

print("Zero")

Q11. Write a Python program to calculate the sum of all elements in a list. (K3, CO2, PO3)

Solution:

numbers = [10, 20, 30, 40]

total = sum(numbers)

print("Sum:", total) # Output: 100

Q12. Write a Python program to demonstrate looping through dictionary keys and values. (K3,
CO2, PO3)

Solution:

student = {"name": "John", "age": 21, "grade": "A"}

for key, value in student.items():

print(key, ":", value)


Output:

name : John

age : 21

grade : A

Q13. Explain the difference between while and for loops with examples. (K4, CO2, PO4)

Solution:

Feature For Loop While Loop

Usage Used for iterating over sequences Used when a condition must be met

Example for i in range(5): while i < 5:

Example:

# For loop

for i in range(3):

print(i)

# While loop

i=0

while i < 3:

print(i)

i += 1

Q14. Write a Python program to count occurrences of elements in a list using a dictionary. (K4,
CO2, PO4)

Solution:

numbers = [1, 2, 2, 3, 3, 3, 4]

count_dict = {}

for num in numbers:

count_dict[num] = count_dict.get(num, 0) + 1

print(count_dict)
# Output: {1: 1, 2: 2, 3: 3, 4: 1}

Q15. Analyze the use of looping structures in handling large datasets. (K5, CO2, PO5)

Solution:
Loops allow efficient traversal and modification of large datasets. For loops iterate over structured
data, while while loops are useful when conditions must be met dynamically.

Example (processing a large list):

data = [i for i in range(1000000)]

sum_data = sum(data)

print(sum_data)

Great! Let’s move on to Unit 3: Objects, Classes, and Files with short and long questions along with
solutions, categorized based on Bloom's Taxonomy (K1-K6), COs, and POs.

Unit 3: Objects, Classes, and Files – Questions & Solutions

Short Questions (2 Marks Each)

Q1. What is a class in Python? (K1, CO1, PO1)

Solution:
A class is a blueprint for creating objects. It defines attributes (variables) and behaviors (methods).

Example:

class Car:

def __init__(self, brand):

self.brand = brand

my_car = Car("Toyota")

print(my_car.brand) # Output: Toyota

Q2. Define an object in Python and give an example. (K1, CO1, PO1)

Solution:
An object is an instance of a class. It contains data (attributes) and functions (methods).

Example:

class Student:

def __init__(self, name):


self.name = name

s1 = Student("Alice")

print(s1.name) # Output: Alice

Q3. What is the purpose of the __init__ method in Python classes? (K2, CO1, PO2)

Solution:
The __init__ method is the constructor that initializes an object’s attributes when it is created.

Example:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

Q4. What is inheritance in Python? Explain with an example. (K2, CO1, PO2)

Solution:
Inheritance allows a class (child) to inherit attributes and methods from another class (parent).

Example:

class Animal:

def speak(self):

return "Animal speaks"

class Dog(Animal):

def speak(self):

return "Bark"

d = Dog()

print(d.speak()) # Output: Bark

Q5. What is polymorphism in Python? (K2, CO1, PO2)


Solution:
Polymorphism allows different classes to have methods with the same name but different
implementations.

Example:

class Cat:

def sound(self):

return "Meow"

class Dog:

def sound(self):

return "Bark"

animals = [Cat(), Dog()]

for animal in animals:

print(animal.sound())

Q6. What are class variables and instance variables? (K2, CO1, PO2)

Solution:

 Class variables are shared across all instances.

 Instance variables are specific to an object.

Example:

class Student:

school = "XYZ School" # Class variable

def __init__(self, name):

self.name = name # Instance variable

Q7. How does Python handle file operations? (K2, CO1, PO2)

Solution:
Python provides built-in functions like open(), read(), and write().

Example:

with open("sample.txt", "w") as file:


file.write("Hello, World!")

Long Questions (4 Marks Each)

Q8. Write a Python program to create a class, instantiate an object, and access its attributes and
methods. (K3, CO2, PO3)

Solution:

class Car:

def __init__(self, brand, model):

self.brand = brand

self.model = model

def details(self):

return f"{self.brand} {self.model}"

my_car = Car("Toyota", "Corolla")

print(my_car.details()) # Output: Toyota Corolla

Q9. Write a Python program demonstrating multiple inheritance. (K3, CO2, PO3)

Solution:

class Parent1:

def func1(self):

return "Function from Parent1"

class Parent2:

def func2(self):

return "Function from Parent2"

class Child(Parent1, Parent2):

pass

c = Child()
print(c.func1()) # Output: Function from Parent1

print(c.func2()) # Output: Function from Parent2

Q10. Explain method overriding with an example. (K3, CO2, PO3)

Solution:
Method overriding allows a child class to provide a different implementation of a method from its
parent class.

Example:

class Animal:

def speak(self):

return "Animal speaks"

class Dog(Animal):

def speak(self):

return "Bark"

d = Dog()

print(d.speak()) # Output: Bark

Q11. Write a Python program to create and read a file. (K3, CO2, PO3)

Solution:

# Writing to a file

with open("test.txt", "w") as file:

file.write("Hello, Python!")

# Reading the file

with open("test.txt", "r") as file:

content = file.read()

print(content)

Q12. Explain the concept of file handling modes in Python. (K4, CO2, PO4)

Solution:
Mode Description

r Read (default)

w Write (overwrite)

a Append

x Create (fails if file exists)

Example:

with open("data.txt", "a") as f:

f.write("New data")

Q13. Write a Python program to copy the contents of one file to another. (K4, CO2, PO4)

Solution:

with open("source.txt", "r") as src, open("dest.txt", "w") as dest:

dest.write(src.read())

Q14. Explain the concept of serialization and deserialization using the pickle module. (K5, CO2,
PO5)

Solution:
Serialization (dump) converts objects to a binary format, while deserialization (load) restores them.

Example:

import pickle

data = {"name": "Alice", "age": 25}

# Serialization

with open("data.pkl", "wb") as f:

pickle.dump(data, f)

# Deserialization

with open("data.pkl", "rb") as f:

loaded_data = pickle.load(f)
print(loaded_data) # Output: {'name': 'Alice', 'age': 25}

Q15. Explain exception handling in Python with an example. (K5, CO2, PO5)

Solution:
Exception handling uses try-except to prevent crashes.

Example:

try:

num = int(input("Enter a number: "))

print(10 / num)

except ZeroDivisionError:

print("Cannot divide by zero!")

except ValueError:

print("Invalid input!")

Q16. Analyze how object-oriented programming enhances code reusability. (K6, CO2, PO6)

Solution:
OOP improves code reusability through:

1. Encapsulation → Bundles data and methods.

2. Inheritance → Reuses existing code.

3. Polymorphism → Allows method flexibility.

4. Abstraction → Hides implementation details.

Example:

class Vehicle:

def start(self):

return "Starting"

class Car(Vehicle):

pass

c = Car()

print(c.start()) # Output: Starting


Great! Let's move on to Unit 4: Regular Expressions and Exception Handling with short and long
questions along with solutions, categorized based on Bloom's Taxonomy (K1-K6), COs, and POs.

Unit 4: Regular Expressions and Exception Handling – Questions & Solutions

Short Questions (2 Marks Each)

Q1. What is a regular expression in Python? (K1, CO1, PO1)

Solution:
A regular expression (regex) is a sequence of characters defining a search pattern. Python's re
module provides regex functionalities.

Example:

import re

pattern = r"\d+" # Matches digits

result = re.findall(pattern, "Order 123 is ready")

print(result) # Output: ['123']

Q2. List any four special characters used in regular expressions. (K1, CO1, PO1)

Solution:

1. . → Matches any character except newline

2. ^ → Matches the start of a string

3. $ → Matches the end of a string

4. \d → Matches any digit (0-9)

Q3. What is the difference between match() and search() in the re module? (K2, CO1, PO2)

Solution:

 match() checks for a pattern at the beginning of a string.

 search() checks for a pattern anywhere in a string.

Example:

import re

text = "Python is great"

print(re.match("Python", text)) # Matches at the start

print(re.search("great", text)) # Matches anywhere


Q4. What are exceptions in Python? (K1, CO1, PO1)

Solution:
Exceptions are errors detected during execution that disrupt normal flow. Examples:
ZeroDivisionError, ValueError, FileNotFoundError.

Example:

try:

x = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero!") # Output: Cannot divide by zero!

Q5. What is the purpose of the finally block in exception handling? (K2, CO1, PO2)

Solution:
The finally block always executes after try-except, regardless of whether an exception occurred.

Example:

try:

print(1 / 0)

except ZeroDivisionError:

print("Error")

finally:

print("This will always execute.")

Q6. What is the difference between raise and assert in Python? (K2, CO1, PO2)

Solution:

 raise manually throws an exception.

 assert checks a condition and throws an exception if false.

Example:

x = -1

assert x >= 0, "Negative value!" # Raises AssertionError

raise ValueError("Custom error!") # Raises ValueError


Q7. What is the purpose of the try-except block? (K2, CO1, PO2)

Solution:
The try-except block handles runtime errors to prevent crashes.

Example:

try:

num = int(input("Enter a number: "))

except ValueError:

print("Invalid input!")

Long Questions (4 Marks Each)

Q8. Write a Python program to extract all email addresses from a given text using regex. (K3, CO2,
PO3)

Solution:

import re

text = "Contact us at support@example.com or sales@company.com"

emails = re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", text)

print(emails) # Output: ['support@example.com', 'sales@company.com']

Q9. Write a Python program to validate if a given phone number follows the pattern (XXX)-XXX-
XXXX. (K3, CO2, PO3)

Solution:

import re

def validate_phone(number):

pattern = r"\(\d{3}\)-\d{3}-\d{4}"

return bool(re.fullmatch(pattern, number))

print(validate_phone("(123)-456-7890")) # Output: True

print(validate_phone("123-456-7890")) # Output: False

Q10. Explain the working of findall(), sub(), and split() in regex with examples. (K3, CO2, PO3)
Solution:

 findall() → Returns all matches in a list.

 sub() → Replaces matches with a string.

 split() → Splits the string at each match.

Example:

import re

text = "apple orange banana"

print(re.findall(r"\w+", text)) # ['apple', 'orange', 'banana']

print(re.sub(r"orange", "grape", text)) # apple grape banana

print(re.split(r"\s", text)) # ['apple', 'orange', 'banana']

Q11. Write a Python program to handle multiple exceptions. (K4, CO2, PO4)

Solution:

try:

x = int(input("Enter a number: "))

print(10 / x)

except ZeroDivisionError:

print("Cannot divide by zero!")

except ValueError:

print("Invalid input!")

Q12. How does Python handle user-defined exceptions? Write a program for the same. (K4, CO2,
PO4)

Solution:
Python allows users to define custom exceptions using a class.

Example:

class NegativeValueError(Exception):

pass

def check_value(num):
if num < 0:

raise NegativeValueError("Negative values are not allowed!")

try:

check_value(-5)

except NegativeValueError as e:

print(e) # Output: Negative values are not allowed!

Q13. What is exception chaining in Python? Give an example. (K5, CO2, PO5)

Solution:
Exception chaining links one exception to another using raise from.

Example:

try:

raise ValueError("Initial error")

except ValueError as e:

raise RuntimeError("New error occurred") from e

Q14. Explain the role of logging in exception handling. Write a Python program to log exceptions to
a file. (K5, CO2, PO5)

Solution:
Logging allows errors to be recorded for debugging.

Example:

import logging

logging.basicConfig(filename="errors.log", level=logging.ERROR)

try:

print(1 / 0)

except ZeroDivisionError as e:

logging.error("Error occurred: %s", e)

Q15. Compare checked and unchecked exceptions in Python. (K6, CO2, PO6)
Solution:

 Checked exceptions must be handled using try-except (e.g., FileNotFoundError).

 Unchecked exceptions occur due to logical errors (e.g., ZeroDivisionError).

Example:

# Checked Exception

try:

with open("file.txt") as f:

print(f.read())

except FileNotFoundError:

print("File not found!")

# Unchecked Exception

print(10 / 0) # ZeroDivisionError

Unit 5: Database Interaction & Multithreading – Questions & Solutions

(Includes Short & Long Questions with Solutions, Based on Bloom’s Taxonomy, COs, and POs)

Short Questions (2 Marks Each)

Q1. What is a database connection in Python? (K1, CO1, PO1)

Solution:
A database connection allows Python to interact with databases (e.g., MySQL, SQLite). The sqlite3
and mysql.connector modules are commonly used.

Example:

import sqlite3

conn = sqlite3.connect("test.db") # Connect to SQLite database

print("Connected successfully!")

conn.close()

Q2. What is SQL Injection, and how can it be prevented? (K1, CO1, PO1)

Solution:
SQL Injection is a security vulnerability where attackers inject malicious SQL queries into input fields.
It can be prevented using parameterized queries.
Example (Unsafe Query – Vulnerable to SQL Injection):

cursor.execute("SELECT * FROM users WHERE username = '" + user_input + "'")

Example (Safe Query – Using Parameterized Queries):

cursor.execute("SELECT * FROM users WHERE username = ?", (user_input,))

Q3. What is multithreading in Python? (K1, CO2, PO1)

Solution:
Multithreading allows multiple tasks to run concurrently within a single process.

Example:

import threading

def print_hello():

print("Hello from thread!")

thread = threading.Thread(target=print_hello)

thread.start()

thread.join()

Q4. Explain the difference between Threading and Multiprocessing. (K2, CO2, PO2)

Solution:

Feature Threading Multiprocessing

Memory Usage Shared Memory Separate Memory

Speed Faster for I/O-bound tasks Faster for CPU-bound tasks

Example Use Web Scraping, File I/O Image Processing, Data Analysis

Q5. What is the difference between synchronous and asynchronous programming? (K2, CO2, PO2)

Solution:

 Synchronous Programming: Tasks execute sequentially (one after another).

 Asynchronous Programming: Tasks execute concurrently, allowing non-blocking operations.

Example (Synchronous):

def task1():
print("Task 1 completed")

def task2():

print("Task 2 completed")

task1()

task2()

Example (Asynchronous):

import asyncio

async def task1():

print("Task 1 completed")

async def task2():

print("Task 2 completed")

asyncio.run(task1())

asyncio.run(task2())

Long Questions (4 Marks Each)

Q6. Write a Python program to connect to a MySQL database and retrieve data from a table. (K3,
CO3, PO3)

Solution:

import mysql.connector

conn = mysql.connector.connect(host="localhost", user="root", password="1234",


database="mydb")

cursor = conn.cursor()

cursor.execute("SELECT * FROM employees")

for row in cursor.fetchall():

print(row)
conn.close()

Q7. How can we create and search a table in an SQLite database using Python? (K3, CO3, PO3)

Solution:

import sqlite3

conn = sqlite3.connect("company.db")

cursor = conn.cursor()

# Create Table

cursor.execute('''CREATE TABLE IF NOT EXISTS employees (id INTEGER PRIMARY KEY, name TEXT,
salary REAL)''')

# Insert Data

cursor.execute("INSERT INTO employees (name, salary) VALUES ('Alice', 50000)")

conn.commit()

# Search Data

cursor.execute("SELECT * FROM employees WHERE name = 'Alice'")

print(cursor.fetchone())

conn.close()

Q8. What is database normalization? Explain its advantages. (K4, CO3, PO4)

Solution:
Database normalization organizes a database to reduce redundancy and improve data integrity.

Advantages:

1. Eliminates duplicate data

2. Ensures data consistency

3. Optimizes storage space

4. Improves data retrieval efficiency


Example:
Unnormalized Table:

ID Name Department Dept_Location

1 John HR New York

2 Alice HR New York

Normalized Table (Separate Departments Table):

Dept_ID Department Location

1 HR New York

ID Name Dept_ID

1 John 1

2 Alice 1

Q9. Write a Python program to perform multithreading for running two functions simultaneously.
(K4, CO4, PO4)

Solution:

import threading

def task1():

for _ in range(5):

print("Task 1 running")

def task2():

for _ in range(5):

print("Task 2 running")

t1 = threading.Thread(target=task1)

t2 = threading.Thread(target=task2)

t1.start()

t2.start()
t1.join()

t2.join()

Q10. Explain how thread synchronization works in Python. (K4, CO4, PO4)

Solution:
Thread synchronization ensures only one thread accesses a shared resource at a time using Locks.

Example:

import threading

lock = threading.Lock()

balance = 100

def withdraw(amount):

global balance

lock.acquire()

try:

if balance >= amount:

balance -= amount

print(f"Withdrawn {amount}, Remaining Balance: {balance}")

else:

print("Insufficient balance")

finally:

lock.release()

t1 = threading.Thread(target=withdraw, args=(50,))

t2 = threading.Thread(target=withdraw, args=(70,))

t1.start()

t2.start()

t1.join()
t2.join()

Q11. What is deadlock in multithreading? How can it be prevented? (K5, CO4, PO5)

Solution:
Deadlock occurs when two or more threads wait for each other indefinitely.

Prevention Methods:

1. Avoid Nested Locks: Ensure threads acquire locks in a consistent order.

2. Use a Timeout: Set a timeout when acquiring a lock.

3. Use Deadlock Detection Algorithms.

Example (Deadlock Scenario):

import threading

lock1 = threading.Lock()

lock2 = threading.Lock()

def task1():

lock1.acquire()

lock2.acquire() # Deadlock occurs if task2 acquires lock2 first

def task2():

lock2.acquire()

lock1.acquire()

t1 = threading.Thread(target=task1)

t2 = threading.Thread(target=task2)

t1.start()

t2.start()

t1.join()

t2.join()
Q12. What is the Global Interpreter Lock (GIL), and how does it affect multithreading in Python?
(K6, CO4, PO6)

Solution:
The Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time,
limiting true parallel execution.

Impact:

 Useful for I/O-bound tasks (e.g., file handling).

 Inefficient for CPU-bound tasks (e.g., image processing).

 Workaround: Use multiprocessing instead of threading.

You might also like