简体   繁体   中英

try / except not catching string inputs as expected

Although I am using try except blocks in factorial for str inputs, but I am getting value error with int(input) , when I enter a str .

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))

The exception is being raised by int before fact is ever called. You need to catch the exception when it occurs. (As such, it's not really worth doing this type of run-time error checking in fact : document that fact requires an int as an argument, and let the caller face the consequences of passing some other type.)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM