# # this program generates a random string expression # # also shows the use of if/elif/else statements. # # pre-lists, hence a bit "primitive", we'll see a nicer # way to do this later in the term. # # version 4 (much like version 4, but yet more compact # we got rid of the op1-4 variables) # uses methods with parameter and return values # also uses CONSTANTS # # written by e.bonakdarian oct 2009 # from random import randint # used for operand MIN_VAL = 1 MAX_VAL = 15 ############################################################ def get_Operator(op): # function maps the operator (op) into the appropriate # string values and returns them to the caller # # + == 0 # - == 1 # * == 2 # / == 3 if op == 0: str_val = ' + ' elif op == 1: str_val = ' - ' elif op == 2: str_val = ' * ' else: str_val = ' / ' return str_val ############################################################ def generate_Expr(): # generate an expression using random numbers. # expression will have 4 operands and 3 operators # # using 3 operators in expressions from (-, +, *, /) # operands in range MIN_VAL, MAX_VAL # generate first operand val1 = randint(MIN_VAL, MAX_VAL) # generate second operand val2 = randint(MIN_VAL, MAX_VAL) # generate third operand val3 = randint(MIN_VAL, MAX_VAL) # generate last operand val4 = randint(MIN_VAL, MAX_VAL) print val1, get_Operator(randint(0, 3)), print val2, get_Operator(randint(0, 3)), print val3, get_Operator(randint(0, 3)), print val4 ############################################################ def main(): print 'Program generates a random of string expressions' generate_Expr() generate_Expr() generate_Expr() raw_input('\n to exit.') main()