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

Python条件语句失效求助:选择乘法却执行加法运算

问题分析与解决方案
  • 核心错误:逻辑判断写法错误
    你写的if operation == "add" or "Add"并不是判断operation等于"add"或者"Add",Python会把它解析成(operation == "add") or "Add"。非空字符串在布尔判断里是True,所以这个条件永远成立——不管你输入什么操作,都会执行加法分支。同理,elif里的operation == "multiply" or "Muptiply"不仅有逻辑判断错误,还把"Multiply"拼写成了"Muptiply",双重错误导致乘法分支永远不会触发。

  • 两种正确的修正写法

    1. 明确对每个选项做相等判断:
      if operation == "add" or operation == "Add":
      
    2. 统一转换为小写(或大写)后判断,更简洁且容错性更强(比如用户输入"ADD"也能识别):
      if operation.lower() == "add":
      
  • 修正后的完整代码
    优化后的代码同时修复了拼写错误、逻辑问题,还调整了格式和可读性:

    input("Welcome to this calculator, press ENTER to continue")
    
    operation = input("Type one : Add  Subtract  Multiply  Divide   ")
    first_number = input(f"Type the first number you want to {operation}   ")
    second_number = input("Type the second number   ")
    
    if operation.lower() == "add":
        final_number = int(first_number) + int(second_number)
        new_operation = "adding "
    elif operation.lower() == "multiply":
        final_number = int(first_number) * int(second_number)
        new_operation = "multiplying "
    else:
        print("Not Yet Implemented")
        exit()  # 避免后续print因new_operation未定义报错
    
    print(f"Your result of {new_operation}{first_number} to {second_number} was {final_number}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:28:01