我的程序不断收到错误“除以零”

时间:2016-02-18 20:52:47

标签: python if-statement while-loop eval

此程序旨在计算未指定数量的整数, 确定已读取的负值和正值的数量, 并计算输入值的平均值和总数。

如果用户输入0,程序将结束。每次输入0时,我都会收到一条错误,指出“除以零”。调试器说它来自最后一行。

我想这与sum / count部分有关。当我使用负数时,它从同一行代码中说同样的事情。最后,我不确定如何显示文本“你没有输入任何数字”。我尝试过if else语句,但我不认为我这样做是正确的。

data = eval(input("Enter an integer, the input ends if it is 0: "))
count = 0
sum = 0
negCount = 0
if data != 0:             
    while data > 0:     
        count = count + 1
        sum = sum + data 
        data = eval(input("Enter an integer, the input ends if it is 0: "))       
        while data < 0:
            negCount = count + 1
            sum = sum + data
            data = eval(input("Enter an integer, the input ends if it is 0: "))
            while data != 0:
                sum = sum + data              
                data = eval(input("Enter an integer, the input ends if it is 0: "))
                break
            else:   
                print("You didn't enter any number")                       



print("The number of positives is", count)
print("The number of negatives is", negCount)
print("The total is", sum)
print("The average is", sum / count)

2 个答案:

答案 0 :(得分:4)

output = []
while True:
    data = int(input("Enter an integer, the input ends if it is 0: "))
    if data == 0:
        break
    output.append(data)

positives = len([i for i in output if i > 0])
negatives = len(output) - positives
total = sum(output)

if len(output) != 0:
    print("The number of positives is", positives)
    print("The number of negatives is", negatives)
    print("The total is", total)
    print("The average is", total / len(output))
else:
    print("You didn't enter any number")

答案 1 :(得分:2)

如果输入0,则跳过if块(if data != 0)。如果跳过if块,则count为0.如果count为0,则sum / count未经数学定义,并将引发ZeroDivisionError