Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complex if statement in python

Tags:

python

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   ... 
like image 906
Neverland Avatar asked Mar 22 '10 15:03

Neverland


People also ask

What are the 3 types of Python conditional statements?

Python Conditional Statements: If, Else & Switch.

Can you have multiple if statements in Python?

It works that way in real life, and it works that way in Python. if statements can be nested within other if statements. This can actually be done indefinitely, and it doesn't matter where they are nested. You could put a second if within the initial if .

What are the conditional statements in Python?

Decision-making in a programming language is automated using conditional statements, in which Python evaluates the code to see if it meets the specified conditions. The conditions are evaluated and processed as true or false. If this is found to be true, the program is run as needed.


2 Answers

This should do it:

elif var == 80 or var == 443 or 1024 <= var <= 65535: 
like image 135
Daniel Roseman Avatar answered Oct 10 '22 02:10

Daniel Roseman


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 
like image 27
unwind Avatar answered Oct 10 '22 01:10

unwind