Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...
like image 496
Tickon Avatar asked Sep 22 '11 05:09

Tickon


1 Answers

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
like image 69
Dietrich Epp Avatar answered Sep 21 '22 07:09

Dietrich Epp