1

Is there a way to do effectively do:

if operator != ('+' or '-' or '*' or '/'):

without having to do

operator != '+' and operator != '-' and operator != '*'
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
taytay
  • 59
  • 7

2 Answers2

5

use the in operator

if operator not in ('+', '-', '/')
srj
  • 9,591
  • 2
  • 23
  • 27
  • ..and [`operator not in {'+', '-', '/'}` in Python 3.2+](https://docs.python.org/3/whatsnew/3.2.html#optimizations) – Ashwini Chaudhary Oct 07 '14 at 21:08
  • @AshwiniChaudhary -- Ooo ... I didn't realize that the python3.2 optimizer was that smart. That's fantastic. – mgilson Oct 07 '14 at 21:16
  • Works with python 2 as well https://docs.python.org/2/reference/expressions.html#set-displays – srj Oct 07 '14 at 21:22
  • @srj It is not about how sets are displayed, it is about the optimization done by [peephole.c](https://github.com/python/cpython/blob/master/Python/peephole.c#L84) in Python 3.2+ when it sees set literals being used with `in` and `not in` operators. See [issue 6690](http://bugs.python.org/issue6690) for details. – Ashwini Chaudhary Oct 07 '14 at 21:34
0

Effective to read solution would be: if operator in ('+', '-', '*', '/') or simply if operator in '+-*/' (thanks @kindall) which is like looking for a char in a string. I personally find it less readable though.

Otherwize you use a dictionnary (for instance, to bind a function to each operator) and just use exceptions:

ops = {'+': 'plus', '-': 'minus', '*': 'times', '/': 'div'}
operator = '/'
try:
  print ops[operator]
except KeyError:
  print "Unknow operation (%s)" % (operator)
Aif
  • 11,015
  • 1
  • 30
  • 44