[Tutor] Using try, except else inside function definition
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Oct 21 05:22:06 EDT 2021
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
More information about the Tutor
mailing list