我正在进行“保留更改任务”,在该操作中,我将购买金额四舍五入为整数,然后将更改添加到储蓄帐户中。但是,循环不会遍历我的外部文本文件中的所有值。它仅计算最后一个值。我尝试拆分文件,但它给了我一个错误。可能是什么问题?我的外部文本文件是这样的:
10.90 13.59 12.99 (每行不同)
def main():
account1 = BankAccount()
file1 = open("data.txt","r+") # reading the file, + indicated read and write
s = 0 # to keep track of the new savings
for n in file1:
n = float(n) #lets python know that the values are floats and not a string
z= math.ceil(n) #rounds up to the whole digit
amount = float(z-n) # subtract the rounded sum with actaul total to get change
print(" Saved $",round(amount,2), "on this purchase",file = file1)
s = amount + s
x = (account1.makeSavings(s))
答案 0 :(得分:1)
我相当确定这是因为您要打印已保存到文件中的金额。通常,您不想更改要迭代的对象的长度,因为它会引起问题。
account1 = BankAccount()
file1 = open("data.txt","r+") # reading the file, + indicated read and write
s = 0 # to keep track of the new savings
amount_saved = []
for n in file1:
n = float(n) #lets python know that the values are floats and not a string
z= math.ceil(n) #rounds up to the whole digit
amount = float(z-n) # subtract the rounded sum with actaul total to get change
amount_saved.append(round(amount,2))
s = amount + s
x = (account1.makeSavings(s))
for n in amount_saved:
print(" Saved $",round(amount,2), "on this purchase",file = file1)
这将在完成遍历之后在文件末尾打印您保存的金额。