22POP13 · Python Programming — Module 4 Study Guide
22POP13 — Python Programming
Module 4 Study Guide
Files, Directories, Compression & Debugging — Repeated Question Bank with Full
Answers
Exam-Ready Study Guide · Exam-Frequency Ranked Notes
Symbol Meaning
■ Repeated 4 Times Asked in 4 or more previous exams — highest priority
■ Repeated 2 Times Asked in 2 previous exams — high priority
■ Very Important Core theory topic, likely to repeat
■ Asked Only Once Appeared once, but conceptually important
Topic-Wise Repetition Overview
# Topic Frequency Priority
1 Assertions Repeated 4 Times Very Important
2 ZIP Files / Folder Backup / Compression Repeated 4 Times Very Important
3 Shutil Module Repeated 4 Times Very Important
4 Logging Module Repeated 2 Times Very Important
5 File Sorting Program Repeated 2 Times Important
(Programming)
6 File Operations: Copy / Move / Delete Asked Once Important
7 DivExp Program (Assertion + Exception) Asked Once Important
(Programming)
8 Debug Control Window Asked Once Important
9 [Link]() vs [Link]() Asked Once Important
Page 1
22POP13 · Python Programming — Module 4 Study Guide
1. Assertions in Python
■ Repeated 4 Times · ■ Very Important — 10 Marks
Q. Explain Assertions with a suitable program.
Previous Exam Question Variants:
• Define assertions. What does an assert statement in python consist of? Give an
example.
• What are Assertions? Write the contents of an assert statement. Explain them with
examples.
• Define assertions. What does an assert statement in python consist of?
• Explain the role of Assertions in Python with a suitable program.
Definition
An assertion is a debugging tool in Python used to check whether a condition is True or
False. It is used to find errors while developing a program. If the condition is True, the
program continues normally. If the condition is False, Python stops the program and
raises an AssertionError. Assertions help programmers detect mistakes early.
Exam-Ready One-Line Definition
An assertion is a sanity check used to verify whether a condition is true. If the condition
is false, Python raises an AssertionError.
Why are Assertions Used?
• Check whether a condition is true.
• Find programming mistakes during development.
• Stop the program immediately if something unexpected happens.
• Make debugging easier.
• Ensure that important assumptions in the program are correct.
• Improve program reliability.
Syntax of the Assert Statement
assert condition, "Error Message"
The assert statement consists of four parts:
Page 2
22POP13 · Python Programming — Module 4 Study Guide
• assert keyword – used to perform the assertion.
• Condition (Expression) – a Boolean expression that becomes True or False.
• Comma ( , ) – separates the condition from the error message.
• Error Message (Optional) – displayed if the condition is False.
Working of Assertions
Case 1: Condition is True — assertion passes, program continues normally, no error
shown.
age = 20
assert age >= 18, "Age must be 18 or above."
print("Eligible to vote")
Output:
Eligible to vote
Case 2: Condition is False — the program stops immediately.
age = 15
assert age >= 18, "Age must be 18 or above."
print("Eligible to vote")
Output:
AssertionError: Age must be 18 or above.
Role of Assertions in Python
• Verify important conditions in a program.
• Detect logical errors quickly.
• Help during debugging.
• Prevent incorrect data from being processed.
• Make the code easier to test.
• Improve the quality and reliability of programs.
Advantages vs Disadvantages
Advantages of Assertions Disadvantages of Assertions
Easy to use. Not meant for handling user input errors.
Helps detect bugs early. Should not replace exception handling.
Page 3
22POP13 · Python Programming — Module 4 Study Guide
Advantages of Assertions Disadvantages of Assertions
Improves code quality. If an assertion fails, the program stops
immediately.
Makes debugging easier. Mainly used during development and
debugging.
Stops execution when unexpected conditions
occur.
Assertion vs Exception Handling
Assertion Exception Handling
Used for debugging Used to handle runtime errors
Raises AssertionError Handles different exceptions like ValueError,
ZeroDivisionError
Checks programmer assumptions Handles unexpected user/program errors
Program stops if assertion fails Program can continue using try-except
Page 4
22POP13 · Python Programming — Module 4 Study Guide
2. ZIP Files – Folder Backup & Compression
■ Repeated 4 Times · ■ Very Important — 10 Marks
Q. Explain compressing/backing up a folder using the zipfile module.
Previous Exam Question Variants:
• What is meant by compressing files? Explain reading, extracting and creating zip files
with code snippet.
• With suitable code, explain Backing up a Folder into a Zip file. Clearly mention the
steps involved.
• Develop a program to back up a given folder (in the current working directory) into a
zip file using relevant modules and methods.
• Explain the process of compressing files with the zipfile module.
What is Compressing Files?
Compressing a file means reducing its size by packing its data more efficiently, so it
takes up less storage space and can be transferred faster. Python provides the built-in
zipfile module to read, extract, and create ZIP archives.
Steps to Back Up a Folder into a ZIP File
• Get the absolute path of the folder to be backed up.
• Create a new ZIP file using [Link]() in write mode.
• Use [Link]() to visit every subfolder and file inside the main folder.
• Add each folder and file into the ZIP archive using write().
• Close the ZIP file to save the changes.
Complete Program – Folder Backup
Page 5
22POP13 · Python Programming — Module 4 Study Guide
import zipfile
import os
def backupToZip(folder):
folder = [Link](folder)
zipName = [Link](folder) + ".zip"
backupZip = [Link](zipName, "w")
for folderName, subFolders, fileNames in [Link](folder):
[Link](folderName)
for fileName in fileNames:
filePath = [Link](folderName, fileName)
[Link](filePath)
[Link]()
print("Backup Completed Successfully.")
backupToZip("MyFolder")
Explanation of the Program
Statement Purpose
[Link]() Gets the full (absolute) folder path.
[Link]() Creates a new ZIP file in write mode.
[Link]() Visits every subfolder and file inside the folder.
write() Adds files and folders into the ZIP file.
close() Saves and closes the ZIP file.
Reading and Extracting ZIP Files
Page 6
22POP13 · Python Programming — Module 4 Study Guide
import zipfile
# Opening and reading a zip file
exampleZip = [Link]("[Link]")
print([Link]()) # List all files in the archive
info = [Link]("[Link]")
print(info.file_size, info.compress_size)
# Extracting all files
[Link]("extracted_folder")
# Extracting a single file
[Link]("[Link]", "extracted_folder")
[Link]()
Advantages of ZIP Files
• Saves storage space.
• Faster file transfer.
• Easy to email.
• Stores many files in one single file.
• Easy backup and recovery.
• Reduces upload/download time.
• Organizes files neatly.
• Supported by almost all operating systems.
Applications of ZIP Files
• Backup of important documents.
• Sharing project files.
• Emailing large files.
• Archiving old data.
• Storing software packages.
• Compressing photos and videos.
Page 7
22POP13 · Python Programming — Module 4 Study Guide
3. Shutil Module
■ Repeated 4 Times · ■ Very Important — 10 Marks
Q. Explain the functions of the shutil module with examples.
Previous Exam Question Variants:
• Explain the functions of shutil module with example.
• How do you copy files and folders using Shutil module? Explain in detail.
• Explain the functions with examples: [Link](), [Link](), [Link]().
What is the Shutil Module?
The shutil (Shell Utilities) module is a built-in Python module used to perform
high-level file and folder operations. It provides simple functions to copy, move,
rename, and delete files and folders, and is more powerful than the os module because
it can handle complete folders in a single function call.
Features of the Shutil Module
• Built-in Python module – no separate installation needed.
• Performs high-level file operations.
• Can copy both files and folders.
• Can move files and folders, renaming them if required.
• Can permanently delete folders.
• Works on Windows, Linux, and macOS.
• Reduces the amount of code needed for file handling.
import shutil
Key Functions of shutil
Function Purpose
[Link](src, dst) Copies a single file to a new location.
[Link](src, dst) Copies an entire folder, including subfolders.
[Link](src, dst) Moves a file or folder to a new location.
[Link](path) Permanently deletes a folder and all its contents.
Page 8
22POP13 · Python Programming — Module 4 Study Guide
(i) [Link]() – Copying a File
import shutil
[Link]("C:\\[Link]", "C:\\Documents")
Copies [Link] into the Documents folder, keeping the original file unchanged. A new
filename can also be given to copy and rename in one step:
[Link]("C:\\[Link]", "C:\\Documents\\[Link]")
(ii) [Link]() – Copying an Entire Folder
import shutil
[Link]("C:\\Project", "C:\\Project_Backup")
Copies the Project folder along with all files and subfolders into a brand-new folder
named Project_Backup. The destination folder must not already exist.
(iii) [Link]() – Moving a File or Folder
import shutil
[Link]("C:\\[Link]", "C:\\Documents")
# Moving and renaming at the same time
[Link]("C:\\[Link]", "C:\\Documents\\[Link]")
# Moving an entire folder
[Link]("C:\\Project", "D:\\Backup")
[Link]() removes the file/folder from its original location and places it at the
destination; it can also rename the item while moving.
(iv) [Link]() – Deleting a Folder with Contents
import shutil
[Link]("OldProject")
Deletes the folder along with all files and subfolders inside it, permanently.
Advantages of the Shutil Module
• Saves programming time and reduces lines of code.
• Copies complete folders including subfolders in one call.
• Useful for backup applications and automation projects.
• Simplifies file management tasks.
Page 9
22POP13 · Python Programming — Module 4 Study Guide
4. Logging Module
■ Repeated 2 Times · ■ Very Important — 10 Marks
Q. Explain the logging module and logging levels.
Previous Exam Question Variants:
• Illustrate the logging levels in python.
• Explain the logging module and debug the factorial of number program.
• Discuss the basicConfig() method to configure the logging with an example.
What is Logging?
Logging is the process of recording the events and activities of a program while it is
running. It helps programmers understand what the program is doing, which part is
currently executing, whether any errors have occurred, and the values of variables at
different stages. Instead of using many print() statements, Python provides the logging
module to display messages in a professional way.
Exam-Ready Definition
The logging module is a built-in Python module used to record events, errors,
warnings, and debugging information while a program is running. It helps programmers
monitor and debug programs easily.
Importing and Configuring Logging
import logging
[Link](
level=[Link],
format='%(asctime)s - %(levelname)s - %(message)s'
)
basicConfig() configures how log messages are displayed – it sets the logging level,
chooses the message format, and can display the date and time of each event.
Logging Levels in Python
Level Function Meaning / Severity
DEBUG [Link]() Detailed information, useful only for diagnosing
problems.
Page 10
22POP13 · Python Programming — Module 4 Study Guide
Level Function Meaning / Severity
INFO [Link]() Confirms that things are working as expected.
WARNING [Link]() Something unexpected happened, but the program
still works.
ERROR [Link]() A serious problem – the program could not perform
a function.
CRITICAL [Link]() A very serious error – the program itself may stop
running.
Debugging the Factorial Program Using Logging
import logging
[Link](
level=[Link],
format='%(asctime)s - %(levelname)s - %(message)s'
)
def factorial(n):
[Link]("Start of factorial(%s)" % n)
total = 1
for i in range(1, n + 1):
total *= i
[Link]("i = %s, total = %s" % (i, total))
[Link]("End of factorial(%s)" % n)
return total
print(factorial(5))
Output (log messages shown along with the result):
2026-01-01 10:00:00,000 - DEBUG - Start of factorial(5)
2026-01-01 10:00:00,001 - DEBUG - i = 1, total = 1
2026-01-01 10:00:00,001 - DEBUG - i = 2, total = 2
2026-01-01 10:00:00,001 - DEBUG - i = 3, total = 6
2026-01-01 10:00:00,001 - DEBUG - i = 4, total = 24
2026-01-01 10:00:00,001 - DEBUG - i = 5, total = 120
2026-01-01 10:00:00,001 - DEBUG - End of factorial(5)
120
Advantages of Logging
• Easy to debug programs.
Page 11
22POP13 · Python Programming — Module 4 Study Guide
• Keeps a record of program execution.
• Helps identify errors quickly.
• Better than using many print() statements.
• Useful for both small and large projects.
• Improves software quality.
Page 12
22POP13 · Python Programming — Module 4 Study Guide
5. File Sorting Program
■ Repeated 2 Times · ■ Important (Programming) — 10 Marks
Q. Develop a program to sort file contents.
Previous Exam Question Variants:
• Develop a program to sort contents of a text file and write the sorted content into a
separate file.
Definition
A File Sorting Program reads the contents of a text file, sorts the data in alphabetical
order, and writes the sorted contents into another text file. This is useful for organizing
data such as names, words, or records.
Algorithm
• Open the source (input) file in read mode.
• Read all the lines using readlines() and store them in a list.
• Sort the list using the sort() method.
• Open a new file in write mode.
• Write the sorted lines using writelines().
• Close both files and display a success message.
Complete Program
Page 13
22POP13 · Python Programming — Module 4 Study Guide
# Open the input file
inputFile = open("[Link]", "r")
# Read all lines
data = [Link]()
# Sort the lines alphabetically
[Link]()
# Open the output file
outputFile = open("[Link]", "w")
# Write sorted data
[Link](data)
# Close the files
[Link]()
[Link]()
print("Contents sorted successfully.")
Sample Input and Output
[Link] [Link]
Orange Apple
Apple Banana
Banana Grapes
Mango Mango
Grapes Orange
Output:
Contents sorted successfully.
Explanation of Key Steps
Statement Purpose
inputFile = open("[Link]", "r") Opens the file in read mode.
data = [Link]() Reads all lines and stores them as a list of strings.
[Link]() Sorts the list of lines alphabetically, in place.
Page 14
22POP13 · Python Programming — Module 4 Study Guide
Statement Purpose
outputFile = open("[Link]", "w") Opens a new file in write mode.
[Link](data) Writes the sorted list into the new file.
[Link]() / [Link]() Closes both files and saves the changes.
Page 15
22POP13 · Python Programming — Module 4 Study Guide
6. File Operations: Copying, Moving & Deleting
■ Asked Only Once but Important — 10 Marks
Q. Explain copying, moving, and deleting files/folders in Python.
Previous Exam Question Variants:
• Explain the following file operations in Python with example: (i) Copying files and
folders (ii) Moving files and folders (iii) Permanently deleting files and folders.
Overview
Python provides modules such as shutil and os to perform file operations. These
operations help us copy, move, rename, and delete files and folders easily.
(i) Copying Files and Folders
Copying means creating another copy of a file or folder at a different location. The
original file or folder remains unchanged, while a new copy is created. Python uses the
shutil module for copying.
import shutil
# Copy a single file
[Link]("C:\\[Link]", "C:\\Documents")
# Copy and rename a file
[Link]("C:\\[Link]", "C:\\Documents\\[Link]")
# Copy an entire folder
[Link]("C:\\Project", "C:\\Project_Backup")
Advantages: keeps original data safe, creates backups, easy to share and organize
files.
(ii) Moving Files and Folders
Moving means transferring a file or folder from one location to another – the file is
removed from the original location and appears only at the new location. Python uses
[Link]().
Page 16
22POP13 · Python Programming — Module 4 Study Guide
import shutil
# Move a file
[Link]("C:\\[Link]", "C:\\Documents")
# Move and rename
[Link]("C:\\[Link]", "C:\\Documents\\[Link]")
# Move an entire folder
[Link]("C:\\Project", "D:\\Backup")
Advantages: organizes files, saves storage space, allows renaming while moving.
(iii) Permanently Deleting Files and Folders
Python provides three main ways to delete:
Function Deletes
[Link](path) Deletes a single file.
[Link](path) Deletes an empty folder (error if not empty).
[Link](path) Deletes a folder along with all its files and subfolders.
import os
import shutil
[Link]("[Link]") # Delete a file
[Link]("OldFolder") # Delete an empty folder
[Link]("OldProject") # Delete a folder with all its contents
Safe Delete Using send2trash
Instead of deleting permanently, the send2trash module moves files to the Recycle Bin
so they can be restored later:
import send2trash
send2trash.send2trash("[Link]")
Copy vs Move vs Delete
Operation Purpose Original File
Copy Creates another copy Remains unchanged
Move Changes file location Removed from old location
Page 17
22POP13 · Python Programming — Module 4 Study Guide
Operation Purpose Original File
Delete Removes the file/folder Permanently removed
Page 18
22POP13 · Python Programming — Module 4 Study Guide
7. DivExp Program – Assertion + Exception Handling
■ Asked Only Once but Important — Programming Question
Q. Develop the DivExp program using assertion and exception handling.
Previous Exam Question Variants:
• Develop a program with a function named DivExp which takes two parameters a, b
and returns a value c (c = a / b). Write a suitable assertion for a > 0 inside DivExp,
and raise an exception when b = 0. Develop a program that reads two values from the
console and calls DivExp.
Approach
• Use assert a > 0 to check the assumption that 'a' must be positive.
• Use an if statement to raise ZeroDivisionError explicitly when b = 0.
• Wrap the function call in a try-except block to handle both AssertionError and
ZeroDivisionError.
Complete Program
def DivExp(a, b):
# Assertion: a must be greater than 0
assert a > 0, "Value of 'a' must be greater than 0"
# Exception: b must not be zero
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed")
c = a / b
return c
# Main Program
try:
a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
result = DivExp(a, b)
print("Result =", result)
except AssertionError as e:
print(e)
except ZeroDivisionError as e:
print(e)
Sample Outputs
Page 19
22POP13 · Python Programming — Module 4 Study Guide
Output 1 – Normal Execution:
Enter value of a: 20
Enter value of b: 4
Result = 5.0
Output 2 – Assertion Error (a is negative):
Enter value of a: -5
Enter value of b: 2
Value of 'a' must be greater than 0
Output 3 – Division by Zero:
Enter value of a: 10
Enter value of b: 0
Division by zero is not allowed
Page 20
22POP13 · Python Programming — Module 4 Study Guide
8. Debug Control Window
■ Asked Only Once but Important — 10 Marks
Q. Explain the Debug Control Window.
Previous Exam Question Variants:
• Explain about the Debug Control Window.
What is Debugging?
Debugging is the process of finding and fixing errors (bugs) in a program. Python IDLE
provides a Debugger that helps programmers execute the program one line at a time,
making it easier to understand how the program works and to identify errors.
Exam-Ready Definition
The Debug Control Window is a feature of Python IDLE that allows a program to be
executed one line at a time. It helps programmers find errors by showing the current
line of execution and the values of variables.
How to Open the Debug Control Window
• Open Python IDLE.
• Click on Debug in the menu.
• Select Debugger.
• Run the program – the Debug Control Window will appear.
Components of the Debug Control Window
Component Displays
Stack The list of active function calls – helps track function execution.
Source The source code, highlighting the current line being executed.
Locals All local variables and their current values, updated automatically.
Globals All global variables, including Python's built-in globals.
Buttons in the Debug Control Window
Page 21
22POP13 · Python Programming — Module 4 Study Guide
Button Function
Go Runs the program continuously until it finishes or a breakpoint is reached.
Step Executes one line at a time, entering functions when they are called.
Over Executes one line at a time, but does not enter functions (runs them fully).
Quit Stops debugging immediately and closes the debugger.
Step vs Over
Step Over
Executes one line at a time Executes one line at a time
Enters the function Does not enter the function
Useful for debugging function code Useful when function already works correctly
Shows every statement inside the function Executes the function completely at once
Example – Debugging Walkthrough
print("Enter first number:")
a = int(input())
print("Enter second number:")
b = int(input())
print("Sum =", a + b)
Suppose the user enters 10 and 20. The debugger executes and displays variable
values step by step:
Step Statement Executed Locals After Step
1 print("Enter first number:") –
2 a = int(input()) → user enters 10 a = 10
3 print("Enter second number:") a = 10
4 b = int(input()) → user enters 20 a = 10, b = 20
5 print("Sum =", a + b) → Output: Sum = 30 a = 10, b = 20
Advantages of the Debug Control Window
Page 22
22POP13 · Python Programming — Module 4 Study Guide
• Finds errors quickly.
• Executes one line at a time.
• Displays local and global variables.
• Helps understand program flow.
• Saves programming time.
• Useful for beginners to learn program execution.
Page 23
22POP13 · Python Programming — Module 4 Study Guide
9. [Link]() vs [Link]()
■ Asked Only Once but Important
Q. Differentiate [Link]() and [Link]().
Previous Exam Question Variants:
• List out the difference between [Link]() and [Link]().
Basis [Link]() [Link]()
Definition Copies a single file from one Copies an entire folder along with all
location to another. files and subfolders.
Purpose Used to copy only one file. Used to copy a complete directory
(folder).
Source Source must be a file. Source must be a folder (directory).
Destination Can be a folder or a new filename. Must be a new folder that does not
already exist.
Copies No – cannot copy subfolders. Yes – copies all subfolders
Subfolders automatically.
Syntax [Link](source, destination) [Link](source, destination)
Speed Faster – only one file is copied. Slower – many files/folders may be
copied.
Applications Copying documents, images, text Creating project backups or copying
files, etc. complete folders.
Example – [Link]()
import shutil
[Link]("C:\\[Link]", "C:\\Documents")
# Copies [Link] to the Documents folder; original file remains unchanged.
Example – [Link]()
import shutil
[Link]("C:\\Project", "C:\\Project_Backup")
# Copies the entire Project folder, including all files and subfolders,
# into a new folder named Project_Backup.
Page 24
22POP13 · Python Programming — Module 4 Study Guide
End of Module 4 – Files, Directories, Compression & Debugging. Revise the ■
4-times-repeated topics (Assertions, ZIP/Backup, Shutil Module) first, followed by
Logging and the programming questions.
Page 25