Search code examples
pythonloopserror-handlingtry-except

Error trapping combined with a counter not working


I'm making a code that makes a user enter RLE line by line. I then send the entered data to a function that decodes it. Within the function, I've included some basic error trapping.

My error is that when the user can only enter incorrect data the number of times they choose (they choose the amount of lines they want to enter). i.e. if the user enters 2 (out of 3) correct lines of RLE and then enters an incorrect line, the code won't ask to enter the RLE again, but if they enter an incorrect line at the first or second input it works.

Code:

if line_amount>2:
            print ("Please enter the compressed data one line at a time")
            while line_amount > counter:
                compressed_data = input('->') #ENTER RLE DATA
                counter+=1
                RLEtoASCII(compressed_data,counter)

RLEtoASCII:

def RLEtoASCII(compressed_data,counter):
    try:
        pairs = [(int(compressed_data[i:i+2]), compressed_data[i+2]) for i in range(0, len(compressed_data), 3)]
        global text
        text = ''.join(n * c for n, c in pairs)
        RLE_Inputs = open("Entered Data.txt", 'a+') #File that lists all the inputs
        #[etc all the file writing]
    except:
        print('THERE WAS A PROBLEM WITH THE VALUES Please re-enter values.\n')

If I try calling RLEtoASCII after the except, it creates a loop. counter -=1 doesn't appear to work after the except either...


Solution

  • By moving the error handling out of your function and into the if loop, we can more easily control the iteration:

    if line_amount>2:
                print ("Please enter the compressed data one line at a time")
                while line_amount > counter:
                    compressed_data = input('->') #ENTER RLE DATA
                    if compressed_data != '':
                        try:
                            RLEtoASCII(compressed_data)
                            counter+=1
                        except:
                            print('THERE WAS A PROBLEM WITH THE VALUES Please re-enter values.\n')
    

    RLEtoASCII:

    def RLEtoASCII(compressed_data):
        pairs = [(int(compressed_data[i:i+2]), compressed_data[i+2]) for i in range(0, len(compressed_data), 3)]
        global text
        text = ''.join(n * c for n, c in pairs)
        RLE_Inputs = open("Entered Data.txt", 'a+') #File that lists all the inputs
        #[etc all the file writing]