Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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_Python 3.x - Fatal编程技术网

试图让我的python程序在循环后添加总值,但它会输出最终值

试图让我的python程序在循环后添加总值,但它会输出最终值,python,python-3.x,Python,Python 3.x,我尝试过的不同配置要么在每次输入后添加,要么只添加最后一个值 您仅在最后一天向total和car添加了值,而下面的代码每天都在添加值 #Variables total = 0 day = 0 car = 0 while day <= 4: day += 1 if day <= 5: print('Cars sold on day', day, end = ': ',) carSold = int(input('')) for amount in

我尝试过的不同配置要么在每次输入后添加,要么只添加最后一个值

您仅在最后一天向total和car添加了值,而下面的代码每天都在添加值

#Variables
total = 0
day = 0
car = 0

while day <= 4:
  day += 1

  if day <= 5:
    print('Cars sold on day', day, end = ': ',)
    carSold = int(input(''))

    for amount in range(carSold):
      print('Selling price of car', amount + 1, end = ':\t')
      price = int(input('$'))

  if day >= 5:
    total += price
    car += carSold
    print('\nYou sold', car, 'cars for a total of $', format(total,',.2f'))
编辑: 在Python中编写简洁的代码非常重要,错误检查也非常重要,因为键入数字以外的任何内容都很容易产生错误:

#Variables
total = 0
car = 0

for day in range(1, 6):
    carSold = int(input('Cars sold on day {}: '.format(day)))
    car += carSold

    for amount in range(carSold):
        total += int(input('Selling price of car {}: $'.format(amount+1)))

    if day == 5:
        print('\nYou sold', car, 'cars for a total of $', format(total,',.2f'))

你就是炸弹。您能解释一下day和amount+1的格式是什么吗?它们将{}替换为输入参数。
total = 0
day = 0
car = 0
carSold = 0
lastsold = 0


while day <= 4:
    day += 1
    try:
        if day <= 5:
            lastsold += int(input('Cars sold on day %i: '%day))
            carSold += lastsold

        for amount in range(carSold):
            total += int(input('Selling price of car %i: $'%(amount+1)))
    except:
        day -= 1
        carSold -= lastsold
        continue
    lastsold = 0

    if day >= 5:
        print('\nYou sold %i cars for a total of $%.2f'%(car,total))