Python循环语句

时间:2017-02-03 05:20:45

标签: python-3.x loops for-loop while-loop

我一直在为我的作业制作一个程序: 为每周工作五天的汽车销售人员编写一个程序。该程序应提示每天售出多少辆汽车,然后在当天提示每辆汽车的售价(如果有的话)。输入所有五天的数据后,程序应报告销售的汽车总数和该期间的总销售额。参见示例输出。注意:复制显示的总销售额货币格式

示例输出 第1天售出了多少辆汽车? 1 卖车1的价格? 30000 第2天卖了多少辆汽车? 2 卖车1的价格? 35000 卖车2的价格? 45000 第3天卖了多少辆汽车? 0 第4天卖了多少辆汽车? 1 卖车1的价格? 30000 第5天卖了多少辆汽车? 0 您售出4辆汽车,总销售额为140,000.00美元

我确实有一些我已经处理过的代码,但是我被卡住了。我可以弄清楚如何让程序提示用户在第2天销售了多少辆汽车,依此类推。任何帮助,将不胜感激!

这是我的代码,我也参加了一个基本的python课程,所以我是新手!!

    def main () :

   cars_sold = []
   num_days = int(input('How many days do you have sales?'))

   for count in range(1, num_days + 1):
       cars = int(input('How many cars were sold on day?' + \
                        str(count) + ' '))

   while (cars != cars_sold):
    for count in range(1, cars + 1):
        cars_sold = int(input('Selling price of car' ' ' + \
                           str(count) + ' '))

main()

1 个答案:

答案 0 :(得分:0)

为此,您需要使用嵌套的for循环来提示输入的每辆车。

def main():
    cars_sold = 0
    total = 0
    num_days = int(input('How many days do you have sales? '))

    # for each day
    for i in range(1, num_days + 1):
        num_cars = int(input('How many cars were sold on day {0}? '.format(i)))
        cars_sold += num_cars

        # for each car of each day
        for j in range(1, num_cars + 1):
            price = int(input('Selling price of car {0}? '.format(j)))
            total += price

    # Output number of cars and total sales with $ and comma format to 2 decimal places
    print('You sold {0} cars for total sales of ${1:,.2f}'.format(cars_sold, total))

# Output
>>> main()
How many days do you have sales? 5
How many cars were sold on day 1? 1
Selling price of car 1? 30000
How many cars were sold on day 2? 2
Selling price of car 1? 35000
Selling price of car 2? 45000
How many cars were sold on day 3? 0
How many cars were sold on day 4? 1
Selling price of car 1? 30000
How many cars were sold on day 5? 0
You sold 4 cars for total sales of $140,000.00