# This program prompts for and evaluates a prefix expression. # Returns True if the given string can be converted # into a float successfully, or False if not. def is_float(s): try: n = float(s) return True except ValueError: return False # pre : operator is one of +, -, *, /, or % # post: returns the result of applying the given operator # to the given operands def apply(operator, operand1, operand2): if operator == "+": return operand1 + operand2 elif operator == "-": return operand1 - operand2 elif operator == "*": return operand1 * operand2 elif operator == "/": return operand1 / operand2 elif operator == "%": return operand1 % operand2 else: raise ValueError("bad operator: " + operator) # pre : tokens represent a legal prefix expression # post: expression is evaluated and the result is returned def evaluate(tokens): # extract first token first = tokens.pop(0) if is_float(first): # base case: a numeric token return float(first) else: # recursive case: an operator operand1 = evaluate(tokens) operand2 = evaluate(tokens) return apply(first, operand1, operand2) def main(): print("This program evaluates prefix expressions that") print("include the operators +, -, *, /, and %.") print() expr = input("Expression? ") while expr != "": tokens = expr.split(" ") value = evaluate(tokens) print("value =", round(value, 2)) expr = input("Expression? ") print("Exiting.") main()