简体   繁体   English

尝试 / 除了没有按预期捕获字符串输入

[英]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 .虽然我在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))

The exception is being raised by int before fact is ever called. int在调用fact之前引发异常。 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.) (因此,它不是真正值得做这种类型的运行时错误检查的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