0

I'm trying to compare two strings e.g. if self.Ends == '101100' or '001101' . self.Ends is in a class to compare two 3D co-ordinates. it may hold 000100. There are eight if elif comparisons.

The program always returns an 'a' even self.Ends holds another 01 string.

if self.Ends == '100101' or '101100':
     P_line.Line = 'a'   

elif self.Ends == '000100' or '100000':
     P_line.Line = 'b'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • `'101100'` is a non-zero-length string and as such is always true. So is `'100000'`. Therefore both your `if` statements are always true. – kindall Feb 04 '14 at 22:59
  • Ordinarily I'm a big fan of language constructs that read like English, but this one trips up far too many people. – Mark Ransom Feb 04 '14 at 23:10

2 Answers2

5

You need to compare the string to self.Ends on both sides of the or. Otherwise it will always be true. ie. if 1: is the same as if 'a': They will both evaluate to True

  if self.Ends == '100101' or self.Ends == '101100':
         P_line.Line = 'a'   

   elif self.Ends == '000100' or self.Ends == '100000':
         P_line.Line = 'b'
jramirez
  • 8,537
  • 7
  • 33
  • 46
1

@jramirez answered the why, but this is an alternative approach to begin with.

This might be better than making all of those if, elif, else

>>> mapper = {'a': ('100101', '101100'), 'b': ('000100', '100000')}
>>> def get_line(bits, default='default'):
...     for k, v in mapper.items():
...         if bits in v:
...             return k
...     return default
...
>>> get_line('100101')
'a'
>>> get_line('000100')
'b'
>>> get_line('1', 'z')
'z'

So your code would look like

P_line.Line = get_line(self.Ends)

or with an optional default

P_line.Line = get_line(self.Ends, 'z')
sberry
  • 128,281
  • 18
  • 138
  • 165