complex if statement in python

后端 未结 2 2081
醉梦人生
醉梦人生 2021-02-11 18:02

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:

2条回答
  •  北海茫月
    2021-02-11 18:21

    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
    

提交回复
热议问题