【问题标题】:Count not incrementing properly in python while loop在python while循环中计数没有正确递增
【发布时间】:2019-03-09 07:59:51
【问题描述】:

谁能告诉我为什么当我在这段代码中输入 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()

【问题讨论】:

  • 你调用inputPositiveInteger(),检查它是否等于-1,否则忽略它的值,然后另一个调用inputPositiveInteger(),并将它添加到你的总计和计数(即使是 -1)。

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


【解决方案1】:

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

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

您首先调用inputPositiveInteger 并在您的条件下抛出结果。您需要存储结果,否则忽略两个输入中的一个,即使是-1,也会添加另一个。

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

改进

不过,请注意,您的代码可以得到显着改进。请参阅以下代码改进版本中的 cmets。

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

【讨论】:

    猜你喜欢
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 2013-12-26
    • 2016-08-26
    相关资源
    最近更新 更多