# # 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 2 # 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 val1 = randint(1, 15) # generate first operator op1 = randint(0, 3) # generate second operand val2 = randint(1, 15) # generate second operator op2 = randint(0, 3) # generate third operand val3 = randint(1, 15) # generate third operator op3 = randint(0, 3) # generate last operand val4 = randint(1, 15) print val1, op1_str = get_Operator(op1) print op1_str, print val2, op2_str = get_Operator(op2) print op2_str, print val3, op3_str = get_Operator(op3) print op3_str, print val4 ############################################################ def main(): print 'Program generates a random of string expressions' generate_Expr() generate_Expr() generate_Expr() raw_input('\n to exit.') main()