Python的异常
try:a = int(input("please input a number:"))
r = 10 / a
print('result:', r)
except ZeroDivisionError:
print("ZeroDivisionError: division by zero")
except ValueError:
print("ValueError: invalid literal for int() with base 10:",a)
以上是我写的代码,遇到被零除异常,可以返回输入的
但是遇到值异常就会报错,请问如何解决,并输出我想输出的
本帖最后由 tommyyu 于 2022-11-24 10:00 编辑
由于在输入非整数时,int(input())将会报错,此时 a 就无法被赋值,而 except ValueError 中又有打印 a 的语句,此时会因为 a 没有被定义而报错。可以这样改try:
a = input("please input a number:")
r = 10 / int(a)
print('result:', r)
except ZeroDivisionError:
print("ZeroDivisionError: division by zero")
except ValueError:
print("ValueError: invalid literal for int() with base 10:",a)
please input a number:a
ValueError: invalid literal for int() with base 10: a 本帖最后由 jackz007 于 2022-11-24 10:41 编辑
while True:
try:
a = int(input("please input a number:"))
r = 10 / a
break
except Exception as e:
print(e)
print('input again.')
print('result:', r)
运行实况:
D:\\Python>python x.py
please input a number:abc
invalid literal for int() with base 10: 'abc'
input again.
please input a number:0
division by zero
input again.
please input a number:3
result: 3.3333333333333335
D:\\Python>
页:
[1]