2016-04-14 15 views
0

私は何かをしようとしています。関数が入力を受け取り、整数の場合は数行を実行します。または文字列の場合はまたはが特定のコマンド(完了)であればループを終了します。私の問題は、ループを終了しない限り、常にエラーメッセージを表示する代わりに整数を検出しないことです。入力値が整数、コマンド、または悪いデータ(Python)であるかどうかを調べる

#The starting values of count (total number of numbers) 
#and total (total value of all the numbers) 
count = 0 
total = 0 

while True: 
    number = input("Please give me a number: ") 
    #the first check, to see if the loop should be exited 
    if number == ("done"): 
     print("We are now exiting the loop") 
     break 
    #the idea is that if the value is an integer, they are to be counted, whereas 
    #anything else would display in the error message 
    try: 
     int(number) 
     count = count + 1 
     total = total + number 
     continue 
    except: 
     print("That is not a number!") 
     continue 
#when exiting the code the program prints all the values it has accumulated thus far 
avarage = total/count 
print("Count: ", count) 
print("Total: ", total) 
print("Avarage: ", avarage) 

コードで少し周り突っついから、問題は(1 +カウント=カウント)と(1 +合計=合計)が、私は理由を見ることができないんだとあるように、それはそうです。どんな助けでも大歓迎です。

答えて

1

int(数値)は何にも割り当てられていないので、文字列のままです。

2つのことを行う必要があります。実際のエラーを出力するように例外処理を変更して、何が起こっているかを知ることができます。このコードは次のことを行います。

except Exception as e: 
    print("That is not a number!", e) 
    continue 

出力:あなたはあなたが行うことができない、一緒に文字列と整数を追加すること

That is not a number! unsupported operand type(s) for +: 'int' and 'str' 

try: 
    int(number) <------- This is not doing anything for your program 
    count = count + 1 
    total = total + number 

あなたはそれが恒久的にintに番号を変更すると思うので、あなたは後でそれを使用することができますが、そうではありません:あなたのコードを見て、あなたはでそれを行います。その1行のためだけですので、次のように2行移動する必要があります:

try: 
    count = count + 1 
    total = total + int(number) 
関連する問題