这是一个数字游戏的学校项目代码:我尝试将用户的姓名和分数存储在数据库中,然后打印所有用户名和分数的列表。
当我运行代码时,每次都会覆盖用户名和分数,而不会保存之前的用户和分数。
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()
发布于 2018-07-12 03:01:06
附注:你不需要import shelve
两次。
shelve所做的就是在python中存储一个“类字典”对象。当您将'key1‘键重新分配给一个不同的值时,您实际上是在覆盖它。取而代之的是,尝试只使用一个数据库,将"name“作为键,将"score”作为值。
https://stackoverflow.com/questions/51292438
复制相似问题