Python 如果 var 不存在则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13744276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:31:24  来源:igfitidea点击:

Python if a var doesn't exist then

pythonif-statementimapimaplib

提问by SkyDrive26

I'm developing some IMAP checker. Now the inbox count is prints a message in the following layout: ['number'].

我正在开发一些 IMAP 检查器。现在收件箱计数以以下布局打印一条消息:[' number']。

Now that that number is split to the numberin var num. See the following code:

现在,这个数字被分流到以VAR NUM。请参阅以下代码:

for num in data[0].split():
    print num

Now the thing is, if there ain't any new emails num doesn't exist so I want an if statement like this:

现在的问题是,如果没有任何新电子邮件 num 不存在,那么我想要这样的 if 语句:

if <num doesn't exist>: print "No new emails found."

But what should that if statement look like?

但是 if 语句应该是什么样的呢?

采纳答案by bereal

The most pythonic way to achieve what you seem to want to, is:

实现您似乎想要的最pythonic方法是:

nums = data[0].split()
for num in nums:
   print num
if not nums:
   print "No new emails found"

since the code reflects the intention precisely.

因为代码准确地反映了意图。

回答by alemangui

Check this site, they have a useful snippet to check if the variable exists or if it is None:

检查这个站点,他们有一个有用的片段来检查变量是否存在或是否为无:

# Ensure variable is defined
try:
   num
except NameError:
   num = None

# Test whether variable is defined to be None
if num is None:
    some_fallback_operation()
else:
    some_operation(num)

回答by kahowell

Check the size of the split data and use that as your condition:

检查拆分数据的大小并将其用作条件:

for num in data[0].split():
    print num
if len(data[0].split()) == 0:
    print "No new emails found."

More elegant way:

更优雅的方式:

for num in data[0].split():
    print num
if not data[0].split():
    print "No new emails found."

回答by glglgl

I would do

我会做

num = None
for num in data[0].split(): 
    print num
if num is None:
    print "No new emails found."

If Noneis a valid data portion, use

如果None是有效的数据部分,请使用

num = sentinel = object()
for num in data[0].split(): 
    print num
if num is sentinel:
    print "No new emails found."

instead.

反而。