[Tutor] Using try, except else inside function definition
dereje.anbessie at gmail.com
dereje.anbessie at gmail.com
Thu Oct 21 05:36:56 EDT 2021
Thank you.
On Thursday, October 21, 2021, 11:25:24 AM GMT+2, Alan Gauld via Tutor <tutor at python.org> wrote:
On 21/10/2021 02:29, Manprit Singh wrote:
> Dear Sir,
>
> I have written the count_words function again, but this time i am not
> including try except and else inside function, this seems more good to me
>
> def count_words(filename):
> with open(filename) as fileobj:
> content = fileobj.read()
> return len(content.split())
>
> try:
> filename ="fileread.txt"
> wdcnt = count_words(filename)
>
> except FileNotFoundError:
> print("File not exists")
>
> else:
> print("Number of words in file are", wdcnt)
I'd say it was better because your function could now be used
in other contexts.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list