-4
def finding(a,b):

    try:
        result=a+b
        return result
    except TypeError:
        return "please type only num"
    finally:
        return "this line will get print at last"

print(finding (5, 2)) 

I'm getting the output from the finally, but I'm not getting the output from the try.

  • I should also get output of "finally" With output of "try" (result=7) – Mohit Mishra Oct 25 '22 at 08:15
  • Why do you expect that? Your function can only `return` once and the one in `finally` is overriding both of the others. – tripleee Oct 25 '22 at 08:19
  • Tangentially, overriding the useful default exception to `return` (or print, or whatever) something useless is a pathological antipattern. Exceptions are useful and informative, at least compared to what you are replacing them with here. – tripleee Oct 25 '22 at 08:22
  • @PatrickArtner yeah i remembered just now that return will return once not twice.. Im new to python – Mohit Mishra Oct 25 '22 at 08:23
  • @tripleee thankyou for correcting my mistake.. Im new to python sometimes i get confused.. I just remembered that return can used once .. Thank you – Mohit Mishra Oct 25 '22 at 08:25

1 Answers1

-1

Change your last two returns to print statements:

def finding(a,b):

    try:
        result=a+b
        return result
    except TypeError:
        print("please type only num")
    finally:
        print("this line will get print at last")

print(finding (5, 2)) 
Tanner
  • 171
  • 1
  • 12
  • 1
    This will fix the immediate error, but now the function returns `None` when there's a problem, which still hides it from the calling code. (Also, interactive I/O makes the function less suitable for use from other functions.) – tripleee Oct 25 '22 at 08:28
  • 3
    And, you didn't fix the syntax error (`def` instead of `Def`) – tripleee Oct 25 '22 at 08:31
  • @tripleee thank you i will remember your explanation – Mohit Mishra Oct 25 '22 at 08:38