开发者

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

开发者 https://www.devze.com 2023-04-06 09:54 出处:网络
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, i

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...


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


The code as you've written it in the question executes the statements in two cases:

  • var evaluates to true and has a length of 5
  • var evaluates to false (e.g. it's None or False)

You can combine those into one conditional as follows:

if not var or len(var) == 5:
    ...

The conditional that some other answers are suggesting, var and len(var) == 5, only evaluates to True in the first case, not the second. I will say, though, that the two cases you've chosen are kind of an unusual combination. Are you sure you didn't intend to execute the statements only if the variable has a non-false value and has a length of 5?

Additionally, as 6502 wrote in a comment, functions are intended for exactly this case, namely making reusable code blocks. So another easy solution would be

 def f():
     ....
 if var:
     if var.length == 5:
         f()
 else:
     f()


Well, exceptions seem to be perfectly fine here.

try:
    if len(var) == 5:
        do_something()
except TypeError:
    pass

You're saying that var can be null, therefore a TypeError exception would be thrown. If, however, in fact var can be non-existant at all, you should catch for NameError exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消