1

I have the following function, and PyCharm is alerting me on the elif statements about "simplify chained comparison". The code works and I am getting the object I want, just wondering about the warning and how I can make it better?

     def preferred_contacts(self):
         x = random.randint(0, 100)
         email = u'E'
         text = u'M'
         phone = u'P'
         letter = u'L'
         none = u'N'

         if x < 25:
            return email
         elif x >= 26 and x <= 50:
            return text
         elif x >= 51 and x <= 75:
            return phone
         elif x >= 76 and x <= 100:
            return letter
         else:
            return none
Lesmana
  • 25,663
  • 9
  • 82
  • 87
DarthOpto
  • 1,640
  • 7
  • 32
  • 59
  • 4
    You could certainly remove all of the `x >=` comparisons, since by virtue of reaching `elif` it's already been shown to not match the earlier conditions – mhlester Feb 27 '14 at 18:27
  • 1
    Also, you'll be glad to learn that : `elif 76 <= x <= 100:` would you what you expect it to do. – SylvainD Feb 27 '14 at 18:29
  • 2
    Really you don't need the `and` ops either; `elif 26 <= x <= 50` and so on... – Drewness Feb 27 '14 at 18:35
  • 2
    Also, this will never return `none`, as you've bounded `x` at 100, and 100 will return `letter`. – Silas Ray Feb 27 '14 at 18:39
  • Thank you all for your suggestions. – DarthOpto Feb 27 '14 at 20:23
  • 2
    Possible duplicate of [PyCharm: "Simplify Chained Comparison"](https://stackoverflow.com/questions/26502775/pycharm-simplify-chained-comparison) – Lesmana Dec 10 '17 at 14:35

2 Answers2

1

@mhlester should get the credit for noting that you can drop the >= clauses from the conditions as they are already implicit since you are using elif. However, you could also condense things more if you wanted by putting your data in a tuple then indexing in to it.

return ('E', 'M', 'P', 'L', 'N')[x / 25] # This assumes x has an upper bound of 124 or less.

Of course, in this particular instance, you could make your life even simpler.

return random.choice(('E', 'M', 'P', 'L', 'N'))
Silas Ray
  • 25,682
  • 5
  • 48
  • 63
1

Simplified chained calls for much cleaner code. See below

def preferred_contacts(self):
x = random.randint(0, 100)
email = u'E'
text = u'M'
phone = u'P'
letter = u'L'
none = u'N'

if x < 25:
    return email
elif 26 <= x <= 50: # reads as "x is between 26 and 50, inclusive
    return text
elif 51 <= x <= 75: # reads as "x is between 51 and 75, inclusive
    return phone
elif 76 <= x <= 100: # reads as "x is between 76 and 100, inclusive
    return letter
else:
    return none