views:

207

answers:

6

Hello,

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():


    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

+2  A: 

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.

Hank Gay
+4  A: 

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')
sykora
+1  A: 

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.

Max Shawabkeh
+2  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))
...
Anssi
int() might throw an exception on character input ...
jellybean
That's true. Not usable as such
Anssi
+5  A: 
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'
jellybean
@jellybean -- Thanks for this. This work's the best, all other answers are good but this code catches the user entering any other incorrect variable.
chrissygormley
+1  A: 
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)
ghostdog74