Tickon Tickon - 14 days ago 6
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...
else:
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

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
False
>>> True and 1/0
ZeroDivisionError: division by zero
Comments