判断输入是否为数字 续
这里用到了检测与处理异常的try-except语句。
下面是一个例子,在Python交互环境执行的:
>>> a = int(raw_input('Please input an integer ... '))
Please input an int number ... t
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 't'
那么,如果使用了try-except语句,结果就是这样的。
>>> try:
... a = int(raw_input('Please input an integer ... '))
... except ValueError, error_info:
... print error_info
...
Please input an int number ... t
invalid literal for int() with base 10: 't'
我们可以把这段代码更加完善成,如果用户没有输入数字,就一直叫用户重新尝试。
>>> trigger = True
>>> while trigger:
... try:
... trigger = False
... a = int(raw_input('Please input an integer ... '))
... except ValueError:
... trigger = True
... print 'You did not input an integer, try again ... '
...
Please input an integer ... a
You did not input an integer, try again ...
Please input an integer ... 1.1
You did not input an integer, try again ...
Please input an integer ... *
You did not input an integer, try again ...
Please input an integer ... @
You did not input an integer, try again ...
Please input an integer ... 0.
You did not input an integer, try again ...
Please input an integer ... 0
>>>
这里有个新问题,程序会把数字0.也认为不是一个整数。会有更好的处理办法吗?
下面是检测与处理异常的try-except语句的一个典型例子。能帮助你理解try-except语句。
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> try:
... 1/0
... except ZeroDivisionError, e:
... print e
...
integer division or modulo by zero
>>>