2017-02-25 10 views
-3

が、これは私が答えなければならない問題である。私はこの構文エラーを取得:TypeError例外:+のためのサポートされていないオペランドのタイプ(複数可):「int型」と「str」は

は外の(入力試験の点数にプログラムを書きます100)を入力し、「quit」と入力します。試験のスコアを入力すると、すべての試験のスコアの平均が印刷されます。

ヒント: 平均を調べるには、試験のスコアの合計と入力した数字のカウントを保持する必要があります。 プログラムを1回実行させてから、終了条件を見つけてwhile True:ループを使用してください。

実行例は: 試験のスコアやタイプを入力します「終了」:100 試験のスコアやタイプ「終了」を入力:100 試験のスコアやタイプ「終了」を入力:50 は、試験の点数やタイプ「終了」を入力します。終了 スコアの数が3の平均は83.33

である。これは私のコードです:

count = 0 
average = sum 
while True: 
    num =input('Enter an exam score or type "quit":') 
    count = count + 1 
    average = sum(num) 
    print ('the total of exams is %d and the average is %f' % count, average) 
    if num == 'quit': 
     break 
print ('this is ok for now') 
+0

「num」を最初にint(..)する必要があります。 –

+0

ありがとう、これは私が持っているものです:TypeError: 'int'オブジェクトは反復不可能です –

+0

しかし、要素を1つずつ入力します。だから、毎回 'num'を追加する実行変数を使うべきです... –

答えて

0

この行は、多くの問題があります:average = sum(num)

sumの適切な入力は、合計する数値のリストです。あなたの場合、代わりに単一の番号または "quit"という単語があります。

total = 0 
count = 0 
while True: 
    # With raw_input, we know we are getting a string instead of 
    # having Python automatically try to interpret the value as the 
    # correct type 
    num = raw_input('Enter an exam score or type "quit":') 
    if num == "quit": 
     break 
    # Convert num from a string to an integer and add it to total 
    total += int(num) 
    count = count + 1 
average = total/count 
print("The total number of exams is {} and the average is {}".format(count, average)) 
0

私のテイクが終了するためstatisticsモジュールとsysを使用することになります。あなたがする必要がどのような

は、最後にあなたの除算を行い、カウント数と、実行中の合計を追跡することです。また、非int型(または非float型)の入力を処理し、ValueErrorで終了する代わりに適切なメッセージを出力する。

import statistics, sys 

notes = [] 
count = 0 
average = 0 # or None 
while True: 
    note = input('Enter score: ') 
    # handle quit request first, skip any calculation 
    # if quit is the first request 
    if note == 'quit': 
     print('Program exit. Average is %s' % average) 
     sys.exit() 
    else: 
     # test if the entered data can be an int or float 
     try: 
      note = int(note)  # can be replaced with float(note) if needed 
      count += 1   # increase the counter 
      notes.append(int(note)) 
      average = statistics.mean(notes) # calculate the average (mean) 
      print('Total %s average is %s' % (count, average)) 
     # just print an error message otherwise and continue 
     except ValueError: 
      print('Please enter a valid note or "quit"') 
関連する問題