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