使用另一个变量的输出更新一个变量

青葱年少 python 210

原文标题updating a variable using using the output from another variable

每当完成新计算时,我都会尝试将“next_answer”的值添加到 current_answer,但是当我运行代码时,next_answer 不会添加到 current_answer。我是否错误地定位了“current_answer += next_answer”?请帮我:)

#calculator
#Add
def add(n1, n2):
  return n1 + n2
#subtract
def subtract(n1, n2):
  return n1 - n2

#multiply
def multiply(n1, n2):
  return n1 * n2

#divide
def divide(n1, n2):
  return n1 / n2

operations = {
  "+": add,
  "-": subtract,
  "*":multiply,
  "/":divide,
}

num1 = int(input("What is the first number?: "))


for operation in operations:
  print(operation)
select_operator = input("Which operator do you want? Type +, - * or /")
num2 = int(input("What is the next number?: "))

operation_function = operations[select_operator]
answer = operation_function(num1, num2)
print(f"{num1} {select_operator} {num2} = {answer}")

continue_ = True
while continue_:
  current_answer = answer
  next_calculation = input(f"Type 'y' to continue calculating with                                 
{current_answer} or type 'n' to exit.:")
  if next_calculation == "y":
    select_operator = input("Which operator do you want? Type +, - * or /")
    next_number = int(input("What is the next number?:"))
    operation_function = operations[select_operator]
    next_answer = int(operation_function(current_answer, next_number))
    print(f"{current_answer} {select_operator} {next_number} = {next_answer}")
    current_answer += next_answer
  elif next_calculation == "n":
    continue_ = False
    print("Thanks for using my calculator")

原文链接:https://stackoverflow.com//questions/71476330/updating-a-variable-using-using-the-output-from-another-variable

回复

我来回复
  • MohamedAly8的头像
    MohamedAly8 评论

    请注意,每次执行while循环时,您将current_answer设置为answer,这是第一个答案。因此,您正在覆盖对第一个计算的更新。

    见行current_answer = answer

    2年前 0条评论
  • maya的头像
    maya 评论

    部分内容已经简化,请酌情参考:

    operations = {"+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y}
    
    
    select_operator = input("Which operator do you want? Type: +, - * or /:")
    num1 = int(input("What is the first number?: "))
    num2 = int(input("What is the next number?: "))
    
    answer = operations[select_operator](num1, num2)
    print(f"{num1} {select_operator} {num2} = {answer}\n")
    
    while True:
        next_calculation = input(f"Type 'y' to continue calculating with {answer} or type 'n' to exit.:")
        if next_calculation == "y":
            preview_answer = answer
            select_operator = input("Which operator do you want? Type: +, - * or /:")
            next_number = int(input("What is the next number?:"))
            answer = operations[select_operator](answer, next_number)
            print(f"{preview_answer} {select_operator} {next_number} = {answer}")
        else:
            print("Thanks for using my calculator")
            exit()
        print()
    
    2年前 0条评论