【问题标题】:How to change the numerical value of a variable after it has already been defined? [duplicate]如何在变量已经定义后更改其数值? [复制]
【发布时间】:2018-09-16 17:11:50
【问题描述】:

如何在变量已经定义后更改它的值,然后在下次运行程序时将变量更改为新值。

p = 0
result = int(input("Test "))
if result == 3:
   points = p+3
   p = points

基本上,我需要它,以便下次运行此代码时,“p”已设置为 3,然后再更改为 6,依此类推。

【问题讨论】:

  • 您可以将变量的值输出到文件中。在程序开始时读取文件并在程序结束时写入文件。
  • 你熟悉读写文件吗?
  • 还是数据库?您需要某种持久性(可能在磁盘上)存储。
  • 您也可以使用pickle 模块并创建一个保存变量值的.pickle 文件。我认为这比使用 .txt 文件更简洁。
  • 我相信您对计算机程序的工作原理存在根本性的误解。当您加载 Python 解释器并执行 Python 程序时,程序的对象会在 main memory 中创建,即 RAM。你要找的是data persistence,一般是通过将你的数据以某种格式写入辅助内存,即写入磁盘来实现的。

标签: python python-3.x python-2.7


【解决方案1】:
import os

with open('tmp.txt', 'r') as file:
     p = file.read()
os.remove("tmp.txt")
result = int(input("Test "))
if result == 3:
   points = int(p)+3
   p = points
   with open('tmp.txt', 'w') as file:
       file.write(str(p))

试试这个。在运行脚本之前,在与您的代码相同的文件夹中创建一个文件“tmp.txt”。

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多