1

I have the following rather simple if statement in Python 3.3.4, it works as it is but surly it can be simplified:

if ans is '1':
    ans = int(ans)
    ans = (opt[ans])
elif ans is '2':
    ans = int(ans)
    ans = (opt[ans])
elif ans is '3':
    ans = int(ans)
    ans = (opt[ans])

I have tried various combinations of this:

if ans is '1' or '2' or '3':
    ans = int(ans)
    ans = (opt[ans])

or this,

if ans == '1' or '2' or '3':
    ans = int(ans)
    ans = (opt[ans])

or this,

if ans is ('1') or ('2') or ('3'):
    ans = int(ans)
    ans = (opt[ans])

I have even tried using dictionaries but most combinations will just allow through any string for 'ans'; am I being silly and missing something really simple or is this not possible? Thanks in advance.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    PLEASE, `is` is not the same as `==`. You should be using `==` in this case. You will almost never need to use `is`, please forget it exists. You will get results you cannot explain and do not expect if you continue to use `is` in place of `==`. – SethMMorton Jun 04 '14 at 18:16
  • Thank you for the warning, I am rather new to Python. What about 'in' or '!='? is this a similar situation? – George Burgess Jun 04 '14 at 19:18
  • No. There is no situation where you could replace `is` or `==` with `in`, so there is no chance of getting it confused with `is` or `==`. `!=` is just the logical opposite of `==`. – SethMMorton Jun 04 '14 at 20:03
  • No that's what I meant, should I use one or the other in a majority of cases, 'in' or '!='? I don't mean to replace '==' or 'is', I know they are the opposite. – George Burgess Jun 04 '14 at 22:44
  • I'm confused. `in` and `!=` mean totally different things. `in` means "is some thing inside this list/dict/tuple/container"? `!=` means "not equal". `==` means "equal". `is` means "the object IDs are equal". What I was trying to say is that there are 0 cases where it would be even syntactically valid to switch `in` for `!=` or vice versa, let alone logically valid. I don't understand the origin of your question. – SethMMorton Jun 04 '14 at 22:49
  • Also, `is` and `==` are not opposite... they do different things. – SethMMorton Jun 04 '14 at 22:52
  • Sorry for the confusion, you answered my very poorly worded question in the previous comment. Thanks – George Burgess Jun 05 '14 at 00:07

1 Answers1

1

Try:

if ans in ['1', '2', '3']
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60