|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
def GetSumAndAvg(num = 10):
sum = 0
i = num
while i:
try :
a = input("please input a integer: ")
if isinstance(a,int) == False:
raise NonIntegerError
except NonIntegerError:
print('Input number is not a integer!')
else:
sum += a
i -= 1
print('sum is %d , average is %d' %(sum,sum/num))
想实现检查输入的数是否是整数,不是整数就抛出异常
这里自定义了一个 异常,运行的时候程序报错 说未定义,请问raise不能这样定义自己命名的异常吗?
>>> GetSumAndAvg(5)
please input a integer: 3.3
Traceback (most recent call last):
File "C:/python/MyProject/exercise7_2_1.py", line 8, in GetSumAndAvg
raise NonIntegerError
NameError: name 'NonIntegerError' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
GetSumAndAvg(5)
File "C:/python/MyProject/exercise7_2_1.py", line 9, in GetSumAndAvg
except NonIntegerError:
NameError: name 'NonIntegerError' is not defined
需要写成这样:
- def GetSumAndAvg(num = 10):
- sum = 0
- i = num
- while i:
- try :
- a = input("please input a integer: ")
- if isinstance(a,int) == False:
- raise Exception('NonIntegerError')
- except Exception:
- print('Input number is not a integer!')
- else:
- sum += a
- i -= 1
- print('sum is %d , average is %d' %(sum,sum/num))
复制代码
|
|