Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views6 pages

Assignment 2 - Answers

The document provides an overview of various Python functionalities, including file operations using the shutil module, logging levels, assertions, and class methods. It also covers concepts like pure functions, polymorphism, operator overloading, and the differences between prototyping and planning in software development. Additionally, it includes code examples for each concept discussed.

Uploaded by

pavithra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views6 pages

Assignment 2 - Answers

The document provides an overview of various Python functionalities, including file operations using the shutil module, logging levels, assertions, and class methods. It also covers concepts like pure functions, polymorphism, operator overloading, and the differences between prototyping and planning in software development. Additionally, it includes code examples for each concept discussed.

Uploaded by

pavithra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Assignment 2 — Module 4

1. Explain the following with respect to shutil module:

i) Copying files and folders

 Use shutil.copy(src, dst) to copy a single file.

 Use shutil.copytree(src, dst) to copy an entire directory.

import shutil

# Copy a file

shutil.copy("file1.txt", "copy_file1.txt")

# Copy a folder

shutil.copytree("folderA", "folderB")

ii) Moving and renaming files and folders

 Use shutil.move(src, dst) to move or rename.

shutil.move("file1.txt", "newfolder/file1.txt") # Move

shutil.move("oldname.txt", "newname.txt") # Rename

2. Write a program to backup a folder into a ZIP file

import zipfile, os

def backup_to_zip(folder):

folder = os.path.abspath(folder)

zip_filename = os.path.basename(folder) + '_backup.zip'

with zipfile.ZipFile(zip_filename, 'w') as backup_zip:

for foldername, subfolders, filenames in os.walk(folder):

for filename in filenames:

filepath = os.path.join(foldername, filename)

backup_zip.write(filepath, os.path.relpath(filepath, folder))

print(f"Backup created: {zip_filename}")


backup_to_zip('myfolder')

 This program creates a ZIP file containing all files in the folder.

3. Explain the different logging levels

Python logging module has 5 main logging levels:

Level Use

DEBUG Detailed diagnostic

INFO General information

WARNING Indication of potential issue

ERROR An error occurred

CRITICAL Severe error

import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug("Debug message")

logging.info("Info message")

logging.warning("Warning message")

logging.error("Error message")

logging.critical("Critical message")

4. What is an assertion? Explain assert keyword with example

 Assertion is used to test if a condition is True during execution.

 If False, it raises AssertionError.

def square_root(x):

assert x >= 0, "Only non-negative numbers allowed"

return x ** 0.5

print(square_root(25)) # OK

print(square_root(-4)) # Raises AssertionError

5. Display folder name, list of subfolders, and files using os.walk()


import os

for foldername, subfolders, filenames in os.walk('.'):

print(f'Folder: {foldername}')

print(f'Subfolders: {subfolders}')

print(f'Files: {filenames}')

print('---')

6. Explain permanent delete and safe delete with suitable Python program

Permanent delete:

import os

os.remove("test.txt") # File is permanently deleted

Safe delete using send2trash:

from send2trash import send2trash

send2trash("important.txt") # File goes to Recycle Bin (safe)

 send2trash is safer for critical files.

7. Write function DivExp(a,b) using assertion for a > 0 and exception for b = 0

def DivExp(a, b):

assert a > 0, "a must be greater than 0"

try:

result = a / b

except ZeroDivisionError:

return "Division by zero is not allowed"

return result

print(DivExp(10, 2)) # Output: 5.0

print(DivExp(10, 0)) # Exception handled

Assignment 2 — Module 5
1. Explain __init__, __str__, __add__ methods with example

 These are special methods in Python:

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

def __str__(self):

return f"Point({self.x}, {self.y})"

def __add__(self, other):

return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)

p2 = Point(3, 4)

print(p1) # Calls __str__

print(p1 + p2) # Calls __add__

2. Define classes and objects. Create a class Student and display attributes

class Student:

def __init__(self, name, age):

self.name = name

self.age = age

def display(self):

print(f"Name: {self.name}, Age: {self.age}")

s1 = Student("Alice", 20)

s2 = Student("Bob", 21)

s1.display()
s2.display()

3. Explain pure functions with examples

 A pure function has:

o No side effects.

o Same output for same input.

def add(a, b):

return a + b # Pure function

# Not pure

total = 0

def add_to_total(x):

global total

total += x

return total

4. Demonstrate polymorphism with function to find histogram of letters

def letter_histogram(text):

histogram = {}

for char in text:

if char.isalpha():

histogram[char] = histogram.get(char, 0) + 1

return histogram

print(letter_histogram("hello world"))

 Polymorphism: +, get() work differently depending on context.

5. Discuss operator overloading. Mention five operators with special functions

 Operator overloading: redefining standard operators for user-defined classes.

Operator Method

+ __add__()
Operator Method

- __sub__()

* __mul__()

/ __truediv__()

== __eq__()

class Num:

def __init__(self, value):

self.value = value

def __add__(self, other):

return Num(self.value + other.value)

def __str__(self):

return str(self.value)

a = Num(5)

b = Num(10)

print(a + b) # 15

6. Explain concept of prototyping vs planning

Prototyping Planning

Create working model quickly Focus on analysis and design

Used to test functionality early Used for long-term structure

Involves more trial & error Involves more documentation & design

Suitable for agile methods Suitable for waterfall methods

You might also like