Checking list by using of exception

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Jun 13 11:34:25 CEST 2008


En Fri, 13 Jun 2008 04:37:44 -0300, Nader <n.emami at gmail.com> escribió:

> Hello,
>
> I read some files name from a directory and then I put these name in a
> list. I will check whether it is empty or not, and I would do it with
> an exception. With if statement it is very simple:
>
> If list_of_files != ""  :            # this can be if list_of_files !=
> []:
>   get the files
> elas:
>    there is no file

If it is simple, just do it! Why do you want to make things more  
complicated? This would be enough:

if list_of_files:
     get_the_files(list_of_files)
else:
     print "there is no file"

(a list has a false boolean value when it is empty)

> But with exception, I can write something as:
>
> try:
>    list_of_files != []
>    get the files
> except ValueError:
>     Print " there is no file"
>
> What can the first statement be inside 'try' if I don't want to use if
> statement?

If you insist on using an exception (and assuming list_of_files is  
actually a list, not a string or other kind of sequence):

try:
     list_of_files[0]
except IndexError:
     ...no files...

This way you're checking that list_of_files contains at least one element.  
But I would not reccomend it.

-- 
Gabriel Genellina




More information about the Python-list mailing list