Python如何在一个if语句中检查变量是否存在及其长度?
这是我的情况:
if var:
if len(var) == 5:
do something...
else:
do the same thing...
为了避免重复同一段代码,我想将这 2 个 if 条件合并为一个。但如果 var 是 None,我无法检查它的长度......知道吗? 我想要这样的东西:
if var and len(var) == 5:
do something...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你尝试过吗?它有效:
如果 LHS 为 false,则
and
运算符不会计算 RHS。试试这个:Did you try that? It works:
The
and
operator doesn't evaluate the RHS if the LHS is false. Try this:您在问题中编写的代码在两种情况下执行语句:
var
计算结果为 true,长度为 5var
计算结果为 false(例如,它是 < code>None 或False
)您可以将它们组合成一个条件,如下所示:
其他一些答案建议的条件,
var and len(var) == 5,仅评估为
True
在第一种情况下,而不是在第二种情况下。不过,我要说的是,您选择的两种情况是一种不寻常的组合。您确定您不打算仅在变量具有非假值且长度为 5 时才执行语句吗?此外,正如 6502 在评论中所写,函数正是针对这种情况,即制作可重用的代码块。所以另一个简单的解决方案是
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 5var
evaluates to false (e.g. it'sNone
orFalse
)You can combine those into one conditional as follows:
The conditional that some other answers are suggesting,
var and len(var) == 5
, only evaluates toTrue
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
好吧,例外在这里似乎完全没问题。
您说
var
可以为 null,因此会抛出TypeError
异常。然而,如果事实上var
可能根本不存在,那么您应该捕获NameError
异常。Well, exceptions seem to be perfectly fine here.
You're saying that
var
can be null, therefore aTypeError
exception would be thrown. If, however, in factvar
can be non-existant at all, you should catch forNameError
exception.