6.8: Checking types

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    Read aloud

    How

    Speed: 1×
    Light up
    Highlight

    Symbols: Mulberry Symbols, © 2018–2026 Steve Lee, CC BY-SA 4.0 (licence, the set), the site's own copies.

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    6.8: Checking types

    What happens if we call factorial and give it 1.5 as an argument?

    >>> factorial(1.5)
    RuntimeError: Maximum recursion depth exceeded
    

    It looks like an infinite recursion. How can that be? The function has a base case—when n == 0. But if \( n \) is not an integer, we can miss the base case and recurse forever.

    In the first recursive call, the value of \( n \) is 0.5. In the next, it is -0.5. From there, it gets smaller (more negative), but it will never be 0.

    We have two choices. We can try to generalize the factorial function to work with floating-point numbers, or we can make factorial check the type of its argument. The first option is called the gamma function and it’s a little beyond the scope of this book. So we’ll go for the second.

    We can use the built-in function isinstance to verify the type of the argument. While we’re at it, we can also make sure the argument is positive:

    def factorial(n):
        if not isinstance(n, int):
            print('Factorial is only defined for integers.')
            return None
        elif n < 0:
            print('Factorial is not defined for negative integers.')
            return None
        elif n == 0:
            return 1
        else:
            return n * factorial(n-1)
    

    The first base case handles nonintegers; the second handles negative integers. In both cases, the program prints an error message and returns None to indicate that something went wrong:

    >>> print(factorial('fred'))
    Factorial is only defined for integers.
    None
    >>> print(factorial(-2))
    Factorial is not defined for negative integers.
    None
    

    If we get past both checks, we know that \( n \) is a non-negative integer, so we can prove that the recursion terminates.

    This program demonstrates a pattern sometimes called a guardian. The first two conditionals act as guardians, protecting the code that follows from values that might cause an error. The guardians make it possible to prove the correctness of the code.

    In Section 11.4 we will see a more flexible alternative to printing an error message: raising an exception.


    This page titled 6.8: Checking types was last modified on Tue, 01 Dec 2020 03:30:48 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.