On 28 April 2015 at 22:40, Cameron Simpson <c...@zip.com.au> wrote: > > As with all things, sometimes that cannot be reasonably achieved, but it > is usually so. > > We can pick over your code as well if you like. Should we? > > Cheers, > Cameron Simpson <c...@zip.com.au>
Sure, but let me include the full working program after fixup. Although I still have to write another program to feed it random problems to work it out. It's a bit spacey, but I ran it through the pep8 program and it suggested that. I think two spaces between such tiny functions is overkill, though. """ 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, 'subtracted': subtract, '-': minus, 'minus': minus, 'multiply': multiply, '*': multiply, 'multiplied': multiply, 'times': multiply, 'divide': divide, '/': divide, 'divided': divide} 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() numbers = [] 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] instructions = '''Enter two numbers and one of the four basid math operations, either mathematical or verbal. i.e. 3 + 2, 12 divided by 14, 10 minus 4, etc. Enter done to quit. ''' try: user_input = input(instructions) while True: if user_input == 'done': break result = parse_string(user_input) if result == None: print("Not a valid math operation.") else: func, num1, num2 = result print(func(num1, num2)) user_input = input() except KeyboardInterrupt: print("Program terminated by user") -- Jim If you only had one hour left to live, would you spend it on Facebook, Twitter, or Google Plus? _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor