0% found this document useful (0 votes)
0 views47 pages

Python Module 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views47 pages

Python Module 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

BANGALORE INSTITUTE OF TECHNOLOGY

Department of Electronics and Communication

Introduction of Python Programming

Prepared & Presented by


Prof. Likhitha K
Assistant Professor

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Module 4

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

MODULE 4
Chapter 10 : ORGANIZING FILES
In this chapter we learn how to automate the some of the task like moving files, renaming the files, compressing
folders.
The shutil Module:
▪The shutil (or shell utilities) module has functions to let you copy, move, rename, and delete files in your
Python programs.
▪To use the shutil functions, you will first need to import shutil.
Copying Files and Folders:
▪shutil.copy(source, destination) - Copy the file at the path source to the folder at the path destination .
Note: Both source and destination can be strings or Path objects.
▪If destination is a filename, it will be used as the new name of the copied file.
▪This function returns a string or Path object of the copied file.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Example:
>>> import shutil, os
>>> 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’

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

▪ shutil.copytree(source, destination) - copy the folder at the path source, along with all of its files and
subfolders, to the folder at the path destination.
▪ The shutil.copytree() call creates a new folder.
▪ The source and destination parameters are both strings.
▪ The function returns a string of the path of the copied folder.

Example:

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Moving and Renaming Files and Folders:


▪ shutil.move(source, destination) - move the file or folder at the path source to the path destination and
▪ The function 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.

Example:
>>> import shutil
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

▪ If the file already exists then it will be overwritten.


▪ The destination path can also specify a filename. The source file is moved and renamed.
Example:
>>> import shutil
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs\\spam.txt')
'C:\\eggs\\spam.txt'
▪ But if there is no folder, then move() will rename bacon.txt to a file named spam.txt.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Example:
>>> import shutil
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs’
▪ The folders that make up the destination must already exist, or else Python will throw an exception.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Permanently Deleting Files and Folders:


▪You 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, you use the shutil module.
1. Calling os.unlink(path) will delete the file at path.
2. Calling os.rmdir(path) will delete the folder at path. This folder must be empty of any files or
folders.
3. Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains
will also be deleted.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Safe Deletes with the send2trash Module:


▪ shutil.rmtree() function irreversibly deletes files and folders, it can be dangerous to use.
▪A much better way to delete files and folders send2trash module.
▪send2trash module will send folders and files to your computer’s trash or recycle bin instead of
permanently deleting them.
Example:
>>> import send2trash
>>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt’)

Note: send2trash is third module, You can install this module by running pip install send2trash
from a Terminal window.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Walking a directory tree:


▪Python provides a function os.walk() to handle this process walk through the directory tree
▪The os.walk(path) function is passed a single string value: the path of a folder. You can use
os.walk() in a for loop statement to walk a directory tree,
▪os.walk() return three values
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

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Example program to walk through the directory:
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('')
Output:

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Compressing files with the zipfile module:


▪ 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.
▪ ZIP file can 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 both create and open (or extract) ZIP files using functions in the zipfile module.

Reading ZIP Files


▪ To read the contents of a ZIP file, first you must create a ZipFile object .
▪ To create a ZipFile object, call the zipfile.ZipFile() function, passing it a string of the .zip file’s filename.
▪ A ZipFile object has a namelist() method that returns a list of strings for all the files and folders contained in
the ZIP file.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Example:
>>> 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']

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

▪Strings from namelist() method 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.
Example:
>>> 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()

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
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.
Example:
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.extractall()
>>> exampleZip.close()
▪ We can also pass a new folder name as path of the folder to extractall() method to extract to specific folder.
▪ If the passed folder is not available then it newly creates a folder.
▪ The extract() method for ZipFile objects will extract a single file from the ZIP file.
Example:
>>> exampleZip.extract('spam.txt')
'C:\\spam.txt'
>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')
'C:\\some\\new\\folders\\spam.txt'
>>> exampleZip.close()
DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING
BANGALORE INSTITUTE OF TECHNOLOGY

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.
▪ 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;
▪ Always set to zipfile.ZIP_DEFLATED Which works for any type of data.
Example:
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w’)
>>> newZip.write('spam.txt',compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

▪ Project: renaming files with American-Style dates to european-Style dates


American-style dates (MM-DD-YYYY), European style dates (DD-MM-YYYY).
▪ It searches all the filenames in the current working directory for American-style dates.
▪ 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:
▪ Create a regex that can identify the text pattern of American-style dates.
▪ Call os.listdir() to find all the files in the working directory.
▪ Loop over each filename, using the regex to check whether it has a date.
▪ If it has a date, rename the file with shutil.move().
Steps of the project:
Step 1: Create a Regex for American-Style Dates
Step 2: Identify the Date Parts from the Filenames
Step 3: Form the New Filename and Rename the Files

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Step 1: Create a Regex for American-Style Dates

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Step 2: Identify the Date Parts from the Filenames

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Step 3: Form the New Filename and Rename the Files

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Project: Backing up a folder into ZIP file

Steps of the project:


Step 1: Figure Out the ZIP File’s Name.
Step 2: Create the New ZIP file.
Step 3: Walk the Directory Tree and Add to the ZIP file.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Step 1: Figure Out the ZIP File’s Name.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Step 2: Create the New ZIP file.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Step 3: Walk the Directory Tree and Add to the ZIP file.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Chapter 11 : Debugging
In this chapter, you will learn about techniques to identify what exactly your code is doing
and where it’s going wrong.
• First, you will look at logging and assertions, two features that can help you detect
bugs early.
• Second, you will look at how to use the debugger. The debugger is a feature of IDLE
that executes a program one instruction at a time, giving you a chance to inspect the
values in variables while your code runs, and track how the values change over the
course of your program.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
RAISING EXCEPTIONS:
▪ Python raises an exception whenever it tries to execute invalid code. So we were using try and except
statements.
▪ We can also raise an exception in code which means “Stop running the code in this function and move the
program execution to the except statement.”
▪ Exceptions are raised with a raise statement. In code, a raise statement consists of the following:
1. The raise keyword.
2. A call to the Exception() function.
3. A string with a error message passed to the Exception() function.
▪ Always the exception is raised within try and except block or else system will crash and prints the error msg in
exception
Example:
>>> 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.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Exception Handling REMEMBERING CONCEPT FROM MODULE - 1


 We need to detect the errors, handle the errors, and then continue to run the program. If not the program may
crash.
 Errors can be handled with try and except stmts. The code that could potentially have an error is put in
a try clause.

Example 1: Example 2: Example 3:

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Program to raise Exception:
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2: Output:
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): OOOOOOOOOOOOOOOOOOOO
print(symbol + (' ' * (width - 2)) + symbol) O O
print(symbol * width) O O
O O
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)): OOOOOOOOOOOOOOOOOOOO
try: An exception happened: Width must be greater than 2.
boxPrint(sym, w, h) An exception happened: Symbol must be a single
except Exception as err: character string.
print('An exception happened: ' + str(err))

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Getting the traceback as a String:
▪ When Python encounters an error, it produces a error information called 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.
Example:
def spam():
bacon()
def bacon():
raise Exception('This is the error message.')
spam()
Error traceback:
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.
DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING
BANGALORE INSTITUTE OF TECHNOLOGY
▪ you can also obtain it as a string by calling traceback.format_exc().
▪ Before using we need to import traceback function.
Example:
>>> 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.’)
Output:
116
The traceback info was written to errorInfo.txt.
Text in errorInfo.txt

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

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.
⮚ Using the logging Module:
Example:
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s’)
▪ 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.
▪ You can always disable log messages by adding a single logging.disable(logging.CRITICAL) call.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

Example of logging:
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n))
total = 1
for i in range(n + 1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
logging.debug('End of program')

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Logging Levels:
▪ Logging levels provide a way to categorize your log messages by importance. There are five logging levels:

▪ Passing logging.DEBUG to the basicConfig() function’s level keyword argument will show messages from all the
logging levels (DEBUG being the lowest level).
▪ But if you are interested only in errors. In that case, you can set basicConfig()’s level argument to logging.ERROR. This
will show only ERROR and CRITICAL messages
DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING
BANGALORE INSTITUTE OF TECHNOLOGY
Example of various logging levels:
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
>>> logging.debug('Some debugging details.')
2024-05-30 06:27:16,475 - DEBUG - Some debugging details.
>>> logging.info('The logging module is working.')
2024-05-30 06:27:26,759 - INFO - The logging module is working.
>>> logging.warning('An error message is about to be logged.')
2024-05-30 06:27:37,742 - WARNING - An error message is about to be logged.
>>> logging.error('An error has occurred.')
2024-05-30 06:27:46,937 - ERROR - An error has occurred.
>>> logging.critical('The program is unable to recover!')
2024-05-30 06:27:56,463 - CRITICAL - The program is unable to recover!

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
▪ Disabling Logging:
▪ The logging.disable() function disables log messages 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.

Example:
>>> import logging
>>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s - %(levelname)s - %(message)s')
>>> logging.critical('Critical error! Critical error!')
2024-05-30 06:27:56,463 - CRITICAL - Critical error! Critical error!
>>> logging.disable(logging.CRITICAL)
>>> logging.critical('Critical error! Critical error!')
>>> logging.error('Error! Error!’)

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Logging to a File:
▪ Instead of displaying the log messages to the screen, you can write log msgs to a text file. The
logging.basicConfig() function takes a filename keyword argument.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Idle’s debugger:
▪ The debugger is a feature of IDLE that allows you to execute your program one line at a time.
▪ 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.

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

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
▪ 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.
▪ 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.
▪ 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.
▪ 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.
▪ 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.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Mu debugger:
To Enable debugger click on debug button, the debugger will be enabled as shown below.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
▪ Continue
Clicking the Continue button will cause the program to execute normally until it terminates or reaches
a breakpoint.
▪ Step In
Clicking the Step In button will cause the debugger to execute the next line of code and then pause again.
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.
▪ Step Over
Clicking the Step Over button will execute the next line of code, similar to the Step In button. if the next line of
code is a function call, the Step 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.
▪ Step Out
Clicking the Step Out button will cause the debugger to execute lines of code at full speed until it returns from
the current function
▪ Stop
If you want to stop debugging entirely and not bother to continue executing the rest of the program, click the
Stop button. The Stop button will immediately terminate the program.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
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)
▪ Click the Over button once to execute the first print() call.
▪ Click Over again to execute the input() function call, and the buttons in the Debug Control window will disable
themselves while IDLE waits for you to type something for the input() call into the interactive shell window.
▪ Enter value and press enter. The Debug Control window buttons will be reenabled.
▪ Follow the same steps until all the inputs has been provided to get the output.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY

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.
▪If you want to debug a program which loops more times we can use breakpoints.
▪If you click Go, the program will run at full speed until it reaches the line with the breakpoint set on
it
▪To set a breakpoint, right-click the line in the file editor and select Set Breakpoint.
▪To remove a breakpoint, right-click the line in the file editor and select Clear Breakpoint.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
Example:
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.')

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

You might also like