Python新手求助:计算器代码触发NameError变量未定义错误
解决Python计算器代码的NameError问题
错误原因
当输入numbercount=3时,代码前半段的条件判断仅在numbercount==2时会给mathtype赋值,而numbercount==3的mathtype赋值逻辑在后续位置,导致程序执行到if mathtype ==1语句时,mathtype变量尚未定义,触发NameError: name 'mathtype' is not defined。
修复后的代码
print("Calculator!!!") loop = 1 # basic inputs numbercount = int(input("How many numbers are you doing math with? max is 3: ")) while loop == 1: if numbercount == 1: print("minimum numbers are 2") elif numbercount == 2: mathtype = int(input("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n")) if mathtype == 1: print("format as\na = [number]\nb = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = a + b print("Your answer is: ", c) elif mathtype == 2: print("format as\na = [number]\nb = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = a - b print("Your answer is: ", c) elif mathtype == 3: print("format as\na = [number]\nb = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = a * b print("Your answer is: ", c) elif mathtype == 4: print("format as\na = [number]\nb = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = a / b print("Your answer is: ", c) else: print("Invalid choice, try again") elif numbercount == 3: mathtype = int(input("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n")) if mathtype == 1: print("format as\na = [number]\nb = [number]\nc = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) d = a + b + c print("Your answer is: ", d) elif mathtype == 2: print("format as\na = [number]\nb = [number]\nc = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) d = a - b - c print("Your answer is: ", d) elif mathtype == 3: print("format as\na = [number]\nb = [number]\nc = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) d = a * b * c print("Your answer is: ", d) elif mathtype == 4: print("format as\na = [number]\nb = [number]\nc = [number]\n") a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) d = a / b / c print("Your answer is: ", d) else: print("Invalid choice, try again") else: print("Max numbers is 3") # 添加退出循环选项,避免无限循环 continue_loop = input("Do you want to calculate again? (y/n): ").lower() if continue_loop != 'y': loop = 0
额外修复点
- 修正拼写错误:
awnser改为answer,Multiplcation改为Multiplication - 修复3个数计算时的输出错误:原本输出输入变量
c,改为输出计算结果d - 添加循环终止逻辑,避免程序无限运行
- 调整代码缩进,让不同
numbercount的逻辑块完全分离,避免交叉执行问题
内容的提问来源于stack exchange,提问作者Yodeling_Tornado
相关产品推荐
相关产品推荐

