Python写回函数不起作用



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

当我运行代码时,每次都会覆盖用户名和分数,并且不会保存以前的用户和分数。

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()

附带说明:您不需要import shelve两次。

shelve所做的是在python中存储一个"类似字典"的对象。当你将"key1"键重新分配给一个不同的值时,你实际上是在覆盖它。相反,试着只使用一个数据库,将"name"作为键,将"score"作为值。

最新更新