# Midterm EECS 12 Summer Session I 2006 # Solution # Mark E. Phair mphair uci.edu import math # for pow import string # for letters #################################################### ####### FUNCTIONS ################################## #################################################### # requirement: function resolve def resolve(argument): """Returns the number if argument is number, does a variable lookup if argument starts with a letter""" if argument[0] in string.letters: # the first character of argument is a letter, so # arugment is a variable name if variables.has_key(argument): return variables[argument] else: print 'Unknown variable:', argument # requirement: unknown variable returns 0.0 return 0.0 else: # the first character of argument is not a letter, # therefore it should be a number return float(argument) #################################################### ############ MAIN ################################## #################################################### variables = {} doLoop = True last = 0 # keep last calculated value while doLoop: # split raw_input immediately, we don't need the full string response = raw_input('? ').split(' ') # This whole thing can be probably better be done # with a dictionary of function objects, but those # had not been taught yet. if response[0] == 'exit': # we're done! doLoop = False # standard operations... resolve and perform the op elif response[0] == '+': last = resolve(response[1]) + resolve(response[2]) print last elif response[0] == '-': last = resolve(response[1]) - resolve(response[2]) print last elif response[0] == '*': last = resolve(response[1]) * resolve(response[2]) print last elif response[0] == '/': last = resolve(response[1]) / resolve(response[2]) print last elif response[0] == 'pow': last = math.pow(resolve(response[1]), resolve(response[2])) print last # storing the last calculated value in a variable elif response[0] == 'store': variables[response[1]] = last print response[1], '=', last # clearing out all calculated values elif response[0] == 'clear': # we can use the empty dictionary method here because # the scope is correct. If we were doing this inside # of a function, we'd have to use some other method. variables = {} print 'Variables cleared.' # show all of the calculated values, printed pretty elif response[0] == 'showall': for key, value in variables.items(): print key, '=', value # the user has entered an operation we don't have else: print 'Unknown operation.'