python - 错误陷阱与计数器结合使用不起作用

标签 python loops error-handling try-except

我正在编写使用户逐行输入RLE的代码。然后,我将输入的数据发送到对它进行解码的函数。在函数中,我包含了一些基本的错误陷阱。

我的错误是,当用户只能输入不正确的数据时,他们选择的次数(他们选择他们要输入的行数)。也就是说,如果用户输入了RLE的2条(共3条)正确的行,然后输入了不正确的行,则代码不会要求再次输入RLE,但是如果用户在第一个或第二个输入中输入了不正确的行,它将起作用。

码:

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

如果我尝试在除外之后调用RLEtoASCII,则会创建一个循环。除外后counter -=1似乎不起作用...

最佳答案

通过将错误处理移出函数并移至if循环,我们可以更轻松地控制迭代:

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]

关于python - 错误陷阱与计数器结合使用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59521657/

相关文章:

确保函数的输入参数是 int/str 的 Pythonic 方法?

javascript - 在数组对象内循环

WCF IErrorHandler.ProvideFault() 行为

c# - 带有自定义错误消息的 MVC 错误处理

powershell - Powershell复制项目退出代码1

python - Visual Studio IntelliCode 不预测方法和变量

python - py2neo 引发 ConstraintViolation 错误,shell 不会

python - 在 Python 中反转字符串

python - 比较一行中的值并将结果写入新列

javascript - 不断循环遍历 JavaScript 文本数组 onclick