3

Python プログラミング入門クラスの宿題に取り組んでいますが、問題が発生しています。手順は次のとおりです。

入力された値の平均を出力するように find_sum() 関数を変更します。前の average() 関数とは異なり、len() 関数を使用してシーケンスの長さを見つけることはできません。代わりに、入力された値を「カウント」する別の変数を導入する必要があります。

入力の数を数える方法がわかりません。誰かが私に良い出発点を与えることができれば、それは素晴らしいことです!

# Finds the total of a sequence of numbers entered by user 
def find_sum(): 
     total = 0 
     entry = raw_input("Enter a value, or q to quit: ") 
     while entry != "q": 
         total += int(entry) 
         entry = raw_input("Enter a value, or q to quit: ") 
     print "The total is", total 
4

2 に答える 2

3

input を読み取るたびtotal += int(entry)に、その直後に変数をインクリメントする必要があります。

num += 1他の場所で 0 に初期化した後は、これで十分です。

whileループ内のすべてのステートメントでインデント レベルが同じであることを確認してください。あなたの投稿 (最初に書かれたもの) にはインデントが反映されていませんでした。

于 2013-03-06T03:30:02.960 に答える
0

@BlackVegetableが言ったように、いつでも反復カウンターを使用できます。

# Finds the total of a sequence of numbers entered by user 
def find_sum(): 
     total, iterationCount = 0, 0 # multiple assignment
     entry = raw_input("Enter a value, or q to quit: ") 
     while entry != "q": 
         iterationCount += 1
         total += int(entry) 
         entry = raw_input("Enter a value, or q to quit: ") 
     print "The total is", total 
     print "Total numbers:", iterationCount

または、各数値をリストに追加してから、合計と長さを出力することもできます。

# Finds the total of a sequence of numbers entered by user
def find_sum(): 
     total = []
     entry = raw_input("Enter a value, or q to quit: ") 
     while entry != "q": 
         iterationCount += 1
         total.append(int(entry))
         entry = raw_input("Enter a value, or q to quit: ") 
     print "The total is", sum(total)
     print "Total numbers:", len(total)
于 2013-03-06T03:34:40.023 に答える