# # 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 3 (much like version 2, but more compact # see the print statements in generate_Expr(), # we got rid of some extra variables etc...) # uses methods with parameter and return values # # written by e.bonakdarian oct 2009 # from random import randint ############################################################ 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 1 - 15 # generate first operand + operator val1 = randint(1, 15) op1 = randint(0, 3) # generate second operand + operator val2 = randint(1, 15) op2 = randint(0, 3) # generate third operand + operator val3 = randint(1, 15) op3 = randint(0, 3) # generate last operand val4 = randint(1, 15) print val1, get_Operator(op1), print val2, get_Operator(op2), print val3, get_Operator(op3), print val4 ############################################################ def main(): print 'Program generates a random of string expressions' generate_Expr() generate_Expr() generate_Expr() raw_input('\n to exit.') main()