0% found this document useful (0 votes)
9 views12 pages

Question Bank Mid Sem Sem 4

The document is a mid-semester question bank covering key concepts in Python programming, including differences between interpreted and compiled languages, mutable and immutable data types, built-in list methods, string formatting with f-strings, and exception handling. It also addresses Python functions, keyword arguments, class methods, and the significance of access modifiers and abstraction. Additionally, the document includes practical programming exercises and examples to illustrate these concepts.
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)
9 views12 pages

Question Bank Mid Sem Sem 4

The document is a mid-semester question bank covering key concepts in Python programming, including differences between interpreted and compiled languages, mutable and immutable data types, built-in list methods, string formatting with f-strings, and exception handling. It also addresses Python functions, keyword arguments, class methods, and the significance of access modifiers and abstraction. Additionally, the document includes practical programming exercises and examples to illustrate these concepts.
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/ 12

Mid Semester Question Bank:

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.

Mutable Data Types:

 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}

Immutable Data Types:

 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()

 Purpose: Adds a single element to the end of the list.


 Example:

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."

# Using .format() method


greeting = "Hello, my name is {} and I am {} years old.".format(name, age)
# Using % operator
greeting = "Hello, my name is %s and I am %d years old." % (name, age)

Q5. How does slicing work in strings? Explain with examples.


String slicing is a powerful technique that allows you to extract specific portions of a string. It's done
using the following syntax:
string[start:end:step]

 start: The starting index (inclusive).


 end: The ending index (exclusive).
 step: The step size (default is 1).

Examples:

1. Extracting a substring:

my_string = "Hello, world!"

# Extract characters from index 0 to 4 (exclusive)


print(my_string[0:5])

# Extract characters from index 2 to the end


print(my_string[2:])

# Extract characters from the beginning to index 5 (exclusive)


print(my_string[:5])

# Extract characters from index -6 to -1 (exclusive)


print(my_string[-6:-1])

# Extract characters from index -1 to the end (exclusive)


print(my_string[-1:])

# Extract characters from the beginning to index -6 (exclusive)


print(my_string[:-6])

Output:
Hello
llo, world!
Hello
world
!
Hello,

2. Extracting with a step:

# Extract characters from index 0 to the end with a step of 2


print(my_string[::2])

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

for char in my_string:


if char in vowels:
count += 1

print("Number of vowels:", count)

Q7. Write a program to check if two strings are anagrams.


str1 = "listen"
str2 = "silent"

# Convert both strings to lowercase for case-insensitive comparison


str1 = str1.lower()
str2 = str2.lower()

# Check if the lengths of the strings are equal


if len(str1) != len(str2):
print("The strings are not anagrams.")
else:
# Sort the characters in each string
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)

# Check if the sorted strings are equal


if sorted_str1 == sorted_str2:
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")

Q8. Write a program to extract and print the first and last characters of a string.
my_string = "Hello, world!"

# Extract the first character


first_char = my_string[0]

# Extract the last character


last_char = my_string[-1]
print("First character:", first_char)
print("Last character:", last_char)

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)

# Accessing elements using positive indexing


print("Element at index 0:", my_tuple[0])
print("Element at index 2:", my_tuple[2])
print("Element at index 4:", my_tuple[4])

# Accessing elements using negative indexing


print("Element at index -1:", my_tuple[-1])
print("Element at index -3:", my_tuple[-3])
print("Element at index -5:", my_tuple[-5])

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}

# Find the union of two sets


union_set = set1.union(set2)
print("Union:", union_set)

# Find the intersection of two sets


intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)

# Find the difference of two sets (set1 - set2)


difference_set1 = set1.difference(set2)
print("Difference (set1 - set2):", difference_set1)

# Find the difference of two sets (set2 - set1)


difference_set2 = set2.difference(set1)
print("Difference (set2 - set1):", difference_set2)

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 + "!")

greet("Alice") # "Alice" is an argument

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)

my_function(1, 2, 3, name="Alice", age=30)

Output:
args: (1, 2, 3)
kwargs: {'name': 'Alice', 'age': 30}

Q4. Write a function to calculate the sum of squares of a list of numbers.


def sum_of_squares(numbers):

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

Q5. What is the purpose of the __init__ method in Python classes?


 The __init__ method in Python classes is a special method, also known as the constructor.
 Its primary purpose is to initialize the attributes (variables) of an object when it is created.
 It sets the initial state of the object by assigning values to its attributes.
Example:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed

my_dog = Dog("Buddy", "Golden Retriever")

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.")

# Accessing public members


obj = MyClass("Hello")
print(obj.public_attribute) # Accessing public attribute
obj.public_method() # Calling public method
Private Members
 Accessible only within the class where they are defined.
 Not directly accessible from outside the class.
 In Python, private members are conventionally denoted by prefixing their names with two
underscores (__).
Example:
class MyClass:
def __init__(self, private_attribute):
self.__private_attribute = private_attribute

def __private_method(self):
print("This is a private method.")

# Attempting to access private members (will raise an AttributeError)


obj = MyClass("Hello")
print(obj.__private_attribute) # Raises AttributeError
obj.__private_method() # Raises AttributeError

Q7. What is the significance of the super() function in inheritance?


 It allows a subclass to access and call methods defined in its parent class.
 This is crucial when you want to extend or modify the behavior of a parent class method in the
subclass while still utilizing the parent class's implementation.
 super() makes your code more maintainable and flexible, especially in scenarios with multiple
inheritance.
 It ensures that the correct parent class method is called, even if the class hierarchy changes.
Example:
class Animal:
def __init__(self, name):
self.name = name

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!")

my_dog = Dog("Buddy", "Golden Retriever")


my_dog.speak()

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...")

# Create instances of Car and Bike


my_car = Car()
my_bike = Bike()

# Start and stop the vehicles


my_car.start_engine()
my_car.stop_engine()
my_bike.start_engine()
my_bike.stop_engine()

Q9. Explain the difference between docstrings and comments.


Docstrings
 Provide concise and informative descriptions of functions, classes, and modules.
 Serve as the primary source of documentation for your code.
 Can be accessed programmatically using the __doc__ attribute.
 Placed immediately after the function, class, or module definition.
 Typically enclosed within triple quotes ("""...""").
 Used to explain the purpose, parameters, return values, and usage of the object.

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"

# Open the file in append mode ('a')


with open(filename, 'a') as file_object:
# Write the new data to the file
file_object.write(new_data)

print(f"Data appended to {filename} successfully.")


Chapter-3:

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

Q5. Explain the difference between a library, package and a module.


Module
 A single Python file (e.g., my_module.py) containing Python code (functions, classes, variables).
 Encapsulates related functionality.
 Improves code organization and reusability.
 Avoids namespace collisions.
Package
 A collection of related modules organized in a directory.
 Contains a special file named __init__.py (can be empty) to signal that the directory is a Python
package.
 Allows for hierarchical organization of modules.
Library
 A broader term encompassing a collection of modules and packages that provide a set of
functionalities for a specific purpose.
 Examples: pandas, numpy, matplotlib, requests
 Often distributed as a single unit (e.g., through pip).
 May include extensive documentation, tutorials, and examples.

You might also like