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?
添加回答
舉報