complex if statement in python

Question:

I need to realize a complex if-elif-else statement in Python but I don’t get it working.

The elif line I need has to check a variable for this conditions:

80, 443 or 1024-65535 inclusive

I tried

if
  ...
  # several checks
  ...
elif (var1 > 65535) or ((var1 < 1024) and (var1 != 80) and (var1 != 443)):
  # fail
else
  ...
Asked By: Neverland

||

Answers:

It’s often easier to think in the positive sense, and wrap it in a not:

elif not (var1 == 80 or var1 == 443 or (1024 <= var1 <= 65535)):
  # fail

You could of course also go all out and be a bit more object-oriented:

class PortValidator(object):
  @staticmethod
  def port_allowed(p):
    if p == 80: return True
    if p == 443: return True
    if 1024 <= p <= 65535: return True
    return False


# ...
elif not PortValidator.port_allowed(var1):
  # fail
Answered By: unwind
if x == 80 or x == 443 or 1024 <= x <= 65535

should definitely do

Answered By: knittl
if
  ...
  # several checks
  ...
elif not (1024<=var<=65535 or var == 80 or var == 443)
  # fail
else
  ...
Answered By: Tom

This should do it:

elif var == 80 or var == 443 or 1024 <= var <= 65535:
Answered By: Daniel Roseman
if
  ...
  # several checks
  ...
elif ((var1 > 65535) or ((var1 < 1024)) and (var1 != 80) and (var1 != 443)):
  # fail
else
  ...

You missed a parenthesis.

Answered By: Grumpy

I think the most pythonic way to do this for me, will be

elif var in [80,443] + range(1024,65535):

although it could take a little time and memory (it’s generating numbers from 1024 to 65535). If there’s a problem with that, I’ll do:

elif 1024 <= var <= 65535 or var in [80,443]:
Answered By: Khelben

It is possible to write like this:

elif var1 in [80, 443] or 1024 < var1 < 65535

This way you check if var1 appears in that a list, then you make just 1 check, didn’t repeat the “var1” one extra time, and looks clear:

if var1 in [80, 443] or 1024 < var1 < 65535:
print ‘good’
else:
print ‘bad’
….:
good

Answered By: Fabio
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.