问题描述
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')} ")
else:
loggedOn = False
print("Transaction number: ",random.randint(10000,1000000))
解决方法
编辑:泡菜解决方案 我看到你标记了这个泡菜。泡菜的解决方案几乎相同
#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())
如果您有更多变量要保存和重复使用,则可能需要将文件命名为其他名称。