2016-10-07 10 views
-2

私はPythonで一度に1つの等級を求めるプログラムを書くことになっています。ユーザーが「完了」と入力すると、次のように計算されます。Pythonでユーザー入力を計算する方法

これは私がこれまで持っているものです。

def main(): 
    user_input = input("Enter grade: ") 
    number = user_input 
    while True: 
     user_input = input("Enter grade: ") 
     if user_input == "done": 
      break 
    avg(number) 

def avg(a): 
    average = sum(a)/len(a) 
    print(average) 

if __name__ == "__main__": 
    main() 

私が入力するたびに「済」プログラムは私に、このエラーが発生します。

TypeError: 'int' object is not iterable

私はしUSER_INPUT変数を変更しようとしている:

user_input = int(input("Enter grade: "))

しかし、別のエラー:例外TypeError:

'int' object is not iterable user input

私はプログラミングに非常に新しいです。誰でも私がこれを手助けすることができますか?私は過去2時間オンラインで検索してきましたが、別のエラーを生成しただけのものは見つかりませんでした。

+1

をSOへようこそ。すでにかなりの質問がありますので、最初に検索してください。例えば。 http://stackoverflow.com/questions/19190739/user-input-average、またはhttp://stackoverflow.com/questions/12539934/how-to-find-the-average-of-numbers-being-input-with -0-breaking-the-loop。 – Roope

+0

https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output –

答えて

1

私はあなたの問題を解決するかもしれないいくつかのことに気づいています。

  1. 実際に数字のリストを入力する場合は、numberavgに、それに関数を入力しています。
  2. 私はあなたのような何かをする必要があると思う:数字と呼ばれるリストを作成し、そのリストに各ユーザーの入力を追加します。次に、数値リストにavg関数を使用します。
0

あなたのロジックにはいくつかの欠陥があります。

  • main()でユーザー入力を要求するたびに、user_inputの値を上書きします。あなたがしなければならないことは、各番号をlist()に集めています。
  • あなたを言っている何のエラーのPythonは上げ、組み込み関数sum()こと、input()関数は、文字列を返すので、あなたが変換する必要があり、あなたの合格インチ
  • 単一番号、番号のリストを取るされていません整数への入力

私は次のようにプログラムを書き換えます:

def main(): 
    # create a list to store each grade 
    # that the user inputs. 
    grades = [] 

    # while forever 
    while True: 
     # get input from the user. 
     # I am not converting the input to a integer 
     # here, because were expecting the user to 
     # enter a string when done. 
     i = input("Enter grade: ") 

     # if the user enters 'done' break the loop. 
     if i == 'done':break 

     # add the grade the user entered to our grades list. 
     # converting it to an integer. 
     grades.append(int(i)) 

    # print the return value 
    # of the avg function. 
    print("Grade average:", avg(grades)) 

def avg(grades): 
    # return the average of 
    # the grades. 
    # note that I'm using the builtin round() 
    # function here. That is because 
    # the average is sometimes a 
    # long decimal. If this does not matter 
    # to you, you can remove it. 
    return round(sum(grades)/len(grades), 2) 

# call the function main() 
main() 
関連する問題