raise Exception('This is an error message')
'''
******
* *
* *
******
'''
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception('"symbol" needs to be a string of length 1')
if (width < 2) or (height < 2):
raise Exception('"width" and "height" must be greater than or equal to 2')
print(symbol * width)
for i in range(height -2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
boxPrint('*', 15, 5)
import traceback
try:
raise Exception('This is an error message')
except:
errorFile = open('error_log.txt', 'a')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written in error_log.txt')
You get the file path of the log file from print(os.getcwd())
You can also use assertions: assert condition, 'error message'
assert False, 'This is an error message'
Assertions are for detecting programmer errors that are NOT meant to be recovered from. User errors should raise exceptions
market_2nd = {'ns': 'green', 'ew': 'red'}
def switchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 'red':
intersection[key] = 'green'
assert 'red' in intersection[key], 'Neither light is red!' + str(intersection)
print(market_2nd)
switchLights(market_2nd)
print(market_2nd)
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
def factorial(n):
total = 1
for i in range(n+1):
total *= i
return total
print(factorial(5))
The logging module lets you display the logging messages. After calling basicConfig()
to set up logging, call logging.debug()
to create a log message
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 %s, total is %s' % (i, total))
logging.debug('Return value is %s' % (total))
return total
print(factorial(5))
logging.debug('End of program')
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(1, n+1):
total *= i
logging.debug('i is %s, total is %s' % (i, total))
logging.debug('Return value is %s' % (total))
return total
print(factorial(5))
logging.debug('End of program')
When done, you can disable the log messages with logging.disable(logging.CRITICAL)
. Don't use print()
for log messages: It's hard to remove them all when you're done debugging.
The 5 log levels are: DEBUG, INFO, WARNING, ERROR and CRITICAL
You can also log a file instead of the screen with the filename keyword argument to the basicConfig()
function
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
The debugger is a tool that lets you execute Python code one line at a time and shows you the values in variables. Open the Debug Control window with Debug > Debugger
BEFORE running the program. Be sure to select Stack, Source, Locals and Globals check boxes.
print('Enter the first number to add:')
first=input() # 1
print('Enter the second number to add:')
second=input() # 2
print('Enter the third number to add:')
third=input() # 3
print('The sum is ' + first + second + third)
The Over
button will step over the current line of code and pause on the next one. It doesn't go into the function call
The Step
button will step into a function call. The Out
button will step out of the current function you are in. The Go
button will continue the program until the next breakpoint or end of the program. The Quit
button will immediately terminate the program.
Breakpoints can be set by right clicking the line and select set breakpoint
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.')