You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python简易计算器故障:所有运算均返回最后输入数字,求问题排查

计算器程序运算结果异常问题分析

编写的计算器程序无论选择哪种运算操作,执行计算时都会返回最后输入的数字,代码如下:

from time import sleep

# Find function wanted by user
while True:
    operation = input("Would you like to Add, Subtract, Multiply, or Divide(A, S, M, D)? ")
    if operation.upper() in ["A", "S", "M", "D"]:
        break
    else: 
        print("Please only enter A, S, M, or D.")
        sleep(1)

# Find amount of numbers user wants to use
while True:
    amount_of_numbers = (input("How many numbers would you like to use(2-5)? "))
    if amount_of_numbers.isdigit():
        amount_of_numbers = int(amount_of_numbers)
        if 2 <= amount_of_numbers <= 5:
            break
        else:
            print("The amount of numbers must be between 2 and 5.")
            sleep(1)
    else:
        print("Please enter a whole number without anything else added.")
        sleep(1)


# Get the numbers
while amount_of_numbers > 0:
    total = [0]
    chosen_number = input("Type a number. ")
    def isnumber(chosen_number):
        
        try:
            float(chosen_number)
            return True
        except ValueError:
            return False
    
    if isnumber(chosen_number):
        total.append(float(chosen_number))
        amount_of_numbers -= 1
    else:
        print ("Please enter a number.")
        sleep(1)
# Remove placeholder from list
total.remove(0)

#? This part is failing, maybe has to do with very top?
from math import prod 
if operation.upper() == "A":
    result = sum(total)
    print(f"The sum is {result:.2f}.")
elif operation.upper() == "S":
    result = total[0] - sum(total[1:])
    print(f"The difference is {result:.2f}.")
elif operation.upper() == "M":
    result = prod(total)
    print(f"The product is {result:.2f}.")
elif operation.upper() == "D":
    divider = prod(total[1:])
    result = total[0] / divider
    print(f"The quotient is {result:.2f}.")

问题根源

核心错误出在获取数字的while循环内部:每次循环都会执行total = [0],这会把之前输入的数字全部清空,重新初始化列表。比如输入3个数字时,第一次循环添加第一个数字后,第二次循环又将total重置为[0],再添加第二个数字,第三次循环重复此操作,最终total列表里只会保留最后一次输入的数字。后续所有运算基于这个单元素列表,结果自然就是最后输入的数字。

另外,isnumber函数定义在循环内部会导致每次循环都重新定义函数,虽然不影响功能,但属于不良编码习惯。

修正方案

  1. 将total = [0]移到while循环外面,确保列表只会初始化一次,后续输入的数字都追加到同一个列表中。
  2. 将isnumber函数移到循环外部,避免重复定义。

修正后的代码

from time import sleep
from math import prod 

# 定义数字验证函数,放在循环外部
def isnumber(chosen_number):
    try:
        float(chosen_number)
        return True
    except ValueError:
        return False

# Find function wanted by user
while True:
    operation = input("Would you like to Add, Subtract, Multiply, or Divide(A, S, M, D)? ")
    if operation.upper() in ["A", "S", "M", "D"]:
        break
    else: 
        print("Please only enter A, S, M, or D.")
        sleep(1)

# Find amount of numbers user wants to use
while True:
    amount_of_numbers = (input("How many numbers would you like to use(2-5)? "))
    if amount_of_numbers.isdigit():
        amount_of_numbers = int(amount_of_numbers)
        if 2 <= amount_of_numbers <= 5:
            break
        else:
            print("The amount of numbers must be between 2 and 5.")
            sleep(1)
    else:
        print("Please enter a whole number without anything else added.")
        sleep(1)

# Get the numbers
total = [0]  # 移到循环外部,只初始化一次
while amount_of_numbers > 0:
    chosen_number = input("Type a number. ")
    if isnumber(chosen_number):
        total.append(float(chosen_number))
        amount_of_numbers -= 1
    else:
        print ("Please enter a number.")
        sleep(1)

# Remove placeholder from list
total.remove(0)

# 执行运算
if operation.upper() == "A":
    result = sum(total)
    print(f"The sum is {result:.2f}.")
elif operation.upper() == "S":
    result = total[0] - sum(total[1:])
    print(f"The difference is {result:.2f}.")
elif operation.upper() == "M":
    result = prod(total)
    print(f"The product is {result:.2f}.")
elif operation.upper() == "D":
    divider = prod(total[1:])
    result = total[0] / divider
    print(f"The quotient is {result:.2f}.")

内容的提问来源于stack exchange,提问作者user25395407

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 20:05:53