0% found this document useful (0 votes)
43 views23 pages

Chapter - 1 Organizing Files:: Shutil

The document provides an introduction to the shutil module in Python, detailing its functions for organizing files and folders, such as copying, moving, and deleting files. It also covers safe deletion practices using the send2trash module and introduces the os.walk() function for traversing directory trees. Additionally, it explains how to work with ZIP files using the zipfile module for reading, extracting, and creating compressed archives.

Uploaded by

srkeelambi
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)
43 views23 pages

Chapter - 1 Organizing Files:: Shutil

The document provides an introduction to the shutil module in Python, detailing its functions for organizing files and folders, such as copying, moving, and deleting files. It also covers safe deletion practices using the send2trash module and introduces the os.walk() function for traversing directory trees. Additionally, it explains how to work with ZIP files using the zipfile module for reading, extracting, and creating compressed archives.

Uploaded by

srkeelambi
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/ 23

INTRODUCTION TO PYTHON PROGRAMMING

MODULE 4
Chapter – 1 Organizing Files:
The shutil Module

The shutil (short for shell utilities) module in Python helps you work with files and folders. You can use it
to copy, move, rename, and delete files and folders.

Functions in shutil

1. Copying Files

 Function: shutil.copy(source, destination)


Copies a file from one location (source) to another (destination).

 Example:
import shutil
shutil.copy('C:/example.txt', 'C:/backup_folder')
# Copies file to the folder
shutil.copy('C:/example.txt', 'C:/backup_folder/example_copy.txt')
# Copies and renames it

2. Copying Entire Folders

 Function: shutil.copytree(source, destination)


Copies an entire folder and everything inside it.

 Example:
shutil.copytree('C:/projects', 'C:/backup_projects')
# Creates a backup of the projects folder
3. Moving and Renaming Files

 Function: shutil.move(source, destination)


Moves a file or folder from one location to another. Can also rename files.

 Examples:
o Moving a file:
shutil.move('C:/example.txt', 'C:/new_folder')
# Moves example.txt to new_folder
o Moving and renaming a file:
shutil.move('C:/example.txt', 'C:/new_folder/renamed_example.txt')
# Moves and renames it
o Renaming a file (no folder):
shutil.move('C:/example.txt', 'C:/new_name.txt') # Renames the file

4. Important Notes on move()

 If you move a file to a folder that already has a file with the same name, it overwrites the existing
file. Be careful!
 If the destination folder doesn't exist, Python throws an error:
shutil.move('C:/example.txt', 'C:/nonexistent_folder/new_example.txt')
# FileNotFoundError: [Errno 2] No such file or directory

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 1


INTRODUCTION TO PYTHON PROGRAMMING

1. Double-check paths before copying or moving to avoid overwriting files.


2. Test your code with print statements before running it, so you know what files will be affected.
3. Use os.makedirs() to create missing folders if needed.

Example Program: Backing Up Files


import shutil
from pathlib import Path

# Paths
source = Path.home() / 'example.txt' # Your home directory + example.txt
destination_folder = Path.home() / 'backup_folder'

# Create backup folder if it doesn't exist


destination_folder.mkdir(exist_ok=True)

# Copy the file to the backup folder


shutil.copy(source, destination_folder / source.name)
print(f"File {source.name} copied to {destination_folder}")

Example and simplified answeres :

1. shutil.copy(): Copies a file from the source to the destination.


Ex:
import shutil
shutil.copy("source.txt", "destination.txt")
# Copies source.txt to destination.txt

2. shutil.copytree(): Recursively copies an entire directory tree.


shutil.copytree("source_folder", "destination_folder")
# Copies all contents of source_folder

Ex:
import shutil
# Create a directory tree copy
shutil.copytree('C:\\Users\\user\\s', 'C:\\Users\\user\\m')
print("Directory tree copied.")

3. shutil.move(): Moves a file or directory to a new location.


shutil.move("source.txt", "new_folder/")
# Moves source.txt to new_folder

EX:
import shutil
import os

# Create a sample file


with open("source.txt", "w") as file:
file.write("This is a sample file to demonstrate shutil.move().")

# Ensure the destination folder exists


destination_folder = "new_folder"
os.makedirs(destination_folder, exist_ok=True)

# Move the file to the new folder


shutil.move("source.txt", destination_folder)

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 2


INTRODUCTION TO PYTHON PROGRAMMING

Print ("File moved successfully!")


4. shutil.rmtree(): Deletes a directory and its contents.
shutil.rmtree("folder_to_delete")
# Deletes the specified folder

5. shutil.disk_usage(): Provides information about disk space.


usage = shutil.disk_usage("/")
print(f"Total: {usage.total}, Used: {usage.used}, Free: {usage.free}")

Example :
import shutil
usage = shutil.disk_usage("C:\\Users\\user")
print(f"Total: {usage.total}, Used: {usage.used}, Free: {usage.free}")

6. shutil.make_archive(): Creates a compressed archive of a directory.


shutil.make_archive("archive_name", "zip", "folder_to_compress")
# Creates a ZIP archive
Example
Import shutil
shutil.make_archive("janaki", "zip", "F:\\1st sem ia qp - Copy")

7. shutil.unpack_archive(): Extracts a compressed archive.


shutil.unpack_archive("archive_name.zip", "output_folder")
# Unpacks archive

8. shutil.copy2(src, dst)
Similar to shutil.copy, but preserves metadata like timestamps.

Example:
import shutil

# Copy a file with metadata


shutil.copy2('file.txt', 'backup_with_metadata.txt')
print("File copied with metadata.")

Permanently Deleting Files and Folders


Deleting Files and Folders in Python

Python provides multiple ways to delete files and folders. Here’s an overview of the options:

1. Using the os Module

 To delete a file: os.unlink(path)


 To delete an empty folder: os.rmdir(path)

Examples:

import os
os.unlink('example.txt') # Deletes the file
os.rmdir('empty_folder') # Deletes the empty folder

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 3


INTRODUCTION TO PYTHON PROGRAMMING

2. Using the shutil Module

 To delete a folder and all its contents: shutil.rmtree(path)

Example:

import shutil
shutil.rmtree('folder_with_contents') #Deletes the folder and all its files/subfolders

These functions perform permanent deletion. Double-check paths before using them to avoid accidental
data loss.

3. Preventing Accidental Deletes

To avoid unintended deletion, comment out the delete function and use print() to confirm the files or
folders before running the actual delete operation.

Example:

from pathlib import Path


import os

# Check files to delete


for filename in Path.home().glob('*.txt'):
print(filename) # Show files that would be deleted

# Uncomment this line after verifying


# os.unlink(filename)

4. Safe Deletes with the send2trash Module

The send2trash module sends files and folders to the recycle bin instead of permanently deleting them.
This allows for recovery if needed.

import send2trash

# Create a file and send it to the recycle bin


with open('example.txt', 'w') as file:
file.write('This file will be deleted.')

send2trash.send2trash('example.txt') # Safely moves the file to the recycle bin

Advantages:
 Safer than os or shutil functions.
 Files can be recovered from the recycle bin if deleted by mistake.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 4


INTRODUCTION TO PYTHON PROGRAMMING

Difference Between Permanent Delete and Safe Delete

Aspect Permanent Delete Safe Delete


Definition Files or folders are irrevocably removed Files or folders are moved to the Recycle
from the system. Bin/Trash for recovery.
Modules Used os and shutil send2trash
Recovery Cannot be recovered unless you have a Can be restored from the Recycle Bin/Trash.
backup.
Purpose Used when freeing up disk space is Used during development to avoid accidental
necessary. data loss.
Disk Space Yes No, as the file is stored in the Trash.
Freed
Risk High risk of accidental deletion. Low risk, as files can be recovered.

 Use send2trash for safe deletions during development.


 Use os or shutil for freeing disk space or when permanent deletion is necessary.
 Always verify file paths before running deletion commands.

 Permanent Delete: When disk space is limited, or you are confident about the deletion.
 Safe Delete: During development or when there’s a risk of deleting important files by mistake.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 5


