小编CoP*_*PHP的帖子

Python中的异常处理(尝试...例外)

我正在尝试try...except在下面的代码中实现异常处理。当输入类似“ s4”的内容时,我希望出现“非数字值...”的输出。

关于我哪里出问题了吗?

import string

import math

def getSqrt(n):
    return math.sqrt(float(n))

s = input("Enter a numerical value: ")

try:
    for i in s:
        if (i.isdigit() or i == "."):
            sType = "nonstr"

    if (sType =="nonstr"):
        print(getSqrt(s))

    else:
        s = "Non numberical value..."


except ValueError as ex:
    print(ex)


else:
    print(s)
Run Code Online (Sandbox Code Playgroud)

python exception-handling exception try-except

1
推荐指数
1
解决办法
1374
查看次数