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

Mats Wichmann mats at wichmann.us
Wed Nov 4 09:45:47 EST 2020


On 11/4/20 7:42 AM, Manprit Singh wrote:
> Dear sir ,
> 
> In the below written mail , we are only raising an exception . I need to
> make a program that can end normally while displaying a message "Wrong
> value of order entered"  without error  if a user provides inappropriate
> input  in a function call like ser_gen(9, -1).

You wrap the call to the function in a try block, and handle the 
exception the way you want it. In this case you should remove the prints 
in the function and instead print after calling the function.

> 
> Regards
> Manprit Singh
> 
> On Tue, Nov 3, 2020 at 8:14 PM Flynn, Stephen (Life & Pensions) <
> Steve.Flynn at capita.com> wrote:
> 
>>> 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
>>
>> Is the exercise to actually use a try/except block as it's entirely
>> superfluous. Why not:
>>
>> def ser_gen(x, n):
>>          if n < 1:
>>              print("Wrong value of order entered")
>>              raise ValueError
>>      else:
>>          l1 = [x]
>>          for i in range(1, n):
>>              l1.append(l1[-1]*10 + x)
>>          print(sum(l1))


More information about the Tutor mailing list