Ahmed
Ahmed

Reputation: 13

can I re initialize a variable after proceeding the code at python

I want to make a program that takes some information from a user and gives them a certain value that has increased by a certain amount from the last time the program was run.

So to give an example:

Is this even possible in Python?

Upvotes: 1

Views: 42

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20424

First, create a file named something like data.txt in the same directory as your .py file with just the value 0 in it.

Then in your .py file, you could do something like:

curNum = int(open("data.txt", "r").read())

toAdd = int(input("number to add: "))

newNum = curNum + toAdd

print("number is now:", newNum)

open("data.txt", "w").write(str(newNum))

So after creating the file: data.txt with content 0, here is the result of some tests:

1st run

number to add: 10
number is now: 10

2nd run

number to add: 2
number is now: 12

3rd run

number to add: 8
number is now: 20

Hope you can apply this to what you want to do!

Upvotes: 1

Related Questions