0% found this document useful (0 votes)
139 views

Module 4

This document discusses organizing files in Python using various modules like shutil and os. It covers copying, moving, renaming and deleting files and folders. It also discusses compressing files using the zipfile module to create and extract zip archives. Specific topics covered include copying and moving files, recursively copying folders, safely deleting files using send2trash, walking directory trees with os.walk(), and reading/writing zip files using the zipfile module.

Uploaded by

mksaravanamk1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views

Module 4

This document discusses organizing files in Python using various modules like shutil and os. It covers copying, moving, renaming and deleting files and folders. It also discusses compressing files using the zipfile module to create and extract zip archives. Specific topics covered include copying and moving files, recursively copying folders, safely deleting files using send2trash, walking directory trees with os.walk(), and reading/writing zip files using the zipfile module.

Uploaded by

mksaravanamk1
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 96

RNS Institute of Technology

Department of Computer Science and


Engineering (Data Science)

Introduction to Python Programming


BPLCK205B
• Vision: Empowering students to solve complex
real time computing problems involving high
volume multidimensional data.
Course Outcomes
CO1 Demonstrate proficiency in handling of loops and creation of
functions.
CO2 Identify the methods to create and manipulate lists, tuples
and dictionaries.
CO3 Discover the commonly used operations involving regular
expressions and file system.
CO4 Interpret the concepts of Object-Oriented Programming as
used in Python.
CO5 Determine the need for scraping websites and working with
CSV, JSON and other file formats.
Module 4: Organizing Files
• The shutil Module
• The shutil (or shell utilities) module has functions to let you
copy, move, rename, and delete files in your Python
programs.
• Copying Files and Folders:
• shutil.copy(source, destination) will copy the file at the path
source to the folder at the path destination. (Both source and
destination are strings.)
• If destination is a filename, it will be used as the new name
of the copied file.
• This function returns a string of the path of the copied file.
Contd..
• >>> os.chdir('C:\\')
• >>> shutil.copy('C:\\spam.txt', 'C:\\delicious')
• 'C:\\delicious\\spam.txt'
• >>> shutil.copy('eggs.txt','C:\\delicious\\eggs2.txt')
• 'C:\\delicious\\eggs2.txt'
Contd..
• While shutil.copy() will copy a single file,
shutil.copytree() will copy an entire folder and
every folder and file contained in it.
• Calling shutil.copytree(source, destination) will
copy the folder at the path source, along with all of
its files and subfolders, to the folder at the path
destination.
• The source and destination parameters are both
strings. The function returns a string of the path of
the copied folder.
Contd..
• >>> import shutil, os
• >>> os.chdir('C:\\')
• >>> shutil.copytree('C:\\bacon', 'C:\\
bacon_backup')
• 'C:\\bacon_backup'
• The shutil.copytree() call creates a new folder
named bacon_backup with the same content
as the original bacon folder.
Contd..
• Moving and Renaming Files and Folders:
• shutil.move(source, destination) will move the
file or folder at the path source to the path
destination and will return a string of the
absolute path of the new location.
• If destination points to a folder, the source file
gets moved into destination and keeps its
current filename.
Contd..
• >>> import shutil
• >>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
• 'C:\\eggs\\bacon.txt‘
• Assuming a folder named eggs already exists
in the C:\ directory, this will move ‘C:\
bacon.txt ‘ into the folder ‘C:\eggs’.
• If there had been a bacon.txt file already in C:\
eggs, it would have been overwritten.
Contd..
• If there is no eggs folder, then move() will
rename bacon.txt to a file named eggs.
• >>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
• 'C:\\eggs‘ (File_with_no_Extension .txt).
Contd..
• Finally, the folders that make up the destination
must already exist, or else Python will throw an
exception.
>>> shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')
• Traceback (most recent call last):
• File "C:\Python34\lib\shutil.py", line 521, in move
• os.rename(src, real_dst)
• FileNotFoundError: [WinError 3] The system cannot find the
path specified:
• 'spam.txt' -> 'c:\\does_not_exist\\eggs\\ham'
Contd..
• Permanently Deleting Files and Folders
• We can delete a single file or a single empty folder with
functions in the os module.
• To delete a folder and all of its contents, use the shutil
module.
• os.unlink(path) will delete the file at path.
• os.rmdir(path) will delete the folder at path. This folder
must be empty of any files or folders.
• shutil.rmtree(path) will remove the folder at path, and
all files and folders it contains will also be deleted.
Contd..
• It’s often a good idea to first run your program
with calls commented out and with print()
calls added to show the files that would be
deleted:
• import os
• for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
Contd..
• Instead, you should first run the program like this:
• import os
• for filename in os.listdir():
if filename.endswith('.rxt'):
#os.unlink(filename)
print(filename)
• Now the os.unlink() call is commented, so Python
ignores it. Instead, it will print the filename of the
file that would have been deleted.
Contd..
• Safe Deletes with the send2trash Module
• Python’s built-in shutil.rmtree() function can
be dangerous to use.
• A much better way would be to use the
thirdparty send2trash module.
• You must install this module.
Contd..
• send2trash is much safer than Python’s
regular delete functions.
• It will send folders and files to your
computer’s trash or recycle bin instead of
permanently deleting them.
• If a bug in your program deletes something
with send2trash you didn’t intend to delete,
you can later restore it from the recycle bin.
Contd..
• >>> import send2trash
• >>> baconFile = open('bacon.txt', 'a') # creates the file
• >>> baconFile.write('Bacon is not a vegetable.')
• 25
• >>> baconFile.close()
• >>> send2trash.send2trash('bacon.txt')
Walking a Directory Tree
• To rename every file in some folder and also
every file in every subfolder of that folder.
• (If you want to walk through the directory
tree, touching each file as you go. )
• Writing a program to do this could get tricky.
• Python provides a function to handle this
process for you.
Contd..
Contd..
• import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print(‘ ’)
Contd..
• The os.walk() function is passed a value,” the
path of a folder”.
• os.walk() in a for loop statement walk a
directory tree, similar to range() function.
• But unlike range(), the os.walk() function will
return three values on each iteration through
the loop.
Contd..
• 1. A string of the current folder’s name
• 2. A list of strings of the folders in the current
folder
• 3. A list of strings of the files in the current
folder.
• Note: The current working directory of the
program is not changed by os.walk().
Contd..
• 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.
Contd..
• Since os.walk() returns lists of strings for the
subfolder and filename variables, you can use
these lists in their own for loops
Compressing Files with the zipfile Module

• Compressing a file reduces its size, which is useful


when transferring it over the Internet.
• 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,
attached to an email.
• The Python program can both create and open (or
extract) ZIP files using functions in the zipfile
module.
example

example.zip
Reading ZIP Files
• To read the contents of a ZIP file, first you must create
a ZipFile object.
• ZipFile objects are conceptually similar to the File
objects.
• They are values through which the program interacts
with the file.
• 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.
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.namelist()
• ['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
>>> spamInfo = exampleZip.getinfo('spam.txt')
>>> spamInfo.file_size
• 13908
>>> spamInfo.compress_size
• 3828
>>> 'Compressed file is %sx smaller!' %
(round(spamInfo.file_size / spamInfo.compress_size, 2))
• 'Compressed file is 3.63x smaller!'
• >>> exampleZip.close()
Contd..
• 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.
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
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.extractall()
>>> exampleZip.close()
Contd..
• The extract() method for ZipFile objects will
extract a single file from the ZIP file.
>>> exampleZip.extract('spam.txt')
• 'C:\\spam.txt'
>>>exampleZip.extract('spam.txt','C:\\some\\new\\
folders')
• 'C:\\some\\new\\folders\\spam.txt'
>>> exampleZip.close()
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.
Contd..
• 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.
• Set this value to zipfile.ZIP_DEFLATED.
Contd..
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>>newZip.write('spam.txt',compress_type=zipfile.ZIP
_DEFLATED)
>>> newZip.close()
Project: Backing Up a Folder into a ZIP File

• Say you’re working on a project whose files you keep in a


folder named C:\AlsPythonBook.
• You’re worried about losing your work, so you’d like to create
ZIP file “snapshots” of the entire folder.
• You’d like to keep different versions, so you want the ZIP file’s
filename to increment each time it is made; for example,
AlsPythonBook_1.zip, AlsPythonBook_2.zip,
AlsPythonBook_3.zip, and so on.
• You could do this by hand, but it is rather annoying, and you
might accidentally misnumber the ZIP files’ names.
• It would be much simpler to run a program that does this
boring task for you.
Debugging
• Cover some tools and techniques for finding
the root cause of bugs in your program.
• Help you fix bugs faster and with less effort.
• There are a few tools and techniques to
identify what exactly your code is doing and
where it’s going wrong.
• We will look at logging and assertions,
• Help you detect bugs early.
Contd..
• The Debugger is a feature of IDLE that executes a
program one instruction at a time.
• You will get a chance to inspect the values in variables
while your code runs, and track how the values
change over the course of your program.
• This is much slower than running the program at full
speed.
• But it is helpful to see the actual values in a program
while it runs, rather than deducing what the values
might be from the source code.
Raising Exceptions
• Python raises an exception whenever it tries
to execute invalid code.
• You can also raise your own exceptions in your
code.
• Raising an exception is a way of saying, “Stop
running the code in this function and move
the program execution to the except
statement.”
Contd..
• Exceptions are raised with a raise statement.
• The raise keyword
• A call to the Exception() function
• A string with a helpful error message passed to the
Exception() function

>>> raise Exception('This is the error message.')


• Traceback (most recent call last):
• File "<pyshell#191>", line 1, in <module>
• raise Exception('This is the error message.')
• Exception: This is the error message.
Contd..
• If there are no try and except statements
covering the raise statement that raised the
exception.
• The program simply crashes and displays the
exception’s error message.
• A raise statement is always inside a function
and the try and except statements in the code
calling the function.
• def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2:
raise Exception('Width must be greater than 2.')
if height <= 2:
raise Exception('Height must be greater than 2.')
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
Getting the Traceback as a String
• When Python encounters an error, it produces
a treasure trove of error information called
the traceback.
• The traceback includes the error message, the
line number of the line that caused the error,
and the sequence of the function calls that led
to the error.
• This sequence of calls is called the call stack.
Contd..
• errorExample.py:
def spam():
bacon()
def bacon():
raise Exception('This is the error message.')
spam()

• Traceback (most recent call last):


• File "errorExample.py", line 7, in <module>
• spam()
• File "errorExample.py", line 2, in spam
• bacon()
• File "errorExample.py", line 5, in bacon
• raise Exception('This is the error message.')
• Exception: This is the error message.
Contd..
• In programs where functions can be called from multiple
places, the call stack can help you determine which call led to
the error.
• The traceback is displayed by Python whenever a raised
exception goes unhandled.
• But you can also obtain it as a string by calling
traceback.format_exc().
• This function is useful if you want the information from an
exception’s traceback but also want an except statement to
gracefully handle the exception.
• import Python’s traceback module before calling this function.
Contd..
• >>> import traceback
• >>> try:
raise Exception('This is the error message.')
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorInfo.txt.')
• 116
• The traceback info was written to errorInfo.txt.
Contd..
• Instead of crashing your program right when
an exception occurs.
• you can write the traceback information to a
log file and keep your program running.
• You can look at the log file later, when you’re
ready to debug your program.
Assertions
• An assertion is a sanity check to make sure
your code isn’t doing something obviously
wrong.
• These sanity checks are performed by assert
statements.
• If the sanity check fails, then an AssertionError
exception is raised.
Contd..
• The assert keyword
• A condition (that is, an expression that
evaluates to True or False)
• A comma
• A string to display when the condition is False
Contd..
• >>> podBayDoorStatus = 'open'
• >>> assert podBayDoorStatus == 'open', 'The pod bay doors
need to be "open".'
• >>> podBayDoorStatus = 'I\'m sorry, Dave. I\'m afraid I can't do
that.''
• >>> assert podBayDoorStatus == 'open', 'The pod bay doors
need to be "open".'
• Traceback (most recent call last):
• File "<pyshell#10>", line 1, in <module>
• assert podBayDoorStatus == 'open', 'The pod bay doors need to
be "open".'
• AssertionError: The pod bay doors need to be "open".
Contd..
• In plain English, an assert statement says, “I assert that
this condition holds true, and if not, there is a bug
somewhere in the program.”
• Unlike exceptions, your code should not handle assert
statements with try and except.
• if an assert fails, your program should crash.
• By failing fast like this, you shorten the time between the
original cause of the bug and when you first notice the
bug.
• This will reduce the amount of code you will have to check
before finding the code that’s causing the bug.
Using an Assertion in a Traffic Light
Simulation
• The data structure representing the stoplights at an intersection
is a dictionary with keys 'ns' and 'ew', for the stoplights facing
north-south and east-west, respectively.
• The values at these keys will be one of the strings 'green', '
yellow', or 'red'.
• market_2nd = {'ns': 'green', 'ew': 'red'}
• mission_16th = {'ns': 'red', 'ew': 'green'}
• These two variables will be for the intersections of Market
Street and 2nd Street, and Mission Street and 16th Street.
• To start the project, write a switchLights() function, which will
take an intersection dictionary as an argument and switch the
lights.
Contd..
• switchLights() should simply switch each light to the next
color in the sequence.
• def switchLights(stoplight):
for key in stoplight.keys():
if stoplight[key] == 'green':
stoplight[key] = 'yellow‘
elif stoplight[key] == 'yellow':
stoplight[key] = 'red'
elif stoplight[key] == 'red':
stoplight[key] = 'green'
switchLights(market_2nd)
Contd..
• When you finally do run the simulation, the
program doesn’t crash — but your virtual cars do!
• Since you’ve already written the rest of the
program, you have no idea where the bug could
be.
• Maybe it’s in the code simulating the cars or in
the code simulating the virtual drivers.
• It could take hours to trace the bug back to the
switchLights() function.
Contd..
• But if while writing switchLights() you had
added an assertion to check that at least one
of the lights is always red, then included the
following at the bottom of the function:
• assert 'red' in stoplight.values(), 'Neither light
is red! ' + str(stoplight)
• With this assertion , your program would
crash with error message:
Contd..
• Traceback (most recent call last):
• File "carSim.py", line 14, in <module>
• switchLights(market_2nd)
• File "carSim.py", line 13, in switchLights
• assert 'red' in stoplight.values(), 'Neither light
is red! ' + str(stoplight)
• AssertionError: Neither light is red! {'ns':
'yellow', 'ew': 'green'}
Contd..
• While your program crashing is not ideal, it
immediately points out that a sanity check
failed: Neither direction of traffic has a red
light.
• Traffic could be going both ways. By failing fast
early in the program’s execution, you can save
yourself a lot of future debugging effort.
Disabling Assertions
• Assertions can be disabled by passing the -O option
when running Python.
• This is good when you have finished writing and
testing your program and don’t want it to be
slowed down by performing sanity checks.
• Assertions are for development, not the final
product.
• By the time you hand off your program to someone
else to run, it should be free of bugs and not
require the sanity checks.
Logging
• Logging is a great way to understand what’s happening
in your program and in what order its happening.
• Python’s logging module makes it easy to create a
record of custom messages that you write.
• These log messages will describe when the program
execution has reached the logging function call and list
any variables you have specified at that point in time.
• On the other hand, a missing log message indicates a
part of the code was skipped and never executed.
Using the logging Module
• To enable the logging module to display log
messages on your screen.
• import logging
• logging.basicConfig(level=logging.DEBUG,
format=' %(asctime)s - %(levelname)s- %
(message)s')
Contd..
• When Python logs an event, it creates a
LogRecord object that holds information
about that event.
• The logging module’s basicConfig() function
lets you specify what details about the
LogRecord object you want to see and how
you want those details displayed.
Contd..
• A function to calculate the factorial of a
number.
• In mathematics, factorial 4 is 1 × 2 × 3 × 4, or
24 and factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or
5,040.
• It has a bug in it, but you will also enter
several log messages to help yourself figure
out what is going wrong.
Contd..
Contd..
• Here, we use the logging.debug() function when we
want to print log information.
• This debug() function will call basicConfig(), and a
line of information will be printed.
• This information will be in the format we specified
in basicConfig() and will include the messages we
passed to debug().
• The print(factorial(5)) call is part of the original
program, so the result is displayed even if logging
messages are disabled.
Contd..
Contd..
• The factorial() function is returning 0 as the
factorial of 5.
• Change the for i in range(n + 1): line to for i in
range(1, n + 1):
Contd..
Don’t Debug with print()
• import logging
logging.basicConfig(level=logging.DEBUG,
format= '% (asctime)s - %(levelname)s - %
(message)s') is somewhat unwieldy.
• Instead use print() calls, but don’t give in to
this temptation!
• Once you’re done debugging, you’ll end up
spending a lot of time removing print() calls
from your code for each log message.
Contd..
• You might even accidentally remove some print()
calls that were being used for nonlog messages.
• You’re free to fill your program with as many as
logging message you like.
• You can always disable them later by adding a
single logging.disable(logging.CRITICAL) call.
• Unlike print(), the logging module makes it easy to
switch between showing and hiding log messages.
Logging Levels
• Logging levels provide a way to categorize
your log messages by importance.
• Messages can be logged at each level using a
different logging function.
Contd..
• Logging message is passed as a string to these
functions.
• The logging levels are suggestions.
• Ultimately, it is up to you to decide which
category your log message falls into.
Contd..
• >>> import logging
• >>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s -
• %(levelname)s - %(message)s')
• >>> logging.debug('Some debugging details.')
• 2015-05-18 19:04:26,901 - DEBUG - Some debugging details.
• >>> logging.info('The logging module is working.')
• 2015-05-18 19:04:35,569 - INFO - The logging module is working.
• >>> logging.warning('An error message is about to be logged.')
• 2015-05-18 19:04:56,843 - WARNING - An error message is about to be logged.
• >>> logging.error('An error has occurred.')
• 2015-05-18 19:05:07,737 - ERROR - An error has occurred.
• >>> logging.critical('The program is unable to recover!')
• 2015-05-18 19:05:45,794 - CRITICAL - The program is unable to recover!
Disabling Logging
• After you’ve debugged your program, you probably
don’t want all these log messages cluttering the
screen.
• The logging.disable() function disables these so that
you don’t have to go into your program and remove
all the logging calls by hand.
• You simply pass logging.disable() a logging level, and it
will suppress all log messages at that level or lower.
• So if you want to disable logging entirely, just add
logging.disable(logging.CRITICAL) to your program.
Contd..
• >>> import logging
• >>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s -
• %(levelname)s - %(message)s')
• >>> logging.critical('Critical error! Critical error!')
• 2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!
• >>> logging.disable(logging.CRITICAL)
• >>> logging.critical('Critical error! Critical error!')
• >>> logging.error('Error! Error!')

• Since logging.disable() will disable all messages after it,


you will probably want to add it near the import logging
line of code in your program.
Logging to a File
• Instead of displaying the log messages to the
screen, you can write them to a text file.
• The logging.basicConfig() function takes a
filename keyword argument, like:
• import logging
• logging.basicConfig(filename='myProgramLog
.txt', level=logging.DEBUG, format=‘ %
(asctime)s - %(levelname)s - %(message)s')
Contd..
• The log messages will be saved to
myProgramLog.txt.
• While logging messages are helpful, they can
clutter your screen and make it hard to read
the program’s output.
• Writing the logging messages to a file will keep
your screen clear and store the messages so
you can read them after running the program.
IDLE’s Debugger
• The debugger is a feature of IDLE that allows you
to execute your program one line at a time.
• The debugger will run a single line of code and
then wait for you to tell it to continue.
• By running your program “under the debugger”,
you can take as much time as you want to
examine the values in the variables at any given
point during the program’s lifetime.
• This is a valuable tool for tracking down bugs.
Contd..
• To enable IDLE’s debugger, click
Debug▸Debugger in the interactive shell
window.
• When the Debug Control window appears,
select all four of the Stack, Locals, Source, and
Globals checkboxes so that the window shows
the full set of debug information.
Contd..
• While the Debug Control window is displayed,
any time you run a program from the file
editor, the debugger will pause execution
before the first instruction and display the
following:
• The line of code that is about to be executed.
• A list of all local variables and their values.
• A list of all global variables and their values.
Contd..
Contd..
• The program will stay paused until you press one
of the five buttons in the Debug Control window:
Go, Step, Over, Out, or Quit.
• Go
• Clicking the Go button will cause the program to
execute normally until it terminates or reaches a
breakpoint.
• If you are done debugging and want the program
to continue normally, click the Go button.
Contd..
• Step
• Clicking the Step button will cause the debugger to
execute the next line of code and then pause again.
• The Debug Control window’s list of global and local
variables will be updated if their values change.
• If the next line of code is a function call, the
debugger will “step into” that function and jump to
the first line of code of that function.
Contd..
• Over
• Clicking the Over button will execute the next line of code,
similar to the Step button.
• However, if the next line of code is a function call, the Over
button will “step over” the code in the function.
• The function’s code will be executed at full speed, and the
debugger will pause as soon as the function call returns.
• For example, if the next line of code is a print() call, you don’t
really care about code inside the built-in print() function;
• You just want the string you pass it printed to the screen. For
this reason, using the Over button is more common than the
Step button.
Contd..
• Out
• Clicking the Out button will cause the debugger
to execute lines of code at full speed until it
returns from the current function.
• If you have stepped into a function call with the
Step button and now simply want to keep
executing instructions until you get back out,
• click the Out button to “step out” of the
current function call.
Contd..
• Quit
• If you want to stop debugging entirely and not
bother to continue executing the rest of the
program
• Click the Quit button. The Quit button will
immediately terminate the program.
• If you want to run your program normally
again, select Debug▸Debugger again to disable
the debugger.
Debugging a Number Adding Program
• print('Enter the first number to add:')
• first = input()
• print('Enter the second number to add:')
• second = input()
• print('Enter the third number to add:')
• third = input()
• print('The sum is ' + first + second + third)
Contd..
• The program will output something like this:
• Enter the first number to add:
• 5
• Enter the second number to add:
• 3
• Enter the third number to add:
• 42
• The sum is 5342
Contd..
• Enable the Debug Control window and run it
again, this time under the debugger.
• When you press F5 or select Run▸Run Module
(with Debug▸Debugger enabled and all four
checkboxes on the Debug Control window
checked), the program starts in a paused state
on line 1.
• The debugger will always pause on the line of
code it is about to execute.
Contd..
Breakpoints
• A breakpoint can be set on a specific line of
code and forces the debugger to pause
whenever the program execution reaches that
line.
• The following program, simulates flipping a
coin 1,000 times.
Contd..
• import random
• heads = 0
• for i in range(1, 1001):
• if random.randint(0, 1) == 1:
• heads = heads + 1
• if i == 500:
• print('Halfway done!')
• print('Heads came up ' + str(heads) + ' times.')
Contd..
• The random.randint(0, 1) call will return 0 half
of the time and 1 the other half of the time.
• This can be used to simulate a 50/50 coin flip
where 1 represents heads.
• When you run this program without the
debugger, it quickly outputs something like the
following:
• Halfway done!
• Heads came up 490 times.
Contd..
• If you ran this program under the debugger, you
would have to click the Over button thousands of
times before the program terminated.
• If you were interested in the value of heads at the
halfway point of the program’s execution, when 500
of 1000 coin flips have been completed, you could
instead just set a breakpoint on the line
print('Halfway done!') .
• To set a breakpoint, right-click the line in the file
editor and select Set Breakpoint.
Contd..
Contd..
• The line with the breakpoint will be
highlighted in yellow in the file editor. When
you run the program under the debugger, it
will start in a paused state at the first line, as
usual.
• But if you click Go, the program will run at full
speed until it reaches the line with the
breakpoint set on it. You can then click Go,
Over, Step, or Out to continue as normal.
Contd..
• If you want to remove a breakpoint, right-click
the line in the file editor and select Clear
Breakpoint from the menu.
• The yellow highlighting will go away, and the
debugger will not break on that line in the
future.

You might also like