INTRODUCTION TO PYTHON PROGRAMMING

WALKING A DIRECTORY TREE


The os.walk() function in Python is a powerful tool from the os module that allows you to traverse a directory
tree. A directory tree consists of a parent directory (folder) and its subdirectories and files. By using os.walk(),
you can automatically navigate through all folders and subfolders in a directory and perform operations on each file
or folder encountered.

Features of os.walk() (in List Form)

1 Input

 Takes one argument — the root directory path.


Example: os.walk("C:\\delicious")

2 Returns
For each folder it walks through, it returns three values:

 folderName: The path of the current folder.


 subfolders: A list of all subfolder names in the current folder.
 filenames: A list of all filenames in the current folder.

3 Usage

 Typically used in a for loop to recursively traverse all folders, subfolders, and files in a directory
tree.
Example:

Example Program

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 6


INTRODUCTION TO PYTHON PROGRAMMING

Folder structure :

Figure 10-1: An example folder that contains three folders and four files

Output;

The current folder is C:\delicious


SUBFOLDER OF C:\delicious: cats
SUBFOLDER OF C:\delicious: walnut
FILE INSIDE C:\delicious: spam.txt

The current folder is C:\delicious\cats


FILE INSIDE C:\delicious\cats: catnames.txt
FILE INSIDE C:\delicious\cats: zophie.jpg

The current folder is C:\delicious\walnut


SUBFOLDER OF C:\delicious\walnut: waffles

The current folder is C:\delicious\walnut\waffles


FILE INSIDE C:\delicious\walnut\waffles: butter.txt.

Applications of os.walk()

1. Renaming Files: Modify filenames in a directory tree.


2. File Organization: Move files into appropriate subfolders.
3. File Search: Search for specific files based on name or extension.
4. Batch Operations: Perform operations like compression, copying, or deletion.

This makes os.walk() a versatile tool for handling directory-related tasks efficiently.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 7


INTRODUCTION TO PYTHON PROGRAMMING

COMPRESSING FILES WITH THE ZIPFILE MODULE


You may be familiar with ZIP files (with the .zip file extension), which can hold the compressed contents of many
other files. Compressing a file reduces its size, which is useful when transferring it over the internet. And since a
“ZIP file can also contain multiple files and subfolders, it’s a handy way to package several files into one. This single
file, called an archive file, can then be, say, attached to an email.’
Your Python programs can create and open (or extract) ZIP files using functions in the zipfile module. Say you
have a ZIP file named example.zip that has the contents shown in Figure 10-2.

Figure 10-2: The contents of example.zip

Reading ZIP Files


To read the contents of a ZIP file, first you must create a ZipFile object (note the capital
letters Z and F). ZipFile objects are conceptually similar to the File objects you saw returned by
the open() function.
To create a ZipFile object, call the zipfile.ZipFile() function, passing it a string of the .ZIP file’s filename.
Note that zipfile is the name of the Python module, and ZipFile() is the name of the function.
For example, enter the following into the interactive shell:

>>> import zipfile, os # Importing the zipfile and os modules to work with ZIP files and file
paths

>>> from pathlib import Path # Importing Path from pathlib to handle file paths
>>> p = Path.home() # Getting the home directory path
>>> exampleZip = zipfile.ZipFile(p/'example.zip') # Opening the ZIP file located in the home
directory

>>> exampleZip.namelist() # Listing all files and directories inside the ZIP file
['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']

>>> spamInfo = exampleZip.getinfo('spam.txt') # Getting information about the 'spam.txt' file


in the ZIP
>>> spamInfo.file_size # Displaying the original size of 'spam.txt' before compression
13908

>>> spamInfo.compress_size # Displaying the compressed size of 'spam.txt' inside the ZIP
3828

➊ >>> f'Compressed file is {round(spamInfo.file_size / spamInfo.compress_size, 2)}x smaller!'


# Calculating how many times smaller the compressed file is compared to its original size
'Compressed file is 3.63x smaller!'

>>> exampleZip.close() # Closing the ZIP file to free up resources

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 8


