chrisg
chrisg

Reputation: 41675

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

Upvotes: 27

Views: 181795

Answers (7)

ColdNox
ColdNox

Reputation: 1

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

Upvotes: 0

Hank Gay
Hank Gay

Reputation: 71979

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.

Upvotes: 6

Anssi
Anssi

Reputation: 528

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))
...

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342609

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)

Upvotes: 2

Max Shawabkeh
Max Shawabkeh

Reputation: 38643

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.

Upvotes: 4

Johannes Charra
Johannes Charra

Reputation: 29933

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'

Upvotes: 65

sykloid
sykloid

Reputation: 101276

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')

Upvotes: 4

Related Questions