检查输入值是整数,命令还是只是坏数据(Python)

时间:2016-04-14 13:33:03

标签: python python-3.x

我正在努力做一些事情(诚然)。我希望我的函数接受一个输入,如果它是一个整数打印错误消息,如果它是一个字符串,如果它是一个特定命令,则退出循环完成)。我的问题是它从不检测整数,而是总是显示错误信息,除非我退出循环。

#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)

从代码中略微探讨一下,似乎问题在于(count = count + 1)和(total = total + 1),但我无法理解为什么。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您没有将int(数字)分配给任何内容,因此它仍然是一个字符串。

您需要做两件事。更改您的异常处理以打印实际错误,以便您了解正在进行的操作。此代码执行以下操作。

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,因此您可以稍后使用它,但事实并非如此。它只适用于那一行,所以你需要将它移动两行:

try:
    count = count + 1
    total = total + int(number)