python - Python 中的异常处理(Try...Except)

标签 python exception try-except

我试图在下面的代码中实现 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)

最佳答案

Ask for forgiveness - 将输入的值转换为float 并处理ValueError:

try:
    s = float(input("Enter a numerical value: "))
except ValueError:
    print("Non numberrical value...")
else:
    print(getSqrt(s))

演示:

>>> try:
...     s = float(input("Enter a numerical value: "))
... except ValueError:
...     print("Non numberrical value...")
... 
Enter a numerical value: s4
Non numberrical value...

关于python - Python 中的异常处理(Try...Except),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22990451/

相关文章:

python - 找不到 msguniq。确保安装了 GNU gettext 工具 0.15 或更新版本。 (Django 1.8 和 OSX ElCapitan)

php - 故意不捕获异常

visual-studio-2010 - EmguCV 'Emgu.CV.CvInvoke' 异常

python - 使用临时表中的大量数据填充表 - MySQL

python - 从边界点创建闭合多边形

python - 简单;如何合并未知数量的中断

python - 检查函数是否在 try 子句中被调用

Python:从具有不同类型变量的文件中读取行

python - os.system(cmd) 和 subprocess.call(cmd, shell=True) 的执行与 CMD.EXE 不同

java - 使用 @ControllerAdvice 注释的类处理异常时丢失堆栈跟踪