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

自制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")

修复说明

  1. 把:=替换成==,正确判断用户选择的运算类型
  2. 用elif替代第二个独立if,避免重复判断,同时增加else处理无效输入
  3. 输入时直接转成float,减少冗余代码
  4. 用f-string格式化输出,更简洁易读
  5. 变量名sum改成sum_result,避免和Python内置函数sum冲突
  6. 删除了没用的函数和无效print语句

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:15:49