[英]try / except not catching string inputs as expected
虽然我在str
输入中使用 try except 块的阶乘,但是当我输入str
时,我收到了int(input)
值错误。
def fact(x):
if isinstance(x, str):
try:
x * fact(x-1)
except TypeError:
print('factorial of strings cannot be calculated!')
elif x == 0 :
return 1
elif x < 0:
print('factorial of a Negative Number cannot be calculated!')
else:
return x * fact(x-1)
#--------------------------------------------------------
while True:
x = int(input('Enter X: '))
print(fact(x))
int
在调用fact
之前引发异常。 您需要在异常发生时捕获异常。 (因此,它不是真正值得做这种类型的运行时错误检查的fact
:文档fact
需要一个int
作为参数,并让来电者脸上掠过一些其他类型的后果。)
def fact(x):
if x == 0 :
return 1
elif x < 0:
raise ValueError('factorial of a Negative Number cannot be calculated!')
else:
return x * fact(x-1)
#--------------------------------------------------------
while True:
try:
x = int(input('Enter X: '))
except ValueError:
print("Input was not a valid int, try again")
continue
print(fact(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.