0% found this document useful (0 votes)
2 views5 pages

Module4_Answers_Complete

The document provides answers to questions from Modules 4 and 5 of a Python programming course. It covers topics such as the logging module, file operations, directory traversal, exception handling, and the use of zip files for compression. Each answer includes explanations and code examples to illustrate the concepts discussed.

Uploaded by

mhyder105
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)
2 views5 pages

Module4_Answers_Complete

The document provides answers to questions from Modules 4 and 5 of a Python programming course. It covers topics such as the logging module, file operations, directory traversal, exception handling, and the use of zip files for compression. Each answer includes explanations and code examples to illustrate the concepts discussed.

Uploaded by

mhyder105
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/ 5

BPLCK205B - Introduction to Python Programming

Answers to Module 4 and Module 5 Question Bank

Module 4 Answers - Full Set

Q1. Explain the logging module and debug the factorial of a number program

1. The logging module provides a flexible framework for emitting log messages.
2. Logging is used to debug and track the execution flow of a program.
3. `basicConfig()` sets default format and level for logging.
4. Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
5. Factorial is a recursive function; logging helps track each call.
6. `logging.debug()` used inside recursion to show computation.
7. Helps diagnose logic errors and trace program behavior.
8. Example:
import logging
logging.basicConfig(level=logging.DEBUG)
def factorial(n):
logging.debug(f"Calculating factorial({n})")
return 1 if n == 0 else n * factorial(n - 1)
print(factorial(5))

Q2. Backup a folder to a ZIP file

1. Use the zipfile module for working with ZIP archives.


2. Use os.walk to walk through folder structure.
3. Create a ZipFile object with write mode.
4. Add files to the archive using write().
5. Use absolute paths to ensure proper traversal.
6. Filename is generated dynamically using basename.
7. Can be used for backup or deployment.
8. Example:
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 zipf:
for foldername, subfolders, filenames in os.walk(folder):
zipf.write(foldername)
for filename in filenames:
zipf.write(os.path.join(foldername, filename))
backup_to_zip('myfolder')

Q3. Difference between shutil.copy() and shutil.copytree()

1. shutil.copy() copies a single file from source to destination.


2. shutil.copytree() copies an entire directory and its contents.
BPLCK205B - Introduction to Python Programming

Answers to Module 4 and Module 5 Question Bank

3. copy() requires destination file or folder.


4. copytree() automatically creates the destination directory.
5. copytree() is recursive.
6. copy() is typically used for individual file operations.

Q4. Discuss the basicConfig() method with an example

1. basicConfig() is used to configure the logging module.


2. It sets format, level, filename, filemode etc.
3. Must be called before any logging functions.
4. Common levels: DEBUG, INFO, WARNING.
5. Format controls output message appearance.
6. Example:
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info("Logging started")

Q5. Program to traverse directory listing files and folders

1. Use os.walk() to traverse directories.


2. Returns a generator of (dirpath, dirnames, filenames).
3. Can be used to automate file management.
4. Useful for scanning large directory trees.
5. Simple and efficient method.
6. Example:
import os
for dirpath, dirnames, filenames in os.walk('.'):
print("Directory:", dirpath)
print("Folders:", dirnames)
print("Files:", filenames)

Q6. Support for Logging in Python

1. Python has built-in logging support.


2. Provides multiple logging levels (DEBUG to CRITICAL).
3. Output can be sent to files or streams.
4. Configurable via basicConfig().
5. Logging avoids use of print() in production code.
6. Allows filtering messages by severity.
7. Helps debug complex scripts.
8. Example:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Debugging info")
BPLCK205B - Introduction to Python Programming

Answers to Module 4 and Module 5 Question Bank

Q7. File operations: copy, move, delete, rename

1. Copy: shutil.copy('a.txt', 'b.txt')


2. Move: shutil.move('a.txt', 'folder/')
3. Delete: os.remove('file.txt')
4. Rename: os.rename('old.txt', 'new.txt')
5. shutil and os modules are used.
6. File handling is OS-dependent.
7. Be careful while deleting files.
8. File paths must be correctly formatted.

Q8. Benefit of compressing and reading ZIP files

1. Compression reduces file size.


2. Easier and faster to transfer files.
3. Saves storage.
4. Supports grouping multiple files.
5. Example:
import zipfile
with zipfile.ZipFile('test.zip', 'r') as zip_ref:
zip_ref.extractall('output_folder')
6. Efficient for backup and deployment.

Q9. Function DivExp with assertion and exception

1. Define function with parameters a and b.


2. Assert a > 0.
3. Raise ZeroDivisionError if b = 0.
4. Return c = a / b.
5. Use try-except block to catch error.
6. Example:
def DivExp(a, b):
assert a > 0, "a must be > 0"
if b == 0:
raise ZeroDivisionError("b cannot be zero")
return a / b

Q10. How to raise exceptions with example

1. Use `raise` keyword.


2. Raise built-in or custom exceptions.
3. Syntax: raise Exception("message")
4. Helps handle invalid input.
BPLCK205B - Introduction to Python Programming

Answers to Module 4 and Module 5 Question Bank

5. Supports user-defined exception types.


6. Example:
if age < 0:
raise ValueError("Age cannot be negative")

Q11. Rename files from American to European date format

1. Use regex to detect MM-DD-YYYY pattern.


2. Extract parts using groups.
3. Swap to DD-MM-YYYY.
4. Rename using os.rename().
5. Use os.listdir() to iterate.
6. Automates regional renaming.
7. Regular expressions simplify matching.
8. Example included in main notes.

Q12. Compressing files and reading ZIP with code snippet

1. Use zipfile module.


2. Create ZIP using ZipFile().
3. Read using extractall().
4. ZIP reduces size.
5. Works across platforms.
6. Example:
with zipfile.ZipFile('data.zip', 'r') as zipf:
zipf.extractall('data')

Q13. How does os.walk work with code snippet

1. os.walk() generates file names in directory tree.


2. Yields tuple (dirpath, dirnames, filenames).
3. Recursive traversal.
4. Easy directory analysis.
5. Efficient for backups, logs.
6. Example: for root, dirs, files in os.walk('.'): print(files)

Q14. Explain any three buttons in debug control window

1. Step Over: Executes line, skips internal functions.


2. Step Into: Enters called functions.
3. Continue: Runs till next breakpoint.
4. Helps trace program flow.
5. Used during debugging sessions.
BPLCK205B - Introduction to Python Programming

Answers to Module 4 and Module 5 Question Bank

6. Available in IDEs like PyCharm, VS Code.

Q15. Define assertions and assert statement components

1. Assertion checks assumptions in code.


2. Syntax: assert condition, message.
3. Raises AssertionError if condition fails.
4. Used for debugging.
5. Helps find logical errors early.
6. Example: assert x > 0, "x must be positive"

You might also like