python while 循环中的计数未正确递增

Count not incrementing properly in python while loop

谁能告诉我为什么当我在这段代码中输入 1、2、3 和 4 时,我的输出是 6、2、3.00?我认为每次我的 while 循环评估为 true 时它都会将计数递增 1,但输出没有意义。它取了 3 个数字的总数,但只取 2 个数字?我可能只是忽略了一些东西,所以多一双眼睛会很棒。

def calcAverage(total, count):
    average = float(total)/float(count)
    return format(average, ',.2f')


def inputPositiveInteger():
    str_in = input("Please enter a positive integer, anything else to quit: ")
    if not str_in.isdigit():
        return -1
    else:
        try:
            pos_int = int(str_in)
            return pos_int
        except:
            return -1


def main():
    total = 0
    count = 0
    while inputPositiveInteger() != -1:
        total += inputPositiveInteger()
        count += 1
    else:
        if count != 0:
            print(total)
            print(count)
            print(calcAverage(total, count))


main()

您的代码的错误在于这段代码...

while inputPositiveInteger() != -1:
        total += inputPositiveInteger()

你先调用inputPositiveInteger然后把你的条件抛出结果。您需要存储结果,否则两个输入中的一个将被忽略,即使它是 -1.

也会添加另一个
num = inputPositiveInteger()
while num != -1:
        total += num 
        count += 1
        num = inputPositiveInteger()

改进

尽管如此,请注意您的代码可以得到显着改进。请参阅以下代码改进版本中的注释。

def calcAverage(total, count):
    # In Python3, / is a float division you do not need a float cast
    average = total / count 
    return format(average, ',.2f')


def inputPositiveInteger():
    str_int = input("Please enter a positive integer, anything else to quit: ")

    # If str_int.isdigit() returns True you can safely assume the int cast will work
    return int(str_int) if str_int.isdigit() else -1


# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
    # Using the second form of iter is a neat way to loop over user inputs
    nums = iter(inputPositiveInteger, -1)
    sum_ = sum(nums)

    print(sum_)
    print(len(nums))
    print(calcAverage(sum_, len(nums)))

上面代码中值得一读的一个细节是 second form of iter.