2011-02-05 54 views
2

我只是學習Python和我試圖找出如何傳遞參數在「爲範圍」循環的變量範圍循環。在下面的代碼中,我希望'月份'變量是月份的名稱(1月,2月等)。然後,我試圖讓'sales'變量的用戶提示爲'輸入Jan的銷售額'。然後下一個迭代,移動到下一個月份 - 「輸入銷售二月」傳遞參數對於在Python 2.5

謝謝你的任何建議。

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

回答

4

Python的字典和列表對象將帶你走得很遠。

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

calendar.month_name [1] ==「一月」等,這有時是方便的,但對於做手工不教學法上是有用所以+1。 – DSM 2011-02-05 06:41:46

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個位數(而不是更多)。