如何在每个命令中存储我的数据 (python)

How to store my data in every command (python)

我想存储我的数据并在每个命令后添加它们,但是当我再次选择一个新命令时,初始数据将消失。

如何存储我的数据并继续添加?

我的代码:

initial_money = int(input('How much money do you have? ')) 

def records():
    return

def add(records):
    records = input('Add an expense or income record with description and amount:\n').split() 
    amount = initial_money   #I don't know how to modify ...
    amt = records[1]
    amount += int(amt)
    print('Total amount',amount)
    
while True:
    command = input('\nWhat do you want to do (add / view / delete / exit)? ') 
    if command == 'add':
        records = add(records)

输出:

How much money do you have? 1000

What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tree 40
Total amount 1040

What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
mouse 70
Total amount 1070

我想要的输出:

How much money do you have? 1000

What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tree 40
Total amount 1040

What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
mouse 70
Total amount 1110

你只需要将它保存到你的变量中。

global initial_money # this will let you use it anywhere in the code
initial_money = int(input('How much money do you have? ')) 

def records():
    return

def add(records):
    records = input('Add an expense or income record with description and amount:\n').split() 
    amount = initial_money   #I don't know how to modify ...
    amt = records[1]
    amount += int(amt)
    initial_money = amount #this saves it
    print('Total amount',amount)
    
while True:
    command = input('\nWhat do you want to do (add / view / delete / exit)? ') 
    if command == 'add':
        records = add(records)

您的 amount 变量是本地变量,当函数退出时它不会被保存。您可以通过将它放在函数外部并在开头声明 global amount 将其用作全局变量,这样您就可以在 运行.

期间编辑它

您需要将 initial_money 变量声明为全局变量 添加函数中:

initial_money = int(input('How much money do you have? '))

def records():
    return

def add(records):
    records = input('Add an expense or income record with description and 
amount:\n').split()
    amt = records[1]
    global initial_money
    initial_money += int(amt)

    print('Total amount', initial_money)

while True:
    command = input('\nWhat do you want to do (add / view / delete / exit)? ') 
    if command == 'add':
        records = add(records)

这应该有效。