基于列表与循环实现Python计算器触发TypeError报错排查
报错核心原因
range()的入参要求必须是整数,原代码将用户输入的num转为浮点数后直接传入range(num),浮点数无法作为序列生成的范围参数,因此触发TypeError: 'float' object cannot be interpreted as an integer。
除此之外代码还存在多处逻辑缺陷,就算解决当前报错也无法正常运行:
- 变量命名冲突:使用Python内置类型名
list作为自定义列表的变量名,会覆盖原生list类型的调用 - 数值存储逻辑错误:
list.append(numbers)语句写在for循环外部,循环中输入的所有数值只有最后一个会被存入列表 - 终止逻辑失效:循环变量
n是整数类型,永远不可能等于空字符串'',该判断无实际作用,且break会直接中断整个主交互流程 - 计算函数缺失:代码中调用的
add()/subtract()/divide()/multiply()四个核心函数未实现,会触发未定义错误 - 结构混乱:定义的
printIntro()函数从未被调用,操作提示的打印语句缩进位置错误,没有按逻辑封装在介绍流程中
修正后可运行的完整代码
import math def printIntro(): print("This is a simple calculator.") print("Select an operation:\n1) Add\n2) Subtract\n3) Divide\n4) Multiply") # 实现基础计算逻辑 def add(num_list): res = 0 for num in num_list: res += num return res def subtract(num_list): res = num_list[0] for num in num_list[1:]: res -= num return res def divide(num_list): res = num_list[0] for num in num_list[1:]: if num == 0: return "Error: Division by zero" res /= num return res def multiply(num_list): res = 1 for num in num_list: res *= num return res # 主交互流程 if __name__ == "__main__": printIntro() while True: operator = input("Enter your choice of + - / * (input other content to exit): \n").strip() if operator not in ('+', '-', '/', '*'): print("Exiting program...") break # 规避内置list命名冲突 num_list = [] try: count = int(input("Enter the number of values you want to calculate (integer): ")) if count <= 0: print("Please enter a positive integer for value count") continue for _ in range(count): num = float(input("Enter a number: ")) num_list.append(num) except ValueError: print("Invalid input, please enter an integer for value count") continue if operator == '+': print(f"Calculation result: {add(num_list)}") elif operator == '-': print(f"Calculation result: {subtract(num_list)}") elif operator == '/': print(f"Calculation result: {divide(num_list)}") elif operator == '*': print(f"Calculation result: {multiply(num_list)}")
内容的提问来源于stack exchange,提问作者Varioli
相关产品推荐
相关产品推荐

