Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Debugging

The judicious insertion of print() statements can help you find bugs in your code:

def movie_year(number):
    roman = { 1:'I', 5:'V', 10:'X', 50:'L', 100:'C', 500:'D', 1000:'M', }

    output = []
    divisor = 1000
    print(f'movie_year({number})')
    for digit in [int(x) for x in str(number)]:
        print(f'   digit={digit} divisor={divisor}')
        if digit <= 3:
            # e.g. 3 -> 3*'I' -> 'III'
            output.append( roman[divisor] * digit )
        elif digit == 4:
            output.append( roman[divisor] +  roman[divisor * 5] )
        elif 5 < digit <= 8:
            output.append( roman[divisor * 5] + roman[digit] * (divisor - 5) )
        elif digit == 9:
            output.append( roman[divisor] + roman[divisor * 10] )

        divisor = int(divisor / 10)
        print('      ', output)

    return ''.join(output)

Here’s what you’ll get:

>>>
>>> movie_year(2015)
movie_year(2015)
   digit=2 divisor=1000
       ['MM']
   digit=0 divisor=100
       ['MM', '']
   digit=1 divisor=10
       ['MM', '', 'X']
   digit=5 divisor=1
       ['MM', '', 'X']
'MMX'

For production software, print() might not be a good long term solution. Python’s comprehensive logging library is a better choice:

# counters.py
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)

def count_lower_case(item):
    logger.info('count_lower_case(%s)', item)
    num = 0
    for letter in item:
        if 97 <= ord(letter) <= 122:
            logger.debug('  letter *%s* is lowercase', letter)
            num += 1

    logger.info('  returning %s', num)
    return num

Here’s what you’ll get:

>>>
>>> from counters import count_lower_case
>>> count_lower_case('AbCdE')
INFO:counters:count_lower_case(AbCdE)
DEBUG:counters:  letter *b* is lowercase
DEBUG:counters:  letter *d* is lowercase
INFO:counters:  returning 2
2

Daniel Faria on June 10, 2020

Beautiful!

nj8456 on July 7, 2020

Yu guessed my feedback

Become a Member to join the conversation.