Question

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

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

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:

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

But what should that if statement look like?

Was it helpful?

Solution

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

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.

OTHER TIPS

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)

I would do

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

If None is a valid data portion, use

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

instead.

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."
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top