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

Exceptions are part of your function's API


Exceptions are an important aspect of the API of a function. Callers of a function need to know which exceptions to expect under various conditions so that they can ensure appropriate exception handlers are in place. We'll use square-root finding as an example, using a home-grown square-root function, courtesy of Heron of Alexandria (although he probably didn't use Python).

Callers of a function need to know which exceptions to expect:

Figure 6.1: Callers need to know now

Place the following code in a file roots.py:

def sqrt(x):
    """Compute square roots using the method of Heron of Alexandria.

    Args:
        x: The number for which the square root is to be computed.

    Returns:
        The square root of x.
    """
    guess = x
    i = 0
    while guess * guess != x and i < 20:
        guess = (guess + x / guess) / 2.0
        i += 1
    return guess

def main():
    print(sqrt(9))
    print(sqrt(2))

if __name__ == '__main__':
    main...