Python Question Bank Answers
Python Question Bank Answers
(i) join() method: The join() method in Python is used to concatenate the elements of an
iterable (like a list or tuple) into a single string. The elements must be strings.
Syntax:
separator.join(iterable)
Example:
(ii) split() method: The split() method splits a string into a list based on a specified
separator. By default, it splits on whitespace.
Syntax:
string.split(separator, maxsplit)
Example:
b. Illustrate the benefits of compressing files. Also, explain reading a zip file with an
example:
Reading a ZIP File: Python’s zipfile module allows handling ZIP files.
Example:
import zipfile
Question 2
a. Explain the concept of File Handling. Also, explain the reading & writing process with
a suitable example:
File Handling in Python: File handling allows reading, writing, and manipulating files.
r : Read
w : Write
a : Append
rb , wb : Read/Write in binary mode
Example:
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!")
Assertions:
Example:
x = 10
assert x > 5, "x should be greater than 5"
Raise an Exception:
Example:
value = -1
if value < 0:
raise ValueError("Value must be non-negative")
Question 3
a. Difference between shutil.copy() and shutil.copytree() with code snippet:
Example:
import shutil
(i) Operator Overloading: Operator overloading allows defining custom behavior for operators.
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3.x, p3.y) # Output: 4 6
(ii) Type-based Dispatch: Type-based dispatch allows defining methods that behave differently
based on argument types.
Example:
@dispatch(int, int)
def add(a, b):
return a + b
@dispatch(str, str)
def add(a, b):
return a + " " + b
Question 4
a. Write a function named DivExp with assertions and exception handling:
Code:
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("Result:", DivExp(a, b))
except Exception as e:
print("Error:", e)
Remaining Questions
The rest of the questions will be answered with similar detailed explanations and code
examples, including:
s.