如何使用SQLite在python中打印有序分数

时间:2016-03-15 14:20:56

标签: python sqlite

我写这篇文章是因为我的python代码中遇到麻烦,应该是对学生的测试,我无法添加一个有效的解决方案来允许将SQLite数据库的结果打印到此外,我希望用户被问到他们希望如何格式化例如按字母顺序或分数上升/下降。请帮帮我!!!

import random
import sqlite3 as lite
import os

print ("Welcome to the Maths Test") 
Score = 0
question = 0

while True:
    Name = input("Please enter your name here: ")
    if Name.isdigit():
        print ("Do Not Enter a Number")
    elif Name.isalpha():
        break
while True:
    class_group = input("Please enter your class group number here: ")
    if class_group.isalpha():
        print ("Do not enter a number")
    elif class_group.isdigit():
        break       


while question < 10: 
    operation= random.randint(1,3)
    number1 = random.randint(1,25)
    number2 = random.randint(1,25)
    if operation == 1:
        print("What is", number1, "+", number2)
        answer = number1 + number2

    elif operation ==2:
        print("What is", number1, "*", number2)
        answer = number1 * number2

    else: 
        print("What is", number1, "-", number2)
        answer = number1 - number2

    while True:
        try:
            user_answer = int(input())
        except ValueError:
            print ("That is not a valid answer")
            continue 
        else:
            break

    if user_answer == answer: 
        print("Correct")
        Score += 1

    else:
        print("Incorrect")
    question += 1

    if question == 10:
        print("Well done you scored", Score, "/10")
        break
if os.path.isfile('results.db'):
    connection = lite.connect('results.db')
else:
    connection = lite.connect('results.db')

for x in range (1, 4):
    connection.execute('CREATE TABLE %s(Name INTEGER, Score TEXT);'% x)


def Pupil_Results(Name, Score):
    table = 'class%s' % class_group
    with connection:
        cur = connection.cursor()
        cur.execute('SELECT * FROM ' + table + ' WHERE name = "%s";' % Name)
        rows = cur.fetchall()

    if len(rows) > 0:
        cur.execute('UPDATE ' + table + ' SET Name = "%i" WHERE Score = "%s";' % (Name, Score))
    else:
        cur.execute('INSERT INTO ' + table + '(Name, Score) VALUES (?, ?);',           (Name, Score))   
Pupil_Results(Name, Score)

1 个答案:

答案 0 :(得分:0)

您使用SQLite的代码部分存在一些问题。

首先,无论os.path.isfile('results.db')的结果如何,您都以相同的方式连接到数据库,因此只需连接即可。

其次,更重要的是,仅使用一个包含额外列class_group的表而不是单独的表更为实际。

第三,name应为TEXT类型,而score应为INTEGER类型,而不是相反。

第四,该表可能已经存在,因此您应该在命令中添加IF NOT EXISTS

第五,你的函数应该以{{1​​}}为参数。它也应该将连接作为参数,或者自己建立连接。

以下是该部分的外观:

class_group