2 回答
TA贡献1844条经验 获得超8个赞
当程序运行时,它们使用的任何变量都存储在内存中,每当您关闭程序时,内存就会丢失。如果您希望在运行程序时存储数据,则需要将它们保存到文件中。
幸运的是,Python 有一些非常有用的函数可以做到这一点。
您的代码看起来非常整洁并且可以正常工作,我们只需要添加文件读取和写入
首先,您需要使用读取模式打开我们用来存储总计的文件"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
然而,当你第一次运行程序时,这个文件还不存在(因为我们还没有创建它),总数将为 0。我们可以使用一个块try来捕获这个文件,并使用模式创建一个新文件"w+",这将如果同名文件不存在则创建一个文件
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
然后你可以运行你的代码,在我们想要存储新的总计之后,这次以写入模式打开文件"w",这将从文件中擦除旧的总计
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
现在,下次运行程序时,它将加载此总数并正确相加!
这就是全部内容,
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()
TA贡献1824条经验 获得超8个赞
你已经快到了,不要放弃。2个主要错误:
break
如果while
你想让它永远持续下去就没有必要在Python中,标识产生了所有的差异,只有标识的行才进入到while中,我猜你希望所有的行都在里面。
这是我的尝试:
def money_earnt():
total = int()
while True:
try:
pay_this_week = int(input("How much money did you earn this week? "))
except ValueError:
print("Oops! That was no valid number. Try again...")
continue
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)
money_earnt()
我的输出是:
How much money did you earn this week? 4
You've earnt £4 this week!
You have earned £4 in total!
How much money did you earn this week? 5
You've earnt £5 this week!
You have earned £9 in total!
How much money did you earn this week? 6
You've earnt £6 this week!
You have earned £15 in total!
How much money did you earn this week?
添加回答
举报