python - 如何永久制作变量存储,因此当我单击运行时它不会重新启动到原始状态 - python
问题描述
所以我有问题,我想在 python 中计算数字。我想要这样,如果我问一个问题,用户会得到 10 分,但如果我点击运行,它会将分数重新恢复为 0,因为变量等于 0。有没有办法永久存储积分,这样当我再次运行时,积分仍然存在。
我是一个菜鸟,所以我不知道该尝试什么我刚开始学习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()
推荐阅读
- c# - 发布人重新调整空文件,甚至上传文件
- javascript - 对象内的对象
- android - 如何在 Firebase 云消息传递实施期间解决 gradle 依赖问题?
- sequelize.js - 如何在 sequelize.js 中使用子查询?
- angular - 当我们移到外面时,悬停时的 Angular bootstrap Popover 正在关闭。当悬停在弹出框内容本身上时,弹出框应该打开
- sql-server - 如何将 context_info 返回值转换为 xml
- php - php中的sql命令可以用“。”从其他变量中设置吗?连接器?
- python - Python - 字符串到 JSON。错误:AttributeError:“str”对象没有属性“get”
- python - 我正在尝试创建一个程序,将 2 个(用户)输入转换为列表,然后在列表中打印重复项
- mysql - 获取具有最大值的单元格的整行/行