|
#! /Usr/bin/env python
From operator import add, sub
From random import randint, choice
Ops = {'+': add, '-': sub}
# Define a dictionary
MAXTRIES = 2
Def doprob ():
Op = choice ('+ -')
# Use choice to randomly select operators from '+ -'
Nums = [randint (1, 10) for I in range (2)]
# Use randint () to randomly generate a number ranging from 1 to 10. Use range (2) twice)
Nums. sort (reverse = True)
# Sort in ascending order
Ans = ops [op] (* nums)
# Using Functions
Pr = '% d % s % d =' % (nums [0], op, nums [1])
Oops = 0
# Oops is used to calculate the failure test. Answers are automatically given three times.
While True:
Try:
If int (raw_input (pr) = ans:
Print 'correct'
Break
If oops = MAXTRIES:
Print 'answer \ n % s % d' % (pr, ans)
Break
Else:
Print 'encrect... try again'
Oops + = 1
Except T (KeyboardInterrupt, EOFError, ValueError ):
Print 'invalidipnut... try again'
Def main ():
While True:
Doprob ()
Try:
Opt = raw_input ('again? [Y] '). lower ()
If opt and opt [0] = 'N ':
Break
Except T (KeyboardInterrupt, EOFError ):
Break
If _ name _ = '_ main __':
Main ()
|