我使用 Python 制作了一个非常基本的脚本(我是新手),我不知道为什么它不能正常工作

I made a really basic script using Python (I am new at it) and i don't know why it is not working as it should work

问题出在第19行,if条件所在

因此,当您 运行 代码时,它应该要求您输入第一个数字,然后是数学运算(+、加或 -、减),最后是第二个数字。

当你加(加)时它工作得很好,但是当你试图减时它会显示消息"Invalid Operation",我已经尝试过使用其他逻辑运算符但它就是不行工作 D:

请解释一下问题出在哪里,因为我看不到它。

minus = ["-","minus"]
plus = ["+", "plus"]

print("""
    ===========================
            CALCULATOR
    ===========================

    1      2      3      +
    4      5      6      -
    7      8      9

    0      Total:
    ===========================
    ===========================
    """)
n1 = int(input("First Number: "))
operation = input("+ or - ")
if operation not in (minus,plus):
    print("Invalid Operation")
else:

    n2 = int(input("Second Number: "))

    if operation in minus:
        total_minus = n1-n2
        print(f"""
    ===========================
            CALCULATOR
    ===========================

    1      2      3      +
    4      5      6      -
    7      8      9

    0      Total: {total_minus}
    ===========================
    ===========================
        """)
    elif operation in plus:
        total_plus = n1 + n2
        print(f"""
    ===========================
            CALCULATOR
    ===========================

    1      2      3      +
    4      5      6      -
    7      8      9

    0      Total: {total_plus}
    ===========================
    ===========================
        """)



您正在通过形成元组来加入列表:

if operation not in (minus, plus):

您真正想要做的是将列表加在一起:

if operation not in minus + plus:

operation not in (minus,plus) 永远是真的。 operation 是一个字符串,(minus,plus) 是一个包含两个列表的元组。

如果要测试字符串 operation 是否在 minus 列表或 plus 列表中,您可以改用:

if operation not in (minus + plus):

对我来说,您的代码不适用于 + 或 -! 我不知道为什么它对你有用 + 因为我认为它不应该!

您说得对,问题出在您的 if 语句上。 当你写:

if operation not in (minus,plus):

您说的是 "if operation does not equal ["-", "minus"] 或 ["+", "plus"] "

换句话说,您正在将用户的输入与 2 个字符串的列表进行比较!

您可以改写:

if operation not in minus and operation not in plus:

你的程序将运行良好

表达式 operation not in (minus,plus) 正在测试 operation 是否是元组 (minus, plus) 中的列表 minusplus 之一。因为它是一个字符串,所以它永远不会是这些值中的任何一个。

我建议创建一个有效操作的组合列表。

valid_operations = minus + plus # concatenate valid operations

然后测试用户输入的操作是否在该列表中。

if operation not in valid_operations:
    print("Invalid Operation")
else:
    ...

这样可以轻松地将计算器扩展到乘法、除法等

只需更改 if 代码块

if operation in plus or operation in minus:
    your code
else:
    print("Invalid Operation")

您写道:

if operation not in (minus,plus):
    your code

这将永远是 True,因为 operation 永远不会同时出现在两个列表(加号和减号)中,所以该语句是 False,并且由于你写了 'not in',not of False 是 True,这就是你总是在你的 if 块中得到 "Invalid Operation" 的原因。