0

For example,

x = 0
for i in range(5):
   x += 1
print(x)

Here, I want the value of x to remain 5 and not reset to 0 after the program terminates, just the way normal applications do with your settings, personal info etc.

Community
  • 1
  • 1
cheemse
  • 41
  • 6
  • But when you run it again, you immediately set `x = 0`, so how would you know? Maybe [reading through this](https://stackoverflow.com/questions/14509269/best-method-of-saving-data) would help. – Mark Jun 09 '20 at 02:55
  • @MarkMeyer you have a point though.. thanks! – cheemse Jun 09 '20 at 03:03
  • 1
    Normal applications don't work that way, they use some form of *data persistence.* This could be anything as simple as a text file that you read to load the values or a full-fledge database and beyond – juanpa.arrivillaga Jun 09 '20 at 03:12

2 Answers2

2

After a program terminates, anything that was in its memory is gone. The simplest way to persist data permanently is to write it to a file, which you can read about here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

For example:

try:
    with open("save.txt") as save:
        x = int(save.read())
except FileNotFoundError:
    print("No save file found, starting at 0")
    x = 0

for i in range(5):
    x += 1
print(x)

with open("save.txt", "w") as save:
    save.write(str(x))
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

Use a database! You can try storing your data in a database like MongoDB. Another thing you can do is create a local file as mentioned by @Samwise. But it might be better to use a database as it will help in learning how to use it if you are new to databases. You can try using MongoDB with pymongo

Edit

Extending @Samwise's answer. You might want to store multiple values in your local file. To do this try creating a JSON or YAML file. For JSON files you can use the standard json library and for YAML search for one on PyPI

Shardul Nalegave
  • 419
  • 9
  • 16