【发布时间】:2021-11-15 20:08:06
【问题描述】:
我是 python 新手,所以如果它真的很基本,请不要感到惊讶,但我一直在尝试编写这段代码来询问数学问题,然后保存分数以便在开始时再次显示它们的循环,但它不保存分数。我应该改变什么? 这是代码
scores = []
names = []
while True:
f = open("highscore.txt", "r")
for line in f:
line = line.strip("\n")
line = line.split(" ")
names.append(line[0])
scores.append(int(line[1]))
print(f.read())
for pos in range(len(names)) :
print(pos + 1, names[pos], scores[pos])
f.close()
score = 0
print("hello, welcome to maths game")
print("\nQuestion 1: what is 2 x 2 x 2?")
answer = int(input("your answer >"))
if answer == 8:
print("correct")
score = score + 1
print("your score is ", score)
else:
print("incorrect")
print("the score is ", score)
print("\nQuestion 2: what is 34 x 2?")
answer = int(input("your answer >"))
if answer == 68:
print("correct")
score = score + 1
print("your score is", score)
else:
print("incorrect")
print("the score is", score)
name = input("what is your name?")
position = 0
for compare_score in scores :
if score < compare_score:
position = position + 1
scores.insert(position, score)
names.insert(position, name)
scores = scores[:5]
names = names[:5]
f = open("highscore.txt", "w")
for pos in range (len(names)):
f.write(names[pos] + " " + scores[pos])
它不会给出任何类型的错误消息,只是循环返回并且不保存名称,也不保存分数
【问题讨论】:
-
在询问代码相关问题时,始终需要为您使用的语言添加标签。这次我已经为你做了,但以后请记住。
-
顺便说一句,反复将内容写入文件然后再将它们读回是非常低效的。您希望在开始时将文件读入内存一次,然后在游戏结束时写入更新的文件(除非您非常需要程序的多个实例来共享相同的数据,在这种情况下,文本文件非常脆弱并且,同样,效率低下)。
-
我会尽量记住这一点。对于不必要的更新,我很抱歉,但我仍在学习如何编写它们。谢谢你的耐心
-
@S.Tack 每当您使用
while True。确保在某些情况下具有break或return语句(或程序退出)。否则它将永远运行
标签: python loops saving-data