如何保持 运行 程序始终形成最后一个值,所以当我再次打开程序时,程序从最后一个值开始

How to keep and run the program always form the last value, so when I open again the program starts from the last amount

import random
 
amount = 100
loggedOn = True
 
while loggedOn:
    selection = int(input("Select 1 for Deposit, 2 for Withdraw or 3 for Exit: "))
    if not selection:
        break
    if selection == 1:
        deposit = float(input("How much will you deposit? "))
        amount += deposit
        print(f"Deposit in the amount of ${format(deposit, '.2f')} ")
        print(f"Bank account balance ${format(amount, '.2f')} ")
    elif selection == 2:
        withdraw = float(input("How much will you withdraw? "))
        amount -= withdraw
        print(f"Withdraw in the amount of ${format(withdraw, '.2f')} ")
        print(f"Bank account balance ${format(amount, '.2f')} ")
    else:
        loggedOn = False
 
print("Transaction number: ", random.randint(10000, 1000000))

编辑:泡菜解决方案 我看到你给这个泡菜贴了标签。 pickle 的解决方案几乎相同

#import the package
import pickle
#saving the variable
with open("last_amount.pickle",'wb') as f:
    pickle.dump(amount, f)
#getting the variable from save file
with open("last_amount.pickle", 'rb') as f:
    amount = pickle.load(f)

您可以将金额保存在同一目录下的文件中。 我假设程序在退出 while 循环时在这里“关闭”。

此解决方案需要 JSON

import json

保存最后金额

with open("last_amount.txt",'w') as last_amount_file:
    last_amount_file.write(json.dumps(amount))
    #Place this in the block executed when the program closes.

现在最后的金额写在同一目录下名为“last_amount”的文本文件中。 要在再次打开程序时使用上次的金额,您可以这样做。

使用最后的金额

with open("last_amount.txt",'r') as f:
    amount = json.loads(f.readline())

如果您有更多变量要保存和重复使用,您可能希望将文件命名为其他名称。