INTRODUCTION TO PYTHON PROGRAMMING

A ZipFile object has a namelist() method that returns a list of strings for all the files and folders contained in
the ZIP file. These strings can be passed to the getinfo() ZipFile method to return a ZipInfo object about that
particular file. ZipInfo objects have their own attributes, such as file_size and compress_size in bytes, which hold
integers of the original file size and compressed file size, respectively. While a ZipFile object represents an entire
archive file, a ZipInfo object holds useful information about a single file in the archive.
The command at ➊ calculates how efficiently example.zip is compressed by dividing the original file size by the
compressed file size and prints this information.

Extracting from ZIP Files


The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current
working directory.

>>> import zipfile, os


>>> from pathlib import Path
>>> p = Path.home()
>>> exampleZip = zipfile.ZipFile(p / 'example.zip')
➊ >>> exampleZip.extractall()
>>> exampleZip.close()

After running this code, the contents of example.zip will be extracted to C:\. Optionally, you can pass a folder
name to extractall() to have it extract the files into a folder other than the current working directory. If the folder
passed to the extractall() method does not exist, it will be created. For instance, if you replaced the call
at ➊ with exampleZip.extractall('C:\\delicious'), the code would extract the files from example.zip into a
newly created C:\delicious folder.
The extract() method for ZipFile objects will extract a single file from the ZIP file. Continue the interactive
shell example:

>>> exampleZip.extract('spam.txt')
'C:\\spam.txt'
>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')
'C:\\some\\new\\folders\\spam.txt'
>>> exampleZip.close()

The string you pass to extract() must match one of the strings in the list returned by namelist(). Optionally,
you can pass a second argument to extract() to extract the file into a folder other than the current working directory.
If this second argument is a folder that doesn’t yet exist, Python will create the folder. The value
that extract() returns is the absolute path to which the file was extracted.

Creating and Adding to ZIP Files


To create your own compressed ZIP files, you must open the ZipFile object in write mode by passing 'w' as the
second argument. (This is similar to opening a text file in write mode by passing 'w' to the open() function.)
When you pass a path to the write() method of a ZipFile object, Python will compress the file at that path and
add it into the ZIP file. The write() method’s first argument is a string of the filename to add. The second argument
is the compression type parameter, which tells the computer what algorithm it should use to compress the files; you
can always just set this value to zipfile.ZIP_DEFLATED. (This specifies the deflate compression algorithm, which
works well on all types of data.) Enter the following into the interactive shell:

>>> import zipfile


>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 9


INTRODUCTION TO PYTHON PROGRAMMING

This code will create a new ZIP file named new.zip that has the compressed contents of spam.txt.
Keep in mind that, just as with writing to files, write mode will erase all existing contents of a ZIP file. If you want
to simply add files to an existing ZIP file, pass 'a' as the second argument to zipfile.ZipFile() to open the ZIP
file in append mode.

I. PROJECT: RENAMING FILES WITH AMERICAN-STYLE DATES TO


EUROPEAN-STYLE DATES
Say your boss emails you thousands of files with American-style dates (MM-DD-YYYY) in their names and needs
them renamed to European-style dates (DD-MM-YYYY). This boring task could take all day to do by hand! Let’s
write a program to do it instead.
Here’s what the program does:
1. It searches all the filenames in the current working directory for American-style dates.
2. When one is found, it renames the file with the month and day swapped to make it European-style.
This means the code will need to do the following:
1. Create a regex that can identify the text pattern of American-style dates.
2. Call os.listdir() to find all the files in the working directory.
3. Loop over each filename, using the regex to check whether it has a date.
4. If it has a date, rename the file with shutil.move().
For this project, open a new file editor window and save your code as renameDates.py.

Steps to Rename Files with American-Style Dates to European-Style Dates:

1. Import Required Modules:


