#---------------------------------------------------------------------- # Command processor, passing functions to functions # Copyright (C) April 24, 2019 -- Dr. William T. Verts #---------------------------------------------------------------------- import math #---------------------------------------------------------------------- # L is a list, FN is a function. Whatever function is passed in to FN, # that function is applied to every element of L. The try-except is # to protect against errors that would crash the program, such as # taking the square-root or logarithm of a negative number. #---------------------------------------------------------------------- def Process (L, FN): for I in range(len(L)): try: L[I] = FN(L[I]) except: L[I] = "ERROR" return #---------------------------------------------------------------------- # Main program. Things to notice: # Message is a variable where its string value spans several lines, # and gives the user a sense of what commands are legal. # MoretoDo is a bool that determines when to stop the while-loop, # set to False only when QUIT is entered. # Command.upper() returns the entered string capitalized. Must be # assigned back to Command. This is to allow the user # to enter any legal command in any case. # The command CUBERT and ABS aren't implemented yet, so their # actions are "pass" to make Python happy. We'll replace # them later with real code. # We can pass pre-existing functions to Process such as math.sqrt, # int, float, etc., or our own functions such as Double, # or anonymous lambda functions. # Neatness counts! #---------------------------------------------------------------------- def Double (N): return N * 2 def Main(): Message = """ QUIT CLEAR ADD ABS SQRT LOG INT FLOAT SQUARE CUBE NEGATE DOUBLE Enter a command --- """ L = [] MoreToDo = True while MoreToDo: print ("\n\n\n") print (L) Command = input(Message) Command = Command.upper() if (Command == "QUIT" ): MoreToDo = False elif (Command == "CLEAR" ): L = [] elif (Command == "ADD" ): L = L + [float(input("Enter a value to add --- "))] elif (Command == "ABS" ): pass elif (Command == "SQRT" ): Process(L, math.sqrt) elif (Command == "LOG" ): Process(L, math.log) elif (Command == "INT" ): Process(L, int) elif (Command == "FLOAT" ): Process(L, float) elif (Command == "SQUARE"): Process(L, lambda a : a*a) elif (Command == "CUBE" ): Process(L, lambda a : a*a*a) elif (Command == "NEGATE"): Process(L, lambda a : -a) elif (Command == "DOUBLE"): Process(L, Double) elif (Command == "CUBERT"): pass else: print ("Illegal Command") return