【问题标题】:Python loop statementsPython 循环语句
【发布时间】:2017-06-20 09:57:38
【问题描述】:

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

示例输出 第一天卖出了多少辆车? 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) + ' '))

主()

【问题讨论】:

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


    【解决方案1】:

    为此,您需要使用嵌套的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2020-06-18
      • 2015-12-11
      • 2013-07-10
      • 2017-10-13
      • 1970-01-01
      相关资源
      最近更新 更多