首页 > 解决方案 > 为什么我的位置 args 元组错误的替换索引 1 超出范围

问题描述

我不断收到此错误:此代码行中位置参数元组的替换索引 1 超出范围:

print("'{1}', '{2}', '{3}', '{4}'".format(question[3]), question[4], question[5], question[6])

这是我的完整代码


def quiz(userID,topicID):
    with sqlite3.connect("Quiz.db") as db:
        cursor = db.cursor()
    score = 0
    cursor.execute("SELECT * FROM questions WHERE topicID=?",[(topicID)])
    questions = cursor.fetchall()
    numOfQuestions = 0 #use to help work out the score / %
    for question in questions:
        topic = question[1]
        print(question[2])
        print("'{1}', '{2}', '{3}', '{4}'".format(question[3]), question[4], question[5], question[6])
        choice = input("Answer: ")
        if choice == question[7]:
            print("Correct")
            score += 1
            time.sleep(1)
            print("")
        else:
            print("Incorrect")
            numOfQuestions += 1
    #works our % to keep all quiz scores consistent
    score = int((score/numOfQuestions)*100)
    print("Your score was: ",score)
    insertData("INSERT INTO scores(userID,score,topicID) VALUES(?,?,?);")
    cursor.execute(insertData, [(userID), (score), (topic)])
    db.commit()

标签: python

解决方案


使用大于内部元素总数的索引{}将导致index out of range格式化。

由于您在 内部使用了四个元素format(),因此索引范围应为 0 到 3,在您的代码4中导致index out of range错误。

尝试这个:

print("'{0}', '{1}', '{2}', '{3}'".format(question[3], question[4], question[5], question[6]))

或 f-strings(f-strings 的链接):

print(f"'{question[3]}', '{question[4]}', '{question[5]}', '{question[6]}'")

推荐阅读