Question Bank Mid Sem Sem 4
Question Bank Mid Sem Sem 4
Chapter-1
Q1. Explain the difference between an interpreted language and a compiled language. Which one
does Python fall under?
An interpreter converts code from interpreted languages into machine code in real time as it is
executed, line by line. This indicates that before being executed, the code is not transformed into
machine code.
A compiler first transforms compiled languages into machine code, which is subsequently
transformed into an executable file that the computer may run directly. This indicates that before
the code is executed, it is transformed into machine code.
Python is classified as an interpreted language.
Q2. What is the difference between mutable and immutable data types in Python? Give examples.
Definition: These data types can be modified after they are created.
Examples:
o Lists: my_list = [1, 2, 3]
o Dictionaries: my_dict = {'a': 1, 'b': 2}
o Sets: my_set = {1, 2, 3}
Definition: These data types cannot be modified after they are created.
Examples:
o Strings: my_string = 'hello'
o Tuples: my_tuple = (1, 2, 3)
o Integers: my_int = 42
o Floats: my_float = 3.14
Q3. Explain the role of built-in methods like append(), extend(), remove(), and pop() in lists.
append()
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
Output:
[1, 2, 3, 4]
extend()
Purpose: Adds all the elements of an iterable (like another list) to the end of the list.
Example:
my_list = [1, 2, 3]
other_list = [4, 5]
my_list.extend(other_list)
print(my_list)
Output:
[1, 2, 3, 4, 5]
remove()
Purpose: Removes the first occurrence of a specified value from the list.
Example:
my_list = [1, 2, 3, 2, 4]
my_list.remove(2)
print(my_list)
Output:
[1, 3, 2, 4]
pop()
Purpose: Removes and returns the element at a specified index (default is the last element).
Example:
my_list = [1, 2, 3]
removed_item = my_list.pop()
print(my_list)
print(removed_item)
Output:
[1, 2]
3
Q4. What are f-strings, and how are they different from other string formatting techniques?
f-strings is a potent string formatting tool. They offer a clear and understandable method of directly
embedding variables and expressions into strings.
name = "Alice"
age = 30
# Using f-string
greeting = f"Hello, my name is {name} and I am {age} years old."
Examples:
1. Extracting a substring:
Output:
Hello
llo, world!
Hello
world
!
Hello,
Output:
Hlo ol!
3. Reversing a string:
# Extract characters from index 0 to the end in reverse order
print(my_string[::-1])
Output:
!dlrow ,olleH
Q6. Write a Python program to count the number of vowels in a given string.
my_string = "Hello, world!"
vowels = "aeiouAEIOU"
count = 0
Q8. Write a program to extract and print the first and last characters of a string.
my_string = "Hello, world!"
Q9. Write a python program to create a tuple containing five elements and demonstrate accessing
elements using positive and negative indexing.
# Create a tuple with five elements
my_tuple = (10, 20, 30, 40, 50)
Output:
Element at index 0: 10
Element at index 2: 30
Element at index 4: 50
Element at index -1: 50
Element at index -3: 30
Element at index -5: 10
Q10. Implement a program to find the union, intersection, and difference of two sets.
# Define two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
Output:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference (set1 - set2): {1, 2}
Difference (set2 - set1): {5, 6}
Chapter-2
Q1. Explain the difference between arguments and parameters in Python functions.
Parameters:
They are variables enclosed in parenthesis in the definition of a function.
They serve as stand-ins for the values that are given to the function upon call.
Arguments:
They are real values supplied to a function upon invocation.
Provide the information needed by the function to carry out its tasks.
Example:
def greet(name): # 'name' is a parameter
"""This function greets the person passed in as a parameter."""
print("Hello, " + name + "!")
Q2. What are keyword arguments? How do they differ from positional arguments?
Positional arguments:
Passed to a function based on their position in the function's parameter list.
Example: my_function(arg1, arg2) - arg1 is assigned to the first parameter, arg2 to the second.
Keyword arguments:
Passed to a function by explicitly specifying the parameter name and its value.
Example: my_function(arg1=value1, arg2=value2) - You can pass arguments in any order.
Q3. What are *args and **kwargs in Python? Explain with an example.
*args:
Allows a function to accept an arbitrary number of positional arguments.
Inside the function, *args is treated as a tuple containing all the positional arguments passed to
the function.
**kwargs:
Allows a function to accept an arbitrary number of keyword arguments.
Inside the function, **kwargs is treated as a dictionary containing all the keyword arguments
passed to the function.
Example:
def my_function(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
Output:
args: (1, 2, 3)
kwargs: {'name': 'Alice', 'age': 30}
total = 0
for num in numbers:
total += num * num
return total
my_list = [1, 2, 3, 4, 5]
result = sum_of_squares(my_list)
print("Sum of squares:", result)
Output:
55
Q6. Explain the difference between public and private access modifiers in python.
In Python, access modifiers control the visibility and accessibility of class members (attributes and
methods).
Public Members
Accessible from anywhere within the program, including outside the class.
Can be accessed by creating an object of the class and using dot notation.
No special syntax is required for public members in Python.
Example:
class MyClass:
def __init__(self, public_attribute):
self.public_attribute = public_attribute
def public_method(self):
print("This is a public method.")
def __private_method(self):
print("This is a private method.")
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call the parent class constructor
self.breed = breed
def speak(self):
print("Woof!")
Output:
Woof!
Q8. Explain the use of abstraction by creating an abstract base class for vehicles with methods to be
implemented by derived classes (e.g., Car, Bike).
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
class Car(Vehicle):
def start_engine(self):
print("Car: Starting the engine...")
def stop_engine(self):
print("Car: Stopping the engine...")
class Bike(Vehicle):
def start_engine(self):
print("Bike: Starting the engine...")
def stop_engine(self):
print("Bike: Stopping the engine...")
Comments
Explain specific lines or blocks of code within a function or class.
Provide context, clarify logic, or make notes for future reference.
Can be placed anywhere within the code.
Usually preceded by the hash symbol (#).
Used to explain complex algorithms, provide debugging information, or leave reminders for
yourself or other developers.
Q10. Explain the purpose of the try, except, else, and finally blocks in exception handling.
try:
Encloses the code that might potentially raise an exception.
If an exception occurs within the try block, the program immediately jumps to the corresponding
except block.
except:
Handles the specific exception(s) that occurred within the try block.
Executes code to handle the exception gracefully.
Can specify the type of exception to catch (e.g., ZeroDivisionError, ValueError).
If no matching except block is found, the program will terminate with an unhandled exception.
else:
Executes only if no exceptions occurred within the try block.
Often used for code that should run if the operation in the try block was successful.
finally:
Executes regardless of whether an exception occurred or not.
Commonly used for cleanup tasks, such as closing files, releasing resources (like database
connections), or displaying final messages.
Example:
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input. Please enter numbers only.")
else:
print("Result:", result)
finally:
print("Execution complete.")
Q11. Write a Python script that appends new data to an existing file without overwriting its
contents.
# Filename to append data to
filename = "my_file.txt"
# Data to append
new_data = "This is the new line of data.\n"
Q1. What is the difference between a relational database and a non-relational database?
Relational Databases
Data is organized into tables with rows and columns, forming a structured schema.
Based on the relational model, using SQL (Structured Query Language) for data manipulation.
Define relationships between different tables (e.g., one-to-one, one-to-many) using foreign keys.
Strong data integrity and consistency.
Well-suited for complex queries and transactions.
Mature technology with robust tools and support.
Can be less flexible for rapidly evolving data structures.
Scalability can be challenging with very large datasets.
May not be ideal for unstructured or semi-structured data.
Non-Relational Databases (NoSQL)
Use various data models like key-value pairs, document stores, column families, and graph
databases.
More flexible and schema-less or schemaless, allowing for dynamic data structures.
Relationships between data are often implicit or handled differently depending on the data model.
Highly scalable and can handle massive volumes of data.
Excellent for handling unstructured or semi-structured data.
More flexible for rapidly changing data requirements.
May have weaker data consistency guarantees compared to relational databases.
Can be more complex to query and manage in some cases.
Q2. Explain the purpose of the cursor object when executing SQL queries in Python.
The cursor navigates through a query's result set like a pointer.
By enabling you to run SQL commands and access or alter data, it offers an organised method of
interacting with the database.
Cursors are used to execute SQL queries against the database.
They provide methods like execute() to send SQL statements to the database for processing.
Q3. What is the difference between fetchone()and fetchall() in MySQL query execution?
fetchone()
Retrieves only the next single row from the result set.
Used when you need to process data row by row.
Used when you have a large dataset and want to minimize memory usage.
Used in scenarios where you don't need all the data at once.
fetchall()
Retrieves all the rows from the result set at once.
Used when you need to process the entire dataset in memory.
Used when the dataset is relatively small.
Q4. What are collections in MongoDB, and how are they different from tables in MySQL?
Feature MongoDB Collections MySQL Tables
Structure Flexible, document-oriented Rigid, tabular
Schema Schemaless or flexible Schema-defined
Data
Model Document-oriented Relational
Can scale vertically or with more complex
Scalability Generally better for horizontal scaling setups
Data Supports a wide range of data types, including Primarily supports traditional data types
Types embedded documents and arrays like integers, strings, dates