自制Python计算器减法功能异常:始终执行加法请求帮助
你的计算器问题分析与修复方案
问题根源
- 判断逻辑用错运算符:你在
if语句里用了:=(赋值运算符),而不是==(比较运算符)。比如if mathematical_operation:= 'addition'会直接把变量强制赋值为'addition',不管你输入的是什么,所以永远只会执行加法代码块,减法的判断也犯了同样的错误。 - 冗余函数定义:你写了
addition和subtraction函数,但全程没调用,完全是多余的代码。 - 无效的print语句:比如
print("first")只是打印字符串"first",不是你输入的数值,属于无效输出。
修复后的代码
mathematical_operation = input("Choose your mathematical operation: ") if mathematical_operation == 'addition': first = float(input("first: ")) second = float(input("second: ")) sum_result = first + second print(f"sum: {sum_result}") elif mathematical_operation == 'subtraction': first = float(input("first: ")) second = float(input("second: ")) dif_result = first - second print(f"difference: {dif_result}") else: print("Unsupported operation")
修复说明
- 把
:=替换成==,正确判断用户选择的运算类型 - 用
elif替代第二个独立if,避免重复判断,同时增加else处理无效输入 - 输入时直接转成
float,减少冗余代码 - 用f-string格式化输出,更简洁易读
- 变量名
sum改成sum_result,避免和Python内置函数sum冲突 - 删除了没用的函数和无效print语句
内容的提问来源于stack exchange,提问作者Cemsu
相关产品推荐
相关产品推荐

