Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何确保在循环中计算所有值?_Python_Loops_Class_Object - Fatal编程技术网

Python 如何确保在循环中计算所有值?

Python 如何确保在循环中计算所有值?,python,loops,class,object,Python,Loops,Class,Object,我正在做一个“保留零钱任务”,我把购买的钱四舍五入到整美元,然后把零钱加到储蓄账户上。但是,循环并没有遍历外部文本文件中的所有值。它只计算最后一个值。我试图分割文件,但它给了我一个错误。可能是什么问题?我的外部文本文件如下所示: 10.90 13.59 12.99 (各在不同的线路上) def main(): 我很确定这样做的原因是因为您正在打印您已保存到文件中的金额。一般来说,您不希望更改正在迭代的对象的长度,因为这可能会导致问题 account1 = BankAccount()

我正在做一个“保留零钱任务”,我把购买的钱四舍五入到整美元,然后把零钱加到储蓄账户上。但是,循环并没有遍历外部文本文件中的所有值。它只计算最后一个值。我试图分割文件,但它给了我一个错误。可能是什么问题?我的外部文本文件如下所示:

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
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)
这将在完成文件迭代后打印文件末尾保存的金额

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)