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

Python Programming Module 4 & 5 Answers

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)
32 views5 pages

Python Programming Module 4 & 5 Answers

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

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. `[Link]()` used inside recursion to show computation.
7. Helps diagnose logic errors and trace program behavior.
8. Example:
import logging
[Link](level=[Link])
def factorial(n):
[Link](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 [Link] 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 = [Link](folder)
zip_filename = [Link](folder) + '_backup.zip'
with [Link](zip_filename, 'w') as zipf:
for foldername, subfolders, filenames in [Link](folder):
[Link](foldername)
for filename in filenames:
[Link]([Link](foldername, filename))
backup_to_zip('myfolder')

Q3. Difference between [Link]() and [Link]()

1. [Link]() copies a single file from source to destination.


2. [Link]() 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
[Link](level=[Link], format='%(asctime)s - %(levelname)s - %(message)s')
[Link]("Logging started")

Q5. Program to traverse directory listing files and folders

1. Use [Link]() 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 [Link]('.'):
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
[Link](level=[Link])
[Link]("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: [Link]('[Link]', '[Link]')


2. Move: [Link]('[Link]', 'folder/')
3. Delete: [Link]('[Link]')
4. Rename: [Link]('[Link]', '[Link]')
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 [Link]('[Link]', '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 [Link]().
5. Use [Link]() 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 [Link]('[Link]', 'r') as zipf:
[Link]('data')

Q13. How does [Link] work with code snippet

1. [Link]() 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 [Link]('.'): 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"

Common questions

Powered by AI

shutil.copy() is suitable for copying single files as it requires the destination to be specified and only handles one file at a time. On the other hand, shutil.copytree() is used to copy entire directories including all contents, and it automatically creates the destination directory. It is recursive and ideal for operations involving whole directory trees. The use of one over the other depends on whether the task is to copy individual files or entire directories .

Assertions are used in programming to check assumptions about code logic, ensuring conditions are met during execution. They raise an AssertionError if the condition fails. The DivExp function uses assertions to ensure 'a' is greater than 0 as part of its logic: `assert a > 0, 'a must be > 0'`. This checks an assumption that is critical for the function's logic. Additionally, it uses an exception to handle division by zero, demonstrating exception handling in conjunction with assertions .

Logging provides a robust and flexible framework that allows configurable output, multiple severity levels, and directing output to files or streams, unlike print statements which are simplistic and unconfigurable. Logging’s levels (like DEBUG, INFO, WARNING) enable filtering messages based on urgency, facilitating effective debugging and monitoring. In contrast, print statements can clutter output and are not easily manageable in production environments .

The logging module provides a structured way to emit log messages, which helps track the execution flow of a program. For a recursive factorial program, logging can be used to trace each call to the recursive function. By using `logging.debug()`, the program can display these calls, helping diagnose logic errors and trace the program's behavior effectively .

basicConfig() enhances logging functionality by allowing the user to configure settings such as format, level, filename, and filemode. This configuration must be done before logging functions are called. It defines the default behavior of logs, including their messages' appearance and their severity levels (like DEBUG, INFO, WARNING). This allows for a centralized control of how log messages are emitted .

File compression significantly reduces the size of datasets, making them easier and faster to transfer and saving storage space. Compression also allows for the efficient grouping of multiple files into a single archive, simplifying processes such as backups and deployments. Overall, it enhances data management by improving transfer speeds and storage efficiency .

os.walk() provides a simple and efficient method for directory traversal by generating the names of files in a directory tree. It yields tuples containing the directory path, directory names, and file names, thus enabling automated file management tasks. Its recursive nature makes it particularly useful for scanning large directory trees for tasks such as backups or log analyses .

To use the zipfile module for folder backup, first, import the module along with os. Then, convert the folder path to an absolute path. Create a ZipFile object in write mode, and use os.walk to iterate over the folder structure. Use the write() method to add both folder paths and file paths into the archive. This approach can dynamically generate filenames using os.path.basename and is useful for backup and deployment .

Regular expressions, or regex, can identify and manipulate patterns within strings, such as date formats in file names. By using a regex pattern to detect the MM-DD-YYYY format, you can extract date components using groups and then recombine them into the DD-MM-YYYY format. This process involves iterating over files using os.listdir() and renaming them with os.rename(), simplifying the conversion of date formats in file names .

Debugging control features are crucial for tracing and understanding program flow. 'Step Over' executes the current line and skips over function internals, effectively monitoring flow without delving into nested function calls. 'Step Into' allows entry into function calls, providing a detailed view of the program's internal workings at each level. 'Continue' lets the program run until it hits the next breakpoint, facilitating management of program execution pace. These features help in pinpointing errors by allowing detailed inspection at varying granularity during debugging sessions .

You might also like