[英]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.