【发布时间】:2020-04-03 01:41:09
【问题描述】:
我正在尝试编写一个程序来询问起始余额,减去费用。如果用户选择是以获得更多费用,它会正确循环并要求另一个条目。如果用户选择 N,程序将停止并打印起始余额、费用条目总数和所有费用后的期末余额。以下代码全部正确输出,但在所有费用后未输出正确的金额。
# Initialize the accumulator.
account_balance = 0
ending_balance = 0
expense = 0
keep_going = "y"
# Prompt user for account balance.
account_balance = float (input("Enter the starting balance of the account you want to use:"))
# Calculate the balance.
for a in range (1000):
while keep_going == "y":
# Prompt user for an expense.
purchase = int (input("What is the value of the expense?:"))
# Calculate the remaining balance.
ending_balance = account_balance - purchase
#Calculate the total expenses entered.
expense = expense + 1
# Ask if user has another expense.
keep_going = input("Do you have another expense? (Enter y for yes)")
if keep_going == "n":
print("Amount in account before expense subtraction $", format (account_balance, ",.2f"))
print("Number of expenses entered:", expense)
print("Amount in account AFTER expenses subtracted is $", format (ending_balance, ",.2f"))
# Pseudo Code
# Prompt user to enter amount in account in which money will be withdrawn from
# Prompt user to enter amount of first expense
# Subtract expense from account
# Ask user if they would like to add another expense
# If "yes" then ask user to add expense
# If "no" then display the following
# Amount in account BEFORE expenses
# Number of transactions made
# Amount in account AFTER all expenses are subtracted
【问题讨论】:
-
每次
while循环结束时account_balance都不会改变,所以ending_balance总是最初的account_balance减去你输入的最后一个purchase -
这就是我遇到的问题。我不知道如何编写该行以使每个 while 循环的 account_balance 都发生变化。如果我从 500 开始并在两项费用中输入 100,则输出是 400 而不是 300。
-
也许你可以尝试在初始化
account_balance之后添加ending_balance = account_balance,并在循环中修改ending_balance
标签: python