开发者

Help with error handling for Python

开发者 https://www.devze.com 2023-02-05 21:04 出处:网络
For the simple snippet below a = raw_input(\"Enter a number: \") How can I write an exception such that if a string is entered, the user is re-prompted to try again and again until an integer is en

For the simple snippet below

a = raw_input("Enter a number: ")

How can I write an exception such that if a string is entered, the user is re-prompted to try again and again until an integer is entered.开发者_StackOverflow社区

In other words, keep doing this until an integer is entered.:

if a.isdigit == False:
    raw_input("Try again: ") 


The usual way to achieve this is to use int() with exception handling:

>>> n = None
>>> while n is None:
...    a = raw_input("Enter a number: ")
...    try:
...      n = int(a)
...    except ValueError:
...      print "Not a number."
...
Enter a number: abc
Not a number.
Enter a number: cauliflowers are my favourite vegetable
Not a number.
Enter a number: 12
>>>

However if you would prefer to avoid exception handling you can take the following approach. Note that it does not accept negative integers, but only the natural numbers 0, 1, 2, ..., N:

>>> while True:
...   a = raw_input("Enter a number: ")
...   if a.isdigit():
...     break
...   print "Not a number."
...
Enter a number: I like beetroot too
Not a number.
Enter a number: -500
Not a number.
Enter a number: 500
>>>

It becomes a little more involved to handle negative integers in this manner, requiring three cases, one for empty strings, one for negative integers and one for natural numbers:

>>> while True:
...   a = raw_input("Enter a number: ")
...   if len(a) > 0 and ((a[0] == '-' and a[1:].isdigit()) or a.isdigit()):
...     break
...   print "Not a number."
...
Enter a number: Celery stinks.
Not a number.
Enter a number:
Not a number.
Enter a number: -
Not a number.
Enter a number: 1
>>>


You can use a while loop:

a = ""
while not a.isdigit():
    a = raw_input("Enter a number: ")

If you want an error message it becomes something like:

a = raw_input("Enter a number: ")
while not a.isdigit():
    a = raw_input("Try again: ")


while True:
    a = raw_input("Enter a number:")
    try:
        i = int(a)
        break
    except ValueError:
        print "Not a number"


a = raw_input("Enter a number: ")
while (not a.isdigit()):
    a = raw_input("Try again: ")
0

精彩评论

暂无评论...
验证码 换一张
取 消