用户输入函数中的True循环中是否有多个替代项?

问题描述 投票:0回答:2

我对Python比较陌生,目前正在研究第二个教程,特别是使用SQLite。

在我的附加代码(特别是功能Update)中,在这个简单函数中,我有3个while循环和几个中断。我认为这不是一个好习惯,我正在寻找建议,以使其更不容易崩溃和/或更紧凑。

太多的break语句有什么副作用?

def updateData():
    global cursor
    sql = 'SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name'
    cursor.execute(sql)

    rows = cursor.fetchall()

    print("These are the existing tables in the system:")
    tableList = []
    for row in rows:
        print(row[0])
        tableList.append(row[0])

    while True:
        table = input("Enter table to update: ")
        if table in tableList:
            while True:
                phoneLIST = searchDB()

                if len(phoneLIST) == 0:
                    option = tryMessage()
                    if not option:
                        break
                else:

                    numID = int(input("Enter the ID number you want updated: "))

                    sql = 'PRAGMA table_info(%s)' % table
                    cursor.execute(sql)

                    rows = cursor.fetchall()

                    print("These are the existing columns in %s table:" % table)
                    colList = []
                    for row in rows:
                        print(row[1])
                        colList.append(row[1])

                    while True:
                        column = input("Enter the column name of ID: %d you want updated: " % numID)
                        column = column.upper()
                        if column in colList:
                            if column == 'BOD' or column == 'PID':
                                print("You can't change Birth of Date OR PID")
                                option = tryMessage()
                                if not option:
                                    break
                            else:
                                if column == 'PHONE':
                                    newEntry = checkPhone()
                                elif column == 'POSTAL':
                                    newEntry = checkPostal()
                                else:
                                    newEntry = input("Enter new information for column %s: " % column)

                                sql = 'UPDATE %s SET %s = "%s" WHERE PID = %d' % (table, column, newEntry, numID)
                                cursor.execute(sql)

                                displayOneEntry(numID)
                                commitMessage()
                                break
                        else:
                            print("Column not in the table")
                    break
            break
        else:
            print("Table not in the database")
            option = tryMessage()
            if not option:
                break
python sqlite while-loop break
2个回答
0
投票

while True:循环没有错;这是一种反复进行某些操作的自然方法,直到发生错误或用户决定退出为止。

我认为此功能有点笨拙,因为它在许多不同的细节级别上都起作用。最好将其重组为用于表,列ID和值的单独函数,以便每个函数只关心自己的东西,而不用担心上层或下层细节。


0
投票

我进行了如下重构,消除了True时的嵌套:再次感谢@JG!

{other functions ...}

def getTable():
    global cursor
    sql = 'SELECT name FROM sqlite_master WHERE type = "table" ORDER BY name'
    cursor.execute(sql)

    rows = cursor.fetchall()

    tableList = []
    print("These are the available tables:  ")
    for row in rows:
        print(row)
        tableList.append(row[0])

    while True:
        tableName = input("Enter table to update: ")
        if tableName in tableList:
            return tableName
            break
        else:
            print("Table not in the database")
            # provide option to re-enter information
            option = tryMessage()
            if not option:
                break


def getColumn(tableName, numID):
    global cursor
    sql = 'PRAGMA table_info(%s)' % tableName
    cursor.execute(sql)

    rows = cursor.fetchall()

    print("These are the existing columns in %s table:" % tableName)
    colList = []
    for row in rows:
        print(row[1])
        colList.append(row[1])

    while True:
        colName = input("Enter the column name of ID: %d you want updated: " % numID)
        colName = colName.upper()
        if colName in colList:
            return colName
        else:
            print("Column not in the table")
            # provide option to re-enter information
            option = tryMessage()
            if not option:
                break


def getID(idList):
    while True:
        try:
            numID = int(input("Enter the ID number you want updated: "))
        except ValueError:
            print('Enter valid number')
            continue
        if numID in idList:
            return numID
        else:
            print("Wrong ID")


# admin use only
def updateData():
    global tempPassword
    passWord = input("Enter password: ")
    if passWord == tempPassword:
        global cursor
        # Displays valid tables
        tableName = getTable()

        idName = getIDName(tableName)

        while True:
            idList = searchDB()
            # provide option to re-enter information
            if len(idList) == 0:
                option = tryMessage()
                if not option:
                    break
            else:
                numID = getID(idList)
                colName = getColumn(tableName, numID)

                if colName == 'BOD' or colName == idName or colName == 'STATUS':
                    print("You can't change this field")
                    # provides option to re-enter information
                    option = tryMessage()
                    if not option:
                        break
                else:
                    if colName == 'PHONE':
                        # checks format for phone input
                        newEntry = checkPhone()
                    elif colName == 'POSTAL':
                        # checks format for postal code input
                        newEntry = checkPostal()
                    elif colName == 'POSITION_ID':
                        # checks to ensure ID is valid
                        newEntry = checkPositionID()
                    else:
                        newEntry = input("Enter new information for column %s: " % colName)

                    sql = 'UPDATE %s SET %s = "%s" WHERE %s = %d' % (tableName, colName, newEntry, idName, numID)
                    cursor.execute(sql)

                    # display the updated entry for confirmation
                    displayOneEntry(idName, numID)
                    # provide option to commit changes
                    commitMessage(idName)
                    break
    else:
        print("Access requires correct password")

{menu ...}
© www.soinside.com 2019 - 2024. All rights reserved.