#!/usr/bin/env python
'''
$Id$

matheasy.py -- arithmetic educational application for children
'''

from string import lower                        # convert user text input
from operator import add, sub, mul, div                # get arithmetic operations
from random import randint, choice                # choose random values and operation

ops = { '+': add, '-': sub, '*': mul }                # supported operations
MAXTRIES = 2                                        # number of tries before giving answer

# doprob() --> None
def doprob():
    'doprob() -- manage the delivery of a single problem to the user'

    op = choice('+-*')                                        # random operation
    nums = [randint(1,10), randint(1,10)]                # random numbers
    nums.sort() ; nums.reverse()                        # larger number first
    ans = apply(ops[op], nums)                                # preprocess answer
    prompt = '%d %s %s = ' % (nums[0], op, nums[1])        # create user prompt
    oops = 0                                                # track wrong answers
    while 1:                                                # loop until answer correct
        try:
            if int(raw_input(prompt)) == ans:                # return on correct answer
                print 'correct'
                break
            if oops == MAXTRIES:                        # show answer after MAXTRIES
                print 'sorry... the answer is\n%s%d' % (prompt, ans)
            else:                                        # wrong answer indication
                print 'incorrect... try again'
                oops = oops + 1
        except (KeyboardInterrupt, EOFError,                # do not allow quitting
                        ValueError), diag:
            print 'invalid input... try again'


# main() --> None
def main():
    'main() -- prompts user to try another problem'

    while 1:                                                # loop until user quits
        doprob()
        try:                                                # get user decision
            opt = lower(raw_input('Try another? ([y]/n) '))
        except (KeyboardInterrupt, EOFError):                # allow keyboard quit
            print ; break
        if opt and opt[0] == 'n':                        # user quits
            break


# call main() if invoked as script
if __name__ == '__main__':
    main()

