2011-02-05 17 views
2

私はPythonを学んでいるだけで、 'for range'ループの引数を変数に渡す方法を理解しようとしています。以下のコードでは、 'months'変数を月の名前(Jan、Febなど)にしたいと思います。それから私は、 'sales'変数が 'Janの売上を入力する'というユーザーのプロンプトを出そうとしています。その後、次の繰り返しで次の月に移動します。「Febの売上を入力してください」Python 2.5でネストされたFor Rangeループの引数を渡す

ありがとうございます。

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のdictとリストオブジェクトがあなたを遠ざけます。

>>> 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] == 'January'など、手軽ではあるが手技的には便利なので、手動で行うには+1。 – DSM

+2

'enumerate(months、1)'を提案する。 –

+1

セールス[名前]を直接使用しないのはなぜですか? – Rod

2

必要なものは、1〜12の月の数字を月の名前の略語に変換できるものです。 ですが、リストは0ではない1から索引付けされているため、使用する前に月の数値から常に1を減算することを忘れない限り、月名のリストを使用するとかなり簡単に実行できます。 Python辞書を使用する。辞書を使用して

、あなたのプログラムは次のようなもののようになります、私は、ユーザープロンプトが表示されますので、その変数を使用するようにinput()にお電話を修正months辞書の構築を加えることに加えて

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

月の名前。だから、それだけで(代わりに、より多くのの)小数点以下2桁を表示し

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

はところで、あなたはまた、平均を出力文を変更したい場合があります。

関連する問題