簡體   English   中英

嘗試 / 除了沒有按預期捕獲字符串輸入

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM