Checking list by using of exception
Nader
n.emami at gmail.com
Fri Jun 13 06:01:55 EDT 2008
On Jun 13, 11:34 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Fri, 13 Jun 2008 04:37:44 -0300, Nader <n.em... 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
I would accept your suggestion in raltion of checking a list whether
it is empty or not with "if" statement. It is more expressive and
clear. But In this case I would learn more about the "try .... except"
exception.
Nader
More information about the Python-list
mailing list