【问题标题】:How to keep and run the program always form the last value, so when I open again the program starts from the last amount如何保持和运行程序始终形成最后一个值,所以当我再次打开时,程序从最后一个数量开始
【发布时间】:2020-09-06 17:40:06
【问题描述】:
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))

【问题讨论】:

    标签: python pickle shelve


    【解决方案1】:

    编辑: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())
    

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

    【讨论】:

      猜你喜欢
      • 2015-02-11
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多