Determine whether the input is Numeric
Here we use the try-again t statement to detect and handle exceptions.
The following is an example in the Python interaction environment:
>>> 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'
If the try-retry t statement is used, the result is as follows.
>>> Try:
... A = int (raw_input ('Please input an integer ...'))
... Struct t ValueError, error_info:
... Print error_info
...
Please input an int number... t
Invalid literal for int () with base 10: 'T'
We can make this code more perfect. If the user does not enter a number, it will always ask the user to try again.
>>> Trigger = True
>>> While trigger:
... Try:
... Trigger = False
... A = int (raw_input ('Please input an integer ...'))
... Handle T ValueError:
... Trigger = True
... Print 'You did not input an integer, try again ...'
...
Please input an integer...
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
>>>
Here is a new problem. The program will regard the number 0 as not an integer. Is there a better solution?
The following is a typical example of a try-retry t statement for detecting and handling exceptions. It helps you understand the try-retry t statement.
>>> 1/0
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> Try:
.... 1/0
... Reset t ZeroDivisionError, e:
... Print e
...
Integer division or modulo by zero
>>>