When programs are run then any variables they use are stored in ram, which is lost whenever you close the program. If you want your data to be stored between times when you run your program you're going to need to save them to a file.
Luckily python has some really helpful functions to do this.
Your code as is looks very neat and will work just fine, we just need to add the file reading and writing
first you'll want to open the file that we use to store the total, using read mode with "r"
file = open("total.txt", "r") # open the file in read mode
data = file.readline() # read the line
total = int(data) # get the total as an int
however when you first run the program this file won't exist yet (as we haven't made it) and the total will be 0. We can use a try
block to catch this, and create a new file using the "w+"
mode, which will create a file if one with that name does not exist
total = int()
try: # try open the file
file = open("total.txt", "r")
data = file.readline()
total = int(data)
except: # if file does not exist
file = open("total.txt", "w+") # create file
total = 0 # this is the first time we run this so total is 0
file.close() # close file for now
then you can run your code, and after we want to store the new total, opening the file this time in write mode "w"
, this will wipe the old total from the file
file = open("total.txt", "w") # wipe the file and let us write to it
file.write(str(total)) # write the data
file.close() # close the file
now the next time you run your program it will load this total and will be added up properly!
Here is it all together,
def money_earnt():
total = int()
try: # try open the file
file = open("total.txt", "r")
data = file.readline()
total = int(data)
except: # if file does not exist
file = open("total.txt", "w+") # create file
total = 0
file.close() # close file for now
while True:
try:
pay_this_week = int(input("How much money did you earn this week? "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
pay_this_week_message = "You've earnt £{0} this week!".format(pay_this_week)
total = pay_this_week + total
total_message = "You have earned £{0} in total!".format(total)
print(pay_this_week_message)
print(total_message)
file = open("total.txt", "w") # wipe the file and let us write to it
file.write(str(total)) # write the data
file.close() # close the file
money_earnt()