我是 python 的初学者,所以我想通过使用列表来创建 python 计算器(有历史)。但是当我尝试这样做时,当我检查历史记录时总是给我“没有过去的计算可以显示”
如何根据我的要求修改以下代码?
def add(a,b): return a+b def subtract(a,b): return a-b def multiply (a,b): return a*b def divide(a,b): try: return a/b except Exception as e: print(e) def power(a,b): return a**b def remainder(a,b): return a%b def select_op(choice): if (choice == '#'): print("Done. Terminating") exit() elif (choice == '$'): return main() elif (choice in ('+','-','*','/','^','%','?')): while (True): num1s = str(input("Enter first number: ")) print(num1s) if num1s.endswith('$'): return main() if num1s.endswith('#'): print("Done. Terminating") exit() try: num1 = float(num1s) break except: print("Not a valid number,please enter again") continue while (True): num2s = str(input("Enter second number: ")) print(num2s) if num2s.endswith('$'): return main() if num2s.endswith('#'): print("Done. Terminating") exit() try: num2 = float(num2s) break except: print("Not a valid number,please enter again") continue last_calculation_1=last_calculation_2=last_calculation_3=last_calculation_4=last_calculation_5=last_calculation_6=[] if choice == '+': result = add(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) last_calculation_1.append(msg) elif choice == '-': result = subtract(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) last_calculation_2.append(msg) elif choice == '*': result = multiply(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) last_calculation_3.append(msg) elif choice == '/': result = divide(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) last_calculation_4.append(msg) elif choice == '^': result = power(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) last_calculation_5.append(msg) elif choice == '%': result = remainder(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) last_calculation_6.append(msg) elif choice=='?': last_calculation=last_calculation_1+last_calculation_2+last_calculation_3+last_calculation_4+last_calculation_5+last_calculation_6 # x=[str(i) for i in last_calculation] if len(last_calculation) ==0: print("No past calculations to show") else: b="\n".join(last_calculation) print(b) else: print("Something Went Wrong") else: print("Unrecognized operation") return main() def main(): while True: print("Select operation.") print("1.Add : + ") print("2.Subtract : - ") print("3.Multiply : * ") print("4.Divide : / ") print("5.Power : ^ ") print("6.Remainder: % ") print("7.Terminate: # ") print("8.Reset : $ ") print("8.History : ? ") # take input from the user choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ") print(choice) select_op(choice) main()
任务 1:声明一个列表来存储以前的操作 将操作符、操作数和结果保存为单个字符串,用于每次计算后的每个操作
任务 2:实现一个 history() 函数来处理操作“?” 使用新命令“?”显示完整保存的操作列表(按执行顺序)如果历史时没有以前的计算’?使用命令,您可以显示以下消息“没有过去的计算显示”
一种方法是删除所有last_calculation列表并坚持一个列表来调用历史记录history并在主函数中对其进行初始化,然后将其作为参数传递给select_op函数,因此可以在每次后续调用时对其进行更新. history如果?是输入,则设置逻辑以打印列表的内容。例如:
last_calculation
history
select_op
?
def add(a,b): return a+b def subtract(a,b): return a-b def multiply (a,b): return a*b def divide(a,b): try: return a/b except Exception as e: print(e) def power(a,b): return a**b def remainder(a,b): return a%b def select_op(choice, history): if (choice == '#'): print("Done. Terminating") exit() elif (choice == '$'): return main() elif (choice in ('+','-','*','/','^','%')): while (True): num1s = str(input("Enter first number: ")) print(num1s) if num1s.endswith('$'): return main() if num1s.endswith('#'): print("Done. Terminating") exit() try: num1 = float(num1s) break except: print("Not a valid number,please enter again") continue while (True): num2s = str(input("Enter second number: ")) print(num2s) if num2s.endswith('$'): return main() if num2s.endswith('#'): print("Done. Terminating") exit() try: num2 = float(num2s) break except: print("Not a valid number,please enter again") continue if choice == '+': result = add(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) history.append(msg) elif choice == '-': result = subtract(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) history.append(msg) elif choice == '*': result = multiply(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) history.append(msg) elif choice == '/': result = divide(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) history.append(msg) elif choice == '^': result = power(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) history.append(msg) elif choice == '%': result = remainder(num1, num2) msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result)) print(msg) history.append(msg) else: print("Something Went Wrong") elif choice=='?': if len(history) ==0: print("No past calculations to show") else: b="\n".join(history) print(b) else: print("Unrecognized operation") return main() def main(): history = [] while True: print("Select operation.") print("1.Add : + ") print("2.Subtract : - ") print("3.Multiply : * ") print("4.Divide : / ") print("5.Power : ^ ") print("6.Remainder: % ") print("7.Terminate: # ") print("8.Reset : $ ") print("8.History : ? ") # take input from the user choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ") print(choice) select_op(choice, history) main()
还可以对您的代码进行大量进一步的优化,例如创建一个字典来保存运算符及其相应的函数,您还可以使用另一个循环来选择数字以减少重复代码的数量。
这是与上面相同的解决方案,但针对可读性和更少的代码重复进行了优化。
def add(a,b): return a+b def subtract(a,b): return a-b def multiply (a,b): return a*b def divide(a,b): try: return a/b except Exception as e: print(e) def power(a,b): return a**b def remainder(a,b): return a%b def select_op(choice, history): if (choice == '#'): print("Done. Terminating") exit() elif (choice == '$'): return main() elif (choice in ('+','-','*','/','^','%')): nums = [] for _ in range(2): while (True): numstr = str(input("Enter first number: ")) print(numstr) if numstr.endswith('$'): return main() if numstr.endswith('#'): print("Done. Terminating") exit() try: num = float(numstr) nums.append(num) break except: print("Not a valid number,please enter again") continue funcmap = { "+": add, "-": subtract, "*": multiply, "/": divide, "^": power, "%": remainder } if choice in funcmap: num1,num2 = nums result = funcmap[choice](num1, num2) msg = "{0} {1} {2} = {3}".format(num1, choice, num2, result) print(msg) history.append(msg) else: print("Something Went Wrong") elif choice=='?': if len(history) ==0: print("No past calculations to show") else: b="\n".join(history) print(b) else: print("Unrecognized operation") return main() def main(): history = [] while True: print("Select operation.") print("1.Add : + ") print("2.Subtract : - ") print("3.Multiply : * ") print("4.Divide : / ") print("5.Power : ^ ") print("6.Remainder: % ") print("7.Terminate: # ") print("8.Reset : $ ") print("8.History : ? ") # take input from the user choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ") print(choice) select_op(choice, history) main()