【发布时间】:2016-03-18 10:43:53
【问题描述】:
我的问题是我创建了一个数学测验,它会询问用户 10 个随机问题,然后它会在最后输出他们的分数(满分 10)。我已经完成了这项任务的艺术,但我在最后一部分遇到了困难.最后一部分是我需要创建一些东西来存储每个用户的最后 3 个分数。我决定使用 mysql 但我的代码只会让我为每个用户存储 1 个分数。我使用 python 3.4。这是代码.
import random
import operator
import mysql.connector
cnx = mysql.connector.connect(user='root', password='password',
host='localhost',
database='mydb')
cursor = cnx.cursor()
ID = input("what is your ID?")
OPERATIONS = [
(operator.add, "+"),
(operator.mul, "x"),
(operator.sub, "-")
]
NB_QUESTIONS = 10
def get_int_input(prompt=''):
while True:
try:
return int(input(prompt))
except ValueError:
print("Sorry,but we need a number")
if __name__ == '__main__':
name = input("What is your name?").title()
Class=input("Which class do you wish to input results for 1,2 or 3?")
print(name, ", Welcome to the Maths Test")
score = 0
for _ in range(NB_QUESTIONS):
num1 = random.randint(1,10)
num2 = random.randint(1,10)
op, symbol = random.choice(OPERATIONS)
print("What is", num1, symbol, num2)
if get_int_input() == op(num1, num2):
print("Correct")
score += 1
else:
print("Incorrect")
print("Well done", name, "you scored", score, "/", NB_QUESTIONS)
print ("Thank you for doing this mathamatical quiz , goodbye ")
if "ID" in "Class1":
if "score" in "Score1":
add_record = ("INSERT INTO Class1"
"(Score2)"
"VALUES(%s)")
data_record = (score)
if "score" in "Score2":
add_record = ("INSERT INTO Class1"
"(Score3)"
"VALUES(%s)")
data_record = (score)
else:
add_record = ("INSERT INTO Class1"
"(ID, Name, Score1) "
"VALUES (%s, %s, %s)")
data_record = (ID, name, score)
cursor.execute(add_record, data_record)
cnx.commit()
cursor.close()
cnx.close()
在我的数据库中,我有列 ID,name,score1,score2,score3 当我完成测验时,分数、姓名和 ID 将被输入到表格中。但是一旦具有相同 ID 的用户进行测验,就会出现错误。我希望代码为每个用户存储 3 个分数,但出现错误.错误是:
cursor.execute(add_record, data_record) NameError: name 'add_record' 没有定义
感谢您阅读本文,也感谢您的帮助。我期待收到回复。
【问题讨论】:
-
然后标记
php在这里做什么? -
抱歉 id 不是要添加的意思
-
我删除了我的帖子,因为它不正确。不过,正如我在 cmets 中所说的那样。只需在 Python 环境
"ID" in "Class1"中运行它...它将返回False。"score" in "Score1"和"score" in "Score2"也是如此...您的问题是 none 您的 if 语句正在输入。除非您提及您希望这些行做什么,否则没有人可以提供帮助。 -
我想要做的是为我的数据库添加一个分数。例如,我创建了这段代码,它将输入用户 ID、姓名和第一个分数到数据库。但我需要一段代码将为用户添加第二个分数。因此它将显示他们的第一个分数和第二个分数和第三个分数。我不知道如何编码。我将 if 语句放在那里,因为我认为“如果 score1已填充然后将 sccore 输入 score2" 但这不起作用。
-
好的。现在我明白了,暂时忘记数据库。没有它你能做到你刚才说的吗?