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

2024-09-28 05:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

#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'))

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


Tags: offorinputifvariablescaramountprice
2条回答

编辑时间: 在Python中,编写简洁的代码非常重要,错误检查也非常重要,因为键入数字以外的任何内容都很容易产生错误:

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))

您只在最后一天向totalcar添加了值,而下面的代码每天都在添加值

#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'))

相关问题 更多 >

    热门问题