2

I am trying to say that if it is not one of those operators then it should operate the if statement.

if item is ("(" , "+" , "*" , "/" , ")" , "–") == False:

is what I currently have, and it is not working. How should I write it to make it work?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

5 Answers5

3

You want to use the not in operator here:

if item not in ("(", "+", "*", "/", ")", "–"):

The is operator is used to test an object's identity. Below is a demonstration:

>>> 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
>>>
3

You want this:

if item not in ("(" , "+" , "*" , "/" , ")" , "–"):

Also:

  • You are using the is operator in a completely wrong way. NEVER EVER use it if you want to check if two things are "equal" as in "the same string/value/...". ONLY use it to test if two things are actually the same. The only case where you really need this as a beginner is to test if something is None (e.g. foo is None, foo is not None)
  • foo == True and foo == False are something you really don't want to use in Python. Simply use foo and not foo instead.
  • Please read (and follow!) the Python style guide (PEP8)!
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
3

While the answers posted so far are correct, they can be simpler.

if item not in "(+*/.)-": ...

Works just as well as the list versions. This works on the same principle as:

>>> x = "Hello, world"
>>> "Hello" in x
True
>>> "H" in x
True
>>> y = "+"
>>> y in "(+*/.)-"
True

The reason that this works is that strings are iterable, just like lists, so the in operator works as one would expect.

Zach Riggle
  • 2,975
  • 19
  • 26
0

Try if item not in ["(" , "+" , "*" , "/" , ")" , "–"]:

Jerry101
  • 12,157
  • 5
  • 44
  • 63
0

Try:

if item not in ["(" , "+" , "*" , "/" , ")" , "–"]:
    ...
    ...
    ...
else:
    ...

You can also make it shorter using a string:

if item not in "(+*/)–":
    ...
    ...
    ...
else:
    ...

But only if your item is a single character.