开发者

Get a Try statement to loop around until correct value obtained

I am trying to get a user to enter a number between 1 and 4. I have code to check if the number is correct but I want the code to loop around several times until the numbers is correct. Does anyone know how to do this? The code is below:

def Release(开发者_如何学Go):


    try:
        print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
        a = int(input("Please select the type of release required: "))
        if a == 0:
            files(a)
        elif a == 1:
            files(a)
        elif a == 2:
            files(a)
        elif a == 3:
            files(a)
        else:
            raise 'incorrect'
    except 'incorrect':    
        print 'Try Again'
    except:
        print 'Error'

Release()

I am also getting an error about the exception I have entered:

kill.py:20: DeprecationWarning: catching of string exceptions is deprecated
  except 'incorrect':
Error

Thanks for any help


def files(a):
    pass

while True:
    try:
        i = int(input('Select: '))
        if i in range(4):
            files(i)
            break
    except:    
        pass

    print '\nIncorrect input, try again'


Modern Python exceptions are classes; by using raise 'incorrect', you are using a deprecated language feature called string exceptions. The Errors and Exceptions section of the Python tutorial would be a good place to start with basic exception handling in Python.

In general, exceptions are not ideal for your situation anyway—a simple while loop should be sufficient. Exceptions should be reserved for exceptional situations, and bad user input is not exceptional, it's expected.

The loop-based version of Release would look something like this:

def Release():
    a = None
    while a not in (0, 1, 2, 3):
        print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
        try:
            a = int(input("Please select the type of release required: "))
        except ValueError:
            pass  # Could happen in face of bad user input
    files(a)

P.S. a is a bad variable name; you should probably change it to chosen_option or something like that.


Your approach seems to be a very long-winded way to accomplish something fairly simple:

def Release() :
    while True :
        print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
        a = int(input("Please select the type of release required: "))
        if 0 <= a < 4 :
            files(a)
            break
        else :
            print('Try Again')


You are both throwing and catching the exception in the same simple block of code - this is not really what exception handling is about. You can do it better either by breaking out of a loop or by keeping a condition. E.g.:

def isNumberCorrect(x):
   return x in range(4)

def Release():
    num = None # incorrect

    while not isNumberCorrect(num):
        print 'Please select one of the following?\nCompletion = 0\nRelease ID = 1\nVersion ID = 2\nBuild ID = 3\n'
        num_str = raw_input("Please select the type of release required: ")

        try:
            num = int(num_str)
        except ValueError:
            num = None

        if not isNumberCorrect(num):
            print 'Incorrect!'

     # work with num here; it's guaranteed to be correct.

if __name__ == '__main__':
  try:
    Release()
  except:
    print 'Error!'

EDIT: Added error checking in the int parsing.


def Release():
    while 1:
        print """Please select one of the following?
                 Completion = 0
                 Release ID = 1
                 Version ID = 2
                 Build ID = 3
                 Exit = 4 """            
        try:
             a = int(raw_input("Please select the type of release required: "))
        except Exception,e:
             print e
        else:
             if a==4: return 0
             files(a)


Instead of using exceptions you could do something like this:

...
a = raw_input("Please select the type of release required:")
while a not in ['0','1','2','3']: a = raw_input("Try again: ")
files(int(a))
...


I wanted to check if the input is a number: For me, the working solution in my project was:


while True:
    number1 = input("Enter a number: ")
    try:
        n1 = int(number1)
        break
    except ValueError:
        print("It has to be a number!")

# then proceed with your code using this number

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