Python-回写功能不起作用

时间:2018-07-11 18:54:18

标签: python shelve

这是我的学校数字游戏项目代码:我试图将用户名和分数存储在数据库中,然后打印所有用户名和分数的列表。

运行代码时,每次都将覆盖用户名和分数,并且不会保存前一个用户和分数。

writeback = True 函数是否不能防止数据被覆盖?

name=('n')
Fscore=(0)

import shelve

s = shelve.open('hscore_shelf.db',writeback=True)
key1 = [name]
try:
    existing = s['key1']
finally:
    s.close()

print (existing)
import shelve
n = shelve.open('score_shelf.db',writeback=True)
key1 = [Fscore]
try:
    existing = n['key1']
finally:
    s.close()
print(existing)

print("WELCOME TO THE NUMBER QUIZ")
input("HIT ENTER TO START")
name=(input("ENTER YOUR NAME"))
q = (1)
score=(0)
while q <=1 and q >0:

    import random
    num1 =(random.randint(1,9))
    num2 =(random.randint(1,9))
    num3 =(random.randint(1,9))

    index1=num1
    index2=num2
    index3=num3
    e=(" eleven")
    teens=

("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen")
    units=(" ","one","two","three","four","five","six","seven","eight","nine")
    tens=(""," ","twenty ","thirty ","fourty ","fifty ","sixty ","seventy ","eighty ","ninety ")
    hun=("","one hundred and ", "two hundred and ", "three hundred and ", "four hundred and ", "five hundred and ", "six hundred and ", "seven hundred and ", "eight hundred and ", "nine hundred and ")

    print("Type in the following number using digits")
    if num1==0 and num2==0 and num3==0:
        print("zero")
    elif num1==0 and num2==0 and num3>0:
        print(units[index3])
    elif num1==0 and num2==1:
        print(teens[index3])   
    elif num1>0 and num2==1 and num3==1:
        print(hun[index1]+e)
    else:
        print(hun[index1]+tens[index2]+units[index3])

    num11=(int(input("Enter first digit:")))
    num22=(int(input("Enter second digit:")))
    num33=(int(input("Enter third digit:")))

    q = (q-1)
    if num1==num11 and num2==num22 and num3==num33:
        print("Correct")
        score=(score+1)
    else:
        print("Incorrect")


Fscore=(score)
print((name)+" Scored " + str( score))


s = shelve.open('hscore_shelf.db')
try:
    s['key1']=[name]
finally:
    s.close()

n = shelve.open('score_shelf.db')
try:
    n['key1']=[Fscore]
finally:
    n.close()

1 个答案:

答案 0 :(得分:0)

旁注:您无需两次import shelve

搁置所做的是在python中存储“类似于字典”的对象。当您将'key1'键重新分配给另一个值时,实际上是在覆盖它。相反,请尝试仅使用一个数据库,将“名称”作为键,将“得分”作为值。