我想说的是,如果它不是那些运算符之一,那么它应该运行if
语句。
if item is ("(" , "+" , "*" , "/" , ")" , "–") == False:
是我现在拥有的,但它无法正常工作。我应该如何写它才能使它有效?
答案 0 :(得分:4)
你想要这个:
if item not in ("(" , "+" , "*" , "/" , ")" , "–"):
此外:
is
运算符。永远不要使用它,如果你想检查两个东西是否“相同”,如“相同的字符串/值/ ...”。只用它来测试两件事实际上是否相同。作为初学者,您真正需要这个的唯一情况是测试某些内容是None
(例如foo is None
,foo is not None
)foo == True
和foo == False
是您真正不想在Python中使用的内容。只需使用foo
和not foo
代替。答案 1 :(得分:3)
您想在此处使用not in
运算符:
if item not in ("(", "+", "*", "/", ")", "–"):
is
运算符用于测试对象的标识。以下是演示:
>>> class Foo:
... pass
...
>>> f1 = Foo() # An instance of class Foo
>>> f2 = Foo() # A different instance of class Foo
>>> f3 = f1 # f3 refers to the same instance of class Foo as f1
>>> f1 is f3
True
>>> f1 is f2
False
>>>
答案 2 :(得分:3)
虽然到目前为止发布的答案是正确的,但它们可以更简单。
if item not in "(+*/.)-": ...
与列表版本一样有效。这与以下原则相同:
>>> x = "Hello, world"
>>> "Hello" in x
True
>>> "H" in x
True
>>> y = "+"
>>> y in "(+*/.)-"
True
这样做的原因是字符串是可迭代的,就像列表一样,因此in
运算符可以像预期的那样工作。
答案 3 :(得分:0)
尝试if item not in ["(" , "+" , "*" , "/" , ")" , "–"]:
答案 4 :(得分:0)
尝试:
if item not in ["(" , "+" , "*" , "/" , ")" , "–"]:
...
...
...
else:
...
你也可以使用字符串缩短它:
if item not in "(+*/)–":
...
...
...
else:
...
但前提是您的商品是单个字符。