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

Manprit Singh manpritsinghece at gmail.com
Tue Nov 3 02:18:00 EST 2020


Dear sir ,

I have written a program using functions, that print a sum of series upto n
terms :
The Series will be as follows :
a + aa + aaa + aaaa + ------------ upto n terms
output will be sum(9 + 99 +999 + 9999) if the series is made up of integer
9 and up to 4 terms.
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")
    else:
        l1 = [x]
        for i in range(1, n):
            l1.append(l1[-1]*10 + x)
        print(sum(l1))

ser_gen(9, 4)  will print 11106 which is right answer

ser_gen(9, -1) will print 'Wrong value of order entered"


Need your suggestions to improve

Regards
Manprit Singh


More information about the Tutor mailing list