简体   繁体   中英

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))

Edit: solution with pickle I saw you tagged this pickle. The solution with pickle is nearly identical

#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)

You could save the amount in a file in the same directory. I'm assuming that the program "closes" here when escaping the while loop.

You'll need JSON for this solution

import json

Saving last amount

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.

Now the last amount is written in a text file named "last_amount" in the same directory. To use the last amount when opening the program again you can do this.

Using last amount

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

If you have more variables to save and reuse you might want to name the file something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM