0

I have some code that I want to return 'right' if the first two characters in the argument are CH, DL or PR:

def validation_check(trans):
    #Make sure the transaction is in proper format
    r = re.compile('.. .. ......')
    if r.match(trans) is None:
        f = open("validation.errors.log", "a")
        f.write(trans+'-Improper format' '\n')
        f.close()
    elif trans[0:1] != 'CH' or 'DL' or 'PR':
        f = open("validation.errors.log", "a")
        f.write(trans+ "-Invalid action" '\n')
        f.close()
        return "That is not a valid action!"
    else:
        return "right"

print (validation_check('CH SE NST231 072 00/01/23'))

But for some reason it keep executing the elif statement. Why is this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Amon
  • 2,725
  • 5
  • 30
  • 52
  • Thanks for the fast response, I tried `elif trans[0:1] != 'CH' or trans[0:1] != 'DL' or trans[0:1] != 'PR':` But it still doesnt seem to work – Amon Feb 22 '14 at 02:11
  • 1
    It should be `and`, not `or`. – Barmar Feb 22 '14 at 02:12
  • @Amon -- you made two mistakes there: `or` instead of `and` (as Barmar wrote) and only selecting the first character of `trans` instead of two (as zhangxaochen and I said). – Michael Lorton Feb 22 '14 at 02:18
  • @Malvolio Alright thanks, Ill be sure to drill this into my head – Amon Feb 22 '14 at 02:22

2 Answers2

2
In [507]: trans='CHasdf'

In [508]: trans[0:1] != 'CH' #you should use [0:2]
Out[508]: True

In [509]: trans[0:2]
Out[509]: 'CH'

#and "x!= 1 or 2" is not what you want:
In [525]: trans[0:2] != 'CH' or 'DL' or 'PR'
Out[525]: 'DL'

#it evaluates "!=" first, then "or"
In [526]: (trans[0:2] != 'CH') or 'DL' or 'PR'
Out[526]: 'DL'

#use "not in a_list_of_your_candidates":
In [527]: trans[0:2] not in ('CH', 'DL', 'PR')
Out[527]: False
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
1
if 3 == 4 or 5:
   print 'true'

prints 'true'

Why? Because either "3 equals 4" or "5 is truthy".

You want

elif trans[0:2] not in ('CH' , 'DL' , 'PR'):

(NB: it is [0:2] "the substring starting at index 0 and _continuing for two characters" -- not "until index 1" as you seem to think.)

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144