Use the os, shutil, and re modules for file handling, renaming, and pattern matching.
2. Create a Regex for American-Style Dates:
Write a regular expression to match filenames containing dates in the MM-DD-YYYY format.
3. List All Files in the Current Directory:
Use os.listdir('.') to retrieve all filenames in the current working directory.
4. Search for Dates in Filenames:
Loop through each file, and use the regex to check if the filename contains a date.
5. Skip Files Without Dates:
If a file does not match the date pattern, move to the next file using continue.
6. Extract Date Components:
For filenames with dates, use regex groups to extract:
o Text before the date.
o Month, day, and year parts.
o Text after the date.
7. Form the New Filename:
Rearrange the extracted parts to create a new filename in the DD-MM-YYYY format.
8. Generate Absolute Paths:
Convert filenames to absolute paths using os.path.abspath().
9. Rename the File:
Use shutil.move() to rename the file with the new filename.
10. Verify Before Renaming:
Initially, print the old and new filenames for confirmation. Uncomment the renaming code to apply
changes.

# renameDates.py - Renames filenames with American MM-DD-YYYY date format to European DD-MM-YYYY.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 10


INTRODUCTION TO PYTHON PROGRAMMING

PROGRAM

II. Backing Up a Folder into a ZIP File

Step 1: Figuring Out the ZIP File’s Name

 Goal: Each backup ZIP file needs a unique name.


 If the folder is backed up into AlsPythonBook_1.zip, the next backup should go into
AlsPythonBook_2.zip, and so on.
 How it's done: The program checks if AlsPythonBook_1.zip exists. If it does, it checks for
AlsPythonBook_2.zip, then AlsPythonBook_3.zip, etc., until it finds an available filename.

Step 2: Creating the ZIP File

 Goal: Create a ZIP file using the correct, unique filename.


 How it's done: After determining the available ZIP file name (e.g., AlsPythonBook_1.zip), the
program uses zipfile.ZipFile to create the ZIP file in write mode ('w').

Step 3: Walking the Directory Tree and Adding Files

 Goal: Add the folder and all its files (except for other ZIP files) to the newly created ZIP file.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 11


INTRODUCTION TO PYTHON PROGRAMMING

 How it's done: The program uses os.walk() to traverse the entire directory tree. It adds the current
folder and all files to the ZIP file. Files that are already ZIP files (such as previous backups) are
skipped.

Program

Explanation :

1. os.path.abspath(folder): Ensures the folder path is absolute, making it easier to work with
regardless of the current working directory.
2. zipfile.ZipFile(zipFilename, 'w'): This creates the ZIP file, opening it in write mode ('w'). If
the file already exists, it will be overwritten.
3. os.walk(folder): This function walks through the directory tree, starting from the given folder. It
returns three variables for each directory it visits:
 foldername: The current directory's path.
 subfolders: A list of subfolders in the current directory (not used here).
 filenames: A list of files in the current directory.
4. backupZip.write(): Adds a folder or file to the ZIP file.
5. Skipping Backup ZIP Files: The program skips any files that are already ZIP backups by checking
if the filename ends with .zip.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 12


INTRODUCTION TO PYTHON PROGRAMMING

1. The program first checks if a ZIP file with the desired name already exists by appending a number to
the folder's base name (e.g., AlsPythonBook_1.zip, AlsPythonBook_2.zip, etc.). It increments the
number until it finds a name that doesn’t exist.
2. It then creates the ZIP file using zipfile.ZipFile in write mode.
3. The program uses os.walk() to go through every folder and file in the specified directory and its
subdirectories. Each folder and file is added to the ZIP file, except for any existing ZIP backups.
4. After all files and folders are added, the ZIP file is closed, and the program prints "Done." to indicate
the backup is complete.

Output Example:

If you run the program with the folder C:\delicious, the output will look like this:
Creating delicious_1.zip...
Adding files in C:\delicious...
Adding files in C:\delicious\cats...
Adding files in C:\delicious\waffles...
Adding files in C:\delicious\walnut...
Done.

The next time you run the program, it will create delicious_2.zip and so on.

This program automates the backup of a folder by creating a ZIP file with a unique, incrementing name each
time it's run. It ensures that no previous backups are overwritten and efficiently handles the task of backing
up all files and subfolders.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 13


INTRODUCTION TO PYTHON PROGRAMMING

Chapter – 2

Debugging
Raising Exceptions,
In Python, exceptions are used to handle errors that arise during the execution of a program. However, you
can also raise your own exceptions when you want to enforce specific conditions or handle unexpected
situations. Raising an exception is a way of stopping the execution of the current function and transferring
the control to the nearest exception handler (the except block).

Syntax of Raising Exceptions:

To raise an exception in Python, you use the raise keyword, followed by an instance of the Exception
class, optionally passing an error message.

Syntax:

raise Exception(‘Wrong password. Try again or click ‘Forgot password’ to reset it. ')

When an exception is raised and it is not handled within the same block of code (via a try and
except statement), Python will terminate the program and display the exception's error message.

Example code;

OUTPUT

Getting the Traceback as a String


Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 14
INTRODUCTION TO PYTHON PROGRAMMING

What is a Traceback?

 When Python encounters an error, it generates a traceback, which is a detailed error report.
 A traceback includes:
o Error message: Description of the error.
o Line number: Indicates where the error occurred.
o Call stack: The sequence of function calls leading to the error.
 The call stack is helpful for debugging, especially when functions are called from multiple places.

Example of Traceback:

OUTPUT

Explanation of the Traceback:

1. Error Message:
The last line of the traceback shows the type of error and a brief description:
ZeroDivisionError: division by zero.
2. Line Number:
The traceback points out the exact lines where the error occurred:
o Line 2 in the divide_numbers function: return a / b.
o Line 9 in the calculate function: result = divide_numbers(num1, num2).
o Line 12 in the main script: calculate().

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 15


INTRODUCTION TO PYTHON PROGRAMMING

3. Call Stack:
The sequence of function calls leading to the error is shown step-by-step:
o The program started by calling calculate().
o Inside calculate, the function divide_numbers was called.
o Inside divide_numbers, the error occurred when trying to divide by zero.

This traceback is extremely useful for pinpointing where and why the error happened, making debugging
easier.

Using traceback.format_exc():

 Python automatically displays the traceback if an exception isn’t handled.


 However, you can capture the traceback programmatically using the traceback module.
 traceback.format_exc() returns the traceback as a string, which can be written to a file for later
debugging.

I. A traceback helps identify where an error occurred and the sequence of calls leading to it.
II. Use traceback.format_exc() to capture traceback details as a string.
III. Writing traceback to a file is a good debugging practice, ensuring the program doesn’t crash
unexpectedly.

ASSERTION

What is an Assertion?

An assertion is a "sanity check" used during programming to ensure everything is working as expected.

It helps developers confirm the correctness of their code.

If an assertion condition fails, the program stops immediately and raises an AssertionError.

Why use Assertions?

To ensure your code behaves correctly.

Example: "In traffic lights, at least one direction must have a red light" — you can use an assertion to
confirm this.

Syntax of Assertion:

assert condition, "Error message if condition is False"

a. Condition: A logical expression. If it evaluates to True, nothing happens.


b. Error Message: If False, the program stops and shows this message.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 16


INTRODUCTION TO PYTHON PROGRAMMING

Simple Example 1: Comparing Two Numbers

Explanation:

 The assertion checks if x < y (is x smaller than y?).


 If True, the program runs smoothly.
 If False, the program stops and shows:

AssertionError: x is not less than y

Relatable Example 2: Checking Students' Marks


marks = [35, 45, 50, 70]

# Assertion: Marks should not be less than 35


for mark in marks:
assert mark >= 35, f"Mark {mark} is below pass marks!"

print("All students passed!")

Explanation:

 The assertion checks each mark.


 If any mark is below 35, the program stops with an error like:

AssertionError: Mark 20 is below pass marks!

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 17


INTRODUCTION TO PYTHON PROGRAMMING

Traffic Light Simulation Example

Problem Statement:

 In a traffic light simulation, at least one light (either north-south or east-west) must always be red to
prevent accidents.

def switch_lights(lights):
for key in lights.keys():
if lights[key] == "green":
lights[key] = "yellow"
elif lights[key] == "yellow":
lights[key] = "red"
elif lights[key] == "red":
lights[key] = "green"

# Assertion: At least one light should be red


assert "red" in lights.values(), "Danger! Both lights are green!"

# Example
traffic_lights = {
"north-south": "green",
"east-west": "red"
}

print("Before switching:", traffic_lights)


switch_lights(traffic_lights)
print("After switching:", traffic_lights)

Explanation:

 The assertion checks if at least one light is red.


 If the condition is True, the program continues.
 If the condition is False, the program stops and raises an error:

AssertionError: Danger! Both lights are green!

Points TO REMEMBER

1. Purpose of Assertions:
o Assertions are used to detect programmer errors, not user errors.
o They ensure assumptions in your code are correct during development.
2. When to Use Assertions:
o During development to catch bugs early.
o To verify assumptions, e.g., function inputs/outputs.
3. Not for Production:
o Assertions can be disabled in production using the -O flag.
4. Limitations:
o Assertions are not a replacement for testing. Comprehensive testing is still necessary.
o Assertions only check specific conditions you define.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 18


INTRODUCTION TO PYTHON PROGRAMMING

Logging;
Explanation of Logging in Python

Logging is a critical aspect of software development, especially for debugging and monitoring the execution
of your program. It helps you track events in the program, gather information about its flow, and understand
the program's state at various points during execution. Here's an overview of the key concepts and best
practices associated with logging in Python:

What is Logging?

Logging allows developers to keep track of the execution of their program by recording events, errors, and
general information with custom messages. It helps monitor and debug code by providing insights into what
happened during the program's execution, and it can be saved for later analysis.

The key benefits of logging include:

1. Tracking Program Flow: Logging provides a trail of events showing how your program progresses
through different stages.
2. Recording Variable States: By logging variable values, you can understand the state of your
program at any given point.
3. Easier Debugging: Instead of using print statements (which require manual cleanup), logging leaves
a persistent trail of messages that can help you debug issues.

Using the Logging Module

Python provides a built-in logging module, which simplifies the process of logging messages. The steps for
setting it up are as follows:

1. Basic Setup

You start by importing the logging module and configuring it to log messages:

import logging

logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')

 level: Specifies the lowest severity level of messages you want to log. Common levels include:

 DEBUG: Detailed logs meant for debugging.


 INFO: General program events, like program start and stop.
 WARNING: Potential issues that don’t stop the program.
 ERROR: Issues that cause failures or exceptions.
 CRITICAL: Fatal errors that cause the program to stop.

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 19


INTRODUCTION TO PYTHON PROGRAMMING

Example of Logging:
import logging

logging.basicConfig(level=logging.DEBUG)
logging.debug('This is a debug message.')
logging.info('This is an info message.')
logging.warning('This is a warning message.')
logging.error('This is an error message.')
logging.critical('This is a critical message.')

Why Use Logging?

1. Better Debugging: It’s easier to track issues and fix them.


2. Avoid Clutter: Unlike print(), logging keeps your code clean and organized.
3. Persistent Logs: Logs can be saved to files for future reference.

Best Practices:

 Use logging instead of print() for debugging.


 You can log to a file like this:

logging.basicConfig(filename='app.log', level=logging.DEBUG)

 In production, disable logging for less important messages:

logging.disable(logging.CRITICAL)

EXPLAIN THE SUPPORT FOR LOGGING USING LOGING MODULE IN PYTHON

Support for Logging with the logging Module in Python

The logging module in Python provides a flexible framework for logging messages from a program, which
helps in tracking its execution and debugging. It is a built-in module and offers several features for efficient
logging.

Features & Support provided by logging Module:

1. Different Logging Levels: The logging module supports different log levels, which allow you to
control the verbosity of the logs based on their importance. These levels are:
 DEBUG: Provides detailed information for troubleshooting.
 INFO: For general information about the program's progress.
 WARNING: For potential issues or warnings.
 ERROR: For serious problems that affect the program's operation.
 CRITICAL: For fatal errors that cause the program to stop.

Example Code to Show Logging Features:


import logging

# Basic configuration with format and log level


logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s -
%(levelname)s - %(message)s')

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 20


INTRODUCTION TO PYTHON PROGRAMMING

# Logging at different levels


logging.debug('This is a debug message')
logging.info('Program started')
logging.warning('This is a warning message')
logging.error('An error occurred')
logging.critical('Critical error!')

# Logging an exception
try:
1 / 0
except ZeroDivisionError:
logging.exception("Error occurred during division")

Output in the app.log file:

2025-01-06 12:00:00,123 - DEBUG - This is a debug message


2025-01-06 12:00:01,124 - INFO - Program started
2025-01-06 12:00:02,125 - WARNING - This is a warning message
2025-01-06 12:00:03,126 - ERROR - An error occurred
2025-01-06 12:00:04,127 - CRITICAL - Critical error!
2025-01-06 12:00:05,128 - ERROR - Error occurred during division

The logging module provides robust support for tracking events, debugging, and managing logs in Python
programs. It offers multiple levels of logging, configurable handlers, exception tracking, and the ability to
control the output location. This makes it a powerful tool for maintaining large-scale applications and
ensuring smooth program execution.

Debugging in IDLE: Understanding the Debugger

IDLE, the Integrated Development and Learning Environment, comes with a built-in debugger that allows
you to step through your Python program line by line. This tool is particularly helpful for identifying and
fixing bugs by closely monitoring variable values and program execution flow.

Features of IDLE’s Debugger:

1. Breakpoints
o A breakpoint is a marker on a specific line of code where the debugger will pause execution.
o In IDLE, breakpoints can be set by right-clicking on the desired line number in the code
editor and selecting “Set Breakpoint” or using the “Breakpoint” menu option.
o Execution pauses at the breakpoint, allowing you to examine the program state before the line
is executed.
2. Stepping Through Code
o Step: Executes the current line and pauses at the next line. If the current line calls a function,
the debugger steps into that function.
o Over: Executes the current line but skips stepping into any called functions, pausing at the
next line after the function call.
o Out: If inside a function, this steps out and continues execution until the calling function
resumes.
3. Continuing Execution
o Once paused, clicking the Continue button resumes normal execution until the next
breakpoint or program termination.
4. Inspecting Variables

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 21


INTRODUCTION TO PYTHON PROGRAMMING

oWhile paused, you can view and inspect variables in the current scope using the “Debug
Control” window. It displays the variable names and their current values.
5. Stopping Debugging
o To terminate the program and exit debugging mode, use the Quit button in the Debug
Control window.

How to Use IDLE’s Debugger

1. Start Debugging
o Open your Python script in IDLE.
o Click Debug > Debugger to enable the Debug Control panel.
o Start the program using Run > Run Module (F5). The Debugger will now control execution.
2. Set Breakpoints
o Right-click the desired line number in the editor and select Set Breakpoint.
o Alternatively, use Debug > Set Breakpoint.
3. Run and Pause
o Run the program. Execution pauses at the first breakpoint or the beginning of the program if
no breakpoints are set.
4. Step Through Code
o Use the buttons in the Debug Control panel:
 Step to step into code.
 Over to skip stepping into function calls.
 Out to exit the current function.
5. Inspect and Modify Variables
o Check variable values in the Debug Control panel.
o Modify variable values if needed to test scenarios dynamically.
6. Continue or Quit
o Use Continue to proceed with the execution.
o Use Quit to stop debugging.

Example: Debugging a Buggy Addition Program

Steps:

1. Set a breakpoint on the print('The sum is ...') line.


2. Run the program. Enter values like 5, 3, and 42 when prompted.
3. When paused at the breakpoint, inspect the first, second, and third variables in the Debug
Control panel. Notice they are strings, not integers.
4. Modify the code to convert inputs to integers:

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 22


INTRODUCTION TO PYTHON PROGRAMMING

Debugging in IDLE provides a powerful way to understand your program and fix errors systematically.

Important questions;

Mr. Manjunatha G, Asst. Professor, Dept. of CSD Page 23

You might also like