python - 为什么我的位置 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()
解决方案
使用大于内部元素总数的索引{}
将导致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]}'")
推荐阅读
- dart - 如何将飞镖代码文件与 HTML 页面绑定?
- css - Office UI Fabric 网格中的垂直单元格对齐
- graphviz - Graphviz labeljust 无法将文本左对齐
- c++ - std::map 的比较器函数中的段错误/未定义行为
- python - 如何估计噪声层后面的高斯分布?
- sql - 如何避免在 mysql 中的 SELECT 之前写入模式名称?
- sql-server - F# - FSharp.Data.SqlClient – How to specify timeout for Update
- tinkerpop - janusgraph index performance
- python - Why pandas asfreq produces dates not in the input list?
- java - 如何使用 org.ow2.asm 6.0 修改 Java 字节码