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

Python基础计算器问题:if与or联用仅执行加法功能

问题分析

你的代码核心问题出在条件判断的逻辑表达式错误。在Python中,or运算符需要连接两个完整的布尔判断,而你写的if equation_type == "add" or "addition"等价于if (equation_type == "add") or True——非空字符串在布尔判断中会被视为True,所以这个条件永远成立,程序只会执行加法分支,不会进入后续的elif。

修正方案

有两种简洁的修复方式:

方式一:补全完整比较表达式

给每个or两侧都补上完整的变量比较逻辑:

equation_type = input("What kind of math do you want to do? ")
equation_type = equation_type.lower()

first_number = float(input("What is the first number? "))
second_number = float(input("What is the 2nd number? "))

if equation_type == "add" or equation_type == "addition":
        result = first_number + second_number
elif equation_type == "subtract" or equation_type == "subtraction":
        result = first_number - second_number
elif equation_type == "multiply" or equation_type == "multiplication":
        result = first_number * second_number
elif equation_type == "divide" or equation_type == "division":
        result = first_number / second_number
else:
        print("not a valid entry :/")
        result = None
if result is not None:
    print(result)

方式二:用in操作符简化判断

把每个运算的可选关键词放到列表中,用in判断变量是否属于该列表,代码更简洁:

equation_type = input("What kind of math do you want to do? ")
equation_type = equation_type.lower()

first_number = float(input("What is the first number? "))
second_number = float(input("What is the 2nd number? "))

if equation_type in ["add", "addition"]:
        result = first_number + second_number
elif equation_type in ["subtract", "subtraction"]:
        result = first_number - second_number
elif equation_type in ["multiply", "multiplication"]:
        result = first_number * second_number
elif equation_type in ["divide", "division"]:
        result = first_number / second_number
else:
        print("not a valid entry :/")
        result = None
if result is not None:
    print(result)

额外优化说明

当输入无效时,原代码直接打印result会触发未定义报错,所以在else分支给result赋值为None,最后判断非空再打印,避免程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:55:23