Book Image

The Python Apprentice

By : Robert Smallshire, Austin Bingham
Book Image

The Python Apprentice

By: Robert Smallshire, Austin Bingham

Overview of this book

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it’s not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.
Table of Contents (21 chapters)
Title Page
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
12
Afterword – Just the Beginning

Palindrome debugging


Rather than simply list all of the commonly useful PDB commands, we're going to instead debug a simple function. Our function – is_palindrome() – takes in an integer and determines if the digits of the integer are a palindrome or not. A palindrome is a sequence which is the same both forwards and backwards.

The first thing we'll do is create a new file, palindrome.py, with this code:

import unittest

def digits(x):
    """Convert an integer into a list of digits.

    Args:
      x: The number whose digits we want.

    Returns: A list of the digits, in order, of ``x``.

    >>> digits(4586378)
    [4, 5, 8, 6, 3, 7, 8]
    """

    digs = []
    while x != 0:
        div, mod = divmod(x, 10)
        digs.append(mod)
        x = mod
    return digs

def is_palindrome(x):
    """Determine if an integer is a palindrome.

    Args:
      x: The number to check for palindromicity.

    Returns: True if the digits of ``x`` are a palindrome,
      False otherwise....