首页 > 解决方案 > 如何永久制作变量存储,因此当我单击运行时它不会重新启动到原始状态 - python

问题描述

所以我有问题,我想在 python 中计算数字。我想要这样,如果我问一个问题,用户会得到 10 分,但如果我点击运行,它会将分数重新恢复为 0,因为变量等于 0。有没有办法永久存储积分,这样当我再次运行时,积分仍然存在。

我是一个菜鸟,所以我不知道该尝试什么我刚开始学习python,所以我知道的不多,所以你能用简单的术语向我解释一下,因为我刚开始学习并且什么都不懂

标签: python

解决方案


我认为你应该看看如何在 python 中读写文本文件

#get score in your program and then do this
score = 10
def saveScore(x):
    file = open("myfile.txt","a")
    file.write(str(x)+'\n')
    file.close()
def readScore():
    file = open("myfile.txt","r")
    return file.readlines()[-1]

#save score everytime time it changes
saveScore(score)
#this function will score of last saved state
score = readScore()

推荐阅读