[Tutor] Function works one time then subsequently fails

Jim Mooney Py3winXP cybervigilante at gmail.com
Wed Apr 29 05:58:39 CEST 2015


This is really puzzling me. I'm parsing a string to do some simple math
operations and practice tossing functions around. My parser works on the
first run, then it continually fails on the same input.

"""
Takes the name of a binary math operation and two numbers from input,
repeatedly, and displays the results until done
"""

def add(a, b):
    return a + b

def subtract(a, b):
    return b - a

def minus(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

operations = {'add': add, '+': add, 'plus': add, 'subtract': subtract,
              '-': minus, 'minus': minus, 'multiply': multiply, '*':
multiply,
              'times': multiply, 'divide': divide, '/': divide,
              'divided': divide}

numbers = []

def test_number(astring):
    """
    Input: A string that should represent a valid int or float. Output:
    An int or float on success. None on failure.
    """
    for make_type in (int, float):
        try:
            return make_type(astring)
        except ValueError:
            pass
    return None

def parse_string(math_string):
    """Input: A math string with a verbal or mathematical operation
    and two valid numbers to operate on. Extra numbers and operations
    are ignored. Output: A tuple containing a function corresponding
    to the operation and the two numbers. Returns None on failure.
    """
    operation = None
    tokens = math_string.split()
    for token in tokens:
        if token in operations:
            operation = operations[token]
        elif test_number(token) != None:
            numbers.append(test_number(token))
        if len(numbers) > 1:
            break
    if operation is None or len(numbers) < 2:
        return None
    else:
        return operation, numbers[0], numbers[1]

REPL
>>> result = parse_string('1 minus 15')
>>> func, number1, number2 = result
>>> func(number1, number2)
-14
>>> result = parse_string('1 minus 15')
>>> print(result)
None
>>> result = parse_string('1 minus 15')
>>> print(result)
None
>>>


-- 
Jim

If you only had one hour left to live, would you spend it on Facebook,
Twitter, or Google Plus?


More information about the Tutor mailing list