在Python 2.5中的嵌套For Range循环中传递参数

时间:2011-02-05 02:47:04

标签: python

我只是在学习Python,并试图弄清楚如何将'for range'循环中的参数传递给变量。在下面的代码中,我希望'months'变量是月份的名称(Jan,Feb等)。然后我试图让“sales”变量的用户提示符为“输入Jan的销售额”。然后在下一次迭代中,移至下个月 - “输入2月的销售额”

感谢您提出任何建议。

def main():
    number_of_years = input('Enter the number of years for which you would like to compile data: ')
    total_sales = 0.0
    total_months = number_of_years * 12

    for years in range(number_of_years):
        for months in range(1, 13):
            sales = input('Enter sales: ')
            total_sales += sales

    print ' '        
    print 'The number of months of data is: ', total_months
    print ' '
    print 'The total amount of sales is: ', total_sales 
    print ' '
    average = total_sales / total_months    # variable to average results
    print 'The average monthly sales is: ', average

main()

2 个答案:

答案 0 :(得分:4)

Python的dict和list对象将带你走远。

>>> months = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
>>> sales = {}
>>> for num, name in enumerate(months, 1):
    print "Sales for", name
    sales[num] = 14.99 # get the sales here
    print "Num:", num

Sales for Jan
Num: 1
Sales for Feb
Num: 2
Sales for Mar
Num: 3
Sales for Apr
Num: 4
... etc.

>>> for month, price in sales.items():
    print month, "::", price

1 :: 14.99
2 :: 14.99
... etc.

>>> ave = sum(sales.values()) / float(len(sales)) # average sales

答案 1 :(得分:2)

您需要的是允许您将月份数字从1-12转换为月份名称缩写的内容。虽然你可以使用月份名称列表相当容易地做到这一点,只要你记得在使用它之前总是从月份数中减去1,因为列表的索引是从0而不是1.另一个选择不是要求使用Python字典。

使用字典,您的程序可能如下所示:

# construct dictionary
month_names = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
months = dict((i, month) for i, month in enumerate(month_names, 1))

def main():
    number_of_years = input('Enter the number of years for which '
                            'you would like to compile data: ')
    total_sales = 0.0
    total_months = number_of_years * 12

    for years in range(number_of_years):
        for month in range(1, 13):
            sales = input('Enter sales for %s: ' % months[month])
            total_sales += sales

    print
    print 'The number of months of data is: ', total_months
    print
    print 'The total amount of sales is: ', total_sales
    print
    average = total_sales / total_months    # variable to average results
    print 'The average monthly sales is: ', average

main()

除了添加months字典的构造之外,我还将您的调用修改为input()以使用该变量,以便用户提示显示月份的名称。

顺便说一下,您可能还想将打印平均值的语句更改为:

print 'The average monthly sales is: "%.2f"' % average

因此它只显示小数点后的2位数(而不是更多)。