保存和显示Python计算器的计算历史记录

发布于 2025-01-31 19:24:30 字数 2283 浏览 4 评论 0原文

我需要扩展给定的计算程序以记录计算,并使用附加命令'?

要做的事情:

  1. 声明列表以存储以前的操作,
  2. 将操作员,操作数和结果保存为单个字符串,每个操作后,每个操作都在每个计算后
  3. 实现一个历史记录()函数来处理操作'?'
  4. 使用新命令“?”显示完整保存的操作列表(按执行顺序)显示
  5. 如果历史记录时没有以前的计算?使用命令,您可以显示以下消息“没有过去的计算”

有人可以帮助我吗?

  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()```

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()```

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尐籹人 2025-02-07 19:24:30

您需要声明函数历史记录()和列表,

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

然后在if循环中添加以下代码到操作的末尾,

last_calculation.append(result)

然后触发histort()函数,使用“继续”以在呼叫历史记录之后进行操作()

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

You need to declare function history() and list,

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,

last_calculation.append(result)

Then trigger history() function, use 'continue' to make operation after the call history()

if choice=='?':
    history()
    continue
以酷 2025-02-07 19:24:30

为了保存历史记录,您可以添加一个全列表的全局变量。这样:

history = []

...

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


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

这不是不是最干净的解决方案,而是最简单的解决方案,因为您仅使用功能。理想情况下,功能不应具有任何副作用,不应取决于程序的“状态”。为了保存任何类型的“状态”将此实现重构为类,将使事情变得更加干净。 诸如

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)
        ...

提示

通过使用标准库使您的生活更简单

  1. 操作员库提供了addsubmul等。
  2. cmd.cmd类可用于轻松构建交互式控制台。

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.
  2. The cmd.Cmd class can be used to build interactive consoles easily.
静谧幽蓝 2025-02-07 19:24:30

这是我对您面临的问题的回答。我创建了这个并检查了它。

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 = 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 = 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")
        break

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 = 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 = 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")
        break
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文