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

时间:2018-10-04 02:13:55

标签: python-3.x function while-loop increment

有人可以告诉我为什么当我在此代码中输入1、2、3和4时,我的输出是6、2、3.00吗?我以为每次我的while循环评估为true时,计数都会增加一,但是输出没有意义。它总共需要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()

1 个答案:

答案 0 :(得分:0)

您的代码错误是在这段代码上...

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 = list(iter(inputPositiveInteger, -1))
    sum_ = sum(nums)

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

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