1

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?

glglgl
  • 89,107
  • 13
  • 149
  • 217
SkyDrive26
  • 191
  • 2
  • 3
  • 8

4 Answers4

6

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)
alemangui
  • 3,571
  • 22
  • 33
  • why not just - `if num: some_operation(num) else: some_fallback_operation()`? – Rohit Jain Dec 06 '12 at 13:12
  • I decided to add both in case he wants to make a difference between an undefined variable and a None variable. Your solution also works though. – alemangui Dec 06 '12 at 13:14
6

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.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • 1
    Even though the edit was approved, I still think that `if-else` was a more readable option. Purely matter of personal taste, though. – bereal Dec 06 '12 at 14:47
1

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."
kahowell
  • 27,286
  • 1
  • 14
  • 9
  • There are many more ways to do the check. See [this question](http://stackoverflow.com/questions/53513/python-what-is-the-best-way-to-check-if-a-list-is-empty). – kahowell Dec 06 '12 at 13:17
  • Top example fixed now (had misplaced parenthesis and missing colon), in case someone comes back to this. Bottom example worked for me. – kahowell Dec 06 '12 at 13:43
1

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217