Tickon Tickon - 1 year ago 113
Python Question

Python how to check if variable exist and its length, in one if statement?

Here's my situation:

if var:
if len(var) == 5:
do something...
do the same thing...

To avoid repeating the same piece of code, I would like to combine those 2 if conditions, in one. But if var is None, I can't check its length... Any idea?
I would like something like this:

if var and len(var) == 5:
do something...

Answer Source

Did you try that? It works:

if var and len(var) == 5:

The and operator doesn't evaluate the RHS if the LHS is false. Try this:

>>> False and 1/0
>>> True and 1/0
ZeroDivisionError: division by zero
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download