简体   繁体   English

保存并显示python计算器的计算历史

[英]Save and display calculation history of the python calculator

I need to extend the given calculator program to record the calculations, and recall them as a list using an additional command '?'.我需要扩展给定的计算器程序以记录计算,并使用附加命令“?”将它们作为列表调用。

Things to do:要做的事情:

  1. Declare a list to store the previous operations声明一个列表来存储之前的操作
  2. Save the operator, operands, and the results as a single string, for each operation after each calculation将运算符、操作数和结果保存为单个字符串,用于每次计算后的每个操作
  3. implement a history() function to handle the operation '?'实现一个历史()函数来处理操作“?”
  4. Display the complete saved list of operations (in the order of execution) using a new command '?'使用新命令“?”显示完整保存的操作列表(按执行顺序)
  5. If there are no previous calculations when the history '?'如果历史时没有以前的计算'? command is used, you can display the following message "No past calculations to show"使用命令,您可以显示以下消息“没有过去的计算显示”

Can someone help me, please?有人能帮助我吗?

  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 == '#'):
    return -1
  elif (choice == '$'):
    return 0
  elif (choice in ('+','-','*','/','^','%')):
    while (True):
      num1s = str(input("Enter first number: "))
      print(num1s)
      if num1s.endswith('$'):
        return 0
      if num1s.endswith('#'):
        return -1
        
      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 0
      if num2s.endswith('#'):
        return -1
      try:  
        num2 = float(num2s)
        break
      except:
        print("Not a valid number,please enter again")
        continue
    

    if choice == '+':
      result = add(num1, num2)
    elif choice == '-':
      result = subtract(num1, num2)
    elif choice == '*':
      result = multiply(num1, num2)
    elif choice == '/':
      result =  divide(num1, num2)
    elif choice == '^':
      result = power(num1, num2)
    elif choice == '%':
      result = remainder(num1, num2)
    else:
      print("Something Went Wrong")
      
    
  else:
    print("Unrecognized operation")
    
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)
  if(select_op(choice) == -1):
    #program ends here
    print("Done. Terminating")
    exit()```

You need to declare function history() and list,您需要声明函数 history() 和列表,

last_calculation = []

def history():
  global last_calculation
  if last_calculation == []:
    print("No past calculations to show")
  else:
    for i in last_calculation:
        print(*i)  #for single line

Then in the if loop add below code to end of the operations,然后在 if 循环中添加以下代码到操作结束,

last_calculation.append(result)

Then trigger history() function, use 'continue' to make operation after the call history()然后触发history()函数,调用history()后使用'continue'进行操作

if choice=='?':
    history()
    continue

To save the history, you can add a global variable which is an empty list.要保存历史记录,您可以添加一个空列表的全局变量。 Like this:像这样:

history = []

...

def record_history(*args):
    history.append(args)


def select_op(choice):
    ...    
    record_history(choice, num1, num2, result)
    ...

This is not the most cleanest solution, but the simplest one since you are only using functions.不是最干净的解决方案,而是最简单的解决方案,因为您只使用函数。 Ideally functions should not have any side effects and should not depend on the "state" of the program.理想情况下,函数不应该有任何副作用,也不应该依赖于程序的“状态”。 To save any kind of "state" refactoring this implementation into classes would make things more clean.为了保存任何类型的“状态”,将此实现重构为类将使事情更干净。 Something like就像是

class Calculator:

    def __init__(self):
        self.history = []

    def record_history(self, *args):
        self.history.append(args)

    def select_op(self, choice):
        ...
        self.record_history(choice, num1, num2, result)
        ...

Tips提示

Make your life simpler by using the standard library使用标准库让您的生活更简单

  1. The operator library provides functions like add , sub , mul etc. operator库提供了addsubmul等函数。
  2. The cmd.Cmd class can be used to build interactive consoles easily. cmd.Cmd类可用于轻松构建交互式控制台。

strong text This is my answer to the problem you face.强文本这是我对您面临的问题的回答。 I have created this and checked it.我已经创建并检查了它。

calculations = []

def record_history(args):
    calculations.append(args)

def history():
    if calculations == []:
        print("No past calculations to show")
    else:
        for i in calculations:
            print(i)

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 == '#'):
    return -1
  elif (choice == '$'):
    return 0
  elif (choice in ('+','-','*','/','^','%')):
    while (True):
      num1s = str(input("Enter first number: "))
      print(num1s)
      if num1s.endswith('$'):
        return 0
      if num1s.endswith('#'):
        return -1
    
      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 0
      if num2s.endswith('#'):
        return -1
      try:  
        num2 = float(num2s)
        break
      except:
        print("Not a valid number,please enter again")
        continue

    result = 0.0
    last_calculation = ""

    if choice == '+':
      result = add(num1, num2)
    elif choice == '-':
      result = subtract(num1, num2)
    elif choice == '*':
      result = multiply(num1, num2)
    elif choice == '/':
      result =  divide(num1, num2)
    elif choice == '^':
      result = power(num1, num2)
    elif choice == '%':
      result = remainder(num1, num2)

    else:
      print("Something Went Wrong")
  
    last_calculation =  "{0} {1} {2} = {3}".format(num1, choice, num2, result) 
    print(last_calculation)
    record_history(last_calculation)

  elif choice == '?':
        history() 
      
  else:
    print("Unrecognized operation")

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)
  if(select_op(choice) == -1):
    #program ends here
    print("Done. Terminating")
    exit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM