Exception Handling in Python (Try…Except)
我正在尝试将
我知道哪里出错了?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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) |
请求宽恕 - 将输入的值转换为
1 2 3 4 5 6 | try: s = float(input("Enter a numerical value:")) except ValueError: print("Non numberrical value...") else: print(getSqrt(s)) |
演示:
1 2 3 4 5 6 7 | >>> try: ... s = float(input("Enter a numerical value:")) ... except ValueError: ... print("Non numberrical value...") ... Enter a numerical value: s4 Non numberrical value... |