Python 2nd Assignment
Python 2nd Assignment
• The join() method is used to concatenate (join) a sequence of strings using a specified
delimiter. It takes an iterable (e.g., a list, tuple, or string) as its argument and returns a single
string where each element of the iterable is separated by the specified delimiter.
Syntax: delimiter.join(iterable)
split() method:
• The split() method is used to split a string into a list of substrings based on a specified
delimiter. It takes the delimiter as an argument and returns a list of substrings.
• maxsplit (optional): Specifies the maximum number of splits. If not provided, it splits the
string at all occurrences of the delimiter.
2.With the concept of file path, discuss absolute and relative file path.
In Python, the concepts of absolute and relative file paths are similar to those discussed earlier, but they are
used specifically within the context of Python programming to locate files and directories. Python provides
modules like os and os.path that allow you to work with file paths conveniently.
• An absolute file path in Python specifies the exact location of a file or directory on the file
system, starting from the root directory.
• You can create an absolute file path using the full directory structure from the root of the file
system.
• Python's os.path module can be used to construct absolute file paths in a platform-
independent manner.
Eg:
import os
absolute_path = os.path.abspath("/home/user/documents/file.txt")
print(absolute_path)
Relative File Path in Python:
• A relative file path in Python specifies the location of a file or directory relative to the current working
directory of the Python script.
• You can create relative file paths by specifying the path to a file or directory relative to the location of
your Python script.
• Python's os.path module can be used to work with relative file paths as well.
Eg:
import os
relative_path = "file.txt"
absolute_path = os.path.abspath(relative_path)
print(absolute_path)
if specific_file in file_list:
content = zip_file.read(specific_file).decode('utf-8')
print(f"\nContents of '{specific_file}':\n{content}")
else:
print(f"'{specific_file}' not found in the ZIP file.")
5. Bring about the use of the following file operation in Python with a suitable example.
i) Copying files and folders ii) Moving files and folders
iii)Permanently deleting files and folders
import os
# File to be permanently deleted
file_to_delete = 'file_to_delete.txt'
try:
# Get user input for the numerator and denominator
n = float(input("Enter the numerator: "))
m = float(input("Enter the denominator: "))
result = divide(n,m)
print("Result:", result)
except AssertionError as e:
print("Assertion Error:", e)
7. Write a function named DivExp which takes two parameters a,b and
returns a value c (c=a/b).Write suitable assertion for a>0 in function DivExp
and raise an exception for when b=0.Develop a suitable program,which
reads two values from the console and calls a function DivExp.
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed")
return a / b
try:
# Get user input for 'a' and 'b'
a = float(input("Enter the value of 'a': "))
b = float(input("Enter the value of 'b': "))
result = DivExp(a, b)
print(f"Result (a / b): {result}")
except ZeroDivisionError as e:
print("Error:", e)
except AssertionError as e:
print("Assertion Error:", e)
def study(self):
return f"{self.name} is studying!"
(ii) Objects:
An object is an instance of a class. It is a concrete, tangible instance created based on the
structure and behavior defined by the class. Objects represent real-world entities and can
have unique data and behavior while still following the class's blueprint.
student1 = Student("Alice", 20)
student2 = Student("Bob", 22)
(iii) Instance Variables:
Instance variables (also known as instance attributes) are variables that belong to individual
objects created from a class. They store data unique to each object and are accessible using
dot notation (object.variable).
class Student:
def __init__(self, name, age):
self.name = name # Instance variable for name
self.age = age # Instance variable for age
10. Define class and object, Construct the class called rectangle and
initialize it with height=100,width=200, starting point as (x=0.y=0).Write a
program to display the center point coordinates of a rectangle
class Rectangle:
def __init__(self):
self.height = 100
self.width = 200
self.x = 0
self.y = 0
def center(self):
center_x = self.x + (self.width / 2)
center_y = self.y + (self.height / 2)
return center_x, center_y
rectangle = Rectangle()
center_x, center_y = rectangle.center()
print(f"Center Point: ({center_x}, {center_y})")
def __str__(self):
return f"Person: {self.name}, Age: {self.age}"
12. Explain the concept of copying using copy module with an example.
The copy module offers two main functions for copying objects: copy.copy() for shallow
copies and copy.deepcopy() for deep copies.
Shallow Copy:
• A shallow copy of an object creates a new object but does not duplicate the objects
contained within it. Instead, it copies references to the contained objects. This
means that changes made to the inner objects in the copied structure will also be
reflected in the original.
import copy
(2) Slicing:
• Slicing is a way to extract a portion (subsequence) of a sequence, such as a list,
string, or tuple, by specifying a start and end index.
• The syntax for slicing is sequence[start:end], where start is inclusive, and end is
exclusive.
• You can also specify a step value as sequence[start:end:step] to skip elements.
my_list = [1, 2, 3, 4, 5]
sublist = my_list[1:4] # Extract elements from index 1 to 3 (exclusive)
14. Explain the use of in and not in operators in list with suitable examples.
The in and not in operators in Python are used to check for the presence or absence of an
element in a list. These operators return a Boolean value (True or False) based on whether
the element is found in the list.
(1) Use of in Operator:
• The in operator checks if an element exists in a list and returns True if it does, or
False if it doesn't.
my_list = [1, 2, 3, 4, 5]
# Copy a file
shutil.copy("source_file.txt", "destination_folder/destination_file.txt")
17. Explain different methods or modes for opening the file with example
(1) Read Mode ('r'):
• Use this mode to read the contents of an existing file.
• Example: with open("example.txt", 'r') as file:
# Read the contents of an existing file
with open("example.txt", 'r') as file:
content = file.read()
print(content)
(2) Write Mode ('w'):
• Use this mode to create or overwrite a file with new content.
• Example: with open("example.txt", 'w') as file:
# Create or overwrite a file with new content
with open("example.txt", 'w') as file:
file.write("This is new content.")
(3) Append Mode ('a'):
• Use this mode to add new content to the end of an existing file.
• Example: with open("example.txt", 'a') as file:
# Add new content to the end of an existing file
with open("example.txt", 'a') as file:
file.write("This is appended content.")
(4) Binary Mode ('b'):
• Use this mode when working with non-text files like images or audio.
• Example: with open("image.jpg", 'rb') as file:
# Read binary data from an image file
with open("image.jpg", 'rb') as file:
binary_data = file.read()
# Process binary data (e.g., save to another file)
(5) Read and Write Mode ('r+' or 'w+'):
• Use these modes for reading and writing in the same file.
• 'r+' for an existing file, 'w+' for a new or existing file.
• Example: with open("example.txt", 'r+') as file:
# Read and write in the same file
with open("example.txt", 'r+') as file:
content = file.read()
file.write("This is new content appended to the existing file.")
19. Explain the methods __init__ and __str__ with suitable code example to
each.
In Python, the __init__ and __str__ methods are special methods used in classes for object
initialization and string representation, respectively.
(1) __init__ Method:
• The __init__ method is called when an object of a class is created. It initializes the
object's attributes or performs other setup tasks.
• It is also known as the constructor method.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person: {self.name}, Age: {self.age}"
def count_digits(self):
unique_digits = set(self.number_str)
digit_count = {}
return digit_count
def read_complex_number():
real = float(input("Enter the real part: "))
imaginary = float(input("Enter the imaginary part: "))
return ComplexNumber(real, imaginary)
N = int(input("Enter the number of complex numbers (N): "))
if N < 2:
print("N should be greater than or equal to 2.")
else:
result = read_complex_number()
22. Create a Time class with hour, min and sec as attributes. Demonstrate
how two Time objects would be added
class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return f"{self.hour:02d}:{self.minute:02d}:{self.second:02d}"
• We define a Time class with attributes for hours, minutes, and seconds.
• We override the __add__ method to define how two Time objects should be added.
It calculates the total seconds, converts them to hours, minutes, and seconds, and
returns a new Time object.
• The __str__ method is overridden to format the time as a string in HH:MM:SS
format.
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"