0% found this document useful (0 votes)
9 views2 pages

Python Programming Module 4 & 5 Answers

The document provides answers to questions from Modules 4 and 5 of an Introduction to Python Programming course. It covers topics such as the logging module, file backup using zipfile, differences between shutil.copy() and shutil.copytree(), creating a print_time function, defining and accessing classes, and the concepts of pure functions and modifiers. Each answer includes key points and 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)
9 views2 pages

Python Programming Module 4 & 5 Answers

The document provides answers to questions from Modules 4 and 5 of an Introduction to Python Programming course. It covers topics such as the logging module, file backup using zipfile, differences between shutil.copy() and shutil.copytree(), creating a print_time function, defining and accessing classes, and the concepts of pure functions and modifiers. Each answer includes key points and 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

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

1. logging is a standard module to track events.


2. Supports levels like DEBUG, INFO, etc.
3. Useful for debugging recursive programs.
4. basicConfig() sets up logging format.
5. Used in production for diagnostics.
6. Supports logging to files or console.
7. Factorial uses recursion with logs.
8. Example:
import logging
[Link](level=[Link])
def fact(n): return 1 if n==0 else n*fact(n-1)
print(fact(5))

Q2. Backup folder to ZIP using modules

1. Use zipfile and os modules.


2. Walk through folder using [Link]().
3. Use [Link]() to add files.
4. [Link]() used to create archive.
5. Make filename dynamic using folder name.
6. Can compress entire directory.
7. Ensures backup safety.
8. Example:
import zipfile, os
def backup(folder): ... (code omitted for brevity)

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

1. [Link]() copies individual files.


2. [Link]() copies full folder tree.
3. copy() needs src and dst filenames.
4. copytree() creates new dir at dst.
5. copy() overwrites if file exists.
6. copytree() raises error if dir exists.

Module 5 Answers

Q1. Function print_time() that takes a time object


BPLCK205B - Introduction to Python Programming

Answers to Module 4 and Module 5 Question Bank

1. Create class with hour, min, sec.


2. Function prints time as hh:mm:ss.
3. Uses format specifier for leading 0s.
4. Good for displaying clocks.
5. Reusable in other time-related programs.
6. Example:
class Time: ...
def print_time(t): ...

Q2. What is class and how to define/access

1. Class = blueprint for object.


2. Defined with class keyword.
3. __init__() initializes data.
4. Access using [Link]/attribute.
5. self refers to instance.
6. Example:
class Car: def __init__(self, brand): [Link] = brand

Q3. Pure function and modifier, square example

1. Pure function = same input = same output.


2. No external dependency.
3. Doesn't modify outside variables.
4. Modifier changes object state.
5. Helps in functional programming.
6. Example:
def square(x): return x*x

Common questions

Powered by AI

To print a time value in the hh:mm:ss format using a custom class in Python, first, create a class (e.g., Time) with attributes for hours, minutes, and seconds. Define a method within the class, such as print_time(), that formats these attributes into a string of the required format using format specifiers like {:02} for zero-padding. This method can be called to display the time in a consistent, human-readable format. Example: class Time: def __init__(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second def print_time(self): print(f'{self.hour:02}:{self.minute:02}:{self.second:02}').

shutil.copy() is used for copying individual files, requiring both source and destination file paths, and it overwrites the destination if a file with the same name already exists. On the other hand, shutil.copytree() is designed to copy an entire directory tree, including all contained files and directories, to a new destination. It raises an error if the destination directory already exists, enforcing the creation of a fresh directory tree at the specified destination .

Dynamic filename creation during folder compression into a ZIP archive enhances the backup process by ensuring unique and descriptive file names. By incorporating variables like folder names, timestamps, or date stamps into the filename, it avoids overwriting existing archives and facilitates better organization of backup records. This practice aids in quickly identifying backups' content and creation time, streamlining data retrieval and restoration processes .

Pure functions are a core concept of functional programming. They always produce the same output given the same input and do not rely on or modify any external state, leading to predictable behavior. This trait enhances testability and debugging, as well as enables functional optimizations like memoization. An example of a pure function is def square(x): return x * x, which calculates the square of its input without side effects. Pure functions do not modify variables outside their scope, ensuring the integrity and consistency of the program’s state .

In Python, a class is defined using the class keyword, serving as a blueprint for creating objects. The __init__ method is a special function within the class that is automatically called when a new object instantiates from the class, used to initialize the object's attributes. It sets up initial state or values for the object, providing the initial setup context. For instance, class Car includes a constructor Car class Car: def __init__(self, brand): self.brand = brand, where 'brand' is an attribute initialized during object creation .

Using classes over functions in Python is preferred when the problem domain is inherently object-oriented. Classes encapsulate data and behaviors, making them suitable for modeling complex entities and their interactions, as in a simulation of cars where each car is an instance with its attributes and methods for behavior. They facilitate code reuse and structure, essential in extensive applications with interdependent functionalities. If the application demands state maintenance, identity, or relationships among data elements, classes offer a clearer, more modular approach than functions alone, enabling better maintainability and scalability .

In Python, the self identifier is a reference to the current instance of the class and is used to access variables that belong to the class. It is the first parameter of any method in the class, serving as a placeholder to refer to the instance's own attributes and methods. When defining methods, self is used to differentiate between instance attributes and method parameters or local variables, thereby ensuring that each object maintains its unique state and behavior. For example, in a class with an attribute brand, self.brand refers to the attribute specific to the instance upon which the method is called .

To back up a folder into a ZIP file, use Python's zipfile and os modules. Begin by walking through the folder using os.walk() to iterate over its contents recursively. For each file or sub-directory encountered, use ZipFile.write() to add them to the archive. The ZipFile object itself is created by invoking zipfile.ZipFile() in write mode. It is important to make the archive filename dynamic by incorporating elements like the folder name and current date to ensure uniqueness and clarity. This method compresses the entire directory into a ZIP file, facilitating data backup and portability .

The logging module in Python is essential for tracking events during the execution of a program, especially useful in debugging recursive functions like factorial calculations. It supports various logging levels including DEBUG, INFO, etc., which help in identifying the flow and state of the program at each recursion depth. By using logging.basicConfig() to configure the logging details such as level and format, one can capture detailed logs. In the factorial function, each recursive call can log its input, progress, and output at the DEBUG level, which is vital to trace the recursive flow and detect anomalies .

Logging in production environments is beneficial for diagnosing issues, tracking user behavior, and monitoring app performance, which helps in proactive problem-solving and maintenance. Configurable logging levels (e.g., DEBUG, INFO, ERROR) allow developers to manage verbosity and gather useful insights without overwhelming log storage. However, logging can incur performance overhead if not managed properly, as excessive logging can lead to large, unmanageable log files, potentially slowing down the application and cluttering system resources. Strategic logging level choices and log rotation practices mitigate these limitations .

You might also like