繁体   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