2016-04-14 13 views
0

Bir şey yapmaya çalışıyorum (kabul edilir) basit. Eğer bir işlev veya bir tamsayı ise bir satırını almak için işlevimi istiyorum, bir veya dize, , belirli bir komut (bitti) ise döngüden çıkın. Benim sorunum, bir tam sayıyı asla algılamamasıdır, bunun yerine her zaman döngüden çıkmadığım sürece hata mesajını görüntülemektir. Sorun aittir gibi kodla biraz kurcalama itibaren Girdi değeri tamsayı mı, komut mu, yoksa sadece kötü veri mi (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) 

, öyle görünüyor (+ 1'e saymak = saymak) ve (+ toplam = toplam 1), ama neden göremiyorsunuz değilim. Herhangi bir yardım büyük beğeni topluyor.

cevap

1

Int (sayı) öğenizi hiçbir şeye atamadınız, bu nedenle bir dizgi olarak kalır.

Yapmanız gereken iki şey. Gerçek hatayı yazdırmak için istisna işleminizi değiştirin, böylece neler olup bittiğine dair bir ipucunuz olsun. Bu kod aşağıdakileri yapar.

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

Çıktı: Eğer yapamaz, hangi arada bir dize ve bir tamsayı ekliyoruz demektir

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 

Bunu kalıcı bir int sayı değişiyor düşünüyorum, bu nedenle daha sonra kullanabilirsiniz, ama değil: Kodunuzdaki baktığımızda, en bunu. Sadece bir satır için, şu şekilde iki satır aşağı taşımanız gerekecek:

try: 
    count = count + 1 
    total = total + int(number) 
İlgili konular