Error/exceptional handling

Please Tell me my mistake

def facrec(x):
if (x>1):
k=x*facrec(x-1)
return (k)
elif ((x1)or(x0)):
return (1)

n=int(input(“Enter a value:\t”))
try:
a=facrec(n)
except Exception:
print(“You have not entered a Natural Number”)
else:
print("\nThe factorial of “+str(n)+” is “+str(a))
finally:
print(”\nThank You")

Is there some difficulty or error that you’re facing?

Hi @srikarkalyanam,
I suppose that the yellow highlighted code should be

elif (x==1) or (x==0)

instead of x1 or x0

Hope this helps!!

Im trying to learn error handling;

So I tried using factorials as an example

While I input a letter in place of a number

I expect the printstatement in EXCEPT to be the output

but it is not the case.

What is the output that you are getting?

Traceback (most recent call last):

File “C:\Users\AppData\Local\Temp\untitled0.py”, line 14, in
n=int(input(“Enter a value:\t”))

ValueError: invalid literal for int() with base 10: ‘h’

this is because you have try, except block for the function defined by you and not for the input that you are receiving.
The error states that the input you are providing is an invalid literal to be converted to int

thanks…

any ideas on how to correct it?

you need to enclose it in try, except block and there you can either define a custom error message or throw the pre-defined error.

Besides, if you are to execute a block of statement despite errors in previous blocks, you need to define it under finally.

sorry … im just a beginer…this flew over my head

def facrec(x):
if (x>1):
k=x*facrec(x-1)
return (k)
elif ((x1)or(x0)):
return (1)

n=int(input(“Enter a value:\t”))
try:
a=facrec(n)
except ValueError:
print(“You have not entered a Natural Number”)
else:
print("\nThe factorial of “+str(n)+” is “+str(a))
finally:
print(”\nThank You")

This is the code…can you help me by modifying it

The code

n = int(input("Enter a value:\t"))

throws ValueError exception and thereby the code terminates without executing any further statements.

If you wish to further execute any block of statement, despite the error, you need to declare it as

finally:
    *block of code*

exception handling python
Refer to the link here.

Hope this helps!!

1 Like