[Tutor] A problem involving exception handling, need suggestions to improve further

Alan Gauld alan.gauld at yahoo.co.uk
Tue Nov 3 04:47:31 EST 2020


On 03/11/2020 07:18, Manprit Singh wrote:

> Now clearly for values of n(number of terms) below 1, i need to raise an
> exception as for values of n < 1 there will be no valid series and no
> output should be there . in that situation i have to print "Wrong value of
> order entered". The program is written below:
> 
> def ser_gen(x, n):
>     try:
>         if n < 1:
>             raise ValueError
>     except ValueError:
>         print("Wrong value of order entered")

This is completely pointless and extremely inefficient.
All you need here is

if n < 1:
   print(....)

But better would be:

if n < 1:
   raise ValueError("n must be greater than 1")

Why is it better?
Because:
1) it removes any printing from the function - you
   should avoid mixing logic/processing with display.
2) The error message tells the user what was wrong
   not just that something was wrong.
3) By raising the exception to the user of the function
   there is some possibility that they can fix the
   problem rather than being stuck with a printed message.
4) By raising an exception the user of the function will
   get a stack trace that will enable (or at least help)
   them to figure out where the error was introduced.

>     else:
>         l1 = [x]
>         for i in range(1, n):
>             l1.append(l1[-1]*10 + x)
>         print(sum(l1))

See point 1 above. The code that does the processing
should *return* the value not print it.

Also, for your own sanity avoid mixing i,l and 1 in
variable names. They all look so similar that it's
very easy to make mistakes and finding the mistake
becomes a visual nightmare!

Finally, try to name your functions to reflect what
they do. ser_gen() suggests that this function returns
a generated series. In fact it returns a total.
So call the function sum_ser() or something similar.
It's all about making your code readable.

-- 